Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion pkg/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package cmd
import (
"log/slog"
"os"
"strings"

"github.com/spf13/cobra"
"github.com/spf13/viper"
Expand All @@ -14,6 +15,8 @@ var (
edmLoggerLevel *slog.LevelVar
)

const envPrefix = "DNSTAPIR_EDM"

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "dnstapir-edm",
Expand Down Expand Up @@ -67,7 +70,7 @@ func initConfig() {
viper.SetConfigName(".dnstapir-edm")
}

viper.AutomaticEnv() // read in environment variables that match
configureEnv()

// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
Expand All @@ -77,3 +80,9 @@ func initConfig() {
// Make it so we can detect changes to the cryptopan secret in the config
viper.WatchConfig()
}

func configureEnv() {
viper.SetEnvPrefix(envPrefix)
viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
Comment thread
oej marked this conversation as resolved.
viper.AutomaticEnv() // read in environment variables that match
}
67 changes: 67 additions & 0 deletions pkg/cmd/root_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package cmd

import (
"io"
"log/slog"
"os"
"path/filepath"
"testing"

"github.com/spf13/viper"
)

func TestInitConfigIgnoresUnprefixedEnv(t *testing.T) {
initConfigForTest(t, "debug = false\n")
t.Setenv("DEBUG", "release")

initConfig()

var conf struct {
Debug bool `mapstructure:"debug"`
}
if err := viper.UnmarshalExact(&conf); err != nil {
t.Fatalf("unprefixed DEBUG should not affect config unmarshalling: %s", err)
}
if conf.Debug {
t.Fatal("unprefixed DEBUG unexpectedly overrode config debug=false")
}
}

func TestInitConfigUsesPrefixedEnv(t *testing.T) {
initConfigForTest(t, "debug = false\n")
t.Setenv("DEBUG", "release")
debugEnv := envPrefix + "_DEBUG"
t.Setenv(debugEnv, "true")

initConfig()

var conf struct {
Debug bool `mapstructure:"debug"`
}
if err := viper.UnmarshalExact(&conf); err != nil {
t.Fatalf("prefixed debug env should unmarshal cleanly: %s", err)
}
if !conf.Debug {
t.Fatalf("%s=true did not override config debug=false", debugEnv)
}
}

func initConfigForTest(t *testing.T, configData string) {
t.Helper()

viper.Reset()
oldCfgFile := cfgFile
oldLogger := edmLogger
t.Cleanup(func() {
cfgFile = oldCfgFile
edmLogger = oldLogger
viper.Reset()
})

configFile := filepath.Join(t.TempDir(), "dnstapir-edm.toml")
if err := os.WriteFile(configFile, []byte(configData), 0o600); err != nil {
t.Fatalf("unable to write test config: %s", err)
}
cfgFile = configFile
edmLogger = slog.New(slog.NewTextHandler(io.Discard, nil))
}