Skip to content
Merged
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
5 changes: 4 additions & 1 deletion cmd/stickd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,10 @@ func mainContext(parent context.Context, args []string) (err error) {
return fmt.Errorf("unexpected positional arguments: %v", flags.Args())
}

cfg, err := config.Load(*configPath)
cfg, err := config.Load(parent,
config.YAMLProvider{Path: *configPath},
config.EnvironmentProvider{},
)
if err != nil {
return fmt.Errorf("config: %w", err)
}
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ require (
go.opentelemetry.io/otel v1.44.0 // indirect
go.opentelemetry.io/otel/metric v1.44.0 // indirect
go.opentelemetry.io/otel/trace v1.44.0 // indirect
golang.org/x/crypto v0.55.0 // indirect
golang.org/x/crypto v0.56.0 // indirect
golang.org/x/sync v0.22.0 // indirect
golang.org/x/sys v0.47.0 // indirect
golang.org/x/text v0.41.0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,8 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
golang.org/x/crypto v0.56.0 h1:GUh5Ii4J5jtcseSMiRqr1jXCNHoxjeV9Fmekc2oLy6Y=
golang.org/x/crypto v0.56.0/go.mod h1:OMW5y6CY9l38uPLmxU6l6pwcXp1obtLo3e6gT7gQR2I=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
Expand Down
57 changes: 3 additions & 54 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,64 +65,13 @@ type NotificationsConfig struct {
Teams []*TeamsConfig
}

// Config is the normalized application configuration.
// Config is the normalized application configuration returned by Load.
// Providers populate a Config value before Load applies final defaults and
// validation.
type Config struct {
Server ServerConfig
Database DatabaseConfig
Auth AuthConfig
Timezone *time.Location
Notifications NotificationsConfig
}

// rawConfig and its nested types are the YAML representation. Keeping these
// separate from Config prevents unvalidated source values from escaping the
// configuration boundary.
type rawConfig struct {
Server rawServerConfig `yaml:"server"`
Database string `yaml:"database"`
Auth rawAuthConfig `yaml:"auth"`
Timezone string `yaml:"timezone"`
Notifications rawNotificationsConfig `yaml:"notifications"`
}

type rawServerConfig struct {
PublicURL string `yaml:"public_url"`
ListenAddr string `yaml:"listen_addr"`
}

type rawAuthConfig struct {
OIDC rawOIDCConfig `yaml:"oidc"`
SessionSecret string `yaml:"session_secret"`
AdminEmails []string `yaml:"admin_emails"`
}

type rawOIDCConfig struct {
Issuer string `yaml:"issuer"`
ClientID string `yaml:"client_id"`
ClientSecret string `yaml:"client_secret"`
}

type rawNotificationsConfig struct {
SMTP rawSMTPConfigs `yaml:"smtp"`
Webhook rawWebhookConfigs `yaml:"webhook"`
Teams rawTeamsConfigs `yaml:"teams"`
}

type rawSMTPConfig struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
TLSMode string `yaml:"tls_mode"`
Username string `yaml:"username"`
Password string `yaml:"password"`
From string `yaml:"from"`
Subject string `yaml:"subject"`
Body string `yaml:"body"`
}

type rawWebhookConfig struct {
URL string `yaml:"url"`
}

type rawTeamsConfig struct {
URL string `yaml:"url"`
}
65 changes: 53 additions & 12 deletions internal/config/config_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package config_test

import (
"context"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -63,7 +64,7 @@ func loadFromEnv(t *testing.T) config.Config {
t.Fatal(err)
}
t.Cleanup(func() { _ = os.Chdir(original) })
cfg, err := config.Load("")
cfg, err := config.Load(context.Background(), config.YAMLProvider{}, config.EnvironmentProvider{})
if err != nil {
t.Fatal(err)
}
Expand Down Expand Up @@ -145,7 +146,7 @@ auth:
timezone: America/New_York
`)

cfg, err := config.Load(path)
cfg, err := config.Load(context.Background(), config.YAMLProvider{Path: path}, config.EnvironmentProvider{})
if err != nil {
t.Fatalf("Load: %v", err)
}
Expand Down Expand Up @@ -181,7 +182,7 @@ auth:
t.Setenv("STICK_SERVER_PUBLIC_URL", "https://env.example.com/stick/")
t.Setenv("STICK_AUTH_ADMIN_EMAILS", " Alice@Example.com, bob@example.com ")

cfg, err := config.Load(path)
cfg, err := config.Load(context.Background(), config.YAMLProvider{Path: path}, config.EnvironmentProvider{})
if err != nil {
t.Fatalf("Load: %v", err)
}
Expand All @@ -196,6 +197,42 @@ auth:
}
}

func TestLoad_ProvidersApplyInSuppliedOrder(t *testing.T) {
setRequiredEnv(t)
t.Setenv("STICK_SERVER_LISTEN_ADDR", ":7070")
path := writeConfig(t, `
server:
listen_addr: :9090
`)

cfg, err := config.Load(
context.Background(),
config.YAMLProvider{Path: path},
config.EnvironmentProvider{},
)
if err != nil {
t.Fatalf("Load with YAML then environment: %v", err)
}
if cfg.Server.ListenAddr != ":7070" {
t.Errorf("ListenAddr = %q, want environment value", cfg.Server.ListenAddr)
}

cfg, err = config.Load(
context.Background(),
config.EnvironmentProvider{},
config.YAMLProvider{Path: path},
)
if err != nil {
t.Fatalf("Load with environment then YAML: %v", err)
}
if cfg.Server.ListenAddr != ":9090" {
t.Errorf("ListenAddr = %q, want YAML value", cfg.Server.ListenAddr)
}
if cfg.Database.DSN != "/tmp/test.db" {
t.Errorf("Database.DSN = %q, want value preserved from environment", cfg.Database.DSN)
}
}

func TestLoad_NotificationConfig(t *testing.T) {
clearConfigEnv(t)
path := writeConfig(t, `
Expand All @@ -219,7 +256,7 @@ notifications:
subject: "{{.StickName}} ready"
body: "Hello {{.RecipientName}}"
`)
cfg, err := config.Load(path)
cfg, err := config.Load(context.Background(), config.YAMLProvider{Path: path}, config.EnvironmentProvider{})
if err != nil {
t.Fatalf("Load: %v", err)
}
Expand Down Expand Up @@ -262,7 +299,7 @@ notifications:
teams:
url: https://teams.example.com/webhook
`)
cfg, err := config.Load(path)
cfg, err := config.Load(context.Background(), config.YAMLProvider{Path: path}, config.EnvironmentProvider{})
if err != nil {
t.Fatalf("Load: %v", err)
}
Expand All @@ -289,15 +326,15 @@ auth:
session_secret: yaml-session-secret-that-is-long-enough
timezone: Not/ATimezone
`)
if _, err := config.Load(path); err == nil || !strings.Contains(err.Error(), "timezone") {
if _, err := config.Load(context.Background(), config.YAMLProvider{Path: path}, config.EnvironmentProvider{}); err == nil || !strings.Contains(err.Error(), "timezone") {
t.Fatalf("Load error = %v", err)
}
}

func TestLoad_RejectsShortSessionSecret(t *testing.T) {
setRequiredEnv(t)
t.Setenv("STICK_AUTH_SESSION_SECRET", "too-short")
if _, err := config.Load(""); err == nil || !strings.Contains(err.Error(), "SESSION_SECRET") {
if _, err := config.Load(context.Background(), config.YAMLProvider{}, config.EnvironmentProvider{}); err == nil || !strings.Contains(err.Error(), "auth.session_secret") {
t.Fatalf("Load error = %v", err)
}
}
Expand All @@ -316,7 +353,7 @@ auth:
session_secret: 0123456789abcdef0123456789abcdef
unknown_setting: true
`)
if _, err := config.Load(path); err == nil || !strings.Contains(err.Error(), "field unknown_setting not found") {
if _, err := config.Load(context.Background(), config.YAMLProvider{Path: path}, config.EnvironmentProvider{}); err == nil || !strings.Contains(err.Error(), "field unknown_setting not found") {
t.Fatalf("unknown YAML field error = %v", err)
}
}
Expand All @@ -335,24 +372,28 @@ func TestLoad_RejectsInvalidURLs(t *testing.T) {
t.Run(test.name, func(t *testing.T) {
setRequiredEnv(t)
t.Setenv(test.key, test.value)
if _, err := config.Load(""); err == nil {
if _, err := config.Load(context.Background(), config.YAMLProvider{}, config.EnvironmentProvider{}); err == nil {
t.Fatal("expected invalid URL to be rejected")
}
})
}
}

func TestLoad_ExplicitPathNotFound(t *testing.T) {
if _, err := config.Load("/nonexistent/path/config.yaml"); err == nil {
if _, err := config.Load(context.Background(), config.YAMLProvider{Path: "/nonexistent/path/config.yaml"}, config.EnvironmentProvider{}); err == nil {
t.Fatal("expected error for explicit missing config")
}
}

func TestLoad_MissingRequired(t *testing.T) {
clearConfigEnv(t)
if _, err := loadFromEnvWithoutRequired(t); err == nil || !strings.Contains(err.Error(), "missing required config") {
_, err := loadFromEnvWithoutRequired(t)
if err == nil || !strings.Contains(err.Error(), "missing required config") {
t.Fatalf("Load error = %v", err)
}
if strings.Contains(err.Error(), "STICK_") {
t.Fatalf("Load error exposes provider-specific names: %v", err)
}
}

func loadFromEnvWithoutRequired(t *testing.T) (config.Config, error) {
Expand All @@ -366,5 +407,5 @@ func loadFromEnvWithoutRequired(t *testing.T) (config.Config, error) {
t.Fatal(err)
}
t.Cleanup(func() { _ = os.Chdir(original) })
return config.Load("")
return config.Load(context.Background(), config.YAMLProvider{}, config.EnvironmentProvider{})
}
129 changes: 129 additions & 0 deletions internal/config/environment_provider.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
package config

import (
"context"
"fmt"
"os"
"strconv"
"strings"
)

// EnvironmentProvider applies non-empty STICK_* environment variable
// overrides to the accumulated configuration.
type EnvironmentProvider struct{}

// Apply applies environment variable overrides.
func (EnvironmentProvider) Apply(_ context.Context, config *Config) error {
if value := os.Getenv("STICK_DATABASE"); value != "" {
if err := setDatabase(config, value); err != nil {
return err
}
}
if value := os.Getenv("STICK_SERVER_PUBLIC_URL"); value != "" {
if err := setPublicURL(config, value); err != nil {
return err
}
}
if value := os.Getenv("STICK_SERVER_LISTEN_ADDR"); value != "" {
config.Server.ListenAddr = strings.TrimSpace(value)
}
if value := os.Getenv("STICK_TIMEZONE"); value != "" {
if err := setTimezone(config, value); err != nil {
return err
}
}
if value := os.Getenv("STICK_AUTH_OIDC_ISSUER"); value != "" {
config.Auth.OIDC.Issuer = value
}
if value := os.Getenv("STICK_AUTH_OIDC_CLIENT_ID"); value != "" {
config.Auth.OIDC.ClientID = value
}
if value := os.Getenv("STICK_AUTH_OIDC_CLIENT_SECRET"); value != "" {
config.Auth.OIDC.ClientSecret = value
}
if value := os.Getenv("STICK_AUTH_SESSION_SECRET"); value != "" {
setSessionSecret(config, value)
}
if value := os.Getenv("STICK_AUTH_ADMIN_EMAILS"); value != "" {
config.Auth.AdminEmails = strings.Split(value, ",")
}

if err := applySMTPEnvOverrides(config); err != nil {
return err
}
if value := os.Getenv("STICK_NOTIFICATIONS_WEBHOOK_URL"); value != "" {
if len(config.Notifications.Webhook) == 0 {
config.Notifications.Webhook = append(config.Notifications.Webhook, &WebhookConfig{})
}
if config.Notifications.Webhook[0] == nil {
config.Notifications.Webhook[0] = &WebhookConfig{}
}
config.Notifications.Webhook[0].URL = strings.TrimSpace(value)
}
if value := os.Getenv("STICK_NOTIFICATIONS_TEAMS_URL"); value != "" {
if len(config.Notifications.Teams) == 0 {
config.Notifications.Teams = append(config.Notifications.Teams, &TeamsConfig{})
}
if config.Notifications.Teams[0] == nil {
config.Notifications.Teams[0] = &TeamsConfig{}
}
config.Notifications.Teams[0].URL = strings.TrimSpace(value)
}
return nil
}

func applySMTPEnvOverrides(config *Config) error {
keys := []string{
"STICK_NOTIFICATIONS_SMTP_HOST",
"STICK_NOTIFICATIONS_SMTP_PORT",
"STICK_NOTIFICATIONS_SMTP_TLS_MODE",
"STICK_NOTIFICATIONS_SMTP_USERNAME",
"STICK_NOTIFICATIONS_SMTP_PASSWORD",
"STICK_NOTIFICATIONS_SMTP_FROM",
"STICK_NOTIFICATIONS_SMTP_SUBJECT",
"STICK_NOTIFICATIONS_SMTP_BODY",
}
configured := false
for _, key := range keys {
if os.Getenv(key) != "" {
configured = true
break
}
}
if !configured {
return nil
}

var smtp SMTPConfig
if len(config.Notifications.SMTP) == 0 {
config.Notifications.SMTP = append(config.Notifications.SMTP, &smtp)
} else if config.Notifications.SMTP[0] != nil {
smtp = *config.Notifications.SMTP[0]
} else {
config.Notifications.SMTP[0] = &smtp
}

set := func(key string, dst *string, normalize func(string) string) {
if value := os.Getenv(key); value != "" {
*dst = normalize(value)
}
}
set("STICK_NOTIFICATIONS_SMTP_HOST", &smtp.Host, strings.TrimSpace)
set("STICK_NOTIFICATIONS_SMTP_TLS_MODE", &smtp.TLSMode, func(value string) string {
return strings.ToLower(strings.TrimSpace(value))
})
set("STICK_NOTIFICATIONS_SMTP_USERNAME", &smtp.Username, func(value string) string { return value })
set("STICK_NOTIFICATIONS_SMTP_PASSWORD", &smtp.Password, func(value string) string { return value })
set("STICK_NOTIFICATIONS_SMTP_FROM", &smtp.From, strings.TrimSpace)
set("STICK_NOTIFICATIONS_SMTP_SUBJECT", &smtp.Subject, func(value string) string { return value })
set("STICK_NOTIFICATIONS_SMTP_BODY", &smtp.Body, func(value string) string { return value })
if value := os.Getenv("STICK_NOTIFICATIONS_SMTP_PORT"); value != "" {
port, err := strconv.Atoi(value)
if err != nil {
return fmt.Errorf("invalid STICK_NOTIFICATIONS_SMTP_PORT: %w", err)
}
smtp.Port = port
}
config.Notifications.SMTP[0] = &smtp
return nil
}
Loading