~bigbes/lethe

ref: e048bdf74cd7459076a067ae22038a83e4627b6a lethe/internal/config/config.go -rw-r--r-- 8.6 KiB
e048bdf7 — Eugene Blikh web: stats route with backend-driven chart primitives a month ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
// Package config loads and validates the lethe server configuration from a
// YAML file plus LETHE_* environment overrides.
//
// The Config struct is split into substructs (Server, Database, Auth, Logging,
// Ingest); each substruct is tagged with `config-section:""` so that steward
// (Phase 4+) can inject them by type into individual services.
//
// Validation runs in fail-fast mode: any unknown YAML key, missing required
// field, or out-of-range value rejects the load with a culpa-wrapped error
// carrying a machine-readable code (CONFIG_NOT_FOUND, CONFIG_PARSE,
// CONFIG_VALIDATE). There are no silent fallbacks: the only defaults applied
// are the ones explicitly listed in registerDefaults.
package config

import (
	"errors"
	"io/fs"
	"os"
	"regexp"
	"strings"
	"time"

	"github.com/go-playground/validator/v10"
	"github.com/go-viper/mapstructure/v2"
	"github.com/spf13/viper"
	"go.bigb.es/auxilia/culpa"
)

// Config is the root configuration object. Each substruct is exposed to
// steward as a config section via the `config-section:""` tag.
type Config struct {
	Server   ServerConfig   `mapstructure:"server"   config-section:""`
	Database DatabaseConfig `mapstructure:"database" config-section:""`
	Auth     AuthConfig     `mapstructure:"auth"     config-section:""`
	Logging  LoggingConfig  `mapstructure:"logging"  config-section:""`
	Ingest   IngestConfig   `mapstructure:"ingest"   config-section:""`
}

// ServerConfig controls the HTTP listener.
type ServerConfig struct {
	Bind          string        `mapstructure:"bind"           validate:"required,loopback_bind"`
	ShutdownGrace time.Duration `mapstructure:"shutdown_grace" validate:"gt=0"`
}

// DatabaseConfig points at the SQLite file and tunes its busy timeout.
type DatabaseConfig struct {
	Path        string        `mapstructure:"path"         validate:"required"`
	BusyTimeout time.Duration `mapstructure:"busy_timeout" validate:"gt=0"`
}

// AuthConfig is the authentication policy. At least one of ForwardAuth or
// OIDC must be enabled (enforced by the auth_at_least_one struct-level
// validator) and Admins must be a subset of AllowedUsers (enforced by
// admins_subset_of_allowed).
type AuthConfig struct {
	AllowedUsers []string          `mapstructure:"allowed_users" validate:"min=1,dive,required"`
	Admins       []string          `mapstructure:"admins"        validate:"dive,required"`
	ForwardAuth  ForwardAuthConfig `mapstructure:"forward_auth"`
	OIDC         OIDCConfig        `mapstructure:"oidc"`
}

// ForwardAuthConfig consumes a trusted reverse-proxy header.
type ForwardAuthConfig struct {
	Enabled    bool   `mapstructure:"enabled"`
	UserHeader string `mapstructure:"user_header"`
}

// OIDCConfig validates bearer tokens against an OIDC issuer.
type OIDCConfig struct {
	Enabled       bool   `mapstructure:"enabled"`
	Issuer        string `mapstructure:"issuer"         validate:"required_if=Enabled true,omitempty,url"`
	Audience      string `mapstructure:"audience"       validate:"required_if=Enabled true"`
	UsernameClaim string `mapstructure:"username_claim"`
}

// LoggingConfig selects log level and formatter.
type LoggingConfig struct {
	Level  string `mapstructure:"level"  validate:"required,oneof=debug info warn error"`
	Format string `mapstructure:"format" validate:"required,oneof=tint json"`
}

// IngestConfig caps payload sizes and chunking on the ingest path.
type IngestConfig struct {
	MaxBodyBytes        int64 `mapstructure:"max_body_bytes"         validate:"gt=0"`
	MaxTurnContentBytes int64 `mapstructure:"max_turn_content_bytes" validate:"gt=0,ltefield=MaxBodyBytes"`
	ChunkSize           int   `mapstructure:"chunk_size"             validate:"gt=0"`
}

// loopbackBindRe matches `127.0.0.1` or `127.0.0.1:<port>` (1-5 digits).
// Other interfaces are rejected so the listener never binds publicly.
var loopbackBindRe = regexp.MustCompile(`^127\.0\.0\.1(?::\d{1,5})?$`)

// Load reads YAML from path, applies env overrides, fills documented
// defaults, and validates. Errors carry a culpa code.
func Load(path string) (*Config, error) {
	v := viper.New()
	v.SetConfigFile(path)
	v.SetEnvPrefix("LETHE")
	v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
	v.AutomaticEnv()

	registerDefaults(v)

	if err := v.ReadInConfig(); err != nil {
		// viper returns *fs.PathError for missing files; treat any read
		// failure as CONFIG_NOT_FOUND vs CONFIG_PARSE based on type.
		if _, ok := err.(viper.ConfigFileNotFoundError); ok {
			return nil, culpa.WithCode(culpa.Wrap(err, "config file not found"), "CONFIG_NOT_FOUND")
		}
		// Distinguish "missing file" (os PathError) from a parse failure.
		if isFileMissing(err) {
			return nil, culpa.WithCode(culpa.Wrap(err, "config file not found"), "CONFIG_NOT_FOUND")
		}
		return nil, culpa.WithCode(culpa.Wrap(err, "parse config"), "CONFIG_PARSE")
	}

	// Stitch comma-separated env overrides for slice fields. viper does
	// not split string env values into []string by itself, so we do it
	// here for the known slice fields under auth.
	splitCSVEnv(v, "auth.allowed_users", "LETHE_AUTH_ALLOWED_USERS")
	splitCSVEnv(v, "auth.admins", "LETHE_AUTH_ADMINS")

	var cfg Config
	if err := v.UnmarshalExact(
		&cfg,
		viper.DecodeHook(mapstructure.ComposeDecodeHookFunc(
			mapstructure.StringToTimeDurationHookFunc(),
			mapstructure.StringToSliceHookFunc(","),
		)),
		func(c *mapstructure.DecoderConfig) {
			c.ErrorUnused = true
		},
	); err != nil {
		return nil, culpa.WithCode(culpa.Wrap(err, "decode config"), "CONFIG_PARSE")
	}

	val := newValidator()
	if err := val.Struct(&cfg); err != nil {
		return nil, culpa.WithCode(culpa.Wrap(err, "validate config"), "CONFIG_VALIDATE")
	}
	return &cfg, nil
}

// MustLoad calls Load and panics on error. Used by main.go where a bad
// config means the process cannot start anyway.
func MustLoad(path string) *Config {
	cfg, err := Load(path)
	if err != nil {
		panic(err)
	}
	return cfg
}

// registerDefaults sets the documented defaults. Notably, neither
// auth.forward_auth.enabled nor auth.oidc.enabled has a default — the
// operator must explicitly enable at least one mode.
func registerDefaults(v *viper.Viper) {
	v.SetDefault("server.shutdown_grace", 10*time.Second)
	v.SetDefault("database.busy_timeout", 5*time.Second)
	v.SetDefault("auth.forward_auth.user_header", "Remote-User")
	v.SetDefault("auth.oidc.username_claim", "preferred_username")
	v.SetDefault("ingest.max_body_bytes", int64(16*1024*1024))
	v.SetDefault("ingest.max_turn_content_bytes", int64(4*1024*1024))
	v.SetDefault("ingest.chunk_size", 500)
}

// splitCSVEnv converts a comma-separated environment variable into a
// []string and stores it on viper under key. We cannot rely on viper's
// AutomaticEnv to do this for slice destinations because the env value
// arrives as a single string after viper resolves it.
func splitCSVEnv(v *viper.Viper, key, envName string) {
	raw, ok := os.LookupEnv(envName)
	if !ok {
		return
	}
	parts := strings.Split(raw, ",")
	out := make([]string, 0, len(parts))
	for _, p := range parts {
		p = strings.TrimSpace(p)
		if p == "" {
			continue
		}
		out = append(out, p)
	}
	v.Set(key, out)
}

// newValidator builds a *validator.Validate with our custom rules
// registered.
func newValidator() *validator.Validate {
	val := validator.New(validator.WithRequiredStructEnabled())
	// "loopback_bind" is a field-level rule so it can be expressed via the
	// validate tag on ServerConfig.Bind alongside required.
	_ = val.RegisterValidation("loopback_bind", func(fl validator.FieldLevel) bool {
		return loopbackBindRe.MatchString(fl.Field().String())
	})
	val.RegisterStructValidation(authStructValidator, AuthConfig{})
	return val
}

// authStructValidator enforces both auth_at_least_one and
// admins_subset_of_allowed. Struct-level is the right level: both rules
// straddle multiple fields of AuthConfig.
func authStructValidator(sl validator.StructLevel) {
	auth, ok := sl.Current().Interface().(AuthConfig)
	if !ok {
		return
	}
	if !auth.ForwardAuth.Enabled && !auth.OIDC.Enabled {
		sl.ReportError(auth.ForwardAuth.Enabled, "ForwardAuth.Enabled", "forward_auth.enabled", "auth_at_least_one", "")
	}
	allowed := make(map[string]struct{}, len(auth.AllowedUsers))
	for _, u := range auth.AllowedUsers {
		allowed[u] = struct{}{}
	}
	for _, admin := range auth.Admins {
		if _, found := allowed[admin]; !found {
			sl.ReportError(auth.Admins, "Admins", "admins", "admins_subset_of_allowed", "")
			return
		}
	}
}

// isFileMissing reports whether err describes a missing-file condition
// from viper.ReadInConfig. viper wraps the underlying os error.
func isFileMissing(err error) bool {
	var pe *fs.PathError
	if errors.As(err, &pe) {
		return errors.Is(pe.Err, fs.ErrNotExist)
	}
	return errors.Is(err, fs.ErrNotExist)
}