ADR-006: auth posture for non-loopback deploy + token rotation impl

ADR-003 locked the auth substrate; ADR-006 ratifies the operator
playbook + adds two implementation pieces needed for Sprint 4
deployment: env-resolved tokens and dual-token rotation.

Six decisions locked in docs/DECISIONS.md:
- 6.1: Non-loopback bind requires auth.token (mechanical gate at
       shared.Run, already implemented; this ratifies it).
- 6.2: Token from env, not TOML. /etc/lakehouse/auth.env (mode 0600)
       loaded by systemd EnvironmentFile=. New TokenEnv field on
       AuthConfig defaults to "AUTH_TOKEN".
- 6.3: AllowedIPs for inter-service same-trust-domain; Token for
       cross-trust-boundary (gateway ↔ external).
- 6.4: /health stays unauthenticated; everything else under
       shared.Run is gated. Already implemented; ratified here.
- 6.5: Token rotation is dual-token. New SecondaryTokens []string
       on AuthConfig — both primary and any secondary pass auth
       during the rotation window. Implemented in this commit.
- 6.6: TLS terminates at the network edge (nginx/Caddy), not
       in-process. Daemons stay HTTP-only; internal traffic stays
       on private subnets per Decision 6.3.

Implementation:
- internal/shared/config.go: AuthConfig gains TokenEnv +
  SecondaryTokens fields. New resolveAuthFromEnv() called by
  LoadConfig fills Token from os.Getenv(TokenEnv) when Token is
  empty. TokenEnv defaults to "AUTH_TOKEN" so the happy path needs
  no TOML config.
- internal/shared/auth.go: RequireAuth pre-encodes Bearer headers
  for primary + every secondary token; per-request constant-time
  compare walks the slice. Fast path is 1 compare (primary).

Tests:
- TestLoadConfig_AuthTokenFromEnv (3 sub-tests): default env name,
  custom token_env, explicit Token wins over env.
- TestRequireAuth_SecondaryTokenAccepted: both primary + secondary
  tokens pass during rotation window.
- TestRequireAuth_SecondaryTokensOnly: only-secondary path works
  for the case where primary was just promoted-to-empty mid-rotation.

go test ./internal/shared all green; existing auth_test.go
unchanged (constant-time compare path preserved).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
root
2026-04-30 17:51:14 -05:00
co-authored by Claude Opus 4.7
parent 6c93a38093
commit 814197cfd3
6 changed files with 319 additions and 9 deletions
+23 -8
View File
@@ -30,7 +30,7 @@ import (
// RequireAuth returns a chi-compatible middleware that enforces
// the configured AuthConfig. Empty config returns a pass-through.
func RequireAuth(cfg AuthConfig) func(http.Handler) http.Handler {
tokenSet := cfg.Token != ""
tokenSet := cfg.Token != "" || len(cfg.SecondaryTokens) > 0
if !tokenSet && len(cfg.AllowedIPs) == 0 {
// G0 dev mode — no auth wired.
return passthrough
@@ -59,9 +59,20 @@ func RequireAuth(cfg AuthConfig) func(http.Handler) http.Handler {
allowedNets = append(allowedNets, n)
}
// Pre-encode the wire-format Bearer token so per-request
// comparison is one allocation against a precomputed slice.
expectedHeader := []byte("Bearer " + cfg.Token)
// Pre-encode wire-format Bearer headers for primary + every
// secondary token. Per-request comparison walks the slice with
// constant-time compare on each — fast path is the primary
// (first), so the typical case is one compare.
var expectedHeaders [][]byte
if cfg.Token != "" {
expectedHeaders = append(expectedHeaders, []byte("Bearer "+cfg.Token))
}
for _, sec := range cfg.SecondaryTokens {
if sec == "" {
continue
}
expectedHeaders = append(expectedHeaders, []byte("Bearer "+sec))
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -79,10 +90,14 @@ func RequireAuth(cfg AuthConfig) func(http.Handler) http.Handler {
if tokenSet {
got := []byte(r.Header.Get("Authorization"))
// ConstantTimeCompare returns 0 if lengths differ,
// 1 on match. Anything else (would be 0 or 1) is
// treated as no-match.
if subtle.ConstantTimeCompare(got, expectedHeader) != 1 {
matched := false
for _, want := range expectedHeaders {
if subtle.ConstantTimeCompare(got, want) == 1 {
matched = true
break
}
}
if !matched {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
+43
View File
@@ -189,6 +189,49 @@ func TestRequireAuth_InvalidCIDR_LoggedAndDropped(t *testing.T) {
}
}
// TestRequireAuth_SecondaryTokenAccepted locks ADR-006 Decision 6.5:
// during a token rotation, both primary and secondary token strings
// pass auth. After every caller updates, operators promote secondary
// → primary and clear secondary, completing the rotation.
func TestRequireAuth_SecondaryTokenAccepted(t *testing.T) {
cfg := AuthConfig{
Token: "primary-tok",
SecondaryTokens: []string{"secondary-tok"},
}
srv := httptest.NewServer(mountWithAuth(cfg))
defer srv.Close()
if status, _ := get(t, srv, "/data", "Bearer primary-tok"); status != http.StatusOK {
t.Errorf("primary token should pass, got %d", status)
}
if status, _ := get(t, srv, "/data", "Bearer secondary-tok"); status != http.StatusOK {
t.Errorf("secondary token should pass during rotation, got %d", status)
}
if status, _ := get(t, srv, "/data", "Bearer wrong-tok"); status != http.StatusUnauthorized {
t.Errorf("invalid token should still 401, got %d", status)
}
}
// TestRequireAuth_SecondaryTokensOnly locks the case where primary
// is empty but secondaries are set — useful mid-rotation when the
// previous primary was just promoted to nothing and the new primary
// hasn't been written yet. As long as ANY token is configured, auth
// is enforced.
func TestRequireAuth_SecondaryTokensOnly(t *testing.T) {
cfg := AuthConfig{
SecondaryTokens: []string{"only-tok"},
}
srv := httptest.NewServer(mountWithAuth(cfg))
defer srv.Close()
if status, _ := get(t, srv, "/data", "Bearer only-tok"); status != http.StatusOK {
t.Errorf("only-secondary should pass, got %d", status)
}
if status, _ := get(t, srv, "/data", ""); status != http.StatusUnauthorized {
t.Errorf("missing token should 401, got %d", status)
}
}
func TestRemoteIP_SplitHostPortShape(t *testing.T) {
// Sanity: real httptest requests come through with "ip:port"
// shape; ensure remoteIP returns the IP portion.
+31
View File
@@ -298,6 +298,17 @@ func (m ModelsConfig) IsWeak(model string) bool {
type AuthConfig struct {
Token string `toml:"token"`
AllowedIPs []string `toml:"allowed_ips"`
// TokenEnv names an environment variable; LoadConfig populates
// Token from os.Getenv(TokenEnv) when Token is empty. Per ADR-006
// 6.2: production deploys put the secret in /etc/lakehouse/auth.env
// (mode 0600) loaded by systemd EnvironmentFile=, NOT in the
// committed TOML. TokenEnv defaults to "AUTH_TOKEN".
TokenEnv string `toml:"token_env"`
// SecondaryTokens lets operators stage a rotation: both primary
// and any secondary token pass auth during the rotation window.
// After every caller updates, operators promote secondary →
// primary and clear secondary. Per ADR-006 Decision 6.5.
SecondaryTokens []string `toml:"secondary_tokens"`
}
// DefaultConfig returns the G0 dev defaults. Ports are shifted to
@@ -434,5 +445,25 @@ func LoadConfig(path string) (Config, error) {
if err := toml.Unmarshal(b, &cfg); err != nil {
return cfg, fmt.Errorf("parse config: %w", err)
}
resolveAuthFromEnv(&cfg.Auth)
return cfg, nil
}
// resolveAuthFromEnv populates cfg.Auth.Token from os.Getenv(TokenEnv)
// when Token is empty. Per ADR-006 Decision 6.2: production deploys
// keep the secret in /etc/lakehouse/auth.env (mode 0600), loaded by
// systemd EnvironmentFile=, never in the committed TOML.
//
// TokenEnv defaults to "AUTH_TOKEN" so operators don't have to
// configure both — setting AUTH_TOKEN env is enough.
func resolveAuthFromEnv(auth *AuthConfig) {
envName := auth.TokenEnv
if envName == "" {
envName = "AUTH_TOKEN"
}
if auth.Token == "" {
if v := os.Getenv(envName); v != "" {
auth.Token = v
}
}
}
+65
View File
@@ -188,6 +188,71 @@ weak_models = ["custom-judge:latest", "qwen3:latest"]
}
}
// TestLoadConfig_AuthTokenFromEnv locks ADR-006 Decision 6.2:
// production deploys put the secret in /etc/lakehouse/auth.env (mode
// 0600), loaded by systemd EnvironmentFile=, NEVER in the committed
// TOML. The TOML names the env var via token_env; the loader fills
// Token from os.Getenv. TokenEnv defaults to "AUTH_TOKEN" so the
// happy path needs no TOML config at all.
func TestLoadConfig_AuthTokenFromEnv(t *testing.T) {
t.Run("default env name AUTH_TOKEN", func(t *testing.T) {
t.Setenv("AUTH_TOKEN", "from-default-env")
dir := t.TempDir()
path := filepath.Join(dir, "lakehouse.toml")
if err := os.WriteFile(path, []byte(`[auth]
allowed_ips = []
`), 0o644); err != nil {
t.Fatal(err)
}
cfg, err := LoadConfig(path)
if err != nil {
t.Fatalf("LoadConfig: %v", err)
}
if cfg.Auth.Token != "from-default-env" {
t.Errorf("Token = %q, want from AUTH_TOKEN env", cfg.Auth.Token)
}
})
t.Run("custom env name from token_env", func(t *testing.T) {
t.Setenv("CUSTOM_AUTH_TOKEN", "from-custom-env")
dir := t.TempDir()
path := filepath.Join(dir, "lakehouse.toml")
if err := os.WriteFile(path, []byte(`[auth]
token_env = "CUSTOM_AUTH_TOKEN"
`), 0o644); err != nil {
t.Fatal(err)
}
cfg, err := LoadConfig(path)
if err != nil {
t.Fatalf("LoadConfig: %v", err)
}
if cfg.Auth.Token != "from-custom-env" {
t.Errorf("Token = %q, want from CUSTOM_AUTH_TOKEN env", cfg.Auth.Token)
}
})
t.Run("explicit token wins over env", func(t *testing.T) {
t.Setenv("AUTH_TOKEN", "from-env")
dir := t.TempDir()
path := filepath.Join(dir, "lakehouse.toml")
if err := os.WriteFile(path, []byte(`[auth]
token = "from-toml"
`), 0o644); err != nil {
t.Fatal(err)
}
cfg, err := LoadConfig(path)
if err != nil {
t.Fatalf("LoadConfig: %v", err)
}
// Explicit Token in TOML wins over env — the loader only
// fills from env when Token is empty. Lets local dev
// override prod env vars.
if cfg.Auth.Token != "from-toml" {
t.Errorf("Token = %q, want explicit TOML value", cfg.Auth.Token)
}
})
}
func TestLoadConfig_InvalidTOML_ReturnsError(t *testing.T) {
dir := t.TempDir()
cfgPath := filepath.Join(dir, "bad.toml")