Files
traefikoidc/CHANGELOG.md
T
a8ae9fa49b feat: add token-mediating backend endpoint for SPAs (#168)
* feat: add token-mediating backend endpoint for SPAs

Implements the Token-Mediating Backend pattern of
draft-ietf-oauth-browser-based-apps: the plugin keeps the refresh token
server-side and hands the session's access token to the SPA. It is not
a BFF; nothing is proxied. The spec defines no paths or formats, so the
endpoint is modelled on session endpoints such as Azure App Service's
`/.auth/me`: GET reads, POST refreshes.

Setting `tmbSessionURL` enables the endpoint; there is no enable flag.
`Config.Validate` requires a plain absolute path (leading `/`, no
leading `//`, no `?`, `#` or backslash) that is not already served by
the callback, logout (including its `callbackURL` + `/logout` default),
back-channel or front-channel endpoint, because it is matched by exact
request-path comparison, as configured. `tmbClaims` lists the ID-token
claims to return; it is empty by default.

`ServeHTTP` dispatches to `handleTMB` (`tmb.go`) before the bearer
branch, so the endpoint authenticates by session cookie only, never by
bearer token, and answers `401 invalid_session` instead of redirecting.
`shouldBypassAuth` never bypasses the endpoint's path, so excludedURLs,
SSE, WebSocket and preflight handling cannot forward it to the backend.

GET returns `authenticated`, `user_identifier`, `claims` (only the
ID-token claims named in `tmbClaims`, values as in the token), `groups`,
`roles`, `expires_at` (ID token `exp`),
`access_token` and `expires_in` (access token JWT `exp`). The refresh
token and ID token are never returned. The only side effect is the
usual refresh inside `refreshGracePeriod`; query parameters are
ignored.

POST forces a refresh through the existing `refreshToken` path
(coordinator, rotation persistence) once the authorization gates pass,
re-applies the gates to the refreshed claims and returns the GET body:

- IdP rejects the refresh token: `401 invalid_session`, session ended
- any other refresh failure: `502 server_error`, session kept
- session has no refresh token: `401 backend_not_ready`
- external source over `perSourceLoginRateLimit`: `429 rate_limited`,
  `Retry-After: 1`, no refresh attempted (each forced refresh is an
  IdP call; the limiter is off by default and GET is never throttled)

Both methods:

- anything but GET/POST gets `405` with `Allow: GET, POST`
- `403` when `Sec-Fetch-Site` is `cross-site` or `same-site`, or
  `Origin` names another host; checked before any refresh
- no CORS headers: `Access-Control-*` headers added by the
  middleware-wide security headers are removed; `Cache-Control: no-store`,
  `X-Content-Type-Options: nosniff`,
  `Cross-Origin-Resource-Policy: same-origin`
- `allowedUsers`, `allowedRolesAndGroups` and logout-invalidation
  gates apply

`resource` and `scope` are not supported.

Adds `docs/TMB.md`, the `tmbSessionURL` rows in `README.md` and
`docs/CONFIGURATION.md`, a changelog entry and the yaegicheck cases
`tmb-endpoints-invalid-session` and `tmb-endpoint-get-and-forced-refresh`.

* feat(session): record access token expiry, report it from TMB endpoint

The plugin never stored when the access token expires; the token
response's `expires_in` was only logged. The TMB endpoint returns the
access token but reported the ID token's `exp` as `expires_at`, which is
wrong when the two differ. For an opaque access token the plugin's
refresh decision follows the ID token, so the endpoint could serve an
access token that had already expired.

Session:

- `access_token_expires_at` (unix seconds) lives in the main session
  and in its own `combinedSessionPayload` field `Ea`. An int64 in the
  extras map `X` comes back from JSON as a float64, the same reason
  `Ca` is a dedicated field.
- `handleCallback` and `refreshToken` set it from `accessTokenExpiry`:
  the token response's `expires_in` when positive, else the access
  token's `exp` claim (`jwtExpiry`), else 0 for unknown.
- `SetAccessToken` drops it whenever the token changes or is cleared,
  so it never describes another token. Callers call
  `SetAccessTokenExpiresAt` after `SetAccessToken`.
- Sessions saved before this change report 0.
- `requestState.captureSession` captures it as `accessTokenExpiresAt`.

TMB endpoint:

- `expires_at` is the access token's expiry: the recorded value, else
  the token's `exp` claim (`tmbAccessTokenExpiry`), omitted when
  unknown. `expires_in` is no longer returned; one absolute time is
  enough for clients with approximately correct clocks.
- `tmbEstablishSession` also refreshes when that expiry is within
  `refreshGracePeriod` or past, which the plugin's usual rule does not
  do for opaque access tokens.
- It never answers 200 with an expired access token. No refresh token,
  or a refresh token the IdP rejected: `401 invalid_session`. IdP
  unreachable or failing: `502 server_error`. A token that is only due
  is still served when its early refresh fails.

Tests cover the `accessTokenExpiry` table, the session round trip with
combined and legacy cookie storage, invalidation on token change, pool
reset, `handleCallback` recording the expiry, and the TMB reporting and
refresh-when-due cases. `docs/TMB.md` is updated and yaegicheck asserts
`expires_at` and the absence of `expires_in`.

* fix(session): record access-token expiry only for the stored token

SetAccessToken dropped the recorded expiry before it validated the new
token. When the store then failed (token too large, too many chunks, no
request), the previous token stayed in the session without its expiry.
The callers then recorded the new token's expiry for it. The TMB
endpoint could then answer 200 with an expired access token.

SetAccessTokenExpiresAt now takes the token and records the expiry only
if that token is the stored one. SetAccessToken drops the expiry only
where it replaces or clears the stored token.

* refactor(tmb): reuse bypassSessionClaims for claim selection

tmbAuthorize had its own copy of the rule that reads the ID-token
claims, else the access-token claims. bypassSessionClaims already owns
that rule (R118) and also guards a nil extractClaimsFunc. The endpoint
now calls it, so the two paths cannot drift.

* docs(tmb): state what same-origin scripts can read

docs/TMB.md listed the cross-origin protections but did not say that
every script on the origin can read the access token. The draft names
this as the main risk of the token-mediating pattern. The page now
says so and recommends a strict Content-Security-Policy.

It also says that the plugin removes only its own CORS headers, and
cannot remove headers that another middleware adds.

---------

Co-authored-by: Lukasz Raczylo <[email protected]>
2026-11-21 04:00:18 +00:00

8.7 KiB

Changelog

All notable changes to this project are documented in this file.

The format follows Keep a Changelog.

[Unreleased]

Added

  • tmbSessionURL (default unset). Token-mediating backend endpoint for single-page apps (draft-ietf-oauth-browser-based-apps). Setting a path enables it, authenticated by the session cookie: GET returns the user, groups, roles, the claims named in tmbClaims (default none) and the access token; POST forces a refresh first. See TMB.md.

  • allowUnauthenticatedPreflight (default false). Every OPTIONS request needs authentication by default, as in the last release. Set the option to true to let a genuine CORS preflight reach the backend without a session. Only an OPTIONS request that carries both Origin and Access-Control-Request-Method bypasses authentication, and the plugin discards the backend's response body for it, because a browser never reads a preflight body (settings.go, middleware.go, FIX-02). See the option table in CONFIGURATION.md.

  • streamingRefresh (default false). SSE and WebSocket requests do not check the token expiry, so a session stays usable for streaming until the session cookie expires. Set the option to true to refresh an expired token on these requests. If the IdP rejects the refresh with invalid_grant, the request gets 401. If the IdP cannot be reached, the request is forwarded as before. The request waits for the full refresh, so a rotated refresh token is never lost (middleware.go).

Changed

  • Opaque bearer tokens when all three bearer flags are set. A deployment that sets enableBearerAuth, requireTokenIntrospection and allowOpaqueTokens now accepts opaque bearer tokens after RFC 7662 introspection. The last release rejected every non-JWT bearer token. The plugin binds an accepted opaque token to the client through client_id or aud. It also applies the identifier, token-age, logout, revocation and nbf checks (bearer_auth.go).

  • Sessions created before this upgrade can omit post_logout_redirect_uri on their first logout. The plugin now builds that parameter only from the redirect-URI origin recorded at login, never from the logout request's host. Older sessions have no recorded origin, so those users stay on the IdP's logout page once (helpers.go).

  • Shutdown waits up to 5 seconds for a token refresh in progress. On shutdown, for example a Traefik reload, the refresh coordinator lets a refresh that already reached the IdP deliver its tokens, then returns (shutdownRefreshDrainTimeout, refresh_coordinator.go). A refresh that has not started does not start after shutdown.

  • A panic after the request reaches the backend now aborts the connection. The plugin re-panics it, for example the reverse proxy's http.ErrAbortHandler when an upstream drops the connection mid-body. Go's HTTP server then aborts the connection. Before, the plugin recovered the panic, so a truncated response could reach the client as a complete 200. A panic before the request reaches the backend still returns 500 (middleware.go).

  • private_key_jwt now rejects RSA signing keys under 2048 bits. validateAlgKeyMatch stops New() with an error when a configured private_key_jwt RS*/PS* key is smaller than 2048 bits (RFC 7518 §3.3). A smaller key signs locally, but a conformant IdP rejects it at token exchange with invalid_client, so the plugin now fails at construction instead of at every runtime exchange. There is no override: deployments using an RSA key under 2048 bits must generate a 2048-bit-or-larger key before upgrading. The rejection returns a matchable ErrRSAKeyTooSmall sentinel (client_assertion.go).

  • A discovered http:// endpoint is now dropped when providerURL is https://. validateDiscoveredEndpoint refuses to accept an authorization, token, jwks_uri, revocation, end_session, introspection, or registration endpoint served over plaintext HTTP when the operator configured an HTTPS provider (R146): using it as-is would send a client secret or token over an unauthenticated channel. There is no configuration flag to disable this check. A dropped endpoint logs an ERROR line; a dropped token, jwks_uri, or authorization endpoint — the three every login needs — additionally logs a SECURITY:-prefixed line naming the endpoint, the dropped URL, and the fact that there is no override, so the failure is diagnosable instead of surfacing only as a broken login. See Discovered Endpoint Validation (url_helpers.go, main.go).

  • Blacklist entries in Redis use the blacklist: key prefix. The blacklist cache now has its own cache type (CacheTypeBlacklist), so its Redis keys move from the shared token: prefix to blacklist: (R128). A cached token entry and a revocation marker for the same raw token can no longer overwrite each other. For one release, a blacklist miss also reads the legacy token:<key> entry and treats it as revoked only when the stored value is boolean true (checkLegacyBlacklistMarker in universal_cache.go, FIX-16). The fallback works in one direction only: during a rolling deploy, a replica that runs the previous version does not see revocations that an upgraded replica writes under blacklist:. A blacklist miss checks the legacy token: entry at most once per key in each 30 seconds, so the fallback adds little Redis traffic.

  • Claim validation accepts four previously-rejected or silently-dropped claim shapes. Each change below is intentional, matches a production change, and is pinned by an existing regression test.

    • iat (issued-at) is optional in jwt.Verify, per RFC 7519 §4.1.6. A token that omits it is validated on iss/aud/exp/nbf alone, instead of being rejected (jwt.go, R126). The lenient-audience access-token path (accessTokenUnexpired in token_validation_rs.go) applies the same rule, because both paths call verifyTimeClaims (jwt.go, FIX-27). Bearer-token auth still rejects a token with no iat: it returns "missing iat claim" (enforceIatAge in bearer_auth.go), because maxTokenAgeSeconds always applies — 0 falls back to a 24h default (main.go).
    • A numeric sub (bearer-auth identifier) claim is stringified instead of rejected, so an IdP that emits a numeric subject still authenticates (bearer_auth.go resolveBearerIdentifier, R102).
    • A groups/roles claim that is neither a string nor an array (for example a bare number or null) is treated as an empty list instead of failing claim extraction outright, so a malformed claim on one side does not suppress a valid claim on the other (token_manager.go extractGroupsAndRolesFromClaims, R96).
    • A numeric element inside a groups/roles array is stringified into the list instead of being silently dropped, so a numeric group ID survives extraction and can match an allowedRolesAndGroups entry (token_manager.go stringListFromClaim, utilities.go claimScalarString, R105).

Fixed

  • SSE and WebSocket requests now get the configured headers, as normal requests do. The last release sent only X-Forwarded-User on these requests, so a backend that checks a shared-secret header answered 401 on WebSocket upgrades. The same requests now also honor back-channel and front-channel logout (middleware.go, #162).
  • The opaque bearer path rejects a token that RevokeToken added to the blacklist, for example at logout. It also rejects an opaque token whose nbf is in the future (bearer_auth.go).
  • The backchannel-logout replay check treats a Redis error reply such as READONLY, OOM or MISCONF as a failure, not as an unknown outcome. A replayed logout token is now rejected while Redis refuses writes (internal/cache/backends/redis.go).
  • After a failed cache write, a replica no longer ignores a newer value that another replica wrote, such as a later logout. The preference for the local value expires after 5 seconds (backendStaleMarkTTL, universal_cache.go).
  • The token circuit breaker treats HTTP 408 from the token endpoint as a transient failure, the same as 429 (error_recovery.go).
  • With allowUnauthenticatedPreflight enabled, a preflight response no longer carries a stale Content-Length when the backend writes a body without calling WriteHeader (middleware.go).
  • A dropped http:// revocation, end-session or introspection endpoint logs the SECURITY: line when its override (revocationURL, oidcEndSessionURL or introspectionURL) is not configured (main.go).