diff --git a/pkg/cfg/env.go b/pkg/cfg/env.go new file mode 100644 index 00000000..af648344 --- /dev/null +++ b/pkg/cfg/env.go @@ -0,0 +1,33 @@ +// Copyright 2024 Outreach Corporation. All Rights Reserved. + +// Description: Support for env loading env vars as strings or as SecretData + +package cfg + +import ( + "os" + + "github.com/pkg/errors" +) + +// EnvSecret looks up a secret from the environment. +func EnvSecret(name string) (SecretData, error) { + val, err := EnvString(name) + if err != nil { + return "", err + } + return SecretData(val), nil +} + +// EnvString looks up a string from the environment. +func EnvString(name string) (string, error) { + var ( + ok bool + val string + ) + val, ok = os.LookupEnv(name) + if !ok { + return "", errors.Errorf("%q environment variable not set", name) + } + return val, nil +} diff --git a/pkg/cfg/env_test.go b/pkg/cfg/env_test.go new file mode 100644 index 00000000..44edb8e4 --- /dev/null +++ b/pkg/cfg/env_test.go @@ -0,0 +1,49 @@ +package cfg + +import ( + "os" + "testing" + + "github.com/google/uuid" + "gotest.tools/v3/assert" +) + +func TestEnvString(t *testing.T) { + key := uuid.NewString() + value := uuid.NewString() + notsetKey := uuid.NewString() + err := os.Setenv(key, value) + assert.NilError(t, err, "failed to set environment variable") + + t.Run("if key not set; error is returned", func(t *testing.T) { + _, err := EnvString(notsetKey) + assert.ErrorContains(t, err, notsetKey) + assert.ErrorContains(t, err, "environment variable not set") + }) + + t.Run("returns set value", func(t *testing.T) { + v, err := EnvString(key) + assert.NilError(t, err) + + assert.Equal(t, v, value) + }) +} + +func TestEnvSecret(t *testing.T) { + key := uuid.NewString() + value := uuid.NewString() + notsetKey := uuid.NewString() + err := os.Setenv(key, value) + assert.NilError(t, err, "failed to set environment variable") + + t.Run("if key not set; error is returned", func(t *testing.T) { + _, err := EnvSecret(notsetKey) + assert.ErrorContains(t, err, notsetKey) + assert.ErrorContains(t, err, "environment variable not set") + }) + + v, err := EnvSecret(key) + assert.NilError(t, err) + + assert.Equal(t, string(v), value) +}