From 43a23d501c568c89c6f7220c3bff6a92fe0ff3fc Mon Sep 17 00:00:00 2001 From: r3t4 <34656130+r3t4@users.noreply.github.com> Date: Tue, 23 Aug 2022 17:29:01 +0200 Subject: [PATCH] missing DCO verification (#125) Signed-off-by: r3t4 <34656130+r3t4@users.noreply.github.com> Signed-off-by: r3t4 <34656130+r3t4@users.noreply.github.com> --- pkg/config/config.go | 28 ++++++++++++++++++++++++++++ pkg/config/config_test.go | 17 +++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/pkg/config/config.go b/pkg/config/config.go index af23c68..08b72b3 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -17,6 +17,7 @@ import ( "fmt" "io/ioutil" "net/url" + "os" "path/filepath" "regexp" "strconv" @@ -64,6 +65,12 @@ func LoadFile(filename string, logger log.Logger) (*Config, []byte, error) { if err != nil { return nil, nil, err } + + content, err = substituteEnvVars(content, logger) + if err != nil { + return nil, nil, err + } + cfg, err := Load(string(content)) if err != nil { return nil, nil, err @@ -73,6 +80,27 @@ func LoadFile(filename string, logger log.Logger) (*Config, []byte, error) { return cfg, content, nil } +// expand env variables $(var) from the config file +// taken from https://github.dev/thanos-io/thanos/blob/296c4ab4baf2c8dd6abdf2649b0660ac77505e63/pkg/reloader/reloader.go#L445-L462 by https://github.com/fabxc +func substituteEnvVars(b []byte, logger log.Logger) (r []byte, err error) { + var envRe = regexp.MustCompile(`\$\(([a-zA-Z_0-9]+)\)`) + r = envRe.ReplaceAllFunc(b, func(n []byte) []byte { + if err != nil { + return nil + } + + n = n[2 : len(n)-1] + + v, ok := os.LookupEnv(string(n)) + if !ok { + err = fmt.Errorf("Missing env variable: %q", n) + return nil + } + return []byte(v) + }) + return r, err +} + // resolveFilepaths joins all relative paths in a configuration // with a given base directory. func resolveFilepaths(baseDir string, cfg *Config, logger log.Logger) { diff --git a/pkg/config/config_test.go b/pkg/config/config_test.go index 666fae7..32c85bd 100644 --- a/pkg/config/config_test.go +++ b/pkg/config/config_test.go @@ -93,6 +93,23 @@ func TestLoadFile(t *testing.T) { } +// Checks if the env var substitution is happening correctly in the loaded file +func TestEnvSubstitution(t *testing.T) { + + config := "user: $(JA_USER)" + os.Setenv("JA_USER", "user") + + content, err := substituteEnvVars([]byte(config), log.NewNopLogger()) + expected := "user: user" + require.NoError(t, err) + require.Equal(t, string(content), expected) + + config = "user: $(JA_MISSING)" + _, err = substituteEnvVars([]byte(config), log.NewNopLogger()) + require.Error(t, err) + +} + // A test version of the ReceiverConfig struct to create test yaml fixtures. type receiverTestConfig struct { Name string `yaml:"name,omitempty"`