From b07de476942d2e6f4b97927defabcef77e337823 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Gronowski?= Date: Thu, 3 Sep 2026 10:31:30 +0200 Subject: [PATCH] cli/command: Avoid panics after client initialization errors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When client.New rejects an invalid Docker host or other client option, it returns a nil concrete client with an error. Returning that pointer directly as client.APIClient stores a typed-nil interface, so lazy version checks dereference it. Return an error instead. Signed-off-by: Paweł Gronowski --- cli/command/cli.go | 6 +++++- cli/command/cli_test.go | 9 +++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/cli/command/cli.go b/cli/command/cli.go index f7f428b11b..e405c2cc4f 100644 --- a/cli/command/cli.go +++ b/cli/command/cli.go @@ -316,7 +316,11 @@ func newAPIClientFromEndpoint(ep docker.Endpoint, configFile *configfile.ConfigF opts = append(opts, withCustomHeaders) } opts = append(opts, extraOpts...) - return client.New(opts...) + apiClient, err := client.New(opts...) + if err != nil { + return nil, err + } + return apiClient, nil } func resolveDockerEndpoint(s store.Reader, contextName string) (docker.Endpoint, error) { diff --git a/cli/command/cli_test.go b/cli/command/cli_test.go index be5bcabfbb..27be8d348c 100644 --- a/cli/command/cli_test.go +++ b/cli/command/cli_test.go @@ -132,6 +132,15 @@ func TestNewAPIClientFromFlagsWithAPIVersionFromEnv(t *testing.T) { assert.Equal(t, apiclient.ClientVersion(), expectedVersion) } +func TestNewAPIClientFromFlagsWithInvalidAPIVersionFromEnv(t *testing.T) { + t.Setenv("DOCKER_API_VERSION", "1") + t.Setenv("DOCKER_HOST", ":2375") + + apiClient, err := NewAPIClientFromFlags(&flags.ClientOptions{}, &configfile.ConfigFile{}) + assert.ErrorContains(t, err, "invalid API version") + assert.Check(t, apiClient == nil) +} + type fakeClient struct { client.Client pingFunc func() (client.PingResult, error)