From a220cce77eb81ce57f34e4ed83e723575953c272 Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Wed, 9 Sep 2026 21:57:51 +0200 Subject: [PATCH] f-46: config: fail loudly on an unreadable config file #46 Signed-off-by: GnomeZworc --- internal/config/agent/dhcp_test.go | 26 ++++++++++++++++++++++++++ internal/config/agent/struct.go | 8 +++++++- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/internal/config/agent/dhcp_test.go b/internal/config/agent/dhcp_test.go index 6796e56..50fed1c 100644 --- a/internal/config/agent/dhcp_test.go +++ b/internal/config/agent/dhcp_test.go @@ -54,3 +54,29 @@ func TestLoadConfig_ReadsTheTwoBackend(t *testing.T) { t.Errorf("backend = %q, want two", cfg.DHCP.Backend) } } + +func TestLoadConfig_MalformedFileIsReported(t *testing.T) { + path := writeConfig(t, "--\n\ndhcp:\n backend: two\n") + + if _, err := LoadConfig(path); err == nil { + t.Fatal("an unparseable config must be reported: silently falling back to defaults would run the wrong dhcp backend") + } +} + +func TestLoadConfig_TabIndentedFileIsReported(t *testing.T) { + path := writeConfig(t, "dhcp:\n\tbackend: two\n") + + if _, err := LoadConfig(path); err == nil { + t.Fatal("yaml forbids tabs for indentation: that must surface, not be swallowed") + } +} + +func TestLoadConfig_MissingFileStillFallsBackToDefaults(t *testing.T) { + cfg, err := LoadConfig(filepath.Join(t.TempDir(), "absent.yml")) + if err != nil { + t.Fatalf("an absent file remains valid, only an unreadable one is an error: %v", err) + } + if cfg.DHCP.Backend != BackendDnsmasq { + t.Errorf("backend = %q, want %q", cfg.DHCP.Backend, BackendDnsmasq) + } +} diff --git a/internal/config/agent/struct.go b/internal/config/agent/struct.go index d4afea1..0f84a09 100644 --- a/internal/config/agent/struct.go +++ b/internal/config/agent/struct.go @@ -1,6 +1,10 @@ package configuration import ( + "errors" + "fmt" + "os" + "github.com/spf13/viper" ) @@ -86,7 +90,9 @@ func LoadConfig(path string) (*Config, error) { v.SetDefault("logger.level", "info") v.SetDefault("logger.debug", false) - v.ReadInConfig() + if err := v.ReadInConfig(); err != nil && !errors.Is(err, os.ErrNotExist) { + return nil, fmt.Errorf("read %s: %w", path, err) + } var cfg Config if err := v.Unmarshal(&cfg); err != nil {