From 3f19902eae99d3c7e1e79ce4a90922911f5e9b1e Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Tue, 29 Sep 2020 14:49:47 +0200 Subject: [PATCH] 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": "" } }, "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": "" } }, "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 --- cli/config/configfile/file.go | 7 +++++++ cli/config/configfile/file_test.go | 22 +++++++++++++++++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/cli/config/configfile/file.go b/cli/config/configfile/file.go index 951fd973eb..dc9f39eb7e 100644 --- a/cli/config/configfile/file.go +++ b/cli/config/configfile/file.go @@ -169,6 +169,13 @@ func (configFile *ConfigFile) SaveToWriter(writer io.Writer) error { configFile.AuthConfigs = tmpAuthConfigs 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") if err != nil { return err diff --git a/cli/config/configfile/file_test.go b/cli/config/configfile/file_test.go index d6b6228bc3..0ed7b73fdd 100644 --- a/cli/config/configfile/file_test.go +++ b/cli/config/configfile/file_test.go @@ -466,7 +466,27 @@ func TestSave(t *testing.T) { assert.NilError(t, err) cfg, err := ioutil.ReadFile("test-save") 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) {