Config-file: remove User-Agent from config.json when saving

The config.json allows for setting custom HTTP headers, but given that
User-Agent is not customizable, we should remove it from the config before saving;

Before this change;

    $ 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
    {
        "auths": {
            "https://index.docker.io/v1/": {
                "auth": "<base64 auth>"
            }
        },
        "HttpHeaders": {
            "User-Agent": "Docker-Client/19.03.12 (linux)"
        }
    }

    $ 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 14:49:47 +02:00
parent 749c62fb4d
commit 3f19902eae
No known key found for this signature in database
GPG Key ID: 76698F39D527CE8C
2 changed files with 28 additions and 1 deletions

View File

@ -169,6 +169,13 @@ func (configFile *ConfigFile) SaveToWriter(writer io.Writer) error {
configFile.AuthConfigs = tmpAuthConfigs configFile.AuthConfigs = tmpAuthConfigs
defer func() { configFile.AuthConfigs = saveAuthConfigs }() defer func() { configFile.AuthConfigs = saveAuthConfigs }()
// User-Agent header is automatically set, and should not be stored in the configuration
for v := range configFile.HTTPHeaders {
if strings.EqualFold(v, "User-Agent") {
delete(configFile.HTTPHeaders, v)
}
}
data, err := json.MarshalIndent(configFile, "", "\t") data, err := json.MarshalIndent(configFile, "", "\t")
if err != nil { if err != nil {
return err return err

View File

@ -466,7 +466,27 @@ func TestSave(t *testing.T) {
assert.NilError(t, err) assert.NilError(t, err)
cfg, err := ioutil.ReadFile("test-save") cfg, err := ioutil.ReadFile("test-save")
assert.NilError(t, err) assert.NilError(t, err)
assert.Check(t, is.Equal(string(cfg), "{\n \"auths\": {}\n}")) assert.Equal(t, string(cfg), `{
"auths": {}
}`)
}
func TestSaveCustomHTTPHeaders(t *testing.T) {
configFile := New(t.Name())
defer os.Remove(t.Name())
configFile.HTTPHeaders["CUSTOM-HEADER"] = "custom-value"
configFile.HTTPHeaders["User-Agent"] = "user-agent 1"
configFile.HTTPHeaders["user-agent"] = "user-agent 2"
err := configFile.Save()
assert.NilError(t, err)
cfg, err := ioutil.ReadFile(t.Name())
assert.NilError(t, err)
assert.Equal(t, string(cfg), `{
"auths": {},
"HttpHeaders": {
"CUSTOM-HEADER": "custom-value"
}
}`)
} }
func TestSaveWithSymlink(t *testing.T) { func TestSaveWithSymlink(t *testing.T) {