Skip to content

Commit

Permalink
Do not fail creating the provisioner HTTP client
Browse files Browse the repository at this point in the history
This commit avoids an error starting the CA if the `http.DefaultTransport`
is not an `*http.Transport`. If the DefaultTransport is overwritten, the
newHTTPClient method will return a simple *http.Client. With an
*http.Transport, it will return a client that trusts the system
certificate pool and the CA roots.
  • Loading branch information
maraino committed Oct 16, 2024
1 parent 03c4b18 commit 6b872e8
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 20 deletions.
40 changes: 20 additions & 20 deletions authority/http_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 changes: 15 additions & 0 deletions authority/http_client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
}

0 comments on commit 6b872e8

Please sign in to comment.