diff --git a/pkg/webhook/health_check.go b/pkg/webhook/health_check.go index b0dd29f2c71..e0960f681dd 100644 --- a/pkg/webhook/health_check.go +++ b/pkg/webhook/health_check.go @@ -4,23 +4,27 @@ import ( "bytes" "crypto/tls" "fmt" + "io" "net/http" "path/filepath" logf "sigs.k8s.io/controller-runtime/pkg/log" ) -// disabling gosec linting here as the http client used in this checking is intended to skip CA verification -// -//nolint:gosec -var tr = &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, -} -var insecureClient = &http.Client{Transport: tr} - var tlsCheckerLog = logf.Log.WithName("webhook-tls-checker") func NewTLSChecker(certDir string, port int) func(*http.Request) error { + //nolint:forcetypeassert + tr := http.DefaultTransport.(*http.Transport).Clone() + // disabling gosec linting here as the http client used in this checking is intended to skip CA verification + // + //nolint:gosec + tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} + // disable keep alives to ensure that http connection aren't reused, otherwise the check may + // fail if the cert was rotated in between + tr.DisableKeepAlives = true + insecureClient := &http.Client{Transport: tr} + returnFunc := func(_ *http.Request) error { resp, err := insecureClient.Get(fmt.Sprintf("https://127.0.0.1:%d", port)) if err != nil { @@ -28,6 +32,10 @@ func NewTLSChecker(certDir string, port int) func(*http.Request) error { tlsCheckerLog.Error(newErr, "error in connecting to webhook server with https") return newErr } + defer resp.Body.Close() + // explicitly discard the body to avoid any memory leak + _, _ = io.Copy(io.Discard, resp.Body) + if len(resp.TLS.PeerCertificates) == 0 { newErr := fmt.Errorf("webhook does not serve TLS certificate") tlsCheckerLog.Error(newErr, "error in connecting to webhook server with https")