diff --git a/secrets/file.go b/secrets/file.go index 82ff9b89c5..41d5b62b9c 100644 --- a/secrets/file.go +++ b/secrets/file.go @@ -20,6 +20,7 @@ const ( var ( ErrWrongFileType = errors.New("file type not supported") ErrFailedToReadFile = errors.New("failed to read file") + errEmptyFile = errors.New("empty file") ) // SecretsProvider is a SecretsReader and can add secret sources that @@ -81,7 +82,7 @@ func (sp *SecretPaths) Add(path string) error { switch mode := fi.Mode(); { // Kubernetes uses symlink to file case mode.IsRegular() || mode&os.ModeSymlink != 0: - if _, err := os.ReadFile(path); err != nil { + if _, err := readSecretFile(path); err != nil { return err } case mode.IsDir(): @@ -185,6 +186,9 @@ func readSecretFile(path string) ([]byte, error) { if len(data) > 0 && data[len(data)-1] == 0xa { data = data[:len(data)-1] } + if len(data) == 0 { + return nil, errEmptyFile + } return data, nil } diff --git a/secrets/file_test.go b/secrets/file_test.go index 876f7452b3..2abc6fb39e 100644 --- a/secrets/file_test.go +++ b/secrets/file_test.go @@ -235,6 +235,32 @@ func TestSecretPaths(t *testing.T) { checkSecret(t, path, "created") }) + + t.Run("errors on empty file", func(t *testing.T) { + path := t.TempDir() + "/foo" + + writeFile(t, path, "") + + assert.Error(t, sp.Add(path)) + }) + + t.Run("removes empty file", func(t *testing.T) { + path := t.TempDir() + "/foo" + + writeFile(t, path, "created") + + require.NoError(t, sp.Add(path)) + + checkSecret(t, path, "created") + + writeFile(t, path, "") + + _, exists := sp.GetSecret(path) + assert.False(t, exists) + + writeFile(t, path, "re-created") + checkSecret(t, path, "re-created") + }) } func TestSecretPathsDoesNotRefreshAfterClose(t *testing.T) {