Files
traefikoidc/bearer_logout_iat_fallback_test.go
lukaszraczyloGitHubcopilot-swe-agent[bot] <[email protected]>
45e99551f9 Security & correctness hardening: auth flow, cache, recovery, DCR, docs (#155)
* Audit review (rounds 1-31): fix confirmed issues, remove dead code, harden tests

Security/correctness fixes:
- fail-open token validation preserved with lenient-audience; access token that
  fails verification and has no ID token to corroborate now fails closed
- token_manager blacklist-expiry: fix impossible tautology (x>24h && x<24h)
- constant-time OAuth state compare; clear state/nonce/code_verifier on
  callback token-exchange failure to prevent replay of half-failed flows
- StopAllTasks gated on last-instance close
- background-task panic recovery; remove task-registry counter leak
- circuit breaker half-open: release probe slot; CB + per-session outcome
  recorded once per refresh operation, not once per waiter
- Redis connection pool: handle nil receive when pool closed concurrently
- FileStore: atomic temp-write + rename
- errors_recovery health-check data race -> atomic

Test-isolation / hardening:
- reset helpers for Once-pinned global cache manager and transport pool
- coverage: utils 70->93% (redirect URL security contract); fuzz targets for
  bearer parsers; concurrent ServeHTTP race tests for the shared request path

Dead-code removal (verified orphaned, build+suite green): internal/providers
(30 files, 0 importers), internal/compat, internal/features, input_validation.

Verified: govulncheck, go mod tidy, yaegi-validate, cross-compile (darwin+
linux), golangci-lint (new-from-rev clean), 3x full race+shuffle green.

* Lint: fix real int-truncation bug; document intentional gosec findings

- TransportPool configKey: write conn-count ints verbatim (strconv) instead of
  byte() truncation — a config value >=256 previously truncated and made two
  distinct configs collide on one key, silently sharing a transport with the
  wrong settings (real fix, gosec G115).
- Document design-intentional gosec findings with //nolint:gosec + rationale:
  G117 (clients_secret intentionally marshaled into stored creds JSON),
  G704 (tokenURL is the trusted discovery endpoint), G124 (delete/test cookie,
  Secure set conditionally), G118 (long-lived background refresh) and pool
  utils short-ID rune, testutil mock server redirects.

Result: full-tree golangci-lint now reports 0 issues (was ~12). Build, vet,
and the full test suite remain green.

* Fix singleton ResourceManager data race (unlocked read vs test reset)

GetResourceManager returned the process-global via an unprotected read
(singleton_resources.go:50), while resetResourceManagerForTesting and
ResetResourceManager write it under resourceManagerMutex. A live background
task (graceful-degradation health check started by one test) reading the
singleton while a shuffled test resets it was a data race (found via
-race -shuffle: Write at singleton_resources_test.go:941/942 vs Read at
autocleanup.go:554 / error_recovery.go:910).

Fix: hold resourceManagerMutex around the read, matching the sibling
GetGlobalTaskRegistry (autocleanup.go:414). Added a deterministic
concurrent regression test (GetResourceManager vs reset under -race).

Verified: 4x full -race -count=1 -shuffle=on ./... all exit 0, 0 races,
0 fails; source-order suite green; lint clean.

* Fix 6 issues surfaced by adversarial agent team (round 35)

Concurrency/lifecycle (P1, highest-value):
- singleton_resources.go: RegisterBackgroundTask now REPLACES a stopped
  task instead of reusing it. BackgroundTask.Start is sync.Once-guarded,
  so a task stopped on instance close and re-registered (Traefik
  close+recreate for the same provider) was permanently dead: IsTaskRunning
  returned false (started && !stopped) so callers retried a start that
  was a no-op. Metadata refresh, token cleanup, and health checks now
  resume across a recreate cycle.
- error_recovery.go: the shared graceful-degradation health task was
  bound to the FIRST instance's performHealthChecks (later instances'
  checks never ran) and any instance's Close stopped it for all. Added a
  global live-instance registry; the shared task runs every instance's
  checks and is stopped only when the last instance closes (mirrors the
  singleton-token-cleanup gate).

Storage/cache:
- hybrid.go recordL2Error: Store(now) then immediately compared
  time.Since(t)<1s against its own write => ALWAYS fired, so a single
  transient L2 error flipped the whole cache into fallback (full L2
  bypass -> upstream stampede). Now enters fallback only on a PRIOR
  error within the window (true "multiple errors"). Updated two tests
  that had encoded the old single-error-fallback bug.
- redis_pool.go: ConnectionPool.Put checked closed but sent on
  p.connections without holding p.mu; Close closed it under p.mu.
  Window => 'send on closed channel' panic at shutdown. Put now holds
  p.mu (the lock only Close used).

HTTP/transport:
- jwk.go fetchJWKS: added an explicit >1 MiB guard (was silent partial
  read, could yield a truncated keyset and spurious missing-kid).
- http_client_pool.go configKey: now includes every transport-behavior
  field it actually consumes (compression, HTTP2, keep-alives, timeouts,
  buffer sizes, dial) so behaviorally different configs no longer share
  one transport built with the first config's settings.

Each fix has a regression test. Verified: full source-order suite green,
golangci-lint 0 issues, 3x full -race -count=1 -shuffle=on ./... all exit 0.

* Fix round-36 issues: DCR validation, auth-method default, shared metadata task, replay false-positive

Four verified fixes from the round-36 agent team (each confirmed against source
before acting):

- settings.go: Config.Validate now skips the client-credential block when
  Dynamic Client Registration is enabled and no clientID is pre-provisioned
  (RFC 7591 provides credentials at registration). Previously the
  unconditional 'clientID is required' made DCR unreachable via New.
- dynamic_client_registration.go: default registered token_endpoint_auth_method
  to client_secret_post to match the plugin's runtime default; an enforcing
  IdP would otherwise reject the plugin's token exchange.
- utilities.go: gate the shared per-provider singleton-metadata-refresh task
  stop on lastInstance (matching singleton-token-cleanup) so one instance's
  tear down no longer kills 2h metadata refresh for a surviving sibling.
- token_manager.go: stop self-recording the JTI into the per-instance
  tokenBlacklist on every verify. On the cookie path the same valid token is
  re-presented per request; an LRU eviction of the raw-token cache (MaxSize
  1000 / 5 MiB) then turned a legitimate cache miss into a false 'token
  replay detected'. Replay tracking stays in the shared shardedReplayCache.

Regression tests: new review_r36_regression_test.go (4 tests); updated
dynamic_client_registration_test.go and security_edge_cases_test.go which had
encoded the old defaults.

Verified: full source-order suite, full -race -count=1 -shuffle=on ./...
(all packages), and golangci-lint run ./... (0 issues).

* Fix dead CircuitBreaker.ResetTimeout config (round 39)

error_recovery.go: ResetTimeout was copied into the CircuitBreaker but never
consulted by the state machine (used only for a metric), so the documented
"how long to wait before fully closing the circuit" (reset_timeout, default
30s) had no effect: Open->HalfOpen used Timeout (60s), and a single
half-open success closed the circuit immediately, losing the intended
open -> half-open -> (reset cooldown) -> closed hysteresis and letting a
stray success immediately reopen (bounce).

Now the circuit remains half-open after entering it until resetTimeout has
elapsed; only then can a successful request fully close it. Half-open
requests are still allowed as probes. Default behavior is more
conservative (up to Timeout+ResetTimeout before full close).

Tests: updated TestCircuitBreakerHalfOpenTransition to the corrected
semantics; added TestCircuitBreakerResetTimeoutEnforced (fails on the old
dead-field code, where resetTimeout was ignored).

Verified: full source-order suite, full -race -count=1 -shuffle=on ./...
(all packages), golangci-lint run ./... (0 issues).

* Apply configured conn limits in pooled transport (round 41)

http_client_pool.go SharedTransportPool.GetOrCreateTransport built the shared
http.Transport with hardcoded MaxConnsPerHost=5, MaxIdleConnsPerHost=2,
MaxIdleConns=10, IdleConnTimeout=30s while HTTPClientConfig's versions of
those fields drove configKey (cache identity) and were validated and tuned
per preset (Default: 20/10/50/30s; OIDCProvider: 50/25/100/90s). The
config was thus valid, keyed, and validated but silently ignored in the
transport used by main.go (CreatePooledHTTPClient) - dead config that left
OIDC-provider connection tuning without effect. The sibling factory path
(http_client_factory.go) already applied these values.

Now the pooled transport derives MaxConnsPerHost, MaxIdleConnsPerHost,
MaxIdleConns, and IdleConnTimeout from the config, consistent with the
factory path and with configKey.

Test: added TestSharedTransportPoolAppliesConfigLimits, which fails on the
old hardcoded code (fixed values) and passes now.

Verified: full source-order suite, full -race -count=1 -shuffle=on ./...
(all packages), golangci-lint run ./... (0 issues).

* Harden redirect-count accessors against pooled-session data race (round 44)

* Fix bearer Authorization template strip order + nonce constant-time compare (round 45)

* Sanitize claim-derived identifier on auth-bypass headers (round 48)

* R51: guarantee openid scope in buildAuthURL when filter drops it

* R53: enforce 2048-bit minimum RSA key size on verify

* R54: refresh JWKS on unknown-kid to pick up key rotation

* R55: blacklist session tokens on user logout

* R56: honor RateLimit config as sustained req rate

* R57: FIFO eviction; keep fresh replay JTIs in cache

* R58: idempotent RefreshCoordinator Shutdown; no close-close

* R59: honor backend TTL on cache repopulation

* R60: accept single-string groups/roles; fix mem over-evict

* R61: detect truncated chunked token via stored total

* R62: drain queued tasks on goroutine pool shutdown

* R63: Shutdown waits for in-flight refresh goroutines

* R64: cap metadata cache grace by configured limits

* R65: validate ES client-assertion key curve matches alg

* R66: check expiry on lenient-audience token path

* R67: apply allowedRolesAndGroups gate to SSE/WS bypass

* R68: cache expiry TOCTOU, logout open-redirect, session max-age

* R69: fix double pool-return on session-timeout path

* R70: pooled-client cookie jar, refresh Save-failure cleanup

* R71: SSE/WS allowlist, session max-age, sec headers

* R72: validate combined cookie chunk metadata

* R73: logout jti replay, expired ajax, no-value

* R74: recv handler panics, cache TTL race fix

* R75: azure unauth copy-paste, dcr guard, cookie domain

* R76: dcr singleflight, L1 no-resurrect, TLS loopback

* R77: bearer allowedUsers gate, session inUse CAS

* R78: hybrid Clear flush, reauth reacquire, pool CAS

* R79: invalidation ttl tracks maxage, empty tpl hdr

* R80: req secret for introspection, pool conn on panic

* R81: reject empty access token on callback+refresh

* R82: req discovery endpoints, single-use code retry

* R83: DCR require client_secret for confidential auth, validate redirect_uri scheme; reject callback query/fragment

* R86: atomic SetIfAbsent for replay cache; close double-accept and singleton-read race

* R87: validate backchannel logout token exp; live-refresh JWKS for logout kid-miss

* R88: make StopAllTasks cover ResourceManager singleton tasks

TaskRegistry.CreateSingletonTask delegates to ResourceManager.RegisterBackgroundTask
and stores the task in the ResourceManager's registry, not TaskRegistry.tasks.
TaskRegistry.StopAllTasks previously iterated its own (always-empty) registry,
silently leaking every process-global singleton task's ticker goroutine past the
last Close (memory-monitor, replay-cache-cleanup) — tasks kept running real
periodic work with no instance to serve.

Add ResourceManager.StopAllTasks (stops all rm-owned tasks) and have
TaskRegistry.StopAllTasks stop both its own RegisterTask-direct tasks and the
ResourceManager-owned singletons.

Regression TestR88StopAllTasksStopsResourceManagerOwnedTasks (review_r88_test.go):
fails on old code (task still running after StopAllTasks), passes on new.

* R89: normalize excluded-url paths; apply defaults to pooled HTTP clients

Two verified defects from R89 scout round:

1. Excluded-URL dot-segment traversal widening (P1, auth bypass).
   shouldBypassAuth passes req.URL.Path raw (middleware.go:54); Go's server
   leaves '..' in URL.Path (url.ParseRequestURI does not normalize), so an
   exclusion for /public also matched /public/../admin, letting a real
   sibling (/admin) reach the backend unauthenticated. pathExcluded now
   path.Clean()s the request path ('.' -> '' to preserve root semantics)
   before boundary matching. Regression TestR89ExcludedPathDotTraversal
   fails on old (all 4 traversal cases wrongly excluded), passes on new.

2. Pooled HTTP client had no zero-value defaults (P2, unbounded stall).
   CreateHTTPClient applies defaults; CreatePooledHTTPClient and
   GetOrCreateTransport did not, so a partial config yielded Timeout=0 and
   ResponseHeaderTimeout=0 (a hanging upstream stalls forever). Extracted
   applyHTTPClientDefaults (single source of truth) and applied it in all
   three construction paths; pool cache key now reflects normalized values.
   Regression TestR89PooledClientAppliesDefaults fails on old, passes on new.

R89 clean/declined: session max-age IS absolute-and-enforced-every-request
(verified, review_r68 already locks it); AllowedUserDomains fail-closed (P2
'*' not a wildcard, P3 TrimSpace — declined as config-scoped).

* R92: validate all time claims on lenient-audience access tokens

On the lenient-audience path (validateStandardTokensRS), jwt.Verify
short-circuits at the aud check before reaching exp/iat/nbf validation,
leaving every time claim unvalidated. accessTokenUnexpired previously
re-patched only 'exp' (the R66 fix), so a token with a not-yet-reached
'nbf' but a valid exp was trusted for authorization before it was valid.

accessTokenUnexpired now re-applies the full main-path time validation:
verifyExpiration, verifyIssuedAt (iat required), and verifyNotBefore when
present — all clock-skew-aware. Regression TestR92LenientPathRejectsFutureNbf
(plus valid control) fails on old code (future-nbf token accepted), passes on
new.

R92 clean/declined: bearer auth (aud enforced, full claims — clean);
refresh rotation (correctly bound to session; no local reuse detection =
design); logout cookie completeness (all chunk names cleared, no revive;
two P3 non-security notes declined).

* fix(auth): harden OIDC flow, token validation, session, and bearer handling

- replay entry covers exp + clock-skew window; callback GET-only (RFC 6749)
- callback rate-limit returns 429 + Retry-After; panic-recovery sets no-store
- cross-chunk integrity for chunked tokens; bounded chunked-token read scan
- HTTPError classification so 5xx/429 token-endpoint responses retry
- redaction of token/code/state in logs; per-source external auth gate

* fix(cache): harden cache backends, resilience, recovery, and transports

- RESP -ERR no longer closes healthy conn / aborts batch; global cap replacement-aware
- global health-check pass serialized (latent data race); MemoryMonitor via ResourceManager
- token-exchange retry, open-circuit rejections counted as failures
- TLS-posture matching transport reuse (no silent InsecureSkipVerify handoff)

* fix(config,dcr): env fallbacks, DCR self-heal, per-source auth gate

- implement documented OIDC_* env fallbacks; hold metadataMu for clientAssertion write
- re-register client when client_secret expires; require secret for confidential
- add opt-in per-source external auth rate limiting (PerSourceLoginRateLimit)

* docs: complete config reference and config examples

- CONFIGURATION.md: add 11 previously-omitted optional parameters
- README: document 6 implemented-but-undocumented options
- fix example config (raw .env block made invalid YAML)

* build: pin toolchain to go1.26.6 (resolves 5 reachable stdlib CVEs)

- net/http, asn1, idna GO-2026 CVEs cleared; govulncheck now 0 findings

* fix(jwk): use time.Since for elapsed-time computation (S1012)

* test: add R-round regression and security suite

- fail-on-old regression tests for every shipped fix (R-rounds)
- fuzz targets (parseJWT, bearer), concurrency-stress, shuffle-flake guards
- coverage-closing contract tests (health-check backend, TLS-posture reuse)
- r154 ID-token fixture built from parts to avoid false-positive secret scan

* test: mark synthetic PKCE verifier with trufflehog:ignore

Quiet the Lob detector's false positive on the fake test-only code_verifier,
matching the repo's existing // trufflehog:ignore convention in token_test.go.
Local trufflehog filesystem scan is now 0 verified / 0 unverified.

* fix(circuit-breaker): stop open-circuit rejections from re-arming the open timer (FIX-01)

ExecuteWithContext called the promoted BaseRecoveryMechanism.RecordFailure()
on every request rejected while the circuit is open. RecordFailure sets
lastFailureTime, the same field allowRequest read as the Open->HalfOpen
timer, so each rejection re-armed the timer. Under steady traffic shorter
than Timeout the breaker never left Open (the default-on token breaker,
token_resilience.go:31-36, is affected in production).

CircuitBreaker now tracks its own openedAt timestamp, set only on a
genuine Closed->Open or HalfOpen->Open transition in recordFailure.
allowRequest and IsAvailable gate on openedAt instead of lastFailureTime.
An open-circuit rejection still increments total_failures directly via
atomic.AddInt64, preserving the R180 metrics contract, but no longer
touches lastFailureTime or the open timer.

Adds TestCircuitBreakerOpenRejectionsDoNotExtendOpenWindow, which opens
the breaker (MaxFailures 1, Timeout 50ms) and sends a probe every 10ms;
it fails at head because no probe is ever admitted within 500ms.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(circuit-breaker): ignore terminal client errors in the breaker state machine (FIX-09)

After FIX-01, an ordinary fn() error still trips recordFailure(), which
reopens a half-open circuit unconditionally and holds it half-open for a
full ResetTimeout (15s/30s in production). A per-user HTTPError such as
invalid_grant from a replayed code is not a downstream-health signal, so
under a 1% user-error rate roughly 78% of half-open cycles reopened for
another ResetTimeout, extending real outages.

recordFailure() is now skipped for a terminal client error (HTTPError
4xx other than 429); the promoted RecordFailure() metrics counter still
runs, since the operation did return an error to its caller. 429 and
non-HTTPError failures (network errors, 5xx) are unaffected and still
trip the state machine.

Adds three regression tests: a half-open probe returning HTTPError 400
must stay half-open and later close on success (fails at head: reopens);
HTTPError 429 and a net.OpError must still reopen half-open (already
passing, pinned as a guard against over-broadening the exemption).

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(retry): stop single-use retry from matching HTTP response bodies (FIX-14)

ExecuteSingleUseWithContext substring-matched singleUseRetryableErrors
against the raw err.Error() text. helpers.go returns a *HTTPError whose
Message carries up to 10 KiB of the token-endpoint response body once a
response is received, so an IdP 500 that happened to mention "connection
refused" in its own body was retried up to MaxAttempts times even though
the request had definitely reached the server. Re-sending a consumed
authorization code or a rotated refresh token surfaces invalid_grant or
triggers refresh-token-family revocation on rotating IdPs.

Adds isNeverSentError: an *HTTPError (a response was received) is never
retried, and the fragment match now applies only to a genuine *net.OpError
(a dial/connect failure), the concrete type net/http.Client.Do returns
before any request reaches the wire.

Adds TestExecuteSingleUseWithContextNeverRetriesAfterHTTPResponse, which
fails at head (fn called 3 times instead of 1) and passes after the fix,
plus a guard that a real dial error is still retried.

Updates the existing TestRetryExecutor_SingleUse_RetriesPreSendError
(review_r82_test.go) to simulate the dial failure as a *net.OpError
instead of a bare string, matching what client.Do actually returns; the
bare-string form no longer satisfies the tightened, type-based match.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(circuit-breaker): address review for FIX-09

isTerminalClientError used errors.As(err, &httpErr) against an
interpreted *HTTPError target. Under yaegi v0.16.1 (Makefile:9) this
panics with "errors: *target must be interface or implement error",
regardless of the error's own concrete type. CircuitBreaker calls
this on every fn() error, on the default-on token-exchange/refresh
path, so every failed exchange or refresh panicked the goroutine
instead of returning its error, and the panic on the refresh path
(refresh_coordinator.go, an unrecovered goroutine) crashed the
process. Switch to a plain type assertion: the production error
reaches the breaker unwrapped, so no Unwrap chain walk is needed.

Extend cmd/yaegicheck/main.go to drive CircuitBreaker.ExecuteWithContext
under the real interpreter: a plain error (the first call shape that
panicked), a half-open 400 (must stay half-open), a closed-state 400
(must stay closed), and a 429 (must still reopen half-open). make
yaegi-validate now fails on the pre-fix code and passes after.

Also add a Closed-state regression test pinning the existing scope
choice (the terminal-client-error exemption applies to Closed as well
as HalfOpen, not only HalfOpen): a 400 leaves the breaker Closed, and a
following genuine 5xx still opens it. This is coverage-only -- the
Closed-state behavior itself already matched this before the change,
confirmed by running the new test against the pre-fix code (PASS).

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(retry): address review for FIX-14

isNeverSentError used errors.As(err, &httpErr) against an interpreted
*HTTPError target. Under yaegi v0.16.1 (Makefile:9) this panics with
"errors: *target must be interface or implement error", regardless of
the error's own concrete type. ExecuteSingleUseWithContext calls this
on every fn() error, on the default-on authorization-code-exchange and
refresh path, so every failed exchange or refresh panicked instead of
returning its error. Switch to a plain type assertion: the production
error reaches here unwrapped, so no Unwrap chain walk is needed. The
errors.As(err, &opErr) match against *net.OpError is untouched -- a
compiled stdlib type, yaegi-safe.

Also narrow the *net.OpError match to Op "dial" or "proxyconnect".
isNeverSentError previously matched singleUseRetryableErrors against
ANY *net.OpError, including "read"/"write", which happen after the
connection is already established and the single-use request may
already have reached the IdP. Only a failed connect proves the request
never went out. Correct the doc comment, which claimed a *net.OpError
is always pre-wire -- it is not.

Extend cmd/yaegicheck/main.go to drive
RetryExecutor.ExecuteSingleUseWithContext under the real interpreter: a
*HTTPError whose Message happens to contain a retryable-looking
fragment (must be called once, never retried) and a real client.Do
dial failure against a closed local port (must be retried to
MaxAttempts). make yaegi-validate now fails on the pre-fix code and
passes after.

Add a regression pinning the Op-scoping fix: a *net.OpError{Op: "read"}
carrying syscall.EHOSTUNREACH is not retried by
ExecuteSingleUseWithContext (fn called once). Confirmed this fails
against the pre-fix code (fn called 3 times) before applying the fix.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(recovery): stop gdInstances leak from TokenResilienceManager (FIX-18)

Register GracefulDegradation in gdInstances synchronously in
NewGracefulDegradation, before the health-check goroutine starts. A
Close() that ran immediately after construction could otherwise race
the async registration and delete nothing, then the later registration
would add an already-closed instance permanently.

Add Close to ErrorRecoveryManager and TokenResilienceManager.
NewTokenResilienceManager builds its own ErrorRecoveryManager (and
therefore its own GracefulDegradation), separate from the plugin
instance own errorRecoveryManager. Production Close() only ever closed
the first one, so the second leaked in gdInstances forever and the
shared health-check task last-instance stop gate never fired.

TraefikOidc.Close now calls Close on both managers.

Regression test TestFix18_ClosingBothManagersEmptiesGDInstances fails
to build at head (Close undefined on both managers) and passes after
the fix.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(tasks): keep pending singleton task instead of orphaning it (FIX-19)

RegisterBackgroundTask replaced any existing task with
started==0 && stopped==0, including one that is merely pending its
first Start() call. CreateSingletonTask (and the two other call sites
sharing its Register-then-Start pattern) does not hold tasksMu across
that sequence, so a second concurrent caller lands in that window and
replaces a task the first caller is about to start. The first caller
then starts an object no longer reachable from the registry, and
StopAllTasks/Shutdown never reach it again.

Add a startRefused flag to BackgroundTask, set on Starts refused by
the circuit breaker or the concurrency limiter (the two early-return
paths that leave started==0 and stopped==0 permanently).
RegisterBackgroundTask now replaces an existing task only when it is
stopped or its one Start attempt was refused, keeping a task that is
simply not started yet.

review_r122_test.go pinned the old "started==0 && stopped==0 always
means replace" behavior with a fixture that force-sets those fields
directly, without ever exercising a real Start() rejection. Update the
fixture to also set startRefused=1, the precise signal that case now
carries, preserving the R122 invariant (a circuit-breaker-rejected
task is still always replaced) alongside the new one.

Regression test TestFix19_RegisterBackgroundTaskKeepsPendingTaskNoOrphan
fails at head (orphan task keeps ticking after StopAllTasks: 13 -> 25)
and passes after the fix.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(lifecycle): re-check last-instance under shared mutex before stop (FIX-35)

Close() decided whether it was the last live instance once, early
in its shutdown sequence (unregisterLiveInstance return value), then
reused that boolean much later to gate three separate singleton
stops (singleton-token-cleanup, singleton-metadata-refresh-*, and
the general StopAllTasks). Session and cache teardown run in
between, taking real time, during which a concurrently-created new
instance (an overlapping Traefik reload) can register and adopt the
same singletons. The stale decision then stops them anyway, leaving
the surviving instance with no memory monitor, token cleanup, or
metadata refresh until the next reload.

Add liveInstanceMu, taken by registerLiveInstance,
unregisterLiveInstance and a new isLastInstanceNow. Close() now calls
isLastInstanceNow() fresh, immediately before each of the three
singleton stops, instead of reusing one early decision.

main.go now calls registerLiveInstance before New adopts the
memory-monitor singleton (previously called after), so a concurrent
Close elsewhere always sees a new instance counted before it can
decide to stop the singletons that instance depends on.

Regression test
TestFix35_ConcurrentNewKeepsSingletonAliveAcrossOldClose fails to
build at head (isLastInstanceNow undefined) and passes after the fix.
A throwaway scratch probe (not committed) confirmed the runtime bug
independently: reproducing the old stale-decision pattern inline
wrongly stops memory-monitor even after a new instance registered and
adopted it.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(refresh): reject CoordinateRefresh after Shutdown, correct stale ctx comments (FIX-36)

CoordinateRefresh called wg.Add(1) unconditionally, with no check
on rc.stopChan, so a request arriving during or after Shutdown still
registered and ran a new refresh operation. go doc sync.WaitGroup.Add
requires that Adds with a positive delta happening when the counter
is zero happen before a Wait; an Add racing the last Done during an
in-progress Wait can panic with WaitGroup misuse.

Add lifecycleMu (RWMutex). CoordinateRefresh now takes RLock around
its stopChan check and its wg.Add(1) call; Shutdown takes Lock()
before closing stopChan. Lock() cannot succeed while any
CoordinateRefresh call holds RLock, so every Add that will ever
happen has completed before Shutdown reaches wg.Wait().
CoordinateRefresh called after Shutdown now returns an error instead
of running.

The comment on the isNew branch claimed in-flight refreshes "are
aborted promptly via rc.ctx when stopChan closes" - rc.ctx does not
exist. An initial version of this fix added it, deriving
executeRefreshAsync timeout context from it and canceling it in
Shutdown, so Shutdown would return before a genuinely in-flight
refresh finished. That directly regressed two existing, deliberately
written tests - TestRefreshCoordinator_ShutdownWaitsForInFlight
(review_r154) and TestRefreshCoordinatorShutdownWaitsForInflight
(review_r63) - which pin that Shutdown must wait for an in-flight
refresh to finish naturally, not abandon it (avoiding a leaked
refresh goroutine). This fix keeps that contract: Shutdown still
waits via wg.Wait(), bounded only by each operation own
RefreshTimeout, and the stale comments are corrected to describe
that behavior accurately instead of a rc.ctx mechanism that does not
exist.

Regression test TestFix36_CoordinateRefreshRejectedAfterShutdown
fails at head (CoordinateRefresh after Shutdown wrongly succeeds
and runs refreshFunc) and passes after the fix. The R63/R154 tests
were re-run and confirmed still green.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test(refresh): replace timing-margin sleeps with deterministic waits (FIX-22)

Four tests raced the 100ms DeduplicationCleanupDelay cleanup timer
with a 150ms fixed sleep, a 50ms margin. A late timer let the next
call join the previous operation instead of starting a new one,
under-counting circuit-breaker/rate-limit attempts on loaded CI
runners. A fifth test (internal/cache/backends) raced singleflights
own 100ms delayed-cleanup goroutine the same way.

Set DeduplicationCleanupDelay=0 on the four RefreshCoordinator tests
(TestRefreshCoordinatorIntegration CircuitBreaker and RateLimiting
subtests, TestCircuitBreakerProtection,
TestRefreshCoordinator_SuccessOnlyAfterCombinedOperations), matching
the pattern already used elsewhere in refresh_coordinator_test.go.
Delay=0 alone is not fully deterministic: close(operation.done) and
the synchronous cleanup call are two separate statements in the same
deferred closure, so a waiter woken by the channel close can run
concurrently with, and observe the map entry before, that same
goroutines next statement. Confirmed this manually: an
intermediate delay-only version (no polling) failed 1 run out of 20
under -race -shuffle=on with the exact under-counting symptom the
finding describes.

Add waitForRefreshDrain, which polls
RefreshCoordinator.inFlightRefreshes for the tokens removal instead
of sleeping a fixed margin, and use it in all four loops. For
internal/cache/backends/review_r141_test.go, poll
SingleflightCache.calls under its own mutex the same way, per the
todo acceptance criterion.

All four tests plus the r141 test now pass go test -race -count=20
-shuffle=on with no fixed sleep at the previously-flaky sites, and
keep their existing assertions.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test(refresh): assert bounded Shutdown and goroutine exit (FIX-23)

TestRefreshCoordinatorShutdownStopsCleanup called Shutdown() with no
assertion, so it passed on base regardless of whether Shutdown
actually stopped the cleanup goroutine. Only the sibling
TestRefreshCoordinatorShutdownIdempotent caught anything (a panic on
double-close).

Assert Shutdown returns within a 2s deadline, then independently
observe the cleanup goroutine exit via rc.wg (the same WaitGroup
Shutdown wg.Wait() depends on, bracketing exactly cleanupRoutine).

Mutation check performed and reverted: temporarily removing the
"case <-rc.stopChan: return" branch from cleanupRoutine makes the
test fail with "Shutdown did not return within the deadline" (the
goroutine loops on the ticker forever, wg.Done() never fires).
refresh_coordinator.go is unmodified in this commit (git diff
--stat shows only review_r58_shutdown_test.go); the mutation was
applied and reverted locally to prove the pin is live before this
commit.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(recovery): address review for FIX-18

Fix the close-before-goroutine race the review reopened: delete the
duplicate async registration in startHealthCheckRoutine (only
NewGracefulDegradation registers now), and make the goroutine check
gd.stopChan under gd.mutex before creating or adopting the shared
health-check task, so a closed instance can never (re)start it.

Close() now stops the shared task by name via
GetResourceManager().StopBackgroundTask instead of reading this
instance own gd.healthCheckTask field. With two or more instances,
that field can still be nil on the last-closing instance even though
a sibling already started the shared task, which would have skipped
the stop and leaked the task.

Close every remaining GracefulDegradation NewWithContext can leak: add
a deferred cleanup that closes t.errorRecoveryManager and
t.tokenResilienceManager on any error return after they are
constructed.

Add TestFix18_CloseImmediatelyAfterNewDoesNotReRegister (pins the
exact race; fails deterministically pre-fix, green across
-count=300 -cpu=1,4,16 post-fix), TestFix18_TraefikOidcCloseEmptiesGDInstances
(drives the real TraefikOidc.Close instead of calling the managers
Close directly), and TestFix18_NewWithContextClosesManagersOnEarlyError
(pins the NewWithContext error-path leak). Make the existing
TestFix18_ClosingBothManagersEmptiesGDInstances wait for each
instance async health-check goroutine to settle before closing, via
the new gd.healthRoutineSettled helper, so it exercises the
task-already-assigned path deterministically instead of sometimes
racing the goroutine.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(lifecycle): address review for FIX-35

Close the check-then-stop window the review reopened: isLastInstanceNow
released liveInstanceMu as soon as it returned, before the actual
singleton stop ran (StopBackgroundTask / StopAllTasks, which can block
up to 5s per task). A concurrent New() could register and adopt the
very singleton in that gap, and the stop would kill it anyway.

Add stopIfLastInstance, which holds liveInstanceMu across both the
check and the stop callback, and use it at all three gated stops in
Close() (singleton-token-cleanup, singleton-metadata-refresh-*,
StopAllTasks) in place of the bare isLastInstanceNow() check.

Add TestFix35_StopIfLastInstanceHoldsLockAcrossCheckAndStop, which
proves the lock is genuinely held for the stop full duration (a
concurrent registerLiveInstance cannot complete while a slow stop
callback is still running). Rewrite
TestFix35_ConcurrentNewKeepsSingletonAliveAcrossOldClose to drive the
real (*TraefikOidc).Close via a new closeTestHook (nil in production,
invoked once in Close right after unregisterLiveInstance) instead of
re-implementing Close stop decision inline — the previous version
stayed green even with the production fix fully reverted, since it
never called Close at all.

Both new tests fail to build pre-fix (stopIfLastInstance and
closeTestHook are new symbols); green post-fix across
-count=50 -cpu=1,4,16.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(session): expire chunk cookies before writing replacement chunks (FIX-05)

SetRefreshToken and SetIDToken re-Get and fill the new chunk sessions
before calling the expire helper for the old ones. gorilla Registry.Get
returns the same cached *sessions.Session per cookie name for a request,
so the expire pass re-Gets the objects this call just wrote and wipes
their Values, silently dropping the replacement token.

Reorder both methods to match SetAccessToken: validate chunk count,
sizes and reassembly first (pure computation, no store.Get), then
expire the old chunks, then Get and fill the new ones. A session whose
refresh or ID token was loaded from existing chunk cookies and gets
replaced with another token that also needs chunking no longer loses
the new token.

Adds fix05_session_chunk_replace_test.go, adapted from
.claude/review-2026-09-10/repro/zz_g1_chunkwipe_test.go and
zz_g1_chunkwipe_id_test.go with helpers and test names renamed to
describe the behavior pinned.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(session): gate deferred pool-return on ownership generation (FIX-10)

ServeHTTP defers session.returnToPoolSafely() right after GetSession.
The invalidated-session paths deeper in the same request (backchannel/
frontchannel logout detection) can session.Clear() that exact object
and re-acquire a fresh one before ServeHTTP returns. The deferred call
stays bound to the original pointer regardless, so if a concurrent
request pops the same pooled object before this deferred call fires,
its CompareAndSwap(true, false) still succeeds against the new owner
and Reset()s a session another request is actively using (ABA on the
pool-return CAS).

Add a generation counter to SessionData, bumped once by GetSession and
newSession on every handout. ownerGeneration() reads the current
value; returnToPoolIfOwner(gen) only acts if the generation still
matches what the caller captured at acquire time, so a stale deferred
call from a previous ownership epoch is a deliberate no-op instead of
releasing a live session. ServeHTTP now captures the generation right
after GetSession and defers returnToPoolIfOwner instead of the plain
call.

This is the generation-counter alternative the finding names, chosen
over nil-ing the deferred pointer: the Clear+reacquire happens inside
processAuthorizedRequestRS/processAuthorizedRequest, separate
functions from the ServeHTTP-scope defer, so nil-ing a local variable
there cannot reach the already-bound deferred call.

Adds fix10_session_pool_aba_test.go, adapted from
.claude/review-2026-09-10/repro/zz_g1_aba_test.go with the helper
names and test renamed, and rewritten to drive the ABA sequence
deterministically (the pool handing back the same object after Clear
is unspecified sync.Pool timing, not part of the fixed contract, and
did not reproduce on every run).

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(middleware): require real preflight headers for the OPTIONS auth bypass (FIX-02)

shouldBypassAuth bypassed OIDC auth for any request whose method is
OPTIONS. A genuine CORS preflight always carries both an Origin header
and an Access-Control-Request-Method header; gating on the method
alone let an unauthenticated OPTIONS on any protected path reach the
backend with no session check. Reproduced against http.FileServer:
200 with the protected file body, no cookie, no Origin.

Require both headers before treating an OPTIONS request as a
preflight bypass. A genuine preflight still bypasses unconditionally;
every other OPTIONS request now goes through the normal auth
pipeline.

Adds fix02_options_bypass_test.go covering shouldBypassAuth directly
(bare OPTIONS, Origin-only, and a genuine preflight) plus an
end-to-end ServeHTTP reproduction of the leak and its fix. Updates the
existing TestShouldBypassAuth_PassesOptions in review_r124_test.go
(touched_outside) to send a genuine preflight instead of a bare
OPTIONS, since it asserted the vulnerable bypass-on-method-alone
behavior.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(middleware): drop oversized ID token header instead of truncating (FIX-34)

forwardAuthorized truncated an ID token longer than headerTemplateMaxLen
(8192 bytes) and still set X-Auth-Request-Token to the truncated value.
A truncated JWT is structurally invalid: a downstream that verifies the
signature rejects it (fine), but one that only base64-decodes claims
without verifying reads a corrupted value.

Drop the header instead of truncating, matching the fail-closed
pattern already used for X-Forwarded-User / X-Auth-Request-User in the
same function when identifier sanitization fails.

Adds fix34_idtoken_header_test.go (oversized token drops the header;
in-budget token still forwards unmodified). Updates
review_r155_regression_test.go (touched_outside): its existing test
asserted the header was truncated to exactly headerTemplateMaxLen
bytes, which is the behavior this fix replaces; renamed to
TestR155_XAuthRequestToken_DroppedWhenOverHeaderBudget and rewritten
to assert the header is absent.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(middleware): hand next.ServeHTTP the real writer, not the tracking wrapper (FIX-06)

ServeHTTP wraps rw in *trackingWriter (rw = tw) for panic-commit
tracking and then forwards that SAME wrapped writer to every
t.next.ServeHTTP call: excluded, SSE, WebSocket, options bypass, the
default case, and forwardAuthorized (the authenticated path). Traefik
runs the plugin interpreted under yaegi v0.16.1, whose stdlib interop
layer composes a boundary wrapper only for ResponseWriter+Hijacker
crossing into compiled code, never for Flusher or the Unwrap pattern
http.ResponseController relies on. So Traefik's compiled ReverseProxy
calling http.NewResponseController(rw).Flush() for SSE gets "feature
not supported" in production, even though trackingWriter declares
Flush/Unwrap and native tests (which never cross an interpreter
boundary) pass.

Reproduced with a throwaway yaegi run probe (not committed; yaegi
v0.16.1, GOPATH/bin/yaegi) mirroring trackingWriter exactly:
  wrapped:   ResponseController.Flush err=feature not supported, recorderFlushed=false
  unwrapped: ResponseController.Flush err=<nil>,                 recorderFlushed=true
matching the finding's own reproduction.

Add downstreamWriter(rw), used at every t.next.ServeHTTP call site: it
unwraps *trackingWriter to the real writer ServeHTTP received, and
marks the trackingWriter's new calledNext field so the deferred
recover (which may run in a different function than the call site, via
forwardAuthorized) knows control passed downstream.

Handing next the real writer means wroteHeader can no longer observe
writes next makes directly (it bypasses tw entirely). The deferred
panic recovery is updated to skip its fallback 500 once calledNext is
true: guessing in that state risks appending "Internal Server Error"
to a response next already committed, which TestR155_ServeHTTP_
PanicAfterCommitKeepsBodyIntact exists to prevent and is the more
severe failure mode. A panic in the middleware's own pre-forward code
is unaffected and still gets a clean 500
(TestR179_PanicRecoverySetsNoStore). Updates review_r74_test.go
(touched_outside): its existing assertion that a downstream (next)
panic forces a 500 is no longer achievable without that same
corruption risk; rewritten to assert the recovered-but-unwritten
default (200) Go's http.Server already gives any handler that returns
without writing.

Adds fix06_downstream_writer_test.go: asserts next receives the
unwrapped writer on the SSE, WebSocket and authenticated
(forwardAuthorized) paths.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(middleware): make FIX-06 actually load and behave correctly under yaegi (FIX-06)

trackingWriter now declares Header() explicitly instead of relying on
the embedded http.ResponseWriter promotion. yaegi v0.16.1 does not
count a promoted method when it statically checks whether
*trackingWriter satisfies http.ResponseWriter, so the plugin refused
to load under yaegi at all ("missing Header method"), invisible to
every native test. Verified with a temp GOPATH symlinked to this
worktree (the shared GOPATH symlink resolves to the main checkout, not
this branch) via `yaegi run ./cmd/yaegicheck/main.go`: FAIL before
this change, OK after.

ServeHTTP's panic-recovery defer now sends a header-only 500
(Cache-Control: no-store) whenever nothing was written through the
tracking wrapper, even after control has passed to next
(tw.calledNext). WriteHeader is idempotent, so this is a no-op if next
already committed its own response; only the fallback body Write is
still gated on !calledNext, since only a body Write can corrupt an
already-committed response. Previously the whole 500 was skipped once
calledNext was true, so a downstream panic before any write produced
an empty 200 instead of a 500, telling the client a failed request
succeeded. review_r74_test.go is restored to asserting 500 (its
925d627 baseline), with comments updated for the new behavior.

Adds cmd/yaegiflushcheck, a nested Go module (its own go.mod, so it
never enters the root module's build/vendor graph) that drives the
real plugin under yaegi with a COMPILED next handler calling
http.NewResponseController(w).Flush(), reproducing the finding
end-to-end rather than only at import time. Confirmed it fails
("feature not supported") when downstreamWriter is reverted to not
unwrap the tracking writer, and passes ("err=<nil>") against the fix.
fix06_downstream_writer_test.go's dangling reference to a
never-committed fix06_yaegi_probe.go now points at this file.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(middleware): discard the response body on a forged CORS preflight (FIX-02)

The FIX-02 header check (Origin + Access-Control-Request-Method) rules
out an accidental bare OPTIONS request but not a deliberate attacker:
any non-browser client can set both headers itself, and
bypassReasonOptions still forwarded that unauthenticated request to
next with no session check. Reproduced against http.FileServer: a
forged preflight with no cookie still returned the protected file's
body.

This exceeds what the FIX-02 todo originally asked for, so flagging
for maintainer sign-off (see the fixes report's concerns) even though
it is implemented here: severity is major with a concrete exploit, and
leaving it undone seemed worse than the scope overrun.

ServeHTTP's bypassReasonOptions case now hands next an
optionsPreflightWriter instead of the raw writer. It forwards
Header()/WriteHeader() (deleting any Content-Length next sets, since
no body follows) but discards every Write(). A browser never reads a
preflight response body, so a genuine CORS preflight keeps working
unchanged (TestServeHTTP_GenuinePreflightReachesBackend still passes);
a forged one can no longer read protected content through this path.
Declares Header/Write/WriteHeader explicitly rather than relying on
the embedded http.ResponseWriter's promotion, for the same yaegi
reason as trackingWriter (FIX-06): confirmed the plugin still loads
clean under yaegi (cmd/yaegicheck) with this change.

Adds TestServeHTTP_ForgedPreflightDoesNotLeakBody, which reproduces
the finding's own repro (http.FileServer, forged Origin +
Access-Control-Request-Method, no cookie) and asserts the body never
reaches the caller.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(bearer): gate opaque-token introspection and bind it to the client (FIX-03)

buildPrincipalFromOpaqueIntrospection accepted any introspected
active=true token from the IdP, with none of the JWT-path gates: it never
checked allowOpaqueTokens, never bound the response to this client when
audience==clientID (the common default), and never consulted
isSessionInvalidated or bearerIdentifierClaim/sanitizeBearerIdentifier/
maxTokenAge. A token issued to an unrelated client at the same IdP could
authenticate as any user, and IdP-initiated logout did not revoke an opaque
bearer token.

Gate the opaque branch behind the existing allowOpaqueTokens flag (no new
config knob). When audience==clientID, require resp.ClientID==clientID or
an aud containing clientID. Apply the identifier claim, sanitization,
maxTokenAge (resp.Iat) and isSessionInvalidated (by sub; RFC 7662 carries
no sid) the same way the JWT bearer path does. Update review_r159 and
review_r166 fixtures to set allowOpaqueTokens and a matching client_id, and
document the gated contract in docs/BEARER_AUTH.md.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(introspection): stop treating introspection 4xx as token-revoked (FIX-13)

R156 (8640451) mapped any 400-499 status from the introspection endpoint
to a definite "token invalid" verdict, on the session path
(token_validation_rs.go) and both bearer-path introspection call sites
(bearer_auth.go). RFC 7662 s2.2 defines only a 200 response with
active=false as inactive; s2.3 defines a 401 as the plugin own client
credentials being rejected, not a statement about the token. A rotated
client_secret or an IdP 429 therefore turned every valid token into a 401,
fed the bearer per-IP penalty box, and forced a refresh storm on the
session path.

Remove the 4xx-as-invalid special case at all three sites so those errors
fall into the existing generic handling: bearerErrIntrospectionUnavailable
(503) on the bearer path, and the existing requireTokenIntrospection-gated
fail-closed / transient-fallthrough on the session path. Only a 200
response with active=false still rejects the token. Update the R156
fixture that pinned the old (now superseded) 401-forces-refresh contract,
and document the corrected 401/503 split in docs/BEARER_AUTH.md.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(bearer): fail closed on logout invalidation when iat is absent (FIX-24)

buildPrincipalFromBearerToken derived the backchannel-logout invalidation
createdAt from iat, falling back to time.Now() when absent. 8640451 made
iat OPTIONAL in jwt.Verify (R126), so an access token without iat now
reaches this check. The time.Now() fallback made such a token always look
newer than any logout event, so IdP-initiated logout never revoked it,
reintroducing the R98 defect the cookie path already avoids by falling
back to the zero time instead.

Fall back to the zero time (fail closed) instead of time.Now(), matching
sessionCreatedAtForInvalidation on the cookie path. Also correct the stale
comment on enforceIatAge, which claimed jwt.Verify still hard-requires iat.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(bearer): stop sweeping in-progress failure counters (FIX-28)

recordFailure map-growth sweep deleted every entry whose penaltyUntil was
before the cutoff. An entry that has not tripped the penalty box yet has a
zero penaltyUntil, which is always before any cutoff, so once the map
passed defaultBearerEntrySweepThreshold every accumulating counter was
discarded regardless of how recently it started. An attacker who floods
many distinct source IPs (or one interleaving its own failures with
sweeps) could keep any one source below the threshold forever.

Delete an entry only when it is BOTH untripped-or-expired AND outside the
counting window: penaltyUntil.Before(cutoff) AND firstFailureAt is older
than the window. A fresh, still-accumulating counter now survives a sweep;
only entries that have genuinely gone stale are reclaimed. Update the R214
memory-bound test: a fresh flood within the window is now expected to grow
past the threshold (that is the fix, not a regression), while entries that
age past the window still get swept, which the rewritten test verifies in
a second phase.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(jwt): share the time-claims contract between Verify and the lenient path (FIX-27)

accessTokenUnexpired (the lenient-audience-path re-check that runs after
jwt.Verify short-circuits at the aud check) still hard-required iat, even
though 8640451 made iat OPTIONAL in jwt.Verify itself per RFC 7519 4.1.6
(R126). The two paths had drifted onto different contracts for the same
claim: an iat-less lenient-audience access token was always forced to
refresh or re-authenticate, while the identical token with a matching
audience passed through jwt.Verify fine.

Maintainer confirmed the iat-optional contract (R126) stands. Extract the
exp/iat/nbf validation shared by both paths into one verifyTimeClaims
helper in jwt.go and use it from both jwt.Verify and accessTokenUnexpired,
so the two cannot independently drift on which time claims are mandatory
again. Both R92 fixtures (which carry iat) keep passing.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(bearer): amortize the failure-tracker map-growth sweep (FIX-28)

recordFailure swept the whole entries map on every call once the map
crossed defaultBearerEntrySweepThreshold, even when the sweep found
nothing stale to delete. A flood of distinct source IPs (attacker-
controlled) turned this into O(n) work under b.mu on every call, O(n^2)
to fill the map, while blocked() waits on the same mutex on every
bearer request.

Add nextSweepAt, which doubles after each sweep (bounded below by
defaultBearerEntrySweepThreshold), so the scan runs only when the map
has genuinely grown, amortizing its frequency to logarithmic in the
flood size instead of linear. Add sweepPasses to count scans for
tests.

Rewrite TestBearerFailureTrackerSweepBoundsMemory phase 2 to record
failures until the next amortized sweep actually fires, then assert
the aged keys are gone, rather than asserting a fixed total-size
bound that the amortized gate no longer holds to on every call. Add
TestBearerFailureTrackerSweepAmortized: 30,000 fresh distinct sources
must trigger at most 6 sweep passes (HEAD triggers on ~29,000 calls).

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(bearer): close 3 opaque-introspection gaps: sid logout, iat bound, identifier claims (FIX-03)

buildPrincipalFromOpaqueIntrospection had three gaps against the JWT
bearer path it mirrors:

- isSessionInvalidated was always called with an empty sid, so a
  sid-only (front-channel) logout never revoked an opaque token, even
  when the IdP introspection response itself carried a sid. Add Sid
  to IntrospectionResponse and pass resp.Sid through.
- maxTokenAge was applied only when resp.Iat > 0, silently skipping
  the bound on a response with no iat, unlike enforceIatAge on the
  JWT path (which fails closed on a missing iat once maxAge is set,
  and New() always sets it > 0). Route the opaque-path check through
  enforceIatAge itself so the two paths cannot drift again.
- The identifier claims map was built from sub/username only, so any
  other bearerIdentifierClaim value (client_id, scope, iss, jti, aud)
  always 401d with "missing claim", even when the introspection
  response carried it.

Add regression tests for all three (sid-only logout, missing iat with
maxTokenAge set, bearerIdentifierClaim=client_id). Add iat to the
R159/R166 introspection fixtures, which otherwise now fail the
enforced age bound under makeBearerOIDC's 24h maxTokenAge default.
Document the opaque iat requirement and the sid-only logout scope in
docs/BEARER_AUTH.md.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(introspection): stop classifying session-path introspection errors by IdP body text (FIX-13)

validateOpaqueToken wraps introspectTokens *HTTPError for a non-200
introspection response, and HTTPError.Message embeds up to 10 KiB of
the IdPs own response body. validateStandardTokensRS substring-matched
that message for "token is not active", "revoked" or "token has
expired" before reaching the transient/fail-closed branch, so a
401/403/429 whose body happened to contain one of those words (e.g.
the IdPs OWN client-secret-revoked error, RFC 7662 s2.3) still forced
a refresh, even though only a 200 response with active=false may
reject the token.

Detect an *HTTPError via errors.As before the substring match and
route it straight to the requireTokenIntrospection/transient handling.
Only validateOpaqueTokens own generated messages (active=false,
expired, nbf — never an *HTTPError) still reach the substring
classification. Add a regression test: a 401 with "revoked" in the
body, requireTokenIntrospection=false, must not force a refresh.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(bearer): correct maxTokenAge opt-in comments (FIX-24)

The enforceIatAge and TestBearerLogoutInvalidation_NoIatFallsClosedNotOpen
comments called maxTokenAge>0 an "operator opt-in": false. New()s
config-default closure (main.go:357-362) always sets maxTokenAge > 0 —
0/unset becomes 24h — so enforceIatAge rejects every iat-less bearer
JWT in production, opt-in or not. Only a test that constructs
*TraefikOidc directly (bypassing New()) can set maxTokenAge=0.

Reword both comments to state this, and note that the zero-time
createdAt fallback for the logout-invalidation check is mostly
defense in depth given that in production: it is what protects an
iat-less token only when maxTokenAge is explicitly 0 or the object
bypasses New(), since enforceIatAge otherwise rejects the token first.

No behavior change. Separately, docs/BEARER_AUTH.md:164 and
docs/CONFIGURATION.md:288 state "0 disables the check", which
contradicts main.go:357-362 (0 becomes 24h, it is never actually
disabled) -- flagged to the lead as a pre-existing doc/code mismatch
outside this packages scope, not fixed here.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(cache): stop deleting applied-but-slow backend writes on Set failure (FIX-04)

RedisBackend.executeWithRetry checked ctx.Err() before err==nil, so a SET
that completed after the caller gave up waiting reported as failed even
though Redis applied it. UniversalCache.Set then issued a Delete on any
backend Set error, erasing the value that write just landed.

Reorder executeWithRetry to return nil immediately on a successful
operation, before consulting ctx.Err(). Skip the Delete in
UniversalCache.Set when the error is a context deadline/timeout (the
write may have applied), and unconditionally for MonotonicMarkers caches
(blacklist, session invalidation), whose entries are revocation markers
and are never stale regardless of the failure reason.

Adds MonotonicMarkers to UniversalCacheConfig, set for the blacklist and
session-invalidation cache configs in universal_cache_singleton.go.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(cache): add blacklist to getLocal RLock fast path (FIX-15)

The blacklist cache moved to CacheTypeBlacklist but the getLocal fast
path only gained CacheTypeIntrospection, so every blacklist lookup fell
to the exclusive c.mu.Lock(). tokenBlacklist.Get runs on the verify path
for every authenticated request, so this re-created the RLock-convoy
pattern (a single expired entry serializing every concurrent JWT verify
under yaegi) the fast path exists to prevent.

Add CacheTypeBlacklist to the fast-path case list.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(cache): read legacy token: namespace on blacklist miss (FIX-16)

The R128 rename moved the blacklist cache backend namespace from
CacheTypeToken (token:<key>) to CacheTypeBlacklist (blacklist:<key>) with
no migration. Revocation markers written before the upgrade (TTL up to
24h) were ignored after it, and mixed-version replicas in a rolling
deploy did not share revocations, since old and new instances read and
write different namespaces.

On a blacklist miss, also read the legacy token:<key> backend entry.
Treat it as blacklisted only when the stored value deserializes to
boolean true, so a CacheTypeToken claims-map entry for the same raw
token is never misread as a revocation marker. Writes stay on the new
blacklist: namespace only.

Upgrade note: operators upgrading through this release keep denying
tokens revoked by a pre-upgrade instance for the lifetime of the
revocation marker (up to 24h). The legacy-namespace read is a one-release
compatibility shim; a future release can drop checkLegacyBlacklistMarker
and legacyBlacklistPrefix in universal_cache.go once all replicas have
rolled forward past the R128 rename.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(cache): use PTTL and a no-expiry sentinel for Get TTL (FIX-31)

RedisBackend.Get read TTL (second precision), which maps both "no
expiry" (-1) and "under one second left" to a reported ttl of 0.
UniversalCache.Get treated any ttl<=0 as DefaultTTL, so a key on the
verge of expiring in Redis got re-cached locally for the cache's full
DefaultTTL, up to 25h for the session-invalidation cache, well past the
real expiry of the entry.

Switch Get to PTTL (millisecond precision) and return the distinct
NoExpiryTTL sentinel for a key with no associated expiry. Update
UniversalCache.Get to federate DefaultTTL only for that sentinel, and to
skip repopulating the local copy for any other non-positive ttl instead
of defaulting to DefaultTTL.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(cache): address review for FIX-04

Replace the anonymous-interface errors.As in isTimeoutOrDeadlineError
with the compiled net.Error pattern already used in error_recovery.go.
Under yaegi v0.16.1, errors.As against `var x interface{ Timeout() bool
}` panics with "errors: *target must be interface or implement error"
when the plugin package is interpreted the way Traefik loads it (GOPATH
self-import, not `go test`). Every non-context Set error on a
non-monotonic cache panicked UniversalCache.Set in Redis mode. Verified
this session: repointing the ~/.go/src GOPATH symlink to this worktree
(make yaegi-validate otherwise silently validates the main checkout,
see the yaegi-validate-gopath-symlink memory note) reproduces the exact
panic on the old code and confirms it is gone on the new code, both via
a standalone repro script and via a new cmd/yaegicheck guard
(checkUniversalCacheSetDoesNotPanicOnBackendError) that make
yaegi-validate now runs on every call.

Add the backend-stale local-write guard the FIX-04 todo asked for.
Skipping the post-failure Delete (timeout error, or a MonotonicMarkers
cache) leaves the backend holding whatever was there before the failed
Set. Get() previously trusted that backend value unconditionally,
reopening R162 for a deadline-erroring Set that never applied, and
silently masking a newer session-invalidation logout with an older
Redis timestamp when the newer Set's write failed. UniversalCache now
tracks a per-key backend-stale mark (staleBackend, cleared by the next
successful backend Set and by item removal/eviction/Clear); Get()
prefers the live local value over the backend value for a marked key
instead of overwriting it via updateLocalCache. Corrects the
MonotonicMarkers doc comment, which claimed session-invalidation
entries are "never stale" - they are Unix timestamps compared by
value, so an older one really can be stale next to a newer one.

Add SkipAutoCleanup/Close to the FIX-04 and FIX-16 test caches that
were leaking a cleanup goroutine and ticker per test run.

Tests: TestFIX04_TimeoutSetFailureServesFreshLocalNotStale,
TestFIX04_SessionInvalidationNewerLogoutDeadlineServesFreshLocal,
TestFIX04_SessionInvalidationNewerLogoutErrorReplyServesFreshLocal
(new); existing TestFIX04_*, TestFIX16_*, TestR162_* re-run clean.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(cache): address review for FIX-31

Correct the NoExpiryTTL godoc: it said the sentinel covers "Redis PTTL
-2/-1", contradicting the very next sentence, but Get only maps PTTL
-1 to NoExpiryTTL. PTTL -2 (and 0) map to a reported ttl of 0, same as
an about-to-expire key.

Tighten TestFIX31_GetWithRealTTLReportsPositiveDuration with a lower
bound near the set TTL. The prior assertions (ttl>0, ttl<=10s) do not
pin the millisecond-precision PTTL contract: reproduced this session
by mutating Get back to `conn.Do("TTL", ...)` while still reading the
reply as milliseconds — both FIX-31 backend tests still passed, and a
10s key reported "10ms" as its TTL. The new `ttl>9s` bound fails on
that same mutation ("10ms" is not greater than "9s") and passes on the
real PTTL-based code.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(cache): address review for FIX-16

Reword the legacy-blacklist-namespace comment in Get(). It claimed
mixed-version replicas "share revocations" during a rolling deploy,
but the shim is one-directional: an upgraded replica still honors a
revocation a pre-upgrade replica wrote under the legacy "token:"
namespace (checkLegacyBlacklistMarker on a "blacklist:" miss), but a
pre-upgrade replica has no knowledge of "blacklist:" and never sees a
revocation an upgraded replica writes. Writes stay on the new
namespace only, unchanged.

Comment-only change; TestFIX16_* re-run clean.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(cache/redis): drain array after nested -ERR reply (FIX-37)

readArray returned early on the first nested "-ERR" element, leaving
declared-but-unread elements on the connection. Do treats
ErrCommandReply as non-fatal and returns the connection to the pool, so
the leftover bytes could be read as the reply to the next command on
that connection (response desync).

readArray now keeps reading past a nested command-error reply, storing
it as the element value, and only aborts on a genuine IO or protocol
error.

Regression test proves a nested -ERR no longer aborts the array read
and that a subsequent reply on the same stream is not corrupted by
leftover bytes.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(cache/redis): surface pipeline command errors in GetMany (FIX-38)

Pipeline.Execute stores a Redis command-error reply (e.g. LOADING,
WRONGTYPE) as an error value in the responses slice instead of failing
the batch. GetMany ran that value through RESPString, which always
failed on an error value, and counted the failure as a cache miss with
no log. A command error therefore looked identical to "key not found".

GetMany now recognizes an error-valued response, keeps it out of the
miss count, and returns it wrapped with the offending key. Other keys
in the same batch still populate the result map.

Regression test proves a WRONGTYPE reply for one key is surfaced as an
error, not silently dropped, while a good key in the same batch still
comes back.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* chore(cache): remove unreachable internal/cache dead code (FIX-43)

Grep confirms no non-test code imports traefikoidc/internal/cache, and
NewMemoryBackend/NewHybridBackend have no production caller anywhere
(only tests of the twins themselves). The production cache path is
UniversalCache over the root-level backends package; R64/R68/R74/R76/
R78 fixes to these twins had no production effect, and R64 duplicates
logic that already exists in universal_cache.go (unchanged).

Removed:
- internal/cache (parent package): cache.go, manager.go, typed_cache.go,
  compat.go, log_redact.go, and their tests.
- internal/cache/backends: memory.go, memory_shard.go, memory_wrapper.go,
  hybrid.go, and their tests. FIX-20 (hybrid.go asyncWg race) is
  superseded by this removal and is not fixed.

Tests that exercised the deleted MemoryCacheBackend/cacheShard/
MemoryBackend/HybridBackend internals directly are removed with them
(review_r76/78/99/124/125/139_f2/177_regression_test.go under
backends, race_regression_test.go). Tests that used NewMemoryBackend
only as a convenient CacheBackend substrate for still-alive production
code (singleflight.go, review_r141/r212 stress tests, and the root
package JWKCache tests via NewMemoryBackendForTest) now build that
substrate from a miniredis-backed RedisBackend instead. Assertions are
unchanged.

The redis.go retry classifier depended on a small case-insensitive
contains/toLower helper that had been living in hybrid.go; moved to a
new stringutil.go so the redis backend keeps working standalone.

go list ./... no longer lists internal/cache (only backends and
resilience remain); build, vet and the full race test suite are green.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(cache/backends): delete now-unused redactKey (FIX-43)

redactKey had callers only in the deleted hybrid.go. staticcheck U1000
and a full golangci-lint run both flagged it as unused after the FIX-43
deletion. Delete it and move the package doc comment it carried onto
interface.go, replacing that file's stale singular-typo comment.

staticcheck ./... and golangci-lint run ./... (no --new-from-rev) both
report 0 issues in internal/cache/backends after this change.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(cache/backends): treat nested nil array elements as values (FIX-37)

readArray aborted on a nested "$-1" or "*-1" element by returning
ErrNilResponse, leaving trailing array elements unread on the wire.
Do() treats ErrNilResponse as a healthy-connection signal and keeps
the connection pooled, so the next command desyncs onto the leftover
bytes. This is the same desync the nested "-ERR" fix already handles.

Store nil for a nested ErrNilResponse and keep draining the array,
mirroring how Pipeline.Execute already treats ErrNilResponse as a
non-fatal per-command value. Top-level "$-1"/"*-1" still return
ErrNilResponse unchanged.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test(cache/backends): assert misses counter on GetMany command error (FIX-38)

The regression test only checked the returned error and the good key
result, not the misses counter, so the todo acceptance criterion
"does not increment misses" went unenforced.

Snapshot GetStats() before and after GetMany and assert misses is
unchanged and hits goes up by exactly one. Verified the test catches
the regression by temporarily reintroducing r.misses.Add(1) in the
resp.(error) branch: the test fails with "expected: 0 actual: 1" on
the misses assertion. Reverted the mutation; redis.go has no diff.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(test): close miniredis in NewMemoryBackendForTest (FIX-43)

NewMemoryBackendForTest started a miniredis server as a local variable
and never closed it. Callers only deferred backend.Close(), which
closes the RedisBackend pool, not the miniredis listener, so each
call leaked a listener and its goroutines for the rest of the test
binary.

NewMemoryBackendForTest now takes *testing.T and registers the
miniredis server against t.Cleanup(mr.Close), matching the pattern
already used by NewMiniredisServer and setupTestRedis in
internal/cache/backends. Updated both call sites (review_r124_test.go,
review_r130_test.go) to pass t.

New regression test in memory_backend_for_test_leak_test.go dials the
miniredis address after the owning subtest ends and asserts the
connection is refused. It fails against the pre-fix helper (dial
succeeds, listener still up) and passes after the fix.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* docs(cache): fix comments referencing deleted FIX-43 files (FIX-43)

Several comments still pointed at code the FIX-43 dead-code deletion
removed: sharded_cache.go and review_r129_test.go cited
internal/cache/backends/memory_shard.go, and review_r34_regression_test.go
cited a nonexistent hybrid TestRecordL2Error. interface_test.go claimed
the RedisBackend contract subtest actually runs, but setupRedisBackend
also t.Skips, so TestCacheBackendContract currently exercises neither
subtest.

Reword each comment to drop the stale references and, for
interface_test.go, state plainly that both subtests are pending
t.Skip stubs.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(jwk): bound repeat JWKS fetches after a failed refresh (FIX-30)

doLiveRefresh recorded the force-refresh cooldown only after a
successful fetch (R100), so every unknown-kid bearer request and every
backchannel-logout token hit the JWKS endpoint again during an IdP
outage, with no throttling at all.

Record a short 5s failure cooldown (jwksFailureCooldown) by backdating
the existing lastForceRefresh/lastSignatureRefresh timestamps, so a
failure blocks repeat upstream calls briefly without waiting the full
30s success cooldown before retrying once the IdP recovers.

forceJWKSRefresh previously delegated its within-cooldown branch to
GetJWKS, which itself falls back to a live fetch on a cache miss. That
silently defeated the new failure cooldown (nothing is cached after a
failure), so the branch now reads the local cache directly instead.

Update TestForceJWKSRefresh_FailedFetchDoesNotSetCooldown (review_r100_test.go)
to pin the corrected bound: a failure records a short cooldown that
clears well before the 30s success cooldown, not zero cooldown at all -
the previous assertion (no cooldown recorded) is the exact behavior
this fix corrects.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(logout): rebuild post_logout_redirect_uri from the trusted redirect origin (FIX-07)

handleLogout sent every postLogoutRedirectURI value that does not start
with "http" (including the documented default of "/") to a branch that
set postLogoutRedirectURI = "". BuildLogoutURL then omitted the
parameter entirely, so RP-initiated logout left users stranded on the
IdP logout page under the default config plus an end_session_endpoint.

Capture the origin of redirect_url before session.Clear wipes it. That
value was persisted at authentication-initiate time (R136) and already
accepted by the IdP as this deployment redirect_uri, so its scheme and
host are safe to reuse for post_logout_redirect_uri - unlike the
request Host / X-Forwarded-Host, which the browser controls.

When no trusted origin is available (pre-R136 session, or logout
without a completed login), the parameter is still omitted, matching
the existing safe fallback. An operator-configured absolute URL keeps
taking priority over the derived origin.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(logout): log provider revocation failures and bound the calls (FIX-33)

handleLogout makes two synchronous provider revocation round trips
(access token, refresh token) and discarded both errors with "_ =",
so a failing revocation endpoint left no trace, and each call used
context.Background() with no deadline of its own, so a slow or
unreachable provider could hold the logout redirect open with no
bound of its own.

RevokeTokenWithProvider now derives its request context from a
3-second timeout (revocationRequestTimeout) instead of
context.Background(), and returns a sentinel
ErrRevocationEndpointNotConfigured for the expected "no revocation
endpoint" case. handleLogout logs any other error at error level and
still redirects the browser.

Document the logout revocation and post_logout_redirect_uri behavior
in docs/CONFIGURATION.md.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(auth-flow): stop logging CSRF/nonce on login initiation (FIX-29)

defaultInitiateAuthentication logged "Session saved before redirect.
CSRF: %s, Nonce: %s" and the full provider authorize URL (which also
carries state and nonce as query values) at Debug, despite the R153
commit claiming redaction of state in logs.

Drop the CSRF/nonce values from the first log line. The authorize-URL
log now goes through a new redactAuthorizeURLForLog, which calls the
existing redactCallbackURL (state) and additionally strips nonce and
code_challenge - redactCallbackURL alone was written for the callback
URL and does not know about those two authorize-URL-only values.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(auth-flow): drop Retry-After on the rate-limited callback 429 (FIX-32)

handleCallback sent Retry-After on the 429 for ErrRateLimitExceeded, but
clearOneTimeAuthState has already cleared csrf/nonce/code_verifier and
the authorization code has already been redeemed at the IdP by the
time that response is sent. A client that honors Retry-After and
retries the exact callback URL cannot succeed - it hits "CSRF token
missing in session" instead. Drop the header; the 429 status stays.

Update TestR179_CallbackRateLimitReturns429 (review_r179_regression_test.go)
to assert the corrected contract (no Retry-After) instead of the header
it previously required - the header it pinned is exactly what this fix
removes.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(replay): remove the dead JTI replay write path, make backchannel jti check atomic (FIX-17)

verifyTokenWithOpts wrote every verified JTI into the shared
shardedReplayCache, and its comment (R36) claimed this is "the store
jwt.Verify consults for genuine replay detection". Both were wrong:
jwt.Verify replay branch, the only reader of that cache, only runs
when called with skipReplayCheck=false, and the sole non-test
production caller (VerifyJWTSignatureAndClaims) always passes true.
The write was pure overhead - an exclusive replayCacheMu.Lock (via
initReplayCache) on every cache-miss verification, for a cache nothing
in production reads.

Remove the write-only block and correct the comment. jwt.Verify keeps
its replay branch intact rather than being removed too: ~15 existing
tests across several files call Verify directly with the replay check
enabled and assert on it, and rewriting that test surface is out of
this change scope - see the concern in the final report. A comment
in jwt.go now states the branch does not run on any production path.

Make the backchannel-logout jti replay check (OIDC Back-Channel Logout
1.0 section 2.5) atomic: it was a plain Get followed by a separate Set,
so two logout tokens sharing a jti could both observe "not yet
processed" and both proceed. The check now lives in
checkAndMarkLogoutJTIProcessed, serialized by a package-level mutex.

Correct four existing tests whose assertions pinned the removed
write-only behavior (review_r36_regression_test.go,
security_edge_cases_test.go TestJWTReplayAttack, main_test.go
TestAuthenticationFlowReplayDetection): each now asserts the cache is
NOT written by the production path, and where the test also wanted to
show jwt.Verify replay branch still works when called directly, it
now makes two direct Verify calls instead of relying on the removed
cross-path write.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test(replay): correct four more tests pinning the removed FIX-17 write path

TestConcurrentTokenValidation, TestJTIBlacklistBehavior,
TestSessionBasedTokenRevalidation and TestEdgeCasesWithDifferentTokenTypes
(main_test.go) asserted that VerifyToken writes the JTI into the
shared shardedReplayCache, and in two cases relied on that write
happening so a single direct jwt.Verify call would then detect a
replay. FIX-17 removed that write-only path.

Each test now asserts the cache is not written by VerifyToken, and
the two direct-replay-detection cases make two direct Verify calls
(first succeeds and records the JTI itself, second is rejected)
instead of relying on the removed cross-path write.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(jwt): remove the dead replay branch from Verify (FIX-17)

Address verifier review of FIX-17.

Major: the todo's chosen option was to remove the dead jwt.Verify replay
branch, but only its write-only shardedReplayCache.Set call had been
removed; the branch itself and its comment claiming it was "live code"
stayed. Removes the replay-check block and its skipReplayCheck parameter
from JWT.Verify outright, plus the now-unused shardedReplayCache/
replayCache globals and their init/cleanup/stats helpers (jwt.go), and
the startReplayCacheCleanup call that started their background sweep
(main.go). Migrates every non-test and test call site of Verify to the
new two-argument signature, and rewrites or removes the tests whose sole
subject was the removed branch or cache (main_test.go,
security_edge_cases_test.go, review_r179_regression_test.go,
review_r156_regression_test.go, review_r119_test.go, review_r142_test.go
[deleted], review_r126_test.go, review_r36_regression_test.go,
review_r131_test.go, review_r66_lenient_expiry_test.go, audience_test.go,
coverage_boost_final_test.go). New regression coverage:
TestJWTVerify_PerformsNoReplayDetection and
TestVerifyTokenWithOpts_ProductionPathUnaffectedByReplayRemoval
(review_fix17_replay_test.go) pin that Verify performs no jti tracking at
all, and that the production verify path is unaffected.

Minor: verifyOpts.skipReplayMarking is written (bearer_auth.go) but
nothing in verifyTokenWithOpts reads it — the JTI blacklist Set it used
to gate was already removed by an earlier FIX-17 pass without updating
the comments describing it. Rewrites the comments on the field, on
verifyTokenWithOpts, on the blacklist Get, and in bearer_auth.go's
package doc to stop describing a Set that no longer exists. The field
itself is left in place and flagged as dead code needing maintainer
approval to delete, per the dead-code hygiene rule. Also fixes the
repeated "VerifyJWTSignatureAndClaims, via VerifyJWTSignatureAndClaims"
phrase in the R36 correction comment.

Minor: the backchannel-logout jti check (logout.go) uses a process-wide
mutex around Get-then-Set, not an atomic SetIfAbsent, so it is atomic
only within one process, not across Traefik replicas sharing a
Redis-backed sessionInvalidationCache. A real fix needs an atomic
primitive on the cache backend (e.g. Redis SET NX); backends.CacheBackend
has none, and adding one touches many files across internal/cache/
backends owned by unrelated work (FIX-20), which is out of this fix's
scope. Rewrites the backchannelLogoutJTIMu and
checkAndMarkLogoutJTIProcessed comments to state the single-process-only
guarantee explicitly, rather than implying full atomicity.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* docs(logout): correct revocation timing and redirect-uri claims (FIX-33)

Address verifier review of FIX-33.

The Logout Behavior section overstated and misstated logout timing and
redirect behavior. Item 2 said the 3-second revocation timeout means a
slow provider cannot delay the redirect, but the two revocation calls
(access and refresh token) run one after the other, so together they can
delay it by up to about 6 seconds. Items 3-4 gave 'a logout request with
no completed login' as the example of a missing redirect origin, but
that case has no ID token and never reaches the oidcEndSessionURL branch
at all; the real missing-origin case is a session created before R136
started recording the redirect origin. The section also omitted that an
absolute postLogoutRedirectURI is sent unchanged. Rewrites items 2-4 to
state the actual timing and the three real conditions for the
end-session redirect, its redirect_uri handling, and when the parameter
is omitted. Removes the semicolon and the em dash per
simplified-technical-english.md.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test(logout): make the FIX-07 redirect-origin regression table-driven (FIX-07)

Address verifier review of FIX-07.

The regression test set postLogoutRedirectURI to "", which helpers.go
sends through a separate case postLogoutRedirectURI == "" branch, not
the default: branch production actually runs (main.go turns an unset
config into the documented default '/', which goes through default:).
The old test's comment called "" the documented default, which it is
not. Deleting the trustedOrigin rebuild in default: would have kept the
old test green.

Makes the test table-driven with three cases: the production default
'/', a relative '/bye', and the pre-existing '' case, all wanting
https://app.example.com/ or https://app.example.com/bye. Verified with a
scratch mutation of the default: branch (trustedOrigin rebuild removed,
reverted before this commit): the old single-case '' test still passed,
the new '/' and '/bye' subtests failed as expected. Corrects the comment
that called '' the documented default.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(pool): remove racy nil pre-check, move test reset helper (FIX-39)

GetTransportPool read globalTransportPool outside transportPoolOnce,
racing the write inside Once.Do when two goroutines called it for the
first time concurrently. Run the whole body inside Once.Do instead, so
every caller only observes the pointer after Once establishes
happens-before.

Move resetGlobalTransportPoolForTest into a new export_test.go file so
the test-only helper no longer compiles into the plugin package that
imports internal/pool. Update TestCreateHTTPClient_Fallback to exhaust
the real singleton in place (mutate its fields) instead of swapping in
a hand-built *TransportPool, since Once.Do now always builds its own
pool after a reset and would overwrite a manually assigned one.

Regression test TestGetTransportPool_ConcurrentFirstCall pins the race:
it fails under -race at head (WARNING: DATA RACE between the write in
GetTransportPool.func1 and the read at the removed pre-check) and
passes after the fix.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(config): add perSourceLoginRateLimit, clientAssertionKeyPath to configToMap (FIX-40)

configToMap is the single field/redaction list MarshalJSON and
MarshalYAML share (R150), meant to stop the marshalled config from
silently dropping fields. It still dropped two json-tagged Config
fields: perSourceLoginRateLimit (added in the same changeset) and
clientAssertionKeyPath. Neither is a secret, so this reintroduced the
exact drift R150 set out to eliminate.

Add both fields to configToMap. clientAssertionKeyPath is a filesystem
path, not the key content, so it needs no redaction (the content field
clientAssertionPrivateKey is already REDACTED).

TestConfigToMap_IncludesAllJSONFields reflects over every json-tagged
Config field and asserts it is a configToMap key. It fails at head
with exactly the two missing fields and passes after the fix.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test(makefile): run make test under -race (FIX-21)

Several regression pins (R44 TestSessionDataRedirectCountConcurrency,
R111 TestSessionAccessors_ConcurrentAccess, R77
TestSessionPool_ReturnToPool_ExactlyOnce) only fail when the old bug
they pin is reintroduced AND the race detector is on. make test ran
plain go test with no -race, so a regression in any of them would ship
silently. docs/TESTING.md already says to always run with -race.

Add -race to the Makefile test target.

Verified this session: reverting the R77 CAS in returnToPoolSafely
(and the inUse field back to plain bool, matching the pre-R77 shape)
back to a temporary local build, `go test -run
TestSessionPool_ReturnToPool_ExactlyOnce` passes without -race and
fails with -race:

    WARNING: DATA RACE
    Read at ... session.go:1784 (returnToPoolSafely)
    Previous write at ... session.go:1947 (Reset, called from the
    second concurrent returnToPoolSafely)
    --- FAIL: TestSessionPool_ReturnToPool_ExactlyOnce
        testing.go:1865: race detected during execution of test

The revert was local-only and is not part of this commit. Also
confirmed the shared CI workflow (go-pr.yaml@main in
lukaszraczylo/shared-actions, used by .github/workflows/pr.yaml) already
runs `go test -race -coverprofile=... -covermode=atomic ./...`, so CI
was not the gap.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test(session): pin R104 no-reject-on-decompressed via the real read path (FIX-08)

TestValidateChunkingEfficiency_NoRejectOnDecompressed called
cm.validateChunkingEfficiency(big, config) as a bare statement and
asserted nothing. Go lets a statement call drop a return value, so the
test compiled and passed both before and after the R104 fix -
validateChunkingEfficiency changed from returning an error to
returning nothing in the same changeset, and a bare call compiles
either way. The test pinned nothing.

Rewrite it to drive the actual read path: build a JWT-shaped fixture
whose decompressed length exceeds MaxChunks*MaxChunkSize, gzip+base64
it the way a stored compressed cookie is shaped, and call
ChunkManager.GetToken(compressed=true, ...) - the same entrypoint
session.go uses. Assert the token reassembles unchanged with no error.

Verified this session with a temporary, uncommitted local revert of
validateChunkingEfficiency and its validateToken call site to the
pre-R104 base f728f61 shape (hard error on expectedChunks >
MaxChunks): the rewritten test fails there -

    review_r104_test.go:350: GetToken rejected a large
    legitimately-compressed token: access token would require 51
    chunks (max: 50)
    --- FAIL: TestValidateChunkingEfficiency_NoRejectOnDecompressed

and passes again once session_chunk_manager.go is restored to head.
The revert was local-only and is not part of this commit.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(ratelimit): key PerSourceLoginRateLimit on RemoteAddr, not XFF (FIX-11)

sourceIP() preferred the first X-Forwarded-For value, and
isInternalSource then trusted that attacker-controlled value as the
basis for internal classification. An external attacker sending
X-Forwarded-For: 127.0.0.1 (or any RFC 1918 address) was classified
internal and never throttled, making PerSourceLoginRateLimit a no-op
against exactly the attacker it exists to stop. Rotating arbitrary XFF
values also let an attacker dodge the per-source counter and grow the
entries map, or spoof a victim IP to exhaust that IPs budget.

clientIPForBearer (bearer_auth.go) already deliberately ignores XFF
for the same reason - a second mechanism doing the opposite of the
solved one.

Derive sourceIP from RemoteAddr only. No new config: the feature is
opt-in (default 0/off) and this restores the trust boundary it should
have shipped with.

Two existing tests relied on the old XFF-as-source behavior to
simulate distinct/internal sources and are updated to use RemoteAddr
instead, matching the corrected contract: TestR185_InternalSourceNeverThrottled
(review_r185_regression_test.go) and
TestR185_PerSourceLimiterSweepEvictsIdle (review_r213_test.go).

New regression tests (per_source_ratelimit_test.go):
TestPerSourceRateLimit_XFFSpoofDoesNotBypassThrottle drives the full
ServeHTTP callback path with an external RemoteAddr and a spoofed
X-Forwarded-For: 127.0.0.1, and TestSourceIP_IgnoresXForwardedFor pins
sourceIP() directly. Both fail at head:

    per_source_ratelimit_test.go:56: external source spoofing
    X-Forwarded-For: 127.0.0.1 was never throttled
    per_source_ratelimit_test.go:70: sourceIP = "127.0.0.1", want
    RemoteAddr-derived "203.0.113.7"

and pass after the fix.

docs/CONFIGURATION.md and README.md perSourceLoginRateLimit rows now
state the RemoteAddr-only keying.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(http): stop sharing a cookie jar across the pooled token client (FIX-12)

R70 made CreatePooledHTTPClient honor config.UseCookieJar.
TokenHTTPClientConfig and OIDCProviderHTTPClientConfig both set
UseCookieJar: true, and main.go builds one pooled tokenHTTPClient per
plugin instance from TokenHTTPClientConfig, shared by every users
token/refresh exchange. An IdP Set-Cookie on user As exchange response
was stored in that one jar and replayed on user Bs next token request
to the same host - cross-user state confusion at the IdP, with no
config change on upgrade.

Set UseCookieJar to false (the DefaultHTTPClientConfig default) in
both config constructors. Token/refresh calls are stateless
back-channel requests; the nil-client fallback in exchangeTokens
(helpers.go) already builds its own fresh jar per call, which stays
correct and is untouched. CreatePooledHTTPClients own UseCookieJar
honoring (http_client_pool.go) is unchanged and still covers any
future caller that legitimately needs a jar.

TestPooledTokenClient_DoesNotShareCookieJarAcrossRequests
(http_client_jar_test.go) drives CreatePooledHTTPClient(TokenHTTPClientConfig())
against a test IdP that sets a cookie on request 1 and asserts request
2 does not carry it. It fails at head:

    http_client_jar_test.go:31: request 2 carried leaked cookie
    idp_sess=alice from an earlier request

and passes after the fix. Two existing assertions that expected the
old (leaky) behavior are updated to match the corrected contract:
TestOIDCProviderHTTPClientConfigUnit and TestCreateTokenClientUnit
(http_client_factory_unit_test.go).

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test: add newTestOIDC builder, move stubIntrospectionCache, migrate logout round files (FIX-41)

136 added root test files (71 hand-building TraefikOidc literals, 112
in total) make any change to TraefikOidc required fields a many-file
patch. Round files also depend on each others locally declared
helpers: review_r149_test.go used stubIntrospectionCache, declared in
review_r126_test.go, so deleting or renaming either file would break
the other silently at compile time.

Add newTestOIDC(t, opts...) in a new shared newtestoidc_test.go: a
builder with the common ServeHTTP-ready defaults (next handler, error
logger, closed initComplete, a real session manager, both startup
barriers past init, a plausible issuer/callback/client), customized
per test via functional options that set unexported fields directly
(same-package test file).

Move stubIntrospectionCache from review_r126_test.go into the same
shared file. review_r143_test.go and review_r149_test.go, which also
use it, need no change - Go resolves package-level identifiers by
package, not file, so moving it to a shared file removes the
round-to-round coupling without touching either caller.

Migrate the logout round files onto the builder (5 tests):
review_r55_logout_blacklist_test.go, review_r73_test.go, and
review_r87_test.go.

Verified this session that migration did not defang any of these
pins: for 3 of the 5, a temporary uncommitted local revert of the
exact behavior each test regresses made the migrated test fail, then
was restored. All 5 migrated tests, and the full root package (go
test -race), pass at head with the reverts removed.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(http): correct stale cookie-jar comment on CreatePooledHTTPClient (FIX-12)

Reword the comment above the UseCookieJar branch. It described the
jar-less pooled token/OIDC clients as a bug to fix, contradicting the
FIX-12 comments already in http_client_factory.go and inviting a
reintroduction of the cross-user jar R70 introduced. State instead
that TokenHTTPClientConfig and OIDCProviderHTTPClientConfig
deliberately leave UseCookieJar false because a pooled client is
shared across users.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* docs(ratelimit): document the shared-proxy-IP tradeoff for perSourceLoginRateLimit

perSourceLoginRateLimit keys solely on RemoteAddr (per_source_ratelimit.go).
Behind a load balancer or CDN that is the proxy address, not the real
client: a private proxy address is exempt from throttling entirely, and
a public proxy address puts every client into one shared bucket. State
this in both docs rows, matching the tradeoff already documented in
clientIPForBearer (bearer_auth.go).

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test: eliminate remaining cross-round test-helper references (FIX-41)

The prior FIX-41 pass moved only stubIntrospectionCache; 14 references
into 10 other helpers survived, 3 of them into the migrated logout
round files (review_r172_regression_test.go used newR87LogoutHarness
and r87BaseClaims from review_r87_test.go; review_r103_test.go used
mustTemplate from review_r73_test.go). Deleting or renaming any of
those round files would still have broken an unrelated file.

Move every cross-referenced helper into a shared _test.go file, by
topic: jwt_test_helpers_test.go (writeJWKS, signRSAJWTForTest,
makeJWTForTest), cache_test_helpers_test.go (NewMemoryBackendForTest,
mapCache, serializingCache), config_test_helpers_test.go
(r134ValidConfig), plugin_test_helpers_test.go (newR154TestPlugin),
logout_test_helpers_test.go (r87LogoutHarness, newR87LogoutHarness,
r87BaseClaims), and mustTemplate into the existing newtestoidc_test.go.
A go/ast analyzer built for this fix (File.Unresolved checked against
top-level decls of every other review_rNN*_test.go file) now reports 0
cross-round references, down from 20.

Also migrate TestBackchannelLogout_RejectsReplayedJTI
(review_r73_test.go) onto the newTestOIDC builder, the one migration
the prior pass missed among the three logout round files. Verified the
migrated test still catches the regression: with the jti-replay check
in logout.go temporarily disabled (reverted before this commit), it
fails with "review_r73_test.go:109: replayed logout token should be
rejected (400), got 200".

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(client-assertion): pin and document the RSA<2048 private_key_jwt rejection (FIX-42)

validateAlgKeyMatch already rejects an RS*/PS* private_key_jwt signing
key under 2048 bits (RFC 7518 3.3), added by 8640451 with no commit
mention and no CHANGELOG entry. Keep the rejection as-is.

Wrap the error with a new ErrRSAKeyTooSmall sentinel so callers can
match it with errors.Is instead of parsing the message, add a pin
test that generates a 1024-bit and a 2048-bit key and asserts the
reject/accept boundary, and document the minimum in
docs/CONFIGURATION.md and CHANGELOG.md.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(main): name and document dropped http endpoints under https providers (FIX-26)

validateDiscoveredEndpoint already refuses a discovered http:// endpoint
under an https providerURL (R146). Keep that pin; do not add an
opt-out flag.

Wrap the rejection in a named ErrDiscoveredEndpointSchemeDowngrade
sentinel and have updateMetadataEndpoints sanitize log an extra
SECURITY-tagged line, naming the endpoint, the dropped URL, and the
absence of an override, whenever the dropped endpoint is token,
jwks_uri, or authorization — the three a login cannot function
without. The generic per-endpoint log line stays unchanged.

Add a regression test pinning the new log line and a negative test
confirming accepted https endpoints stay silent. Document the
behaviour in docs/CONFIGURATION.md, README.md, and CHANGELOG.md.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* docs(changelog): record the R96/R102/R105/R126 auth relaxations (FIX-25)

security_edge_cases_test.go:459 (+bearer_auth_test.go:225, custom_claims_test.go:158,
main_test.go:2325) pin four claim-validation relaxations that shipped
in 8640451 with no commit-body or CHANGELOG mention: optional iat
(R126), a stringified numeric bearer sub (R102), a malformed
groups/roles claim treated as empty (R96), and stringified numeric
items inside a groups/roles array (R105).

Each relaxation is intentional, matches a production change, and
already has a passing regression test (re-run this session to
confirm: TestMissingClaims/Missing_IssuedAt_is_optional,
TestResolveBearerIdentifier, TestCustomClaimNames_MalformedRoleClaim,
TestCustomClaimNames_MalformedGroupClaim,
TestCustomClaimNames_NonStringInRoleArray,
TestCustomClaimNames_NonStringInGroupArray). Keep all four as-is; no
code change. Record each in CHANGELOG.md so a reviewer of the
squashed commit can see the intent.

Also record the blacklist Redis namespace move (token: -> blacklist:,
FIX-16, implemented elsewhere) and its one-release legacy read, since
CHANGELOG.md is otherwise silent on it too.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(main): restrict SECURITY scheme-downgrade log to no-override endpoints (FIX-26)

sanitize logged the SECURITY line for every dropped endpoint, not only
jwks_uri, authorization and token as docs/CHANGELOG/README say. Revocation,
end_session and introspection have a config override (revocationURL,
oidcEndSessionURL, introspectionURL) that replaces the endpoint right after
sanitize runs, so the "no override; requests will fail" wording was false
for those three.

Add discoveredEndpointHasNoOverride and named constants for the three
endpoints with no config source, and gate the SECURITY line on both the
scheme-downgrade error and endpoint name. Add negative tests pinning that
end_session/revocation/introspection/registration keep only the generic
line, and that a config override still replaces a dropped endpoint. Add one
sentence to docs/CONFIGURATION.md naming which endpoints have an override.
Correct the fix26 test file header comment: the pre-existing ERROR line
already named the scheme-downgrade reason; the new SECURITY line only adds
a distinct tag and the no-override statement.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* docs(changelog): scope the iat relaxation, drop the unbuilt FIX-16 bullet (FIX-25)

The iat bullet overstated the R126 relaxation: it is optional in
jwt.Verify only. Bearer-token auth still rejects a token with no iat
(enforceIatAge, "missing iat claim"), because maxTokenAgeSeconds always
applies and 0 falls back to a 24h default. The lenient-audience
accessTokenUnexpired path also still requires iat on this branch. State
that scope explicitly instead of implying the check is gone everywhere.

Reword the heading to match bullet 4: a numeric groups/roles array item
was silently dropped before R105, not rejected, so "previously-rejected"
alone mis-described it.

Remove the Blacklist Redis-namespace-move bullet: it describes
universal_cache.go changes from commit 4eb876b on fix/d1-universal-cache,
which this branch does not contain. Re-add it when that branch merges.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(yaegi): replace errors.As on interpreted *HTTPError in RetryExecutor

errors.As(err, &target) panics under yaegi v0.16.1 whenever the target
pointed-to type is interpreted. *HTTPError is declared in this plugin, so
RetryExecutor.isRetryableError panicked on the default-on token-exchange/
refresh retry path regardless of the concrete error type reaching it.

Add asHTTPError, a manual errors.Unwrap walk plus type assertions (both
yaegi-safe), and use it in place of both errors.As calls in
isRetryableError. Native classification stays unchanged: the walk mirrors
errors.As exactly for the fmt.Errorf(%w) chains callers actually wrap.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(yaegi): replace errors.As on interpreted HTTPError/OIDCError in internal/recovery

Same yaegi v0.16.1 hazard as error_recovery.go's RetryExecutor: this
package's own *HTTPError and *OIDCError types are interpreted whenever
the traefikoidc plugin loads under yaegi (it imports internal/recovery
transitively through internal/utils/logger_wrapper.go), so
RetryExecutor.isRetryableError's two errors.As calls here panic too.

Add asHTTPError and asOIDCError, the same manual errors.Unwrap-walk
pattern used in the top-level package, and use them in place of
errors.As. Native classification is unchanged (TestR175 stays green).

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(yaegi): drop errors.As from introspection error classification

token_validation_rs.go classified validateOpaqueToken's error with
errors.As(err, &httpErr): *HTTPError is interpreted under yaegi v0.16.1,
so this panicked on every opaque-token session-path classification.

A plain type assertion is yaegi-safe but only if the value arrives
unwrapped, and an interpreted *HTTPError wrapped with fmt.Errorf(%w)
cannot be recovered by a manual errors.Unwrap walk under yaegi either
(verified this session against the pinned interpreter). So instead of
adding an unwrap-walk helper here, fix the producer:
validateOpaqueToken (token_introspection.go) now returns
introspectToken's *HTTPError unwrapped instead of wrapping it with
"token introspection failed: %w", matching the existing yaegi-safe
pattern (isTerminalClientError, isNeverSentError). The call site
switches to a plain err.(*HTTPError) assertion.

Adds native regression coverage for the unwrapped return and for the
5xx classification case (401/429 were already covered).

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test(yaegi): add NEW-01 regression checks to yaegicheck

Extend cmd/yaegicheck/main.go, the program make yaegi-validate runs
under the interpreter, with checks that drive every site fixed by
NEW-01: RetryExecutor.ExecuteWithContext (top-level package) with an
HTTPError 500 (retried), an HTTPError 400 (not retried), and a plain
error (no panic); the same pair for internal/recovery's RetryExecutor,
plus its OIDCError retryable/terminal classification; and a full
plugin instance driving RFC 7662 introspection end to end through the
bearer path for a 4xx and a 5xx response.

Confirmed these checks panic (errors.As at error_recovery.go:723) when
run against the pre-fix commit, and pass on the fixed worktree.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* refactor: remove symbols left unused by the review fixes

staticcheck (U1000) flagged defaultBlacklistDuration in cache_manager.go and isLastInstanceNow in singleton_resources.go. The FIX-35 lifecycle change routes every last-instance stop through stopIfLastInstance, and the blacklist TTL no longer reads the constant. Comments that named the removed function now describe the check they compare against.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test(yaegi): fold the SSE flush check into yaegicheck

Add checkSSEFlushReachesNext to cmd/yaegicheck. It sends an SSE request through the excluded-URL bypass under yaegi and asserts that http.NewResponseController(w).Flush() succeeds on the writer next receives (FIX-06). Remove cmd/yaegiflushcheck, a nested module with its own go.mod (go 1.27.1) and a yaegi dependency that ran the same check. make yaegi-validate now covers it.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* docs(changelog): record the blacklist namespace move, correct the iat scope

Add the FIX-16 entry: the blacklist cache writes under the blacklist: Redis prefix, and for one release it reads a legacy token: entry only when the stored value is boolean true. Correct the iat bullet: accessTokenUnexpired now calls verifyTimeClaims, so the lenient-audience path treats iat as optional, the same as jwt.Verify (FIX-27).

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test(middleware): pin FIX-02 default-deny for genuine OPTIONS preflight

Regression test for the maintainer decision on FIX-02: the released
behavior required auth for every OPTIONS request by default. Confirms
red on base code -- shouldBypassAuth currently bypasses any genuine
CORS preflight (Origin + Access-Control-Request-Method) unconditionally,
so this test currently fails with the backend reached (status=204).

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* feat(settings): add AllowUnauthenticatedPreflight config option

New Config.AllowUnauthenticatedPreflight bool (json tag
allowUnauthenticatedPreflight, default false), wired through to
TraefikOidc.allowUnauthenticatedPreflight (types.go, main.go) and into
configToMap (config_marshalling.go) so it round-trips through
MarshalJSON/MarshalYAML like every other Config field. Naming and
omitempty match the sibling AllowPrivateIPAddresses option. No
behavior change yet -- middleware.go still needs to read the field
(next commit).

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(middleware): gate OPTIONS bypass behind AllowUnauthenticatedPreflight

Maintainer decision for FIX-02: restore the released behavior where
every OPTIONS request needs authentication by default. shouldBypassAuth
now only treats a genuine CORS preflight (Origin +
Access-Control-Request-Method) as an auth bypass when
t.allowUnauthenticatedPreflight is true; with the flag at its default
(false), OPTIONS goes through the normal auth pipeline like any other
method. The optionsPreflightWriter body-discard hardening (forged
preflights cannot read a protected body even when the flag is on)
still applies unchanged inside the bypassReasonOptions case, since
shouldBypassAuth only returns that reason when the flag permits it.

Updates the FIX-02 tests that assumed the bypass was unconditionally
on (fix02_options_bypass_test.go, review_r124_test.go
TestShouldBypassAuth_PassesOptions) to set
allowUnauthenticatedPreflight: true, so they keep exercising the
Origin+Access-Control-Request-Method gate rather than being short-
circuited by the new flag gate. Adds
fix02b_allow_unauthenticated_preflight_test.go pinning the maintainer
decision directly: default config requires auth for a genuine
preflight (red on prior commit); with the flag on, a genuine preflight
still bypasses with its body discarded; with the flag on, a bare
OPTIONS still requires auth.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* docs: document allowUnauthenticatedPreflight option

Adds the new Config.AllowUnauthenticatedPreflight option to the
docs/CONFIGURATION.md security-options table and the README.md option
table, next to its sibling allowPrivateIPAddresses. .traefik.yml is not
touched: it lists only complex opt-in feature blocks (bearer-auth,
Redis) as commented examples, not the plain security-relaxing bools
like allowPrivateIPAddresses -- allowUnauthenticatedPreflight follows
that same precedent.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* style(test): fix wrong test name in FIX-02 cross-reference comment

TestShouldBypassAuth_PassesOptions referenced a
TestShouldBypassAuth_DefaultDoesNotBypassOptions that does not exist;
point it at the real default-off regression test,
TestServeHTTP_DefaultConfigGenuinePreflightRequiresAuth in
fix02b_allow_unauthenticated_preflight_test.go.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(refresh): cancel refresh context on Shutdown so it returns promptly (FIX-36)

Derive each refresh operation's timeout context in executeRefreshAsync from
a coordinator-owned context (rc.ctx) instead of context.WithTimeout(
context.Background(), RefreshTimeout). Shutdown now cancels rc.ctx before
wg.Wait(), so it no longer blocks for up to RefreshTimeout (or the
refreshFunc's own natural completion) per in-flight refresh. A waiter
blocked in CoordinateRefresh on an aborted operation gets an error, not a
hang. RefreshTimeout still caps a refresh that is not aborted by Shutdown.

The refreshFunc call itself runs in an untracked inner goroutine
(executeRefreshAsync) that cannot be aborted given its
func() (*TokenResponse, error) signature; it keeps running past Shutdown
until it returns naturally (in production, until its own HTTP client
timeout). This is documented in code comments on Shutdown and
executeRefreshAsync.

Corrects three comments that described the old contract: the goroutine-
launch comment in CoordinateRefresh, the timeout-context comment in
executeRefreshAsync, and the Shutdown comment — all previously said
Shutdown deliberately does not cancel and must wait for a genuine in-flight
refresh to finish, which is now false.

Rewrites TestRefreshCoordinatorShutdownWaitsForInflight (review_r63) and
TestRefreshCoordinator_ShutdownWaitsForInFlight (review_r154), which pinned
the old "Shutdown blocks until the refresh finishes" contract this commit
intentionally reverses; they now assert the prompt-return contract instead.

Adds TestFix36_ShutdownReturnsPromptlyDuringInFlightRefresh: starts a
refresh whose refreshFunc blocks 3s, calls Shutdown, and asserts Shutdown
returns in under 1s and the waiter gets an error. Fails on pre-fix code at
refresh_coordinator_test.go:871 ("Shutdown did not return within 1s while a
refresh was in flight"); green under go test -race.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test(refresh): pin wg-tracking of the aborted refresh goroutine (FIX-36 review)

TestRefreshCoordinator_ShutdownWaitsForInFlight (review_r154) and
TestRefreshCoordinatorShutdownReleasesWaiterOnInflight (review_r63) only
checked that Shutdown returns promptly and the waiter gets an error. Both
checks also pass when the executeRefreshAsync goroutine is not tracked by
rc.wg, so an untracked-goroutine regression would go unnoticed, and the
R154 test comment claimed wg coverage the test did not assert.

Add an assertion on rc.circuitBreaker.failures right after Shutdown
returns: executeRefreshAsync calls RecordFailure() before it returns, and
the goroutine that calls it is (correctly) covered by wg.Wait(), so the
count must already be 1 by the time Shutdown, and therefore wg.Wait,
returns.

Verified with a local mutation (not committed): replacing
`defer rc.wg.Done()` inside the spawned goroutine with an immediate
`rc.wg.Done()` before `go func(){...}()` made the new assertion fail
20/20 runs for the R154 test and 12/20 for the R63 test under
-race -count=20; both pass 20/20 on the real (tracked) code.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(refresh): skip refreshFunc when rc.ctx is already canceled

executeRefreshAsync spawns an inner goroutine that calls refreshFunc
unconditionally, even when rc.ctx (and therefore refreshCtx) is already
canceled before the goroutine starts. The outer select then always takes
the refreshCtx.Done() branch and discards whatever refreshFunc returned,
but refreshFunc is the IdP refresh-token grant: calling it anyway still
spends a request against a (possibly rotating, one-time-use) refresh
token whose result nobody reads.

Check rc.ctx.Err() as the first statement in the inner goroutine and
return without calling refreshFunc when it is already canceled.

Adds TestFix36_ExecuteRefreshAsyncSkipsRefreshFuncWhenAlreadyCanceled:
cancels rc.ctx directly (isolating this from the stopChan-reject path),
then asserts refreshFunc is never called and the waiter gets an error.
Fails on pre-fix code at refresh_coordinator_test.go:926 ("refreshFunc
must not be called when rc.ctx is already canceled before the refresh
starts"); green under go test -race -count=20.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* docs(refresh): correct stale nolint comment on the tracked refresh goroutine

The nolint reason still said the refresh "intentionally uses a background
context", describing the pre-FIX-36 behaviour. Since FIX-36,
executeRefreshAsync derives its timeout context from rc.ctx (canceled by
Shutdown), capped by RefreshTimeout, not context.Background().

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* feat(cache/redis): add atomic SetNX check-and-set to RedisBackend (FIX-17)

RedisBackend gets SetNX(ctx, key, value, ttl) (bool, error): one Redis
SET key value NX PX <ttl-ms> command instead of a separate GET then
SET, so two callers racing the same key can never both observe
"absent". Backs the UniversalCache.SetIfAbsent primitive the next
commit adds, which the backchannel-logout jti replay check
(logout.go) needs to be atomic across Traefik replicas, not just
within one process (FIX-17, R36 correction).

A nil bulk-string reply (NX condition failed, key already exists) is
reported as (false, nil), not an error: it is a valid protocol
outcome, not a backend failure, so executeWithRetry must not retry it
or surface it as err.

Regression test (miniredis-backed): a second SetNX on an already-set
key does not overwrite the first value or its TTL, and exactly one of
20 concurrent SetNX calls on the same key wins under -race.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* feat(cache): add UniversalCache.SetIfAbsent atomic check-and-set (FIX-17)

SetIfAbsent(key, value, ttl) (bool, error) stores value only if key is
not already present, replacing the TOCTOU-prone separate Get then Set
with one atomic operation (FIX-17, R36 correction).

With no distributed backend, the presence check and the insert happen
inside a single c.mu critical section (setLocalLocked, extracted from
setLocal so SetIfAbsent does not have to re-enter the lock setLocal
already holds). With a backend that implements the optional
backendSetNXer interface (RedisBackend.SetNX, previous commit),
that call alone decides the outcome, so the check is atomic across
every replica sharing that backend too. CacheBackend itself is not
widened to require SetNX: every other implementer and test double
would need a method only this caller needs, so SetIfAbsent reaches it
through a type assertion instead. A successful backend claim is then
mirrored into the local cache as a best-effort read-through.

Exposed to callers as AtomicSetIfAbsentCache (types.go), an optional
capability a CacheInterface value can satisfy, for the same reason:
CacheInterface itself is not widened, since most of its many test
doubles across the suite have no need for the atomic primitive.
CacheInterfaceWrapper (the concrete type sessionInvalidationCache
actually is at runtime) implements it by delegating to
UniversalCache.SetIfAbsent.

Regression tests: SetIfAbsent single-threaded claim/no-overwrite
semantics; exactly one of 20 concurrent same-key calls wins, both with
no backend and with a real Redis backend (miniredis); and
CacheInterfaceWrapper satisfies AtomicSetIfAbsentCache. All green
under -race.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(logout): make backchannel-logout jti check atomic via SetIfAbsent (FIX-17)

checkAndMarkLogoutJTIProcessed now type-asserts sessionInvalidationCache
to AtomicSetIfAbsentCache and, when it is available, uses SetIfAbsent
as the sole check: no separate Get then Set, and no
backchannelLogoutJTIMu. CacheInterfaceWrapper (what
sessionInvalidationCache actually is at runtime) satisfies the
interface, so this is the path production traffic takes, and it is
atomic across Traefik replicas sharing a Redis-backed cache, not just
within one process (FIX-17, R36 correction: the prior commit on this
line only made the check-and-set atomic process-locally).

backchannelLogoutJTIMu is kept as a fallback for a CacheInterface
implementation that does not provide the atomic primitive, guarding
only that case now. A SetIfAbsent backend error falls through to the
same fallback rather than rejecting an otherwise-valid logout token
outright on a transient cache failure.

Regression test: 20 concurrent backchannel-logout submissions of the
same valid logout token, through the production validateLogoutToken
path, must yield exactly one acceptance AND must reach it through
SetIfAbsent alone (asserted via call counts on an instrumented cache
double) rather than the legacy Get/Set fallback, so the test would
catch a regression to the old path even where the outcome happens to
still be correct under backchannelLogoutJTIMu. Green under
-race -count=5.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(cache/resilience): forward SetNX through circuit-breaker and health-check wrappers

Round-2 verifier finding (major): UniversalCache.SetIfAbsent reaches a
Redis backend through the optional backendSetNXer type assertion, but
neither CircuitBreakerBackend nor HealthCheckBackend implemented SetNX,
so wrapping Redis with either (docs/REDIS.md and the example configs
recommend both true in production) made the assertion fail and every
call silently fall back to the process-local-only path. Two replicas
sharing the same wrapped Redis backend both claimed the backchannel-
logout jti and Redis never saw the key.

Add SetNX passthrough to both wrappers: forward to the wrapped backend
when it implements SetNX (through the same circuit-breaker/health
accounting as every other operation), and report the new
backends.ErrSetNXUnsupported sentinel otherwise.

Pin with three regression tests driving two UniversalCache instances
(simulated replicas) over one miniredis-backed RedisBackend wrapped by
NewCircuitBreakerBackend, NewHealthCheckBackend, and the production
wiring order HealthCheck(CircuitBreaker(raw)). All three fail on
b433f42 (second replica also claims; redis keys=[]) and pass here.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(cache): reject SetIfAbsent when backend lacks SetNX, no silent local

Round-2 verifier finding (major, completes the previous commit):
UniversalCache.SetIfAbsent fell back to the local-only path for ANY
backend that failed the backendSetNXer type assertion, not only the
CircuitBreakerBackend/HealthCheckBackend case the previous commit
fixes at the source. Belt-and-suspenders: a distributed backend
attached to the cache now must expose SetNX (directly or through a
wrapper) or SetIfAbsent errors loudly with the new
errSetIfAbsentUnsupported sentinel, instead of quietly giving each
replica a process-local-only guarantee it never asked for.
checkAndMarkLogoutJTIProcessed already falls through to its
backchannelLogoutJTIMu-guarded Get+Set on any SetIfAbsent error, so no
logout.go behavior change is needed there beyond correcting its doc
comments to describe the corrected contract.

Pin with a fake backend that deliberately has no SetNX: two
UniversalCache instances (simulated replicas) sharing it must both
get the same sentinel error and neither may silently claim locally.
Fails on HEAD before this commit (no error returned); passes here.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test(cache): pin SetIfAbsent cross-replica atomicity with two instances

Round-2 verifier finding (minor): the existing Redis-backed SetIfAbsent
test drives 20 concurrent calls through a SINGLE UniversalCache
instance, so its own c.mu already serializes them to exactly one
winner even when the c.backend.(backendSetNXer) branch is mutated
dead — the test cannot tell "one process, one mutex" from "many
replicas, one Redis". Add a test using two separate UniversalCache
instances (simulated replicas) sharing one miniredis-backed
RedisBackend: the second instance must be rejected AND the key must
be present in the shared miniredis, which two independent local maps
cannot produce.

Verified this test (and the pre-existing one) both fail under the
verifiers mutation (backendSetNXer branch forced dead) once the
previous two commits are in place: SetIfAbsent now errors instead of
silently using the local-only path, so the mutation surfaces as
"unexpected error" rather than a quiet pass.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(cache/redis): make SetNX retry-safe when a reply is lost

Round-2 verifier finding (minor): SetNX ran SET key value NX PX inside
executeWithRetry, which blindly retries the whole operation on a
"connection"/"timeout"/"EOF" error by re-issuing the closure. That is
fine for Set (SETEX/PSETEX overwrite unconditionally, so a retry after
a lost reply just repeats the same write) but wrong for SET NX: if the
first SET NX reached Redis and applied, and only the reply was lost,
the retried SET NX sees the caller own write and reports
(false, nil) — "already claimed" — for what was actually a
first-ever claim. checkAndMarkLogoutJTIProcessed then rejected a
legitimate logout token (and every IdP redelivery) as a replay.

Add RedisConn.doTracked, reporting whether the command was already
written when it failed; Do becomes a thin wrapper over it. Give SetNX
its own retry loop: retry a failed connection acquisition (nothing
sent yet, safe), but once doTracked reports the command reached the
wire, stop and return the new backends.ErrSetNXAmbiguous sentinel
instead of guessing. checkAndMarkLogoutJTIProcessed accepts that
specific error outright rather than falling through to the
Get+Set fallback, which would see the same ambiguous write and
misreport the token as a replay.

Pin with a TCP proxy that forwards a SET NX to a real miniredis
instance but swallows its reply: RedisBackend.SetNX must report
(false, ErrSetNXAmbiguous), and the key must actually exist in
miniredis (proving the old (false, nil) was a false negative on a
first-ever claim). Also pin checkAndMarkLogoutJTIProcessed accepting
an ambiguous SetIfAbsent result without consulting Get. Both fail on
the pre-fix code (redis.go:161 gets claimed=false err=nil;
logout_test.go:89 gets a spurious replay error) and pass here.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* docs(changelog): record the allowUnauthenticatedPreflight option (FIX-02)

OPTIONS requests need authentication by default again. The new allowUnauthenticatedPreflight option lets a genuine CORS preflight bypass authentication, with its response body discarded.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test(yaegi): pin SetIfAbsent claim semantics under yaegi (FIX-17)

Add checkSetIfAbsentUnderYaegi to cmd/yaegicheck. It claims one key twice through UniversalCache.SetIfAbsent in local-only mode and through a backend that implements SetNX, and expects exactly one winner each time. A backend without SetNX must return an error instead of a local claim. This covers the optional-interface assertion in SetIfAbsent under the interpreter.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(cache/redis): check sent before ctx.Err() in SetNX

RedisBackend.SetNX checked ctx.Err() before the sent check, so a lost
SET NX reply under the real 500ms SetIfAbsent context almost always
surfaced as context.DeadlineExceeded instead of ErrSetNXAmbiguous.
checkAndMarkLogoutJTIProcessed only special-cases the ambiguous
sentinel, so it fell through to the Get+Set fallback and rejected a
first-ever, never-before-seen logout token as a replay.

Move the sent check ahead of ctx.Err() so ErrSetNXAmbiguous is
reported whenever the command reached the wire, regardless of ctx
state, and keep it returned unwrapped for == comparison under yaegi.

Add a regression test that drives UniversalCache.SetIfAbsent and
checkAndMarkLogoutJTIProcessed through miniredis behind a proxy that
drops the SET NX reply, using a deterministic pre-call delay to avoid
racing the real 500ms timing window.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test(main): cover AllowUnauthenticatedPreflight constructor wiring

FIX-02: main.go NewWithContext wires
Config.AllowUnauthenticatedPreflight into
TraefikOidc.allowUnauthenticatedPreflight, but every existing
middleware test builds *TraefikOidc as a struct literal and sets the
field directly, so deleting that wiring line failed no test.

Add a pair of tests that build the plugin through NewWithContext: one
with the flag enabled, asserting a genuine CORS preflight reaches next
and the response body is discarded; one with the default config,
asserting the same request is redirected into the login flow instead.
Confirmed with a mutation (temporarily removing the wiring line) that
the enabled case fails while the default case still passes, then
restored the line.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(refresh): drop unused nolint:gosec on tracked refresh goroutine

FIX-36: nolintlint (allow-unused: false) reports the //nolint:gosec
directive on the tracked refresh goroutine call as unused — gosec
never flagged this line, so the suppression served no purpose.

Remove the directive suffix and keep the explanatory comment, which
still documents why the goroutine detaches from the request ctx.

nolintlint is not in .golangci.yml enable list in this worktree, so
plain golangci-lint run ./... does not surface this finding either
before or after the change; verified with --enable nolintlint instead
that the report is gone and gosec genuinely does not fire on this
line. The plain run ./... command shows the same 6 pre-existing,
unrelated findings before and after (2x gosec G117 in
internal/dcrstorage, 2x gosec G710 in internal/testutil/servers,
1x gosec G124 in internal/testutil/suite.go, 1x unparam in
token_manager.go) — left untouched, out of scope.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* refactor(token): remove the dead verifyOpts parameter

FIX-17 removed the only reader of verifyOpts.skipReplayMarking, so golangci-lint (unparam) reported the opts parameter of verifyTokenWithOpts as unused. Remove the verifyOpts type, its dead field, its only write in buildPrincipalFromBearerToken and the parameter, and update the comments that described it. Behaviour does not change. The function keeps its name to avoid churn in the many comments that refer to it.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test(helpers): move round-file-declared cross-file JWT/GD test helpers into shared files

makeTestJWT (review_r92_test.go) was consumed by
access_token_unexpired_iat_optional_test.go and resetGdInstancesForTest
(review_r34_regression_test.go) was consumed by fix18_gd_lifecycle_test.go,
reintroducing the hidden cross-round-file dependency FIX-41 removed:
deleting or folding either round file would silently break its consumer.

Move makeTestJWT into jwt_test_helpers_test.go (alongside the other shared
JWT builders) and resetGdInstancesForTest into a new
gd_test_helpers_test.go, unchanged in behaviour.

Add TestRoundFilesDependOnlyOnSharedHelpers, a static AST-based regression
pin that parses every _test.go file and fails if any non-Test helper
declared in a review_rNN*_test.go round file is referenced from another
file, catching this class of fragility again.

Closes the remaining partial from FIX-41.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(middleware): drop Content-Length on implicit-200 preflight writes

optionsPreflightWriter only stripped a stale Content-Length inside its
own WriteHeader. A next handler that sets Content-Length and calls
Write with no explicit WriteHeader (the implicit-200 idiom) left the
real header in place while the body stayed discarded, so the client
saw a non-zero Content-Length with an empty body and treated the
preflight response as truncated.

Write now commits an implicit 200 through WriteHeader before
discarding the bytes, so Content-Length is stripped either way.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(middleware): repanic ErrAbortHandler, drop guessed post-next 500

ServeHTTP recovered http.ErrAbortHandler like any other panic and
returned normally, so net/http finished the response as if it were
complete: a reverse-proxied body truncated mid-copy (httputil panics
with this sentinel) reached the client as a clean 200 instead of an
aborted connection. Re-panic it first, before any logging or write,
so the outer net/http recovery aborts the connection the same way it
would with no plugin in front of it.

Separately: once t.next.ServeHTTP has been called it holds the real
ResponseWriter (FIX-06), not the tracking wrapper, so wroteHeader can
no longer prove nothing was sent. The old code still guessed and sent
WriteHeader(500) unconditionally, which is a superfluous call net/http
logs whenever next already committed a response. The recovery now
logs and returns without writing once next has been reached, instead
of guessing. Documented trade-off: a panic in next before it writes
anything no longer gets an explicit 500 from this middleware.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(main): gate the SECURITY log on whether an override is set

discoveredEndpointHasNoOverride was static: it always answered false
for revocation, end_session and introspection, regardless of whether
the operator had actually configured revocationURL/oidcEndSessionURL/
introspectionURL. With no override set, a scheme-downgrade drop of one
of these three is exactly as terminal as a drop of jwks_uri,
authorization or token, yet it never logged the SECURITY line, and the
comment plus docs/CONFIGURATION.md claimed nothing fails for them.

discoveredEndpointHasNoOverride now checks the matching config field
and fires the SECURITY line whenever it is empty. registration is
unaffected: its override is read independently of this discovery
step. Corrects docs/CONFIGURATION.md to match.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(yaegicheck): fail NEW-01 introspection checks on recovered panic

checkNew01IntrospectionBearerStatus only failed when rw.Code == 0,
which httptest.NewRecorder never leaves (it starts at 200), so a
reintroduced errors.As panic on the bearer path -- recovered by
ServeHTTP as a 500 -- still printed PASS. Require the exact expected
status (503, bearerErrIntrospectionUnavailable) instead.

The bearer path also shares introspectToken with the SESSION path
(token_validation_rs.go, the NEW-01 fix site) but never reaches it, so
no check exercised the classification commit d7686c3 actually fixed.
Adds checkNew01OpaqueSessionIntrospectionClassification: builds an
authenticated cookie session holding an opaque access token via a
second SessionManager sharing cfgs encryption key and cookie
parameters (the plugins own session manager is an unexported field,
unreachable from this package, but the cookie codec key is a pure
function of those inputs), then drives it through ServeHTTP against a
5xx introspection response and requires the expected 302
re-authentication redirect.

Verified both checks fail under yaegi v0.16.1 with a temporarily
reintroduced errors.As at their respective sites (bearer_auth.go
buildPrincipalFromOpaqueIntrospection, token_validation_rs.go
validateStandardTokensRS), then reverted.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* ci(pr): run cmd/yaegicheck under yaegi v0.16.1 on every PR

The 15 yaegi-only regression checks in cmd/yaegicheck (errors.As on an
interpreted target, SSE Flush across the interpreter boundary, ...)
only ran locally via `make yaegi-validate`. The shared go-pr.yaml
workflow has no yaegi step, so a PR reintroducing an errors.As on an
interpreted type -- the exact shape of the NEW-01 production break --
passed CI.

Adds a sibling yaegi-validate job: checkout, setup-go, install yaegi
pinned to v0.16.1 (the version Traefik v3.7.1 vendors, matching
Makefile YAEGI_VERSION), symlink the checkout into GOPATH so yaegi
resolves the plugins own import path, then run cmd/yaegicheck.
contents:read only and a 10-minute timeout; no non-actions/* action is
used, so nothing needs SHA pinning. The existing pr-checks job is
unchanged.

Validated: python3 -c "import yaml" parses the file, and the shell
steps ran end to end against a fresh private GOPATH (go install +
symlink + yaegi run, exit 0).

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(middleware): repanic instead of swallowing a post-next panic

Once t.next has been called, the deferred recover silently returned
after logging, answering every post-next panic with a false clean
response: an empty 200 for a pre-write panic, and a truncated-but-
"complete" 200 for a mid-body panic. That is the same defect class
the ErrAbortHandler branch above it already exists to prevent.

Re-panic the original value instead, once calledNext is true. This
writes no second WriteHeader and wraps nothing, so it reaches
net/http's own top-level recovery (or, in production, Traefik's
compiled recovery middleware), which can tell whether a response was
already committed and react correctly from outside this plugin.

Update the three regression tests that pinned the old return-normally
behavior (TestServeHTTP_RecoversHandlerPanic,
TestServeHTTP_PanicAfterNextCommitted_NoSuperfluousWriteHeader,
TestR155_ServeHTTP_PanicAfterCommitKeepsBodyIntact) to recover around
ServeHTTP and assert the original panic value comes back out, with the
writer holding only next's own writes.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* docs(middleware): fix stale trackingWriter doc comment on calledNext

The comment said the panic handler still sends a header-only 500 once
calledNext is true. That stopped being true with the repanic fix: the
recover now re-panics the original value and writes nothing.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test(yaegi): pin ErrAbortHandler abort behavior through a compiled next

r == http.ErrAbortHandler only matches a panic raised by compiled
code under yaegi v0.16.1 -- exactly the real production shape, since
only this plugin runs interpreted and every next handler downstream
of it is compiled. Add a yaegicheck that drives that shape for real: a
front-facing server running the interpreted plugin, next a compiled
httputil.ReverseProxy, upstream writes a partial chunk, flushes, then
Hijacks and closes the raw connection. The client must see a non-nil
read error, never a clean 200 with a truncated body.

Amend the comment on the ErrAbortHandler branch: the re-panicked
value is not identical to the sentinel once it crosses back out of
the interpreter, so net/http and Traefik log a panic line even though
the connection still aborts correctly.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(yaegicheck): require an actual introspection hit for NEW-01 session check

checkNew01OpaqueSessionIntrospectionClassification passed on a bare
302 alone. An unauthenticated request with no session cookie at all
also redirects with 302, without ever calling
introspectToken/validateOpaqueToken (the d7686c3 fix site), so a
future regression there could leave the check green.

Count requests that reach the introspection endpoint with an atomic
counter and require at least one, alongside the existing 302 check.

Verified: with the cookie deliberately withheld (simulating the
second SessionManager cookie no longer decoding), the check now FAILS
with "expected at least one request to reach the introspection
endpoint ... got 0" instead of silently printing PASS.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test(main): cover revocation and introspection in the override-replace test

TestUpdateMetadataEndpoints_ConfigOverrideReplacesDroppedEndpoint only
pinned end_session. A regression that stopped applying
configRevocationURL or configIntrospectionURL specifically left every
test green.

Verified: with discoveredEndpointHasNoOverride hardcoded to always
report no override for revocation/introspection (ignoring the
configured override), the prior test suite still passed. The new
table-driven version, run against the same mutation, fails for both
revocation and introspection; reverted, all three subtests pass.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* docs(config): correct registration override wording for scheme-downgrade drops

The prior wording implied an override always covers registration. It
does not: RegisterClient falls back to the discovered
registrationURL whenever dynamicClientRegistration.registrationEndpoint
is unset (main.go), so an unset override plus a scheme-downgrade drop
breaks Dynamic Client Registration with only the generic ERROR line --
the same unset-override case this fix already made loud for
revocation, end_session and introspection.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(session): make pool-return ownership check and release atomic

returnToPoolIfOwner checked sd.generation.Load() != gen and then called
returnToPoolSafely, whose inUse.CompareAndSwap(true, false) is a second,
independent atomic. GetSession/newSession hand an object out with
inUse.Store(true) before generation.Add(1), so a stale deferred return
from a previous owner could land its generation check in that window,
then have its CAS succeed against a concurrently re-acquired object,
releasing (and Reset()ing) a session another request still owns.

Replace inUse+generation as the ownership gate with a single atomic
word, sessionOwner: 0 means free, any nonzero value is the current
owner's generation. A handout claims it with Store(newGeneration); a
release claims it back with one CompareAndSwap(gen, 0). generation
itself never resets and is never reused, so once a release zeroes
sessionOwner, no later stale CompareAndSwap naming an older generation
can ever match again, regardless of timing against a new owner's own
writes.

inUse stays as a best-effort, observational field for callers that only
need a snapshot (token_manager.go's refreshToken abort check); it is no
longer part of the ownership decision. ReturnToPool now delegates to
returnToPoolSafely so both unconditional-release call sites share one
gate instead of racing two independent CAS mechanisms.

Adds a stress regression test that races the real returnToPoolIfOwner
against a goroutine performing the exact writes GetSession/newSession
make on a handout of a freshly-freed object. A cruder version of the
same race (matching the old two-field design, where a release never
touched generation) reproduced the bug in 362/400000 iterations against
the unfixed code; the fixed code shows 0 hits deterministically across
repeated -race runs.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test(session): pin ServeHTTP's generation-gated pool-return wiring

The only existing regression for FIX-10 (fix10_session_pool_aba_test.go)
calls returnToPoolIfOwner directly and never drives ServeHTTP, where the
actual fix lives (middleware.go:700-701:
'defer session.returnToPoolIfOwner(sessionGen)' instead of a plain
'defer session.returnToPoolSafely()'). Reverting those two lines
compiles and leaves the whole root suite green (re-review finding at
session.go:1825).

Add a test that drives a real ServeHTTP call through the
Clear-and-reacquire branch (processAuthorizedRequestRS's backchannel/
front-channel-logout invalidation check). A small test-only hook,
sessionClearReleaseHook (nil outside tests, called at the end of
Clear()'s existing pool-return defer), lets the test pause the
invalidated request's goroutine the instant its session is freed and
deterministically steal that exact object with a direct GetSession
call, mark it as a different user's live session, then let the
invalidated request run to completion including its outer ServeHTTP
defer.

Verified the test fails (5/5 runs) against a temporary, uncommitted
revert of middleware.go:700-701 to 'defer session.returnToPoolSafely()'
(inUse=false: the stale call released the concurrent owner's session),
and passes (including under -race) against the unmodified wiring.
middleware.go itself is untouched by this commit.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(session): make the ServeHTTP pool-owner wiring test deterministic

The initial version of TestServeHTTP_InvalidatedSessionReacquireDoesNotStealConcurrentSession
was flaky in two independent ways, both found by stress-running it:

1. Stealing the freed session object via a second, real GetSession call
   (even from the same goroutine, immediately after the Put, with
   GOMAXPROCS(1) and GC disabled) missed the just-freed object in roughly
   a quarter of runs -- sync.Pool's exact reuse behavior here is an
   unspecified implementation detail. Fixed by having the hook swap the
   SessionManager's pool for a fresh, empty one the instant it captures
   the freed pointer, so request A's own reacquire can only allocate a
   new object, never collide with the stolen one.

2. The test asserted on the stolen object's user identifier
   (SetUserIdentifier/GetUserIdentifier), which lives in the gorilla
   session's Values map. gorilla/sessions caches a decoded session on the
   *http.Request's context keyed by cookie name; request A's own reacquire
   reads the SAME request, so it aliases the SAME underlying mainSession
   the stolen SessionData points to, even once it is a distinct SessionData
   struct. Request A's own re-auth bookkeeping then legitimately (and
   correctly) mutates that shared map, which looked like corruption but
   had nothing to do with the pool-ownership bug being tested. Fixed by
   asserting only on the SessionData struct's own ownership fields
   (inUse/sessionOwner via ownerGeneration), which ns's aliased
   mainSession cannot touch.

Verified: 80/80 passes against the correct wiring and 20/20 failures
against a temporary, uncommitted revert of middleware.go:700-701 to
'defer session.returnToPoolSafely()', both under -race. middleware.go
itself remains untouched.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(session): simulate the real handout sequence in the FIX-10 ABA test

The stale-return simulation wrote inUse and generation but left
sessionOwner at 0. returnToPoolIfOwner gates on sessionOwner, so the
stale return CAS mismatched because the object looked already-free
(owner 0), not because a real new owner held it. The cleanup call at
the end of the test was therefore a no-op: it never released the
object back to the pool.

Set sessionOwner to the freshly bumped generation before inUse, the
same order GetSession/newSession use on every real handout
(session.go:1076-1078, 1108-1110). Verified against the current
session.go: before this change the cleanup left inUse true and
activeSessions unchanged; after it, inUse goes false and
activeSessions decrements by one, as a real release does.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test(session): skip the pool-owner race test below GOMAXPROCS 2, fix rate claim

TestSessionPoolReturnIfOwner_ConcurrentHandoutRace only catches the
regression statistically: it needs two OS threads to interleave a
stale returnToPoolIfOwner with a concurrent handout. At GOMAXPROCS=1
it passes with 0 hits even against the unfixed two-field gate, so a
single-CPU runner would report green for the wrong reason. Skip the
test below GOMAXPROCS 2 instead.

The comment also claimed a rate "consistent with" a different,
unrelated experiment (about 3 hits per 1.2M), which does not hold up:
reverting returnToPoolIfOwner/returnToPoolSafely to the pre-fix
two-field gate and running this exact test gives 76-89 hits per
400000 on this 16-core machine, roughly 100x that figure. Replace the
claim with the rate actually measured for this test against that
mutation, plus the 0-hits-at-GOMAXPROCS=1 control that motivates the
skip.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(bearer): check local revocation blacklist and nbf on opaque path

buildPrincipalFromOpaqueIntrospection never read t.tokenBlacklist, so a
captured opaque bearer token kept authenticating after logout for as
long as the introspection endpoint still reported it active (RevokeToken
blacklists locally; provider-side revocation is best-effort and silent
by default). Reject the raw token and, when the introspection response
carries one, its jti (gated on disableReplayDetection), the same way
verifyTokenWithOpts gates the JWT path. Also enforce nbf, which
validateOpaqueToken already applies on the session path and the JWT
path applies through verifyTimeClaims, but the opaque bearer path
skipped.

Regression tests: RevokeToken-blacklisted raw token, blacklisted jti
echoed in the introspection response, and a future nbf all now 401;
each failed on the base code before this fix.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* docs(bearer): correct maxTokenAgeSeconds:0 opt-out claim

main.go maps every maxTokenAgeSeconds <= 0 (unset or an operator setting
0) to a 24h default; there is no config value that disables the iat-age
check. The FIX-24 comment and BEARER_AUTH.md both said 0 could disable
it and be used as an opt-out for an iat-less opaque introspection
response. State plainly that 0 means the 24h default and that a
response without iat is rejected once the bound is in effect, which it
always is.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* docs(bearer): rewrite stale JTI replay marking claim

FIX-17 removed the last writer of the JTI replay cache: no request path
Sets a JTI any more, so the header comment and BEARER_AUTH.md row that
described a Set/Get split ("skips the Set but the Get stays active")
were stale. Revocation does not depend on that cache: RevokeToken
blacklists the raw token and a JWTs jti, and both the JWT and (as of
the previous commit) the opaque-introspection bearer path check that
blacklist before accepting a token.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* chore(cache): remove dead ShardedCache

FIX-17 removed jwt.gos replay cache, ShardedCaches last production
caller. Nothing outside its own tests referenced NewShardedCache or
ShardedCache after that (verified with grep across the package and a
clean go build). Delete sharded_cache.go and the test functions that
existed only to exercise it:

- review_r57_shard_eviction_test.go, review_r86_test.go: deleted whole
  files, entirely ShardedCache-specific.
- cache_test.go, cache_bench_test.go, review_r129_test.go,
  review_r153_regression_test.go: deleted only the ShardedCache-specific
  functions/benchmarks, keeping unrelated tests in the same file.
  BenchmarkShardedVsGlobalMutex is dropped whole since its purpose was
  comparing against ShardedCache.

Approved dead-code removal per review decision; go build and the full
test suite are clean after the removal.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* docs(bearer): scope JTI replay claim to access tokens

bearer_auth.go header and BEARER_AUTH.md JTI-replay row said no path
writes a JTI to a replay cache at all. Backchannel logout still writes
logout-token JTIs via checkAndMarkLogoutJTIProcessed (made atomic by
FIX-17, not removed). Limit the claim to access-token JTIs and name the
one JTI replay check left.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* docs(bearer): correct stale JTI Set/Get replay claim in README

README said the bearer path skips the JTI Set but keeps the Get active,
contradicting the rewritten BEARER_AUTH.md and bearer_auth.go, both of
which say no access-token JTI Set exists on this path at all. Replace
with a bullet matching the corrected wording: revocation goes through
the raw-token (and JWT jti) blacklist, not a JTI-replay Get.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* docs(config): correct maxTokenAgeSeconds opt-out claim

CONFIGURATION.md said maxTokenAgeSeconds:0 disables the age check.
main.go maps any value <= 0 to a 24h default; no value disables the
check. BEARER_AUTH.md already carries the corrected wording; this was
the sibling copy the earlier fix missed.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* docs(bearer): correct nbf clock-skew-tolerance claim in comment

Comment on the opaque-introspection nbf check said it was the same
check the JWT path applies through verifyTimeClaims. It is not: the JWT
path's verifyNotBefore allows 10s of ClockSkewTolerancePast, this check
allows none. It does match validateOpaqueToken's strict comparison and
this function's own strict exp check. Comment only, no behaviour
change.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test(bearer): assert opaque-token rejects return 401 not 503

TestBearerOpaqueIntrospection_RevokedTokenRejected,
_BlacklistedJtiRejected and _NbfFutureRejected only checked bErr != nil.
A mutant that swaps those three gates to
newBearerError(bearerErrIntrospectionUnavailable, ...) (mapped to 503,
and skipped by the per-IP failure tracker) still passed bErr == nil.
Add a kind == bearerErrTokenInactive check to each so the tests pin the
401 status, not just any error.

Verified against the described mutant before reverting it: all three
tests failed with 'got kind 6' (bearerErrIntrospectionUnavailable);
reverting the mutant restores a clean pass.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test(bearer): pin disableReplayDetection skips jti blacklist check

The jti-blacklist gate at bearer_auth.go:928 guards itself with
!t.disableReplayDetection, but no test exercised that guard. Add
TestBearerOpaqueIntrospection_BlacklistedJtiIgnoredWhenReplayDetectionDisabled:
a blacklisted jti on an otherwise-valid introspection response must be
accepted when disableReplayDetection is true.

Verified against a mutant removing the guard before reverting it: the
new test failed with 'token replay detected (jti blacklisted)'
(bearer_opaque_binding_test.go:337); reverting the mutant restores a
clean pass across all TestBearerOpaqueIntrospection_* tests.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(cache/redis): treat a Redis command-error reply as definitive in SetNX

RedisBackend.SetNX reported ErrSetNXAmbiguous for any post-write read
failure, including a RESP -ERROR reply (READONLY, OOM, MISCONF). That
reply proves Redis rejected the command, unlike a genuinely lost reply
after a timeout/EOF/reset. Reporting it as ambiguous let
checkAndMarkLogoutJTIProcessed accept a logout jti-claim outright
instead of falling to its local Get+Set fallback, so a captured
backchannel-logout token could be replayed forever while Redis
rejects writes (e.g. a demoted read-only replica).

Check errors.Is(doErr, ErrCommandReply) before the sent-based
ambiguity check and return it as a plain error. Add a proxy-backed
regression test in internal/cache/backends pinning SetNX itself, and
an end-to-end test wiring a real RedisBackend behind a proxy that
always answers SET-family commands with -READONLY, confirming
checkAndMarkLogoutJTIProcessed now rejects the second delivery of the
same jti.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(cache): let a newer backend value win over a stale-marked local one

FIX-04s backend-stale mark let Get serve the local value over EVERY
later backend value for a marked key, assuming the backend entry
could only be older (a same-replica write that may have landed after
a timeout). That is false across replicas: another replica can write
a genuinely newer value to the same key while this one is still
marked stale, e.g. a later cross-replica backchannel logout. The
session-invalidation cache (MonotonicMarkers, 25h local TTL) could
then ignore a newer logout from another replica for up to 25h.

Add backendValueIsNewer: when both the local and backend values
decode to a comparable timestamp, Get now serves whichever is not
older, so a genuinely newer backend value wins. Values it cannot
compare (e.g. the blacklist caches bool markers) keep the original
FIX-04 behavior of always preferring local. This also keeps the
original protection intact: an applied-but-timed-out Set is still not
clobbered by an older backend value, because local is newer in that
case too.

Add two-replica regression tests (a shared fake backend, no real
Redis needed) for both the plain and MonotonicMarkers cases.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* perf(cache): bound the legacy blacklist-namespace lookup cost

checkLegacyBlacklistMarker ran an extra Redis round trip (PING+GET,
plus PTTL when the key existed) on every single blacklist Get miss,
which is nearly every blacklist check, since most tokens are never
revoked. It also fully JSON-decoded whatever it found there, even a
CacheTypeToken claims map cached under the same raw token, just to
learn the value was not the boolean marker.

Compare the raw legacy value against the exact bytes serialize(true)
produces before decoding anything, and remember a miss (or a
non-bool legacy hit) locally per key for legacyBlacklistMissCacheTTL
(30s), so a repeated check for the same key skips the legacy round
trip until the window elapses. A genuine legacy marker already in
Redis is still honored once the window is up. Prune expired entries
opportunistically from cleanup(), which already runs on a timer for
every cache including the blacklist one.

Add miniredis CommandCount-based regression tests: the fix reduces a
repeated miss from 4 Redis commands to 2, and separate tests pin that
a real legacy marker is still found and a cached claims map is still
never misread as one.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* chore(cache): remove dead memory/hybrid backend config

FIX-43 deleted MemoryBackend and HybridBackend, but config.go still
declared BackendTypeMemory, BackendTypeHybrid, TypeMemory, TypeHybrid,
DefaultConfig (Type: memory) and DefaultHybridConfig — config for
backends with no implementation left. Confirmed no production caller
of backends.DefaultConfig or backends.DefaultHybridConfig outside
their own now-deleted tests (servers.DefaultConfig in
internal/testutil/servers is an unrelated function).

Remove both functions and the memory/hybrid constants; keep
BackendTypeRedis/TypeRedis, the only backend now implemented. Delete
config_test.go, which exercised only DefaultHybridConfig.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test(cache): run the backend contract suite against a real RedisBackend

TestCacheBackendContract was a no-op: setupMemoryBackend and
setupRedisBackend were both t.Skip stubs, so no CacheBackend
implementation ever ran the 13 shared contract tests. MemoryBackend
no longer exists (FIX-43), so drop that subtest and wire
setupRedisBackend to a real miniredis-backed RedisBackend, matching
the pattern redis_test.go and singleflight_test.go already use.

miniredis only expires a key when its own simulated clock is moved
forward (FastForward) - it never expires anything on real elapsed
time, so testTTLExpirations time.Sleep never actually exercised
expiry against it. Thread an advanceClock func through
runContractTests/testTTLExpiration and pass mr.FastForward for it, so
that subtest genuinely proves expiry rather than passing by coincidence.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(cache): bound the backend-stale mark in time for values FIX-04 cannot compare

markBackendStale/backendStaleLocalValue let Get serve the local value over
every later backend value, for as long as the local entry stayed live,
whenever backendValueIsNewer cannot decode the value into a comparable
number (a string, a map, a struct). The DCR client-credentials cache
(a JSON string, TTL up to 100*365 days) hit this on every replica whose
write timed out: a stale credential could pin over a value a different
replica legitimately wrote, for the entry's whole TTL.

staleBackend now records when each key was marked (map[string]time.Time),
and backendStaleLocalValue treats a mark older than the new
backendStaleMarkTTL (5s, well above the 500ms Set timeout) as expired,
deleting it so the current backend value is trusted again. The numeric
newer-wins comparison for MonotonicMarkers caches is unchanged.

Two regression tests pin both directions for a non-numeric (string) value
across two replicas sharing one backend: within the bound an older
backend write does not clobber the surviving local value, and after the
bound a newer value written by another replica is served.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(cache): gate the backend-stale numeric comparison on MonotonicMarkers

backendValueIsNewer's "larger number wins" comparison ran for every
cache, not only MonotonicMarkers ones. For a non-monotonic numeric cache
a larger number is not necessarily a newer write, so an older, larger
backend value could clobber a fresh, smaller local write that survived a
timed-out Set — the exact clobber FIX-04 exists to prevent.

Get now gates the comparison behind c.config.MonotonicMarkers. Every
other cache recovers from a stale mark via the time bound added in the
previous commit instead of by numeric order.

Rebuilt TestR4_BackendStale_CrossReplicaNewerValue_PrefersNewerBackend on
the time bound instead of numeric order, since its cache never set
MonotonicMarkers, and added a regression test pinning the direction it
used to get backwards (an old, larger backend value must not clobber a
fresh, smaller local write on a non-monotonic cache).

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* perf(cache): cap legacyBlacklistMissUntil at the cache's MaxSize

legacyBlacklistMissUntil had no size cap of its own. Its keys came from
the raw bearer token, looked up before signature verification, so a
caller who can send unique tokens fully controlled how many distinct
entries piled up. Pruning ran only from cleanup()'s 5-minute tick, so
each unique key stayed in memory for up to ~5.5 minutes regardless of
volume — unbounded memory a caller could grow at will.

recordLegacyBlacklistMiss now caps the map at c.config.MaxSize (already
>0 for every cache), pruning expired entries inline when the cap is hit
before deciding whether to record. If it is still full afterward, the
miss is simply not recorded — the only cost is one extra legacy lookup
next time, exactly what every check paid before this bound existed. The
map is also keyed by a sha256 digest of the lookup key instead of the raw
string, so an entry's size no longer grows with token length.

Regression test drives a small-MaxSize blacklist cache through 4x its
cap in unique misses and asserts the map never exceeds the cap, and that
a genuine legacy marker is still honored while the map sits at capacity.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(cache): honour the pre-#117 legacy blacklist marker encoding

checkLegacyBlacklistMarker's byte compare recognized only the current
serialize() encoding (0x01 type-marker byte + json.Marshal(true)). Code
before #117 (commit 775de2a; every tag up to and including v0.8.17) wrote
plain json.Marshal(true) with no type-marker byte at all - 4 bytes,
'true'. deserialize's legacy no-marker fallback still accepts that
shape, and the OLD checkLegacyBlacklistMarker (which deserialized instead
of comparing bytes) honored it, so a Redis-mode upgrade straight from
v0.8.17 or earlier could silently drop revocations written up to the
blacklist's TTL before the upgrade.

Also accept legacyBlacklistTrueMarker with its type-marker byte stripped.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test(lifecycle): fix order-dependent baseline and global-state leaks in FIX-35/18/19 tests

TestFix35_ConcurrentNewKeepsSingletonAliveAcrossOldClose registered a live
instance without capturing a liveInstanceCount baseline first. A live
instance left registered by an earlier test in the same run already makes
the pre-FIX-35 stale "was last" decision false on its own, so the test
cannot tell a reverted production fix from a working one under -shuffle.
Save/reset/restore the counter via a new resetLiveInstanceCountForTest
return value and t.Cleanup instead. Reproduced with a temporary leaked
instance ahead of the test plus a manual revert of the FIX-35 decision in
Close(): the test passed either way before this change, now fails as
expected. TestFix35_StopIfLastInstanceHoldsLockAcrossCheckAndStop is
updated to the same save/restore pattern.

TestFix18_CloseImmediatelyAfterNewDoesNotReRegister called the shared
resetGdInstancesForTest helper, which wipes the process-global gdInstances
registry with no restore, discarding any GracefulDegradation instances
other tests left registered. Add snapshotAndClearGdInstancesForTest, which
saves the prior set and restores it via t.Cleanup.

TestFix19_RegisterBackgroundTaskKeepsPendingTaskNoOrphan called
rm.StopAllTasks() on the process-global ResourceManager, which stops every
registered singleton task (memory-monitor, singleton-token-cleanup, etc.),
not just the one this test created. Replace it with
StopBackgroundTask(name) so the test only touches its own task.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(recovery): treat HTTP 408 as transient in isTerminalClientError

isTerminalClientError excluded only 429 from the terminal-4xx breaker
exemption, so a burst of token-endpoint 408 Request Timeout responses
never opened the refresh circuit breaker. token_validation_rs.go (FIX-13),
bearer_auth.go, and internal/recovery already classify 408 as a transient
service-health signal, not a per-request rejection. Exclude 408 alongside
429.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* refactor(recovery): move healthRoutineSettled out of production code

GracefulDegradation.healthRoutineSettled was added to error_recovery.go
(production) but its only caller is fix18_gd_lifecycle_test.go, and its
own doc comment says "Tests use this". FIX-39 established the pattern of
keeping test-only helpers out of the production binary
(internal/pool/export_test.go). Move the method into
fix18_gd_lifecycle_test.go next to its sole caller,
waitForHealthRoutineSettled.

No behavior change: verified via go build (production code compiles with
the method removed) and the FIX-18 test suite, unchanged.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test(refresh): remove fixed-sleep dedup race in TestRefreshRateLimiting

TestRefreshRateLimiting used the default 100ms DeduplicationCleanupDelay
and a 150ms sleep to outrun it before starting the next iteration -- the
same fixed-sleep-vs-cleanup-timer race FIX-22 removed from its siblings
(TestCircuitBreakerProtection, issue67, review_refresh_cb), but not from
this test.

Reproduced deterministically by temporarily setting
DeduplicationCleanupDelay above the 150ms sleep: the next CoordinateRefresh
call then joins the still-registered previous operation instead of
starting fresh, so attempts is miscounted (5 instead of 3) and cooldown
never triggers. Fix: DeduplicationCleanupDelay=0 plus waitForRefreshDrain
polling the in-flight map, matching the sibling tests.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(refresh): bound Shutdown's abandonment of in-flight refreshes to a drain cap

FIX-36 made Shutdown cancel rc.ctx immediately, aborting every in-flight
refresh unconditionally -- including one whose refreshFunc call had
already reached the IdP and would complete on its own. Discarding that
result loses the token response, and for a rotating IdP (Zitadel,
Authentik), consumes a one-time-use refresh token that gets thrown away,
forcing the next refresh into invalid_grant and a re-login.

DECIDED: Shutdown now waits for in-flight refreshes to drain naturally, up
to a new shutdownRefreshDrainTimeout (5s) constant. A refresh that
completes within the cap delivers its result to its waiters as normal;
Shutdown only cancels rc.ctx (abandoning whatever is still running) once
the cap elapses, so Shutdown itself never blocks longer than the cap.
CoordinateRefresh's stopChan check (still gated by lifecycleMu, still
ahead of wg.Add) is unchanged: a call arriving after Shutdown starts is
still rejected immediately, without waiting for the drain cap.

Reproduced with a probe mirroring the finding's evidence (refreshFunc
completes 300ms after Shutdown starts): the waiter got "refresh
coordinator is shutting down: context canceled" instead of its tokens on
unfixed code. Added as
TestFix36_ShutdownDeliversResultForRefreshCompletingWithinDrainCap
(fails on base at refresh_coordinator_test.go:905) and
TestFix36_ShutdownReturnsNearCapWhenRefreshExceedsIt (fails on base:
Shutdown returned after 4.666us instead of waiting out the cap), plus a
rejected-during-drain coverage test. Rewrote
TestFix36_ShutdownReturnsPromptlyDuringInFlightRefresh into these two,
since its "always cancel immediately" assertions directly contradicted
the new contract, and its refreshFunc's fixed 3s time.Sleep left a
goroutine running past the test -- both replacements block on a channel
released via t.Cleanup instead.

Updated review_r63's TestRefreshCoordinatorShutdownReleasesWaiterOnInflight
and review_r154's TestRefreshCoordinator_ShutdownWaitsForInFlight to the
same drain-cap contract: their refreshFunc never completes on its own, so
they now assert Shutdown gives up near the cap (not immediately) and the
waiter still gets an error, while keeping their original wg-tracking
assertion (circuit-breaker failure recorded before Shutdown returns).

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(refresh): gate the pre-start refresh on stopChan, not only rc.ctx

Shutdown closes stopChan synchronously but only cancels rc.ctx after
shutdownRefreshDrainTimeout (or once every in-flight refresh drains).
executeRefreshAsyncs inner goroutine checked only rc.ctx.Err() before
calling refreshFunc, so an operation whose wg.Add ran just before
Shutdown started, but whose goroutine reached that check afterward,
still spent the IdP grant for nothing during the whole drain window.

Add a stopChan gate ahead of the rc.ctx check so a refresh not yet
started is skipped and its waiter gets the shutdown error immediately.
Also make Shutdown cancel rc.ctx unconditionally before it returns (not
only on the drain-cap path), so a clean Shutdown with nothing in flight
still leaves rc.ctx canceled instead of dead. Update the stale FIX-36
comments describing the old cancel-immediately contract.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test(refresh): wait on stopChan instead of fixed sleeps in two Fix36 tests

TestFix36_CoordinateRefreshRejectedAfterShutdownStillImmediate slept
20ms hoping Shutdown had closed stopChan by then; a late-scheduled
Shutdown would let the second CoordinateRefresh get wrongly accepted.
TestFix36_ShutdownDeliversResultForRefreshCompletingWithinDrainCap
slept 50ms before releasing the refresh; if Shutdown had not started
yet, the refresh would finish before Shutdown ran, passing even on the
reverted cancel-immediately code (a false negative).

Both now block on <-rc.stopChan (with a 2s failure timeout) so the
release/second-call always happens strictly after Shutdown has begun.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test(lifecycle): remove duplicated doc paragraph in FIX-35 test

be3ac67 duplicated the TestFix35_ConcurrentNewKeepsSingletonAliveAcrossOldClose
doc paragraph word for word. Delete the copy and keep the baseline
paragraph that follows it.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test(lifecycle): restore process-global singleton state in fix18/fix35 tests

TestFix18_TraefikOidcCloseEmptiesGDInstances made its synthetic
instance the last live one, so Close() ran stopIfLastInstance and
stopped singleton-token-cleanup and (via StopAllTasks) every other
process-global singleton, including memory-monitor, with nothing to
restart them. TestFix35_ConcurrentNewKeepsSingletonAliveAcrossOldClose
unconditionally reset the global memory monitor on entry and on
cleanup, discarding whatever state an earlier test in the same binary
left running.

Fix18: register a sentinel live instance so this test is never the
last one, leaving Close()s last-instance stop path unreached.
Fix35: capture whether memory-monitor was running before this tests
own reset, and restart it in a cleanup (registered first, so it runs
last) when it was.

Verified with a throwaway probe (started both singletons, ran both
tests via t.Run, asserted running-state after): failed at HEAD with
singleton-token-cleanup=false/memory-monitor=false after fix18 and
memory-monitor still false after fix35; passes with this change.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(lifecycle): surface StopBackgroundTask errors in FIX-19 test

_ = rm.StopBackgroundTask(name) discarded the "task not registered"
error StopBackgroundTask returns on a failed lookup, which would let
the test fail later with a misleading "orphan escaped registry"
message instead of pointing at the real cause. Fail the test directly
with the actual error, and fix the stale StopAllTasks wording in the
neighboring failure message to name the call this test actually makes.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* docs(changelog): record the round-4 re-review fixes

Record the behaviour changes users can notice: opaque bearer tokens with all three bearer flags, the first post-upgrade logout for older sessions, the 5-second refresh drain on shutdown, and panics after forwarding that now abort the connection. Add a Fixed section for the six round-4 fixes and note that the legacy blacklist check runs at most once per key in each 30 seconds.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(cache): keep the backend-stale mark for MonotonicMarkers caches

The round-4 time bound on the backend-stale mark also expired it for MonotonicMarkers caches. When a replica could not write a newer session-invalidation marker to Redis, it fell back to the older backend marker after 5 seconds and stopped enforcing the newer logout, which is the case FIX-04 exists for. Exempt MonotonicMarkers caches from the bound. Get still lets a newer marker from another replica win through the newer-wins compare. The regression test fails before this change (Get returns 1000) and passes after it.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* chore(git): ignore the .claude directory

Local Claude Code state (todos, review artifacts, agent worktrees) lives under .claude/ and must not be committed. Replace the narrower .claude/*.out rule with the whole directory.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(make): fail make lint on golangci-lint findings

The lint recipe "golangci-lint run ./... || echo ..." turned every lint failure into exit 0, so make lint always reported success. Use an explicit if/else: run golangci-lint when it is installed and return its exit status, otherwise print the skip message. TestMakeLintPropagatesGolangciLintResult runs the target with a fake golangci-lint and fails on the old recipe.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix: avoid narrowing int conversions flagged by gosec G115

reserveConnectionSlot and the half-open gate narrowed an int limit to int32, so a configured value above MaxInt32 wrapped negative and refused every connection or probe. Compare in int64 instead. BuildSessionName used rune(0+index) for any index below 10, so a negative index produced a non-digit; limit the fast path to 0..9. Regression tests fail on the old code.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* chore(gosec): annotate intentional findings with #nosec

GitHub code scanning runs standalone gosec, which ignores golangci //nolint:gosec directives and honors only #nosec. Replace the directive with a #nosec Gxxx comment and a reason at the nine intentional sites: persisted DCR client_secret (G117), operator-enabled insecureSkipVerify (G402), the conditional-Secure deletion cookie and a test request cookie (G124), and the test mock IdP redirects (G710). golangci-lint also honors #nosec, so it stays at 0 issues.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* ci: build with Go 1.26

staticcheck@latest (v0.8.1) and govulncheck@latest (v1.8.0) now require Go 1.26. The shared workflow runs them with GOTOOLCHAIN=local on the pinned 1.25.x, so the Static Analysis and Security Scan jobs failed to install them. Pin 1.26.x in pr.yaml (both jobs) and release.yml, matching toolchain go1.26.6 in go.mod.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(recovery): stop health routine restarting task after last Close

GracefulDegradation.Close closed stopChan without gd.mutex. A health
routine that passed its stopChan check could then reach the task registry
after the last Close stopped the shared task. RegisterBackgroundTask
replaces a stopped task, so the routine started a task that no live
instance can stop. This made TestSharedHealthTaskSurvivesOtherInstanceClose
flaky when an earlier test left the shared task running.

Close now closes stopChan under gd.mutex, so an in-flight routine finishes
before the instance unregisters. The lock is released before the task
stop, because BackgroundTask.Stop waits for a pass that takes gd.mutex.

TestSharedHealthTaskNotRestartedAfterLastClose parks the routine after its
check and fails on the old code in 20 of 20 runs.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test(recovery): keep shared health pass out of health-check subtests

TestGracefulDegradationHealthChecks calls performHealthChecks directly.
The shared health-check task also runs the same registered checks in the
background, so the race detector reported a write to healthCheckCalled.
The background pass could also clear the degraded state before the first
assertion. The subtests failed 18 of 1000 runs alone under -race.

The two subtests now hold globalHealthCheckMu, so no background pass runs
during their assertions. The unlock is deferred after Close, so it runs
first and Close never waits on a blocked pass.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(tls): drop the deprecated PreferServerCipherSuites field

crypto/tls ignores Config.PreferServerCipherSuites since Go 1.18, and staticcheck v0.8.1 (SA1019), which CI now installs, fails the Static Analysis job on it. Remove the field at its three sites and the stale #nosec comment beside one of them. Behaviour does not change.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test(cleanup): wait for the processed-task metric in TestWorkerPool_GetMetrics

executeTask increments tasksProcessed in a deferred call that runs after the task returns, so the task wg.Done() can fire first, and wg.Wait() returned while the metric still read 1. CI failed on this once. Poll the counter with a 2 second deadline before asserting. With a 20ms delay injected before the increment, the old test fails in 3 of 3 runs and the new test passes.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(recovery): serialize GracefulDegradation creation with the last-instance stop

GracefulDegradation.Close removed the instance from gdInstances, decided it
was the last one, and released the lock before stopping the shared
health-check task. A GracefulDegradation created in that gap registered at
once, and its health routine adopted the still-running task. The stop then
killed the task that the new, live instance relies on, and nothing
restarted it.

Add gdLifecycleMu. NewGracefulDegradation registers under it, and Close holds
it across the last-instance check and the stop. A new instance now either
counts toward the check or registers after the stop, and its routine then
replaces the stopped task. The health-check pass never takes this lock, so
the stop can still wait for an in-progress pass.

TestSharedHealthTaskSurvivesCreateDuringLastClose pauses Close between the
check and the stop through a nil-by-default test seam
(beforeSharedTaskStop). With the seam on the old Close logic, it fails in 10
of 10 runs. With this change, it passes in 20 of 20 runs under -race.

Production impact today is limited: no production code registers a health
check, and degraded state expires through RecoveryTimeout, not the task.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* fix(session): delete stale cookies at the configured cookiePath

Session cookies are written at the configured cookiePath
(EnhanceSessionSecurity), but CleanupOldCookies wrote its deletion cookies
at a hardcoded "/". A browser deletes a cookie only when name, domain and
path all match, so the cleanup removed nothing when cookiePath was set.

Add SessionManager.effectiveCookiePath (the configured cookiePath, or "/")
and use it for cookie writes, for the deletion cookies, and in
getSessionOptions, so the three sites cannot drift. The cleanup deletes
only at the configured path. Cookies written at "/" before an operator set
cookiePath stay until they expire.

TestCleanupOldCookies_UsesConfiguredCookiePath fails on the old code
(deletion Path "/", want "/app") and passes after the fix.

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

* test: close leaked graceful-degradation managers and guard against leaks

Eleven root tests created an ErrorRecoveryManager or TokenResilienceManager,
or built a manager with a GracefulDegradation, and never closed it. Each one
left an instance registered and the shared health-check task running for
every later test in the process. That made lifecycle tests that assume a
clean start flaky (TestSharedHealthTaskSurvivesOtherInstanceClose).

The leakers were found by running each of the 1156 root tests alone, followed
by a check of gdInstances and the task state. Each leaker now registers
t.Cleanup(<manager>.Close).

TestMain now fails the package when tests leave a GracefulDegradation
unclosed or the shared task running, after a 2-second settle window for
plugin instances that close asynchronously. On a leaking test it reports
"tests leaked 1 unclosed GracefulDegradation instance(s)".

Claude-Session: https://claude.ai/code/session_01KwtV5ecajCrftcf8TkfPad

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
2026-09-28 12:55:10 +01:00

101 lines
4.2 KiB
Go

package traefikoidc
import (
"testing"
"time"
)
// FIX-24 regression test.
//
// buildPrincipalFromBearerToken derived the IdP-logout-invalidation
// "createdAt" from the token's iat claim, falling back to time.Now() when
// iat was absent. Since 8640451 made iat OPTIONAL in jwt.Verify (R126), an
// access token without iat now reaches this check. time.Now() makes such a
// token always look newer than any logout event (isSessionInvalidated only
// matches when invalidationTime >= createdAt), so IdP-initiated
// (backchannel) logout never revokes it — reintroducing the R98 defect the
// cookie path already fixed by falling back to zero time instead.
//
// Fail-on-old: a bearer token without iat, for a sid invalidated by
// backchannel logout, still authenticates (200) after the logout.
func TestBearerLogoutInvalidation_NoIatFallsClosedNotOpen(t *testing.T) {
cache := NewCache()
defer cache.Close()
oidc := makeBearerOIDC(t, nil)
oidc.sessionInvalidationCache = cache
// Disable the unrelated maxTokenAge/enforceIatAge bound (a DIFFERENT
// check that also rejects a missing iat, and that New() always turns on
// in production — 0/unset becomes 24h, main.go:357-362 — this override
// only exists because this test constructs *TraefikOidc directly,
// bypassing New()) so this test isolates the isSessionInvalidated
// createdAt fallback under test. That fallback is what actually matters
// once maxTokenAge is 0: with maxTokenAge > 0 (the production default),
// enforceIatAge rejects an iat-less token before this logout check is
// even reached.
oidc.maxTokenAge = 0
claims := defaultBearerClaims()
delete(claims, "iat") // provider omits iat (now legal per R126)
claims["sub"] = "user-1"
claims["sid"] = "session-1"
token := makeBearerJWT(t, defaultBearerHeader(), claims)
seedVerified(t, oidc, token, claims)
// Backchannel logout invalidates the session a full hour before this
// request (set directly rather than via invalidateSession's real-clock
// Unix() call, so the comparison is deterministic regardless of
// test-execution timing rather than depending on two time.Now() calls
// landing in the same second). The buggy time.Now() fallback for
// createdAt makes the token look newer than this invalidation
// (invalidationTime.Before(createdAt) == true -> NOT invalidated); the
// fix's zero-time fallback is never after any invalidation timestamp.
invalidatedAt := time.Now().Add(-time.Hour).Unix()
cache.Set(oidc.buildSessionInvalidationKey("sid", "session-1"), invalidatedAt, time.Hour)
_, bErr := oidc.buildPrincipalFromBearerToken(token)
if bErr == nil {
t.Fatal("a bearer token without iat, whose sid was invalidated by backchannel logout, must be rejected (fail closed), not authenticated as if issued after the logout")
}
}
// TestBearerLogoutInvalidation_WithIatStillHonored is the positive control:
// a token WITH iat issued before the logout must still be invalidated (the
// existing R146 behavior), and one issued after must still pass.
func TestBearerLogoutInvalidation_WithIatStillHonored(t *testing.T) {
cache := NewCache()
defer cache.Close()
oidc := makeBearerOIDC(t, nil)
oidc.sessionInvalidationCache = cache
if err := oidc.invalidateSession("session-2", ""); err != nil {
t.Fatalf("invalidateSession: %v", err)
}
// Issued well before the logout above.
staleClaims := defaultBearerClaims()
staleClaims["sub"] = "user-2"
staleClaims["sid"] = "session-2"
staleClaims["iat"] = float64(time.Now().Add(-time.Hour).Unix())
staleToken := makeBearerJWT(t, defaultBearerHeader(), staleClaims)
seedVerified(t, oidc, staleToken, staleClaims)
if _, bErr := oidc.buildPrincipalFromBearerToken(staleToken); bErr == nil {
t.Fatal("a token issued before the logout must still be invalidated")
}
// Freshly issued after the logout, for an unrelated sid.
freshClaims := defaultBearerClaims()
freshClaims["sub"] = "user-3"
freshClaims["sid"] = "session-3"
freshClaims["iat"] = float64(time.Now().Unix())
freshToken := makeBearerJWT(t, defaultBearerHeader(), freshClaims)
seedVerified(t, oidc, freshToken, freshClaims)
if _, bErr := oidc.buildPrincipalFromBearerToken(freshToken); bErr != nil {
t.Fatalf("a freshly issued token for an uninvalidated sid must pass, got: %v", bErr)
}
}