requestid_test.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. package e2e
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "net"
  7. "path/filepath"
  8. "sync"
  9. "testing"
  10. "github.com/smallstep/certificates/authority/config"
  11. "github.com/smallstep/certificates/ca"
  12. "github.com/smallstep/certificates/ca/client"
  13. "github.com/smallstep/certificates/errs"
  14. "github.com/stretchr/testify/assert"
  15. "github.com/stretchr/testify/require"
  16. "go.step.sm/crypto/minica"
  17. "go.step.sm/crypto/pemutil"
  18. )
  19. // reservePort "reserves" a TCP port by opening a listener on a random
  20. // port and immediately closing it. The port can then be assumed to be
  21. // available for running a server on.
  22. func reservePort(t *testing.T) (host, port string) {
  23. t.Helper()
  24. l, err := net.Listen("tcp", ":0")
  25. require.NoError(t, err)
  26. address := l.Addr().String()
  27. err = l.Close()
  28. require.NoError(t, err)
  29. host, port, err = net.SplitHostPort(address)
  30. require.NoError(t, err)
  31. return
  32. }
  33. func Test_reflectRequestID(t *testing.T) {
  34. dir := t.TempDir()
  35. m, err := minica.New(minica.WithName("Step E2E"))
  36. require.NoError(t, err)
  37. rootFilepath := filepath.Join(dir, "root.crt")
  38. _, err = pemutil.Serialize(m.Root, pemutil.WithFilename(rootFilepath))
  39. require.NoError(t, err)
  40. intermediateCertFilepath := filepath.Join(dir, "intermediate.crt")
  41. _, err = pemutil.Serialize(m.Intermediate, pemutil.WithFilename(intermediateCertFilepath))
  42. require.NoError(t, err)
  43. intermediateKeyFilepath := filepath.Join(dir, "intermediate.key")
  44. _, err = pemutil.Serialize(m.Signer, pemutil.WithFilename(intermediateKeyFilepath))
  45. require.NoError(t, err)
  46. // get a random address to listen on and connect to; currently no nicer way to get one before starting the server
  47. // TODO(hs): find/implement a nicer way to expose the CA URL, similar to how e.g. httptest.Server exposes it?
  48. host, port := reservePort(t)
  49. cfg := &config.Config{
  50. Root: []string{rootFilepath},
  51. IntermediateCert: intermediateCertFilepath,
  52. IntermediateKey: intermediateKeyFilepath,
  53. Address: net.JoinHostPort(host, port), // reuse the address that was just "reserved"
  54. DNSNames: []string{"127.0.0.1", "[::1]", "localhost"},
  55. AuthorityConfig: &config.AuthConfig{
  56. AuthorityID: "stepca-test",
  57. DeploymentType: "standalone-test",
  58. },
  59. Logger: json.RawMessage(`{"format": "text"}`),
  60. }
  61. c, err := ca.New(cfg)
  62. require.NoError(t, err)
  63. // instantiate a client for the CA running at the random address
  64. caClient, err := ca.NewClient(
  65. fmt.Sprintf("https://localhost:%s", port),
  66. ca.WithRootFile(rootFilepath),
  67. )
  68. require.NoError(t, err)
  69. var wg sync.WaitGroup
  70. wg.Add(1)
  71. go func() {
  72. defer wg.Done()
  73. err = c.Run()
  74. require.Error(t, err) // expect error when server is stopped
  75. }()
  76. // require OK health response as the baseline
  77. ctx := context.Background()
  78. healthResponse, err := caClient.HealthWithContext(ctx)
  79. require.NoError(t, err)
  80. if assert.NotNil(t, healthResponse) {
  81. require.Equal(t, "ok", healthResponse.Status)
  82. }
  83. // expect an error when retrieving an invalid root
  84. rootResponse, err := caClient.RootWithContext(ctx, "invalid")
  85. if assert.Error(t, err) {
  86. apiErr := &errs.Error{}
  87. if assert.ErrorAs(t, err, &apiErr) {
  88. assert.Equal(t, 404, apiErr.StatusCode())
  89. assert.Equal(t, "The requested resource could not be found. Please see the certificate authority logs for more info.", apiErr.Err.Error())
  90. assert.NotEmpty(t, apiErr.RequestID)
  91. // TODO: include the below error in the JSON? It's currently only output to the CA logs. Also see https://github.com/smallstep/certificates/pull/759
  92. //assert.Equal(t, "/root/invalid was not found: certificate with fingerprint invalid was not found", apiErr.Msg)
  93. }
  94. }
  95. assert.Nil(t, rootResponse)
  96. // expect an error when retrieving an invalid root and provided request ID
  97. rootResponse, err = caClient.RootWithContext(client.WithRequestID(ctx, "reqID"), "invalid")
  98. if assert.Error(t, err) {
  99. apiErr := &errs.Error{}
  100. if assert.ErrorAs(t, err, &apiErr) {
  101. assert.Equal(t, 404, apiErr.StatusCode())
  102. assert.Equal(t, "The requested resource could not be found. Please see the certificate authority logs for more info.", apiErr.Err.Error())
  103. assert.Equal(t, "reqID", apiErr.RequestID)
  104. }
  105. }
  106. assert.Nil(t, rootResponse)
  107. // done testing; stop and wait for the server to quit
  108. err = c.Stop()
  109. require.NoError(t, err)
  110. wg.Wait()
  111. }