http_client.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package authority
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "net/http"
  6. "sync/atomic"
  7. "github.com/smallstep/certificates/authority/poolhttp"
  8. "github.com/smallstep/certificates/authority/provisioner"
  9. "github.com/smallstep/certificates/internal/httptransport"
  10. )
  11. // systemCertPool holds a copy of the system cert pool. This cert pool must be
  12. // initialized when the authority is created and we should always get a clone of
  13. // this pool.
  14. var systemCertPool atomic.Pointer[x509.CertPool]
  15. // initializeSystemCertPool initializes the system cert pool if necessary.
  16. func initializeSystemCertPool() error {
  17. if systemCertPool.Load() == nil {
  18. pool, err := x509.SystemCertPool()
  19. if err != nil {
  20. return err
  21. }
  22. systemCertPool.Store(pool)
  23. }
  24. return nil
  25. }
  26. // newHTTPClient will return an HTTP client that trusts the system cert pool and
  27. // the given roots.
  28. func newHTTPClient(wt httptransport.Wrapper, roots ...*x509.Certificate) provisioner.HTTPClient {
  29. return poolhttp.New(func() *http.Client {
  30. pool := systemCertPool.Load().Clone()
  31. for _, crt := range roots {
  32. pool.AddCert(crt)
  33. }
  34. tr, ok := http.DefaultTransport.(*http.Transport)
  35. if !ok {
  36. tr = httptransport.New()
  37. } else {
  38. tr = tr.Clone()
  39. }
  40. tr.TLSClientConfig = &tls.Config{
  41. MinVersion: tls.VersionTLS12,
  42. RootCAs: pool,
  43. }
  44. rr := wt(tr)
  45. return &http.Client{Transport: rr}
  46. })
  47. }