From b9bafc582ce3ef7263217fdfe22e2a3e59f0d216 Mon Sep 17 00:00:00 2001 From: Alexey Zagarin Date: Thu, 9 May 2019 18:58:24 +0700 Subject: [PATCH] Strip newlines when reading environment variables from `_FILE` suffixed files. (#872) --- platform/config/env/env.go | 2 +- platform/config/env/env_test.go | 47 +++++++++++++++++++++++---------- 2 files changed, 34 insertions(+), 15 deletions(-) diff --git a/platform/config/env/env.go b/platform/config/env/env.go index cdb1941b..f489c657 100644 --- a/platform/config/env/env.go +++ b/platform/config/env/env.go @@ -159,5 +159,5 @@ func GetOrFile(envVar string) string { return "" } - return string(fileContents) + return strings.TrimSuffix(string(fileContents), "\n") } diff --git a/platform/config/env/env_test.go b/platform/config/env/env_test.go index 3bd5c403..57ba7ad2 100644 --- a/platform/config/env/env_test.go +++ b/platform/config/env/env_test.go @@ -289,25 +289,44 @@ func TestGetOrFile_ReadsFiles(t *testing.T) { varEnvFileName := "TEST_LEGO_ENV_VAR_FILE" varEnvName := "TEST_LEGO_ENV_VAR" - err := os.Unsetenv(varEnvFileName) - require.NoError(t, err) - err = os.Unsetenv(varEnvName) - require.NoError(t, err) + testCases := []struct { + desc string + fileContent []byte + }{ + { + desc: "simple", + fileContent: []byte("lego_file"), + }, + { + desc: "with an empty last line", + fileContent: []byte("lego_file\n"), + }, + } - file, err := ioutil.TempFile("", "lego") - require.NoError(t, err) - defer os.Remove(file.Name()) + for _, test := range testCases { + t.Run(test.desc, func(t *testing.T) { - err = ioutil.WriteFile(file.Name(), []byte("lego_file"), 0644) - require.NoError(t, err) + err := os.Unsetenv(varEnvFileName) + require.NoError(t, err) + err = os.Unsetenv(varEnvName) + require.NoError(t, err) - err = os.Setenv(varEnvFileName, file.Name()) - require.NoError(t, err) - defer os.Unsetenv(varEnvFileName) + file, err := ioutil.TempFile("", "lego") + require.NoError(t, err) + defer os.Remove(file.Name()) - value := GetOrFile(varEnvName) + err = ioutil.WriteFile(file.Name(), []byte("lego_file\n"), 0644) + require.NoError(t, err) - assert.Equal(t, "lego_file", value) + err = os.Setenv(varEnvFileName, file.Name()) + require.NoError(t, err) + defer os.Unsetenv(varEnvFileName) + + value := GetOrFile(varEnvName) + + assert.Equal(t, "lego_file", value) + }) + } } func TestGetOrFile_PrefersEnvVars(t *testing.T) {