mirror of
https://github.com/shankar0123/certctl.git
synced 2026-06-07 21:31:34 +00:00
2a1a0b347c
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
184 lines
6.2 KiB
Go
184 lines
6.2 KiB
Go
package oidc
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"io"
|
|
"log/slog"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
// =============================================================================
|
|
// Token-leak hygiene: no secret value (ID token, access token, refresh
|
|
// token, authorization code, PKCE verifier, state, nonce, signing key
|
|
// material) appears in any log line at any level.
|
|
//
|
|
// Methodology mirrors Bundle 1's
|
|
// internal/auth/bootstrap/service_test.go::TestService_TokenLeakHygiene:
|
|
// redirect slog.Default to a buffer, run the OIDC service paths,
|
|
// grep-assert the secret string never appears in any captured line.
|
|
//
|
|
// This is the load-bearing invariant for Phase 3's "tokens never
|
|
// logged" contract. Every secret-bearing path that enters the
|
|
// service.go code MUST flow through write-once-to-response patterns;
|
|
// adding a `slog.Info("got token", "value", token)` somewhere would
|
|
// fail this test immediately.
|
|
// =============================================================================
|
|
|
|
// captureLogger swaps the slog.Default with one that writes to the
|
|
// returned buffer. The returned restore func re-installs the original
|
|
// logger; callers must defer it.
|
|
func captureLogger(t *testing.T) (*bytes.Buffer, func()) {
|
|
t.Helper()
|
|
buf := &bytes.Buffer{}
|
|
original := slog.Default()
|
|
slog.SetDefault(slog.New(slog.NewTextHandler(io.Writer(buf), &slog.HandlerOptions{
|
|
Level: slog.LevelDebug,
|
|
})))
|
|
return buf, func() { slog.SetDefault(original) }
|
|
}
|
|
|
|
// TestLoggingHygiene_HandleAuthRequest_LeaksNothing exercises the full
|
|
// HandleAuthRequest path against a mock IdP and asserts that the
|
|
// generated state, nonce, PKCE verifier, and pre-login cookie never
|
|
// appear in any captured log line.
|
|
func TestLoggingHygiene_HandleAuthRequest_LeaksNothing(t *testing.T) {
|
|
idp := newMockIdP(t)
|
|
svc, _ := newServiceWithProviderAndPL(t, idp.URL(), "op-leak-1")
|
|
|
|
buf, restore := captureLogger(t)
|
|
defer restore()
|
|
|
|
authURL, cookieValue, _, err := svc.HandleAuthRequest(context.Background(), "op-leak-1", "", "")
|
|
if err != nil {
|
|
t.Fatalf("HandleAuthRequest: %v", err)
|
|
}
|
|
|
|
// Extract state from the authURL query so we can grep-assert.
|
|
parts := strings.Split(authURL, "state=")
|
|
if len(parts) < 2 {
|
|
t.Fatalf("authURL missing state param: %q", authURL)
|
|
}
|
|
stateValue := strings.SplitN(parts[1], "&", 2)[0]
|
|
|
|
captured := buf.String()
|
|
for _, secret := range []string{stateValue, cookieValue} {
|
|
if secret == "" {
|
|
continue
|
|
}
|
|
if strings.Contains(captured, secret) {
|
|
t.Errorf("secret value %q appeared in log output:\n%s", secret, captured)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestLoggingHygiene_HandleCallback_LeaksNothing runs the full callback
|
|
// flow (against the mock IdP) and grep-asserts the captured log buffer
|
|
// has no occurrence of the access token, the ID token, the
|
|
// authorization code, or the PKCE verifier.
|
|
func TestLoggingHygiene_HandleCallback_LeaksNothing(t *testing.T) {
|
|
idp := newMockIdP(t)
|
|
svc, pl := newServiceWithProviderAndPL(t, idp.URL(), "op-leak-2")
|
|
|
|
// Pre-login row with a known verifier we can grep for after.
|
|
verifier := "test-verifier-do-not-leak-aaaaaaaaaaaaa"
|
|
cookie, _, err := pl.CreatePreLogin(context.Background(), "op-leak-2", "the-state", "test-nonce-fixed", verifier, "", "")
|
|
if err != nil {
|
|
t.Fatalf("CreatePreLogin: %v", err)
|
|
}
|
|
|
|
buf, restore := captureLogger(t)
|
|
defer restore()
|
|
|
|
authCode := "secret-auth-code-do-not-leak"
|
|
res, err := svc.HandleCallback(context.Background(), cookie, authCode, "the-state", "", "10.0.0.1", "Mozilla")
|
|
if err != nil {
|
|
t.Fatalf("HandleCallback: %v", err)
|
|
}
|
|
|
|
captured := buf.String()
|
|
|
|
// Direct secrets that flow through HandleCallback's parameter list.
|
|
for _, secret := range []string{
|
|
authCode,
|
|
verifier,
|
|
"test-access-token",
|
|
idp.receivedCode,
|
|
idp.receivedVerifier,
|
|
} {
|
|
if secret == "" {
|
|
continue
|
|
}
|
|
if strings.Contains(captured, secret) {
|
|
t.Errorf("secret value %q appeared in log output:\n%s", secret, captured)
|
|
}
|
|
}
|
|
|
|
// The session cookie + CSRF token are returned by the mint stub;
|
|
// in production they're set on the response, not logged. Pin that
|
|
// we never logged them.
|
|
for _, secret := range []string{res.CookieValue, res.CSRFToken} {
|
|
if secret == "" {
|
|
continue
|
|
}
|
|
if strings.Contains(captured, secret) {
|
|
t.Errorf("session secret %q appeared in log output:\n%s", secret, captured)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestLoggingHygiene_AlgPinningDoesNotLogAlg is a defense-in-depth pin:
|
|
// when isDisallowedAlg rejects a token, the alg name might land in an
|
|
// error returned to the handler — but the service.go MUST NOT log the
|
|
// alg value itself (an attacker could probe to discover allow-list
|
|
// composition). The handler maps to a uniform 400; alg detail lives
|
|
// only in audit rows the operator owns.
|
|
func TestLoggingHygiene_AlgRejectionDoesNotLogAlg(t *testing.T) {
|
|
buf, restore := captureLogger(t)
|
|
defer restore()
|
|
|
|
// Direct call to the helper; this exercises the deny-list match.
|
|
_, _ = isDisallowedAlg("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.body.sig")
|
|
|
|
captured := buf.String()
|
|
if strings.Contains(captured, "HS256") {
|
|
t.Errorf("alg value HS256 appeared in log output (defense-in-depth violation):\n%s", captured)
|
|
}
|
|
}
|
|
|
|
// TestLoggingHygiene_ProviderLoadDoesNotLogClientSecret pins that
|
|
// even on getOrLoad failures, the decrypted client_secret bytes never
|
|
// land in a log line. Decryption happens before verifier construction;
|
|
// any error path that flows through must not surface the plaintext.
|
|
func TestLoggingHygiene_ProviderLoadDoesNotLogClientSecret(t *testing.T) {
|
|
idp := newMockIdP(t)
|
|
|
|
// Use a provider with a recognizable plaintext "secret" (no encryption
|
|
// key set, so decryptClientSecret returns the bytes as-is).
|
|
prov := makeProvider(idp.URL(), "op-leak-secret")
|
|
prov.ClientSecretEncrypted = []byte("client-secret-plaintext-do-not-leak-xxxxx")
|
|
|
|
pl := newStubPreLogin()
|
|
svc := NewService(
|
|
&stubProviderLookup{provider: prov},
|
|
&stubMappings{roleIDs: []string{"r-operator"}},
|
|
newStubUsers(),
|
|
&stubSessions{},
|
|
pl,
|
|
"",
|
|
)
|
|
|
|
buf, restore := captureLogger(t)
|
|
defer restore()
|
|
|
|
if _, err := svc.getOrLoad(context.Background(), "op-leak-secret"); err != nil {
|
|
t.Fatalf("getOrLoad: %v", err)
|
|
}
|
|
|
|
captured := buf.String()
|
|
if strings.Contains(captured, "client-secret-plaintext-do-not-leak") {
|
|
t.Errorf("client secret plaintext appeared in log output:\n%s", captured)
|
|
}
|
|
}
|