Răsfoiți Sursa

Merge pull request #2034 from smallstep/mariano/http-client

Do not fail creating the provisioner HTTP client
Mariano Cano 2 ani în urmă
părinte
comite
4d59f35212
2 a modificat fișierele cu 35 adăugiri și 20 ștergeri
  1. 20 20
      authority/http_client.go
  2. 15 0
      authority/http_client_test.go

+ 20 - 20
authority/http_client.go

@@ -7,28 +7,28 @@ import (
 	"net/http"
 )
 
-// newHTTPClient returns an HTTP client that trusts the system cert pool and the
-// given roots.
+// newHTTPClient will return an HTTP client that trusts the system cert pool and
+// the given roots, but only if the http.DefaultTransport is an *http.Transport.
+// If not, it will return the default HTTP client.
 func newHTTPClient(roots ...*x509.Certificate) (*http.Client, error) {
-	pool, err := x509.SystemCertPool()
-	if err != nil {
-		return nil, fmt.Errorf("error initializing http client: %w", err)
-	}
-	for _, crt := range roots {
-		pool.AddCert(crt)
-	}
+	if tr, ok := http.DefaultTransport.(*http.Transport); ok {
+		pool, err := x509.SystemCertPool()
+		if err != nil {
+			return nil, fmt.Errorf("error initializing http client: %w", err)
+		}
+		for _, crt := range roots {
+			pool.AddCert(crt)
+		}
 
-	tr, ok := http.DefaultTransport.(*http.Transport)
-	if !ok {
-		return nil, fmt.Errorf("error initializing http client: type is not *http.Transport")
-	}
-	tr = tr.Clone()
-	tr.TLSClientConfig = &tls.Config{
-		MinVersion: tls.VersionTLS12,
-		RootCAs:    pool,
+		tr = tr.Clone()
+		tr.TLSClientConfig = &tls.Config{
+			MinVersion: tls.VersionTLS12,
+			RootCAs:    pool,
+		}
+		return &http.Client{
+			Transport: tr,
+		}, nil
 	}
 
-	return &http.Client{
-		Transport: tr,
-	}, nil
+	return &http.Client{}, nil
 }

+ 15 - 0
authority/http_client_test.go

@@ -102,4 +102,19 @@ func Test_newHTTPClient(t *testing.T) {
 			assert.Error(t, err)
 		})
 	})
+
+	t.Run("custom transport", func(t *testing.T) {
+		tmp := http.DefaultTransport
+		t.Cleanup(func() {
+			http.DefaultTransport = tmp
+		})
+		transport := struct {
+			http.RoundTripper
+		}{http.DefaultTransport}
+		http.DefaultTransport = transport
+
+		client, err := newHTTPClient(auth.rootX509Certs...)
+		assert.NoError(t, err)
+		assert.Equal(t, &http.Client{}, client)
+	})
 }