Fix initializing client modifying custom HTTPHeaders

When initializing the API client, the User-Agent was added to any custom
HTTPHeaders that were configured. However, because the map was not properly
dereferenced, the original map was modified, causing the User-Agent to also
be saved to config.json after `docker login` and `docker logout`:

Before this change;

    $ cat ~/.docker/config.json
    cat: can't open '/root/.docker/config.json': No such file or directory

    $ docker login -u myusername
    Password:
    ...
    Login Succeeded

    $ cat ~/.docker/config.json
    {
        "auths": {
            "https://index.docker.io/v1/": {
                "auth": "<base64 auth>"
            }
        },
        "HttpHeaders": {
            "User-Agent": "Docker-Client/19.03.12 (linux)"
        }
    }

    $ docker logout
    {
        "auths": {},
        "HttpHeaders": {
            "User-Agent": "Docker-Client/19.03.12 (linux)"
        }
    }

After this change:

    $ cat ~/.docker/config.json
    cat: can't open '/root/.docker/config.json': No such file or directory

    $ docker login -u myusername
    Password:
    ...
    Login Succeeded

    $ cat ~/.docker/config.json
    {
        "auths": {
            "https://index.docker.io/v1/": {
                "auth": "<base64 auth>"
            }
        }
    }

    $ docker logout
    Removing login credentials for https://index.docker.io/v1/

    $ cat ~/.docker/config.json
    {
        "auths": {}
    }

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
This commit is contained in:
Sebastiaan van Stijn 2020-09-29 17:01:55 +02:00
parent f53ba44c39
commit 2b1138c118
No known key found for this signature in database
GPG Key ID: 76698F39D527CE8C
2 changed files with 4 additions and 3 deletions

View File

@ -308,9 +308,9 @@ func newAPIClientFromEndpoint(ep docker.Endpoint, configFile *configfile.ConfigF
if err != nil {
return nil, err
}
customHeaders := configFile.HTTPHeaders
if customHeaders == nil {
customHeaders = map[string]string{}
customHeaders := make(map[string]string, len(configFile.HTTPHeaders))
for k, v := range configFile.HTTPHeaders {
customHeaders[k] = v
}
customHeaders["User-Agent"] = UserAgent()
clientOpts = append(clientOpts, client.WithHTTPHeaders(customHeaders))

View File

@ -45,6 +45,7 @@ func TestNewAPIClientFromFlags(t *testing.T) {
}
assert.Check(t, is.DeepEqual(expectedHeaders, apiclient.(*client.Client).CustomHTTPHeaders()))
assert.Check(t, is.Equal(api.DefaultVersion, apiclient.ClientVersion()))
assert.DeepEqual(t, configFile.HTTPHeaders, map[string]string{"My-Header": "Custom-Value"})
}
func TestNewAPIClientFromFlagsForDefaultSchema(t *testing.T) {