Skip to content

Commit aee0bb2

Browse files
kokeszliang-akamai
andauthored
NewClient panics if http.client is nil and LINODE_CA is set (#635)
I tried a new linodego with a custom CA and a nil HTTP client and encountered a panic. Co-authored-by: Zhiwei Liang <121905282+zliang-akamai@users.noreply.github.com>
1 parent 5fc5868 commit aee0bb2

File tree

2 files changed

+33
-3
lines changed

2 files changed

+33
-3
lines changed

client.go

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -738,7 +738,7 @@ func NewClient(hc *http.Client) (client Client) {
738738

739739
certPath, certPathExists := os.LookupEnv(APIHostCert)
740740

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

884-
func isCustomTransport(transport http.RoundTripper) bool {
885-
if transport != http.DefaultTransport.(*http.Transport) {
884+
func hasCustomTransport(hc *http.Client) bool {
885+
if hc == nil {
886+
return false
887+
}
888+
if hc.Transport != http.DefaultTransport.(*http.Transport) {
886889
log.Println("[WARN] Custom transport is not allowed with a custom root CA.")
887890
return true
888891
}

client_test.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -576,3 +576,30 @@ func TestClient_CustomRootCAWithCustomRoundTripper(t *testing.T) {
576576

577577
log.SetOutput(os.Stderr)
578578
}
579+
580+
func TestClient_CustomRootCAWithoutCustomRoundTripper(t *testing.T) {
581+
caFile, err := os.CreateTemp(t.TempDir(), "linodego_test_ca_*")
582+
if err != nil {
583+
t.Fatalf("Failed to create temp ca file: %s", err)
584+
}
585+
defer os.Remove(caFile.Name())
586+
587+
for _, setCA := range []bool{false, true} {
588+
if setCA {
589+
t.Setenv(APIHostCert, caFile.Name())
590+
}
591+
592+
client := NewClient(nil)
593+
594+
transport, err := client.resty.Transport()
595+
if err != nil {
596+
t.Fatal(err)
597+
}
598+
if setCA && (transport.TLSClientConfig == nil || transport.TLSClientConfig.RootCAs == nil) {
599+
t.Error("expected root CAs to be set")
600+
}
601+
if !setCA && transport.TLSClientConfig != nil {
602+
t.Errorf("didn't set a custom CA, but client TLS config is not nil: %#v", transport.TLSClientConfig)
603+
}
604+
}
605+
}

0 commit comments

Comments
 (0)