From 6a6f369d97dc0253147adb2982502a47e120b5e1 Mon Sep 17 00:00:00 2001 From: fatelei Date: Tue, 22 Aug 2023 19:09:45 +0800 Subject: [PATCH] fix: using errors.As to check x509 error --- client.go | 3 ++- go.mod | 1 + roundtripper_test.go | 31 +++++++++++++++++++++++++++++++ 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/client.go b/client.go index cad96bd..5544864 100644 --- a/client.go +++ b/client.go @@ -28,6 +28,7 @@ import ( "bytes" "context" "crypto/x509" + "errors" "fmt" "io" "io/ioutil" @@ -483,7 +484,7 @@ func baseRetryPolicy(resp *http.Response, err error) (bool, error) { if notTrustedErrorRe.MatchString(v.Error()) { return false, v } - if _, ok := v.Err.(x509.UnknownAuthorityError); ok { + if errors.As(v.Err, &x509.UnknownAuthorityError{}) { return false, v } } diff --git a/go.mod b/go.mod index d05df1b..d3bb6cb 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/hashicorp/go-retryablehttp require ( github.com/hashicorp/go-cleanhttp v0.5.2 github.com/hashicorp/go-hclog v0.9.2 + github.com/stretchr/testify v1.2.2 ) go 1.13 diff --git a/roundtripper_test.go b/roundtripper_test.go index dcb02df..309e55b 100644 --- a/roundtripper_test.go +++ b/roundtripper_test.go @@ -5,7 +5,10 @@ package retryablehttp import ( "context" + "crypto/tls" + "crypto/x509" "errors" + "github.com/stretchr/testify/assert" "io/ioutil" "net" "net/http" @@ -132,6 +135,34 @@ func TestRoundTripper_TransportFailureErrorHandling(t *testing.T) { } } +func TestHTTPClientWithTLSFailure(t *testing.T) { + // Create a mock server with a handler + mockServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + w.Write([]byte("Mock Response")) + })) + defer mockServer.Close() + + // Set up the HTTP client with retryablehttp using a custom transport without InsecureSkipVerify + tr := &http.Transport{ + TLSClientConfig: &tls.Config{}, + } + + // Set up the retryable HTTP client with the custom transport + client := NewClient() + client.HTTPClient.Transport = tr + client.RetryMax = 2 + + // Make a GET request using the retryable HTTP client + _, err := client.Get(mockServer.URL) + + // Check that the error is indeed related to x509 certificate validation + var x509Error *x509.CertificateInvalidError + if assert.Error(t, err) && errors.As(err, &x509Error) { + assert.Contains(t, x509Error.Error(), "x509: certificate is not valid for any names") + } +} + func normalizeError(err error) error { var dnsError *net.DNSError