refactor(config): mandatory app-config rows seeded in DB; rename to session.setup_timeout
All registry keys must exist as rows in the config table: main seeds missing keys with their defaults at startup, LoadApp fails fast on a missing key, and the code-side fallback const/helper for the onboarding setup timeout is gone -- the value rides in SessionConfig.SetupTimeout. The key is renamed session.idle_timeout -> session.setup_timeout, and the /config page's 'overridden' now means 'differs from the default'. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -25,11 +25,12 @@ import (
|
||||
func newCtx() context.Context { return context.Background() }
|
||||
|
||||
var testSessionConfig = SessionConfig{
|
||||
Secret: []byte("test-session-secret-at-least-32-bytes-long"),
|
||||
Duration: time.Hour,
|
||||
Secure: false,
|
||||
BackendURL: "https://geniusrun.example.com",
|
||||
FrontendURL: "https://app.geniusrun.example.com",
|
||||
Secret: []byte("test-session-secret-at-least-32-bytes-long"),
|
||||
Duration: time.Hour,
|
||||
SetupTimeout: 15 * time.Minute,
|
||||
Secure: false,
|
||||
BackendURL: "https://geniusrun.example.com",
|
||||
FrontendURL: "https://app.geniusrun.example.com",
|
||||
}
|
||||
|
||||
func newTestServer(t *testing.T) (*Server, *store.DB, int64) {
|
||||
|
||||
@@ -22,23 +22,27 @@ type configEntry struct {
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
// configView assembles the GET/PUT response: registry defaults overlaid
|
||||
// with DB overrides, plus the env snapshot.
|
||||
// configView assembles the GET/PUT response: every registry key with its
|
||||
// stored value (the DB is fully seeded with defaults at startup; the
|
||||
// registry default only fills in here for a key added since the last
|
||||
// boot, e.g. under httptest where main's seeding never ran), plus the env
|
||||
// snapshot. Overridden means "differs from the default", since every key
|
||||
// always has a row.
|
||||
func (s *Server) configView(r *http.Request) (map[string]any, error) {
|
||||
overrides, err := s.DB.ConfigValues(r.Context())
|
||||
values, err := s.DB.ConfigValues(r.Context())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
registry := config.AppRegistry()
|
||||
app := make([]configEntry, 0, len(registry))
|
||||
for _, k := range registry {
|
||||
value, overridden := overrides[k.Key]
|
||||
if !overridden {
|
||||
value, ok := values[k.Key]
|
||||
if !ok {
|
||||
value = k.Default
|
||||
}
|
||||
app = append(app, configEntry{
|
||||
Key: k.Key, Value: value, Default: k.Default,
|
||||
Overridden: overridden, Description: k.Description,
|
||||
Overridden: value != k.Default, Description: k.Description,
|
||||
})
|
||||
}
|
||||
envVars := s.EnvVars
|
||||
|
||||
@@ -55,8 +55,8 @@ func TestConfig_GetDefaultsAndEnvSnapshot(t *testing.T) {
|
||||
if e := byKey["session.duration"]; e.value != "720" || e.def != "720" || e.overridden {
|
||||
t.Fatalf("session.duration default entry = %+v", e)
|
||||
}
|
||||
if e := byKey["session.idle_timeout"]; e.value != "15" || e.def != "15" || e.overridden {
|
||||
t.Fatalf("session.idle_timeout default entry = %+v", e)
|
||||
if e := byKey["session.setup_timeout"]; e.value != "15" || e.def != "15" || e.overridden {
|
||||
t.Fatalf("session.setup_timeout default entry = %+v", e)
|
||||
}
|
||||
if len(resp.Environment) != 1 || resp.Environment[0].Value != "•••• (set)" {
|
||||
t.Fatalf("env snapshot not passed through: %+v", resp.Environment)
|
||||
|
||||
@@ -53,11 +53,6 @@ type Server struct {
|
||||
// never call os.Getenv.
|
||||
EnvVars []EnvVar
|
||||
|
||||
// SetupSessionIdleTimeout is the app-config session.idle_timeout value
|
||||
// (see internal/config); zero falls back to
|
||||
// defaultSetupSessionIdleTimeout.
|
||||
SetupSessionIdleTimeout time.Duration
|
||||
|
||||
mu sync.Mutex
|
||||
userClient map[int64]garmin.Client
|
||||
userSync map[int64]*garmin.Sync
|
||||
|
||||
@@ -15,7 +15,13 @@ import (
|
||||
type SessionConfig struct {
|
||||
Secret []byte
|
||||
Duration time.Duration
|
||||
Secure bool
|
||||
// SetupTimeout evicts an unfinished onboarding Garmin setup session
|
||||
// once idle this long (app-config key session.setup_timeout, minutes;
|
||||
// distinct from Duration, the login cookie lifetime). Mandatory --
|
||||
// there is no code fallback; the default lives in the DB, seeded at
|
||||
// startup.
|
||||
SetupTimeout time.Duration
|
||||
Secure bool
|
||||
// BackendURL is this app's own externally reachable origin (e.g.
|
||||
// "https://geniusrun.example.com", no trailing slash) -- derives
|
||||
// OIDCRedirectURL (config.Config), the only thing that must stay pointed
|
||||
|
||||
@@ -13,24 +13,6 @@ import (
|
||||
applog "geniusrun/backend/internal/log"
|
||||
)
|
||||
|
||||
// defaultSetupSessionIdleTimeout bounds how long an onboarding Garmin
|
||||
// session survives without being touched (login, MFA, or complete) before
|
||||
// it's evicted -- long enough to check email for an MFA code, short enough
|
||||
// that an abandoned attempt doesn't leave a subprocess running
|
||||
// indefinitely. Tunable via the session.idle_timeout application-config
|
||||
// key (minutes -- distinct from session.duration, the login cookie
|
||||
// lifetime); this constant is the fallback when the Server field was never
|
||||
// wired (tests building a bare NewServer).
|
||||
const defaultSetupSessionIdleTimeout = 15 * time.Minute
|
||||
|
||||
// setupIdleTimeout returns the configured onboarding-session idle timeout.
|
||||
func (s *Server) setupIdleTimeout() time.Duration {
|
||||
if s.SetupSessionIdleTimeout > 0 {
|
||||
return s.SetupSessionIdleTimeout
|
||||
}
|
||||
return defaultSetupSessionIdleTimeout
|
||||
}
|
||||
|
||||
// setupSession is a temporary, not-yet-persisted Garmin authentication
|
||||
// attempt made during onboarding, before any users/profile row exists --
|
||||
// keyed by OIDC subject (the only stable identifier available pre-account)
|
||||
@@ -42,7 +24,7 @@ func (s *Server) setupIdleTimeout() time.Duration {
|
||||
// the next time anything closes and restarts its subprocess; a later
|
||||
// garminFor(ctx, userID) call builds a fresh client with the correct path
|
||||
// instead. Otherwise evicted lazily (the next setup-endpoint touch for that
|
||||
// subject checks staleness first) once idle past setupIdleTimeout().
|
||||
// subject checks staleness first) once idle past SessionConfig.SetupTimeout.
|
||||
type setupSession struct {
|
||||
Client garmin.Client
|
||||
Email, Password string
|
||||
@@ -225,7 +207,7 @@ func (s *Server) setupSessionFor(sub string) (*setupSession, bool) {
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
if time.Since(sess.LastUsed) > s.setupIdleTimeout() {
|
||||
if time.Since(sess.LastUsed) > s.SessionConfig.SetupTimeout {
|
||||
sess.Client.Close()
|
||||
delete(s.setupSession, sub)
|
||||
if s.ClientConfig.TokenStorePath != "" {
|
||||
|
||||
@@ -19,13 +19,13 @@ type AppKey struct {
|
||||
// KeySessionDuration is the session cookie lifetime, in integer hours.
|
||||
const (
|
||||
KeySessionDuration = "session.duration"
|
||||
// KeySessionIdleTimeout bounds an *onboarding Garmin session* (the
|
||||
// ephemeral, pre-account login attempt), not the login cookie --
|
||||
// KeySessionSetupTimeout bounds an *onboarding Garmin setup session*
|
||||
// (the ephemeral, pre-account login attempt), not the login cookie --
|
||||
// session.duration is how long a signed-in user stays signed in
|
||||
// (hours); session.idle_timeout is how long an unfinished setup
|
||||
// (hours); session.setup_timeout is how long an unfinished setup
|
||||
// attempt survives untouched before its subprocess is torn down
|
||||
// (minutes).
|
||||
KeySessionIdleTimeout = "session.idle_timeout"
|
||||
KeySessionSetupTimeout = "session.setup_timeout"
|
||||
)
|
||||
|
||||
var appRegistry = []AppKey{
|
||||
@@ -36,9 +36,9 @@ var appRegistry = []AppKey{
|
||||
Validate: validatePositiveInt,
|
||||
},
|
||||
{
|
||||
Key: KeySessionIdleTimeout,
|
||||
Key: KeySessionSetupTimeout,
|
||||
Default: "15",
|
||||
Description: "Idle timeout in minutes for an unfinished onboarding Garmin session",
|
||||
Description: "Idle timeout in minutes for an unfinished onboarding Garmin setup session",
|
||||
Validate: validatePositiveInt,
|
||||
},
|
||||
}
|
||||
@@ -69,32 +69,35 @@ func ValidateAppValue(key, value string) error {
|
||||
return fmt.Errorf("unknown configuration key %q", key)
|
||||
}
|
||||
|
||||
// AppConfig is the typed result of merging DB overrides over registry
|
||||
// defaults.
|
||||
// AppConfig is the typed application configuration, built from the DB's
|
||||
// config rows.
|
||||
type AppConfig struct {
|
||||
SessionDuration time.Duration
|
||||
SetupSessionIdleTimeout time.Duration
|
||||
SessionDuration time.Duration
|
||||
SetupTimeout time.Duration
|
||||
}
|
||||
|
||||
// LoadApp merges overrides (store.ConfigValues' map) over defaults. Pure
|
||||
// -- it takes the raw map instead of a *store.DB so this package needs no
|
||||
// store dependency and the merge logic tests without a database. A bad
|
||||
// stored value fails fast, same posture as LoadEnv() for env vars.
|
||||
func LoadApp(overrides map[string]string) (AppConfig, error) {
|
||||
merged := map[string]string{}
|
||||
for _, k := range appRegistry {
|
||||
merged[k.Key] = k.Default
|
||||
}
|
||||
for key, value := range overrides {
|
||||
// LoadApp builds the typed AppConfig from the config table's rows. Every
|
||||
// registry key is mandatory: main seeds missing keys with their defaults
|
||||
// at startup (see cmd/geniusrund), so a missing key here means that
|
||||
// seeding didn't run -- fail fast, same posture as LoadEnv() for env
|
||||
// vars, and likewise for an unknown or invalid stored value. Pure -- it
|
||||
// takes the raw map instead of a *store.DB so this package needs no store
|
||||
// dependency and the logic tests without a database.
|
||||
func LoadApp(values map[string]string) (AppConfig, error) {
|
||||
for key, value := range values {
|
||||
if err := ValidateAppValue(key, value); err != nil {
|
||||
return AppConfig{}, fmt.Errorf("app config: %w", err)
|
||||
}
|
||||
merged[key] = value
|
||||
}
|
||||
hours, _ := strconv.Atoi(merged[KeySessionDuration])
|
||||
idleMinutes, _ := strconv.Atoi(merged[KeySessionIdleTimeout])
|
||||
for _, k := range appRegistry {
|
||||
if _, ok := values[k.Key]; !ok {
|
||||
return AppConfig{}, fmt.Errorf("app config: missing key %q (defaults are seeded into the DB at startup)", k.Key)
|
||||
}
|
||||
}
|
||||
hours, _ := strconv.Atoi(values[KeySessionDuration])
|
||||
setupMinutes, _ := strconv.Atoi(values[KeySessionSetupTimeout])
|
||||
return AppConfig{
|
||||
SessionDuration: time.Duration(hours) * time.Hour,
|
||||
SetupSessionIdleTimeout: time.Duration(idleMinutes) * time.Minute,
|
||||
SessionDuration: time.Duration(hours) * time.Hour,
|
||||
SetupTimeout: time.Duration(setupMinutes) * time.Minute,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -8,22 +8,25 @@ import (
|
||||
|
||||
func TestLoadApp(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
overrides map[string]string
|
||||
want time.Duration
|
||||
wantIdle time.Duration
|
||||
wantErr string
|
||||
name string
|
||||
values map[string]string
|
||||
want time.Duration
|
||||
wantIdle time.Duration
|
||||
wantErr string
|
||||
}{
|
||||
{name: "defaults when no overrides", overrides: nil, want: 720 * time.Hour, wantIdle: 15 * time.Minute},
|
||||
{name: "override applied", overrides: map[string]string{"session.duration": "168"}, want: 168 * time.Hour, wantIdle: 15 * time.Minute},
|
||||
{name: "idle timeout override applied", overrides: map[string]string{"session.idle_timeout": "30"}, want: 720 * time.Hour, wantIdle: 30 * time.Minute},
|
||||
{name: "invalid stored value", overrides: map[string]string{"session.duration": "zero"}, wantErr: "session.duration"},
|
||||
{name: "invalid idle timeout", overrides: map[string]string{"session.idle_timeout": "0"}, wantErr: "session.idle_timeout"},
|
||||
{name: "unknown stored key", overrides: map[string]string{"bogus.key": "1"}, wantErr: "unknown configuration key"},
|
||||
// Every registry key is mandatory: main seeds the DB with defaults
|
||||
// at startup, so LoadApp always receives a complete map.
|
||||
{name: "seeded defaults", values: map[string]string{"session.duration": "720", "session.setup_timeout": "15"}, want: 720 * time.Hour, wantIdle: 15 * time.Minute},
|
||||
{name: "custom values", values: map[string]string{"session.duration": "168", "session.setup_timeout": "30"}, want: 168 * time.Hour, wantIdle: 30 * time.Minute},
|
||||
{name: "missing key fails fast", values: map[string]string{"session.duration": "720"}, wantErr: "missing key"},
|
||||
{name: "nil map fails fast", values: nil, wantErr: "missing key"},
|
||||
{name: "invalid stored value", values: map[string]string{"session.duration": "zero", "session.setup_timeout": "15"}, wantErr: "session.duration"},
|
||||
{name: "invalid setup timeout", values: map[string]string{"session.duration": "720", "session.setup_timeout": "0"}, wantErr: "session.setup_timeout"},
|
||||
{name: "unknown stored key", values: map[string]string{"session.duration": "720", "session.setup_timeout": "15", "bogus.key": "1"}, wantErr: "unknown configuration key"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := LoadApp(tt.overrides)
|
||||
got, err := LoadApp(tt.values)
|
||||
if tt.wantErr != "" {
|
||||
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Fatalf("err = %v, want containing %q", err, tt.wantErr)
|
||||
@@ -36,8 +39,8 @@ func TestLoadApp(t *testing.T) {
|
||||
if got.SessionDuration != tt.want {
|
||||
t.Fatalf("SessionDuration = %v, want %v", got.SessionDuration, tt.want)
|
||||
}
|
||||
if got.SetupSessionIdleTimeout != tt.wantIdle {
|
||||
t.Fatalf("SetupSessionIdleTimeout = %v, want %v", got.SetupSessionIdleTimeout, tt.wantIdle)
|
||||
if got.SetupTimeout != tt.wantIdle {
|
||||
t.Fatalf("SetupSessionIdleTimeout = %v, want %v", got.SetupTimeout, tt.wantIdle)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -5,9 +5,10 @@ import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// ConfigValues returns every application-configuration override row as
|
||||
// key -> value. An absent key means its default (from internal/config's
|
||||
// app-key registry) is in effect -- the table stores overrides only.
|
||||
// ConfigValues returns every application-configuration row as key ->
|
||||
// value. The table holds a row for every registry key: main seeds missing
|
||||
// keys with their defaults at startup, so downstream code never needs a
|
||||
// code-side fallback.
|
||||
func (db *DB) ConfigValues(ctx context.Context) (map[string]string, error) {
|
||||
rows, err := db.QueryContext(ctx, `SELECT key, value FROM config`)
|
||||
if err != nil {
|
||||
|
||||
@@ -252,11 +252,13 @@ CREATE TABLE sync_runs (
|
||||
error_message TEXT
|
||||
);
|
||||
|
||||
-- Application configuration: instance-global key/value overrides, shared
|
||||
-- Application configuration: instance-global key/value settings, shared
|
||||
-- by every user -- deliberately the one table with no user_id, because
|
||||
-- application configuration is common to all users by definition. Stores
|
||||
-- overrides only; defaults live in internal/config's app-key registry.
|
||||
-- Cold: read once at startup, a change applies on the next backend restart.
|
||||
-- application configuration is common to all users by definition. Every
|
||||
-- key in internal/config's app-key registry is mandatory here: missing
|
||||
-- rows are seeded with their defaults at startup (cmd/geniusrund), so
|
||||
-- there are no code-side fallbacks. Cold: read once at startup, a change
|
||||
-- applies on the next backend restart.
|
||||
CREATE TABLE config (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL,
|
||||
|
||||
Reference in New Issue
Block a user