From 7ce22b2490b594ebcd601254ef126e97aef99b07 Mon Sep 17 00:00:00 2001 From: Sven Rebhan <36194019+srebhan@users.noreply.github.com> Date: Thu, 14 Mar 2024 19:31:32 +0100 Subject: [PATCH] fix(secrets): Avoid count underflow by only counting initialized secrets (#14991) --- config/config.go | 7 ++++++- config/config_test.go | 1 + config/secret.go | 6 +++--- config/secret_test.go | 25 +++++++++++++++++++++++++ 4 files changed, 35 insertions(+), 4 deletions(-) diff --git a/config/config.go b/config/config.go index 394d22d96..844581ffc 100644 --- a/config/config.go +++ b/config/config.go @@ -478,7 +478,12 @@ func (c *Config) LoadAll(configFiles ...string) error { } // Check if there is enough lockable memory for the secret - c.NumberSecrets = uint64(secretCount.Load()) + count := secretCount.Load() + if count < 0 { + log.Printf("E! Invalid secret count %d, please report this incident including your configuration!", count) + count = 0 + } + c.NumberSecrets = uint64(count) // Let's link all secrets to their secret-stores return c.LinkSecrets() diff --git a/config/config_test.go b/config/config_test.go index 6e427cb89..102396a2d 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -1293,6 +1293,7 @@ type MockupInputPlugin struct { MaxBodySize config.Size `toml:"max_body_size"` Paths []string `toml:"paths"` Port int `toml:"port"` + Password config.Secret `toml:"password"` Command string Files []string PidFile string diff --git a/config/secret.go b/config/secret.go index fba8e9c5d..ade8090a3 100644 --- a/config/secret.go +++ b/config/secret.go @@ -155,10 +155,10 @@ func (s *Secret) Destroy() { if s.container != nil { s.container.Destroy() s.container = nil - } - // Keep track of the number of secrets... - secretCount.Add(-1) + // Keep track of the number of used secrets... + secretCount.Add(-1) + } } // Empty return if the secret is completely empty diff --git a/config/secret_test.go b/config/secret_test.go index 189d59bfd..8aad7288c 100644 --- a/config/secret_test.go +++ b/config/secret_test.go @@ -351,6 +351,31 @@ func TestSecretEnvironmentVariable(t *testing.T) { require.EqualValues(t, "an env secret", secret.TemporaryString()) } +func TestSecretCount(t *testing.T) { + secretCount.Store(0) + cfg := []byte(` +[[inputs.mockup]] + +[[inputs.mockup]] + secret = "a secret" + +[[inputs.mockup]] + secret = "another secret" +`) + + c := NewConfig() + require.NoError(t, c.LoadConfigData(cfg)) + require.Len(t, c.Inputs, 3) + require.Equal(t, int64(2), secretCount.Load()) + + // Remove all secrets and check + for _, ri := range c.Inputs { + input := ri.Input.(*MockupSecretPlugin) + input.Secret.Destroy() + } + require.Equal(t, int64(0), secretCount.Load()) +} + func TestSecretStoreStatic(t *testing.T) { cfg := []byte( `