Skip to content

Commit

Permalink
NewClient panics if http.client is nil and LINODE_CA is set (#635)
Browse files Browse the repository at this point in the history
I tried a new linodego with a custom CA and a nil HTTP client and encountered a panic.

Co-authored-by: Zhiwei Liang <[email protected]>
  • Loading branch information
kokes and zliang-akamai authored Dec 20, 2024
1 parent 5fc5868 commit aee0bb2
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
9 changes: 6 additions & 3 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -738,7 +738,7 @@ func NewClient(hc *http.Client) (client Client) {

certPath, certPathExists := os.LookupEnv(APIHostCert)

if certPathExists && !isCustomTransport(hc.Transport) {
if certPathExists && !hasCustomTransport(hc) {
cert, err := os.ReadFile(filepath.Clean(certPath))
if err != nil {
log.Fatalf("[ERROR] Error when reading cert at %s: %s\n", certPath, err.Error())
Expand Down Expand Up @@ -881,8 +881,11 @@ func generateListCacheURL(endpoint string, opts *ListOptions) (string, error) {
return fmt.Sprintf("%s:%s", endpoint, hashedOpts), nil
}

func isCustomTransport(transport http.RoundTripper) bool {
if transport != http.DefaultTransport.(*http.Transport) {
func hasCustomTransport(hc *http.Client) bool {
if hc == nil {
return false
}
if hc.Transport != http.DefaultTransport.(*http.Transport) {
log.Println("[WARN] Custom transport is not allowed with a custom root CA.")
return true
}
Expand Down
27 changes: 27 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -576,3 +576,30 @@ func TestClient_CustomRootCAWithCustomRoundTripper(t *testing.T) {

log.SetOutput(os.Stderr)
}

func TestClient_CustomRootCAWithoutCustomRoundTripper(t *testing.T) {
caFile, err := os.CreateTemp(t.TempDir(), "linodego_test_ca_*")
if err != nil {
t.Fatalf("Failed to create temp ca file: %s", err)
}
defer os.Remove(caFile.Name())

for _, setCA := range []bool{false, true} {
if setCA {
t.Setenv(APIHostCert, caFile.Name())
}

client := NewClient(nil)

transport, err := client.resty.Transport()
if err != nil {
t.Fatal(err)
}
if setCA && (transport.TLSClientConfig == nil || transport.TLSClientConfig.RootCAs == nil) {
t.Error("expected root CAs to be set")
}
if !setCA && transport.TLSClientConfig != nil {
t.Errorf("didn't set a custom CA, but client TLS config is not nil: %#v", transport.TLSClientConfig)
}
}
}

0 comments on commit aee0bb2

Please sign in to comment.