harden(oidc): pre-login UA/IP binding (MED-16) — RFC 9700 §4.7.1

Audit 2026-05-10 MED-16 closure.

WHAT.

Binds the OIDC pre-login row to the (clientIP, userAgent) tuple of
the /auth/oidc/login request, and enforces a constant-time compare
against the /auth/oidc/callback request at consume time. Defeats
replay of a stolen pre-login cookie by a different browser /
source — the secondary defense layer recommended by RFC 9700 §4.7.1
when the primary layer (HMAC integrity + Path=/ + SameSite=Lax on
the cookie) is bypassed via CSRF / XSS / TLS-termination leak.

WHY.

Pre-fix, the pre-login cookie's HMAC verified only that 'some'
caller of /auth/oidc/login was talking to /auth/oidc/callback; it
did not verify that the SAME browser / source was on both sides.
An attacker who exfiltrated the cookie value via any vector could
replay the bytes through their own user-agent and ride the victim's
authorization. RFC 9700 §4.7.1 calls out the gap explicitly and
recommends binding state to a user-agent fingerprint + source IP.

HOW.

Migration:
  migrations/000044_prelogin_uaip.up.sql
    ALTER TABLE oidc_pre_login_sessions
      ADD COLUMN IF NOT EXISTS client_ip   TEXT,
      ADD COLUMN IF NOT EXISTS user_agent  TEXT;
  Both nullable for in-flight rolling-deploy compat — the consume-
  side check only enforces when both row AND request carry non-empty
  values for the leg in question.

Domain:
  internal/repository/oidc.go (PreLoginSession) — adds ClientIP +
    UserAgent fields.

Repository:
  internal/repository/postgres/oidc_prelogin.go — Create persists
    via sql.NullString (empty → NULL); LookupAndConsume reads back.
    Re-uses package-local nullableString from discovery.go.

Service:
  internal/auth/oidc/service.go
    - PreLoginStore.CreatePreLogin signature takes (clientIP,
      userAgent) as positions 5–6.
    - PreLoginStore.LookupAndConsume returns (clientIP, userAgent)
      as positions 5–6.
    - HandleAuthRequest signature gains (clientIP, userAgent),
      threaded to the store.
    - HandleCallback adds Step 1.5 — UA / IP constant-time compare
      between stored row and incoming request. Per-leg toggles via
      preLoginRequireUA / preLoginRequireIP service fields. Empty
      values on either side pass through (rolling-deploy + headless-
      proxy compat).
    - New sentinels ErrPreLoginUAMismatch, ErrPreLoginIPMismatch.
    - SetPreLoginBindingRequirements(requireUA, requireIP) helper
      for main.go config wiring.

Adapter:
  internal/auth/oidc/prelogin.go — PreLoginAdapter passes the new
    fields through to the repo row.

Handler:
  internal/api/handler/auth_session_oidc.go
    - OIDCAuthHandshaker.HandleAuthRequest signature updated.
    - LoginInitiate captures clientIPFromRequest + r.UserAgent()
      and passes to the service.
    - classifyOIDCFailure adds errors.Is dispatch for the two new
      sentinels → prelogin_ua_mismatch / prelogin_ip_mismatch
      audit categories.

Config:
  internal/config/config.go
    + AuthConfig.OIDCPreLoginRequireUA (default true)
      env CERTCTL_OIDC_PRELOGIN_REQUIRE_UA
    + AuthConfig.OIDCPreLoginRequireIP (default true)
      env CERTCTL_OIDC_PRELOGIN_REQUIRE_IP
  cmd/server/main.go calls oidcService.SetPreLoginBindingRequirements
    from cfg.Auth.OIDCPreLoginRequire{UA,IP}.

Tests (internal/auth/oidc/service_test.go):
  - TestService_HandleCallback_MED16_UAMismatchRejected
  - TestService_HandleCallback_MED16_IPMismatchRejected
  - TestService_HandleCallback_MED16_BothMatch_Succeeds
  - TestService_HandleCallback_MED16_LegacyRowEmptyValues  (rolling-
    deploy compat — empty stored values pass through)
  - TestService_HandleCallback_MED16_RequireUAFalse_AllowsMismatch
    (operator escape-hatch — UA mismatch silently allowed)

Mechanical fan-out:
  - stubPreLogin / stubPreLoginRepo signatures updated.
  - All existing call sites in service_test.go (~40), prelogin_test.go,
    bench_test.go, logging_test.go, provider_enabled_test.go,
    integration_keycloak_test.go, integration_okta_smoke_test.go,
    auth_session_oidc_test.go updated to pass empty strings for the
    new params — pre-existing tests do not exercise UA/IP binding
    semantics.

VERIFY.

- go vet ./internal/auth/oidc/... ./internal/api/handler/...
  ./internal/config/...                                       PASS
- go test -short -count=1 -run MED16 ./internal/auth/oidc/... PASS (5/5)
- go test -short -count=1 ./internal/auth/oidc/...            PASS (4.6s)
- go test -short -count=1 ./internal/api/handler/...          PASS (4.3s)
- go test -short -count=1 ./internal/config/...               PASS

Refs: cowork/auth-bundles-audit-2026-05-10.md MED-16
      cowork/auth-bundles-fixes-2026-05-10/HANDOFF.md item 6
      RFC 9700 §4.7.1 — OAuth 2.0 Security Best Current Practice
This commit is contained in:
shankar0123
2026-05-10 23:18:23 +00:00
parent 2cd2a5c52f
commit 2a1a0b347c
18 changed files with 441 additions and 103 deletions
+38 -6
View File
@@ -75,14 +75,23 @@ func (r *PreLoginRepository) Create(ctx context.Context, p *repository.PreLoginS
return fmt.Errorf("oidc_pre_login encrypt pkce_verifier: %w", verr)
}
// Audit 2026-05-10 MED-16 — persist UA/IP binding on Create.
// Empty values are inserted as NULL via sql.NullString so the
// schema's nullable column constraint is respected and existing
// integration tests that don't provide UA/IP keep working.
clientIP := nullableString(p.ClientIP)
userAgent := nullableString(p.UserAgent)
if p.CreatedAt.IsZero() && p.AbsoluteExpiresAt.IsZero() {
_, err := r.db.ExecContext(ctx, `
INSERT INTO oidc_pre_login_sessions (
id, tenant_id, signing_key_id, oidc_provider_id,
state_enc, nonce_enc, pkce_verifier_enc
) VALUES ($1,$2,$3,$4,$5,$6,$7)`,
state_enc, nonce_enc, pkce_verifier_enc,
client_ip, user_agent
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)`,
p.ID, p.TenantID, p.SigningKeyID, p.OIDCProviderID,
stateEnc, nonceEnc, verifierEnc)
stateEnc, nonceEnc, verifierEnc,
clientIP, userAgent)
if err != nil {
return fmt.Errorf("oidc_pre_login create: %w", err)
}
@@ -98,16 +107,26 @@ func (r *PreLoginRepository) Create(ctx context.Context, p *repository.PreLoginS
_, err := r.db.ExecContext(ctx, `
INSERT INTO oidc_pre_login_sessions (
id, tenant_id, signing_key_id, oidc_provider_id,
state_enc, nonce_enc, pkce_verifier_enc, created_at, absolute_expires_at
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)`,
state_enc, nonce_enc, pkce_verifier_enc,
client_ip, user_agent,
created_at, absolute_expires_at
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)`,
p.ID, p.TenantID, p.SigningKeyID, p.OIDCProviderID,
stateEnc, nonceEnc, verifierEnc, p.CreatedAt, p.AbsoluteExpiresAt)
stateEnc, nonceEnc, verifierEnc,
clientIP, userAgent,
p.CreatedAt, p.AbsoluteExpiresAt)
if err != nil {
return fmt.Errorf("oidc_pre_login create: %w", err)
}
return nil
}
// MED-16 reuses nullableString from discovery.go (same package). It
// returns sql.NullString{Valid:false} for empty strings so the database
// stores NULL rather than the literal empty string — avoiding ambiguity
// at consume time between "row had no binding" and "row had an explicit
// empty binding".
// LookupAndConsume reads the row by id and atomically deletes it
// (single-use). Returns ErrPreLoginNotFound on miss; ErrPreLoginExpired
// when the row was found but past its TTL (the row is still deleted in
@@ -132,16 +151,19 @@ func (r *PreLoginRepository) LookupAndConsume(ctx context.Context, id string) (*
RETURNING id, tenant_id, signing_key_id, oidc_provider_id,
state, nonce, pkce_verifier,
state_enc, nonce_enc, pkce_verifier_enc,
client_ip, user_agent,
created_at, absolute_expires_at`,
id)
var p repository.PreLoginSession
var statePlain, noncePlain, verifierPlain sql.NullString
var clientIP, userAgent sql.NullString
var stateEnc, nonceEnc, verifierEnc []byte
if err := row.Scan(
&p.ID, &p.TenantID, &p.SigningKeyID, &p.OIDCProviderID,
&statePlain, &noncePlain, &verifierPlain,
&stateEnc, &nonceEnc, &verifierEnc,
&clientIP, &userAgent,
&p.CreatedAt, &p.AbsoluteExpiresAt,
); err != nil {
if errors.Is(err, sql.ErrNoRows) {
@@ -168,6 +190,16 @@ func (r *PreLoginRepository) LookupAndConsume(ctx context.Context, id string) (*
p.PKCEVerifier = verifier
}
// Audit 2026-05-10 MED-16 — surface the binding columns for the
// service-layer UA / IP compare. Empty when the row was created
// before this migration landed (rolling-deploy compat).
if clientIP.Valid {
p.ClientIP = clientIP.String
}
if userAgent.Valid {
p.UserAgent = userAgent.String
}
if time.Now().UTC().After(p.AbsoluteExpiresAt) {
return nil, repository.ErrPreLoginExpired
}