From c9808045149595162820ccc085c7c77cdd7b6e2c Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Sat, 25 Dec 2021 22:02:54 -0800 Subject: [PATCH] trim values from envrionment files (#13991) trim values to remove any spaces, newlines from the files while importing credentials and other values. --- cmd/common-main.go | 6 ++++-- cmd/common-main_test.go | 43 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/cmd/common-main.go b/cmd/common-main.go index 8a6ffd8fc..d2225d179 100644 --- a/cmd/common-main.go +++ b/cmd/common-main.go @@ -19,6 +19,7 @@ package cmd import ( "bufio" + "bytes" "context" "crypto/tls" "crypto/x509" @@ -456,7 +457,8 @@ func (e envKV) String() string { } func parsEnvEntry(envEntry string) (envKV, error) { - if strings.TrimSpace(envEntry) == "" { + envEntry = strings.TrimSpace(envEntry) + if envEntry == "" { // Skip all empty lines return envKV{ Skip: true, @@ -529,7 +531,7 @@ func readFromSecret(sp string) (string, error) { } return "", err } - return string(credBuf), nil + return string(bytes.TrimSpace(credBuf)), nil } func loadEnvVarsFromFiles() { diff --git a/cmd/common-main_test.go b/cmd/common-main_test.go index 1b57a9e8b..49bd5e0ae 100644 --- a/cmd/common-main_test.go +++ b/cmd/common-main_test.go @@ -24,6 +24,49 @@ import ( "testing" ) +func Test_readFromSecret(t *testing.T) { + testCases := []struct { + content string + expectedErr bool + expectedValue string + }{ + { + "value\n", + false, + "value", + }, + { + " \t\n Hello, Gophers \n\t\r\n", + false, + "Hello, Gophers", + }, + } + + for _, testCase := range testCases { + testCase := testCase + t.Run("", func(t *testing.T) { + tmpfile, err := ioutil.TempFile("", "testfile") + if err != nil { + t.Error(err) + } + tmpfile.WriteString(testCase.content) + tmpfile.Sync() + tmpfile.Close() + + value, err := readFromSecret(tmpfile.Name()) + if err != nil && !testCase.expectedErr { + t.Error(err) + } + if err == nil && testCase.expectedErr { + t.Error(errors.New("expected error, found success")) + } + if value != testCase.expectedValue { + t.Errorf("Expected %s, got %s", testCase.expectedValue, value) + } + }) + } +} + func Test_minioEnvironFromFile(t *testing.T) { testCases := []struct { content string