mirror of
https://github.com/lukaszraczylo/traefikoidc.git
synced 2026-11-24 11:05:53 +00:00
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]>
This commit is contained in:
+148
@@ -0,0 +1,148 @@
|
||||
# Token-mediating backend endpoint
|
||||
|
||||
Lets a single-page app obtain an access token from the plugin's session without
|
||||
holding a refresh token or running its own OAuth client. This is the
|
||||
"Token-Mediating Backend" pattern of
|
||||
[draft-ietf-oauth-browser-based-apps](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-browser-based-apps):
|
||||
the plugin is the confidential client, keeps the refresh token server-side, and
|
||||
hands the access token to the browser. It is not a BFF: requests to the
|
||||
resource server do not pass through the plugin.
|
||||
|
||||
The spec defines no paths or formats. The endpoint is modelled on session
|
||||
endpoints such as Azure App Service's `/.auth/me`: `GET` reads, `POST`
|
||||
refreshes.
|
||||
|
||||
## Configuration
|
||||
|
||||
The endpoint is off until its path is set. There is no separate enable flag.
|
||||
|
||||
```yaml
|
||||
tmbSessionURL: /auth/session
|
||||
tmbClaims: # optional; default none
|
||||
- email
|
||||
- name
|
||||
```
|
||||
|
||||
The path must be a plain absolute path (leading `/`, no leading `//`, no query,
|
||||
fragment or backslash) and must not be a path another endpoint of the
|
||||
middleware already serves: `callbackURL`, `logoutURL` (its default is
|
||||
`callbackURL` + `/logout`) or the back- and front-channel logout URLs. It is
|
||||
matched against the request path as configured.
|
||||
|
||||
`tmbClaims` names the claims returned in `claims`, read from the ID token (from
|
||||
the access token when the session has no ID token). It is empty by default, so
|
||||
nothing beyond the fields below is exposed.
|
||||
|
||||
## Authentication
|
||||
|
||||
The endpoint is authenticated by the plugin's session cookie, the same one the
|
||||
rest of the plugin uses. It never accepts `Authorization: Bearer` and never
|
||||
redirects to the IdP: with no valid session it answers `401 invalid_session`. It
|
||||
is served ahead of the bypasses (`excludedURLs`, `Accept: text/event-stream`,
|
||||
WebSocket upgrades, unauthenticated preflight), so none of them can forward a
|
||||
request on its path to the backend.
|
||||
|
||||
A session must also pass the normal gates (`allowedUsers`, `allowedUserDomains`,
|
||||
`allowedRolesAndGroups`, back/front-channel logout invalidation); failing
|
||||
`allowedUsers`/`allowedRolesAndGroups` answers `403 access_denied`.
|
||||
|
||||
If `cookiePath` is set, it must cover the configured path, or the browser will
|
||||
not send the cookie to it.
|
||||
|
||||
## Cross-origin protection
|
||||
|
||||
- `GET` and `POST` only (`405` otherwise, with `Allow: GET, POST`).
|
||||
- A request is rejected with `403` when `Sec-Fetch-Site` is `cross-site` or
|
||||
`same-site`, or when `Origin` is present and does not match the request host.
|
||||
A rejected request never triggers a refresh.
|
||||
- The endpoint never emits CORS headers: `Access-Control-*` headers added by
|
||||
`securityHeaders.corsEnabled` are removed from its responses.
|
||||
- Responses carry `Cache-Control: no-store`, `X-Content-Type-Options: nosniff`
|
||||
and `Cross-Origin-Resource-Policy: same-origin`.
|
||||
- No custom request header is required.
|
||||
|
||||
The plugin removes only the CORS headers that it adds itself. It cannot remove
|
||||
headers that another middleware adds to its responses, for example CORS headers
|
||||
from a Traefik `headers` middleware. Do not add such a middleware to the router
|
||||
that serves `tmbSessionURL`.
|
||||
|
||||
## What scripts on the origin can read
|
||||
|
||||
The endpoint gives the access token to every script that runs on the same
|
||||
origin. Thus a cross-site scripting flaw or a compromised third-party script on
|
||||
that origin can read the access token. Without this endpoint, the access token
|
||||
stays on the server. Before you enable the endpoint, set a strict
|
||||
`Content-Security-Policy` on the pages of that origin. Keep the access token
|
||||
lifetime at the IdP short.
|
||||
|
||||
## `GET`: read the session
|
||||
|
||||
```json
|
||||
{
|
||||
"authenticated": true,
|
||||
"user_identifier": "user-1",
|
||||
"claims": {"email": "[email protected]", "name": "U One"},
|
||||
"groups": ["admins"],
|
||||
"access_token": "…",
|
||||
"expires_at": 1767225600
|
||||
}
|
||||
```
|
||||
|
||||
- `user_identifier` is the claim named by `userIdentifierClaim`. `groups` and
|
||||
`roles` use `groupClaimName` / `roleClaimName` and are omitted when empty.
|
||||
- `claims` holds exactly the claims listed in `tmbClaims`, with their values as
|
||||
they appear in the token (arrays and objects included). A claim the token
|
||||
lacks is omitted, and `claims` itself is omitted when nothing is listed.
|
||||
- `access_token` is the session's access token. The refresh token and ID token
|
||||
are never returned.
|
||||
- `expires_at` (unix seconds) is when the access token expires, not the ID
|
||||
token, which may expire at a different time. The plugin records it at login
|
||||
and at every refresh, from the token response's `expires_in` and otherwise
|
||||
from the token's own `exp` claim, so opaque access tokens are covered when the
|
||||
IdP sends `expires_in`. A session that predates the record falls back to the
|
||||
`exp` claim. The field is omitted when the expiry is unknown.
|
||||
- A `GET` has no side effects on the session, except that the access token is
|
||||
refreshed first when its expiry is within `refreshGracePeriod` or past. This
|
||||
goes beyond the plugin's usual rule, which for an opaque access token follows
|
||||
the ID token's expiry and could hand out a token that has already expired.
|
||||
If an expired token cannot be refreshed, the endpoint does not return it: it
|
||||
answers `401 invalid_session` when there is no refresh token to try or the IdP
|
||||
rejected it, and `502 server_error` when the IdP could not be reached. A token
|
||||
that is merely due keeps being served if its early refresh fails. Query
|
||||
parameters are ignored.
|
||||
|
||||
## `POST`: force a refresh
|
||||
|
||||
Runs a refresh-token grant through the same path as the automatic refresh,
|
||||
saves the new tokens and any rotated refresh token to the session, and returns
|
||||
the same body as `GET` with the new token. Use it when the API rejected the
|
||||
current token. The request body is ignored. The refresh runs only after the
|
||||
user passed the authorization gates, which are applied again to the refreshed
|
||||
token's claims. Each forced refresh is one IdP call, so it is subject to
|
||||
`perSourceLoginRateLimit` when that is set (off by default).
|
||||
|
||||
## Errors
|
||||
|
||||
`application/json` with `error` and optional `error_description`:
|
||||
|
||||
| Status | `error` | Cause |
|
||||
|--------|---------|-------|
|
||||
| 401 | `invalid_session` | No valid authenticated session (missing, expired or logged out); the IdP rejected the refresh token (the session is ended); or the access token has expired and there is no refresh token to renew it. No `WWW-Authenticate` header is sent: the session cookie has no HTTP auth scheme, as for the plugin's other `401`s. |
|
||||
| 401 | `backend_not_ready` | `POST` but the session has no refresh token, so it cannot be refreshed and the user has to authenticate again. The session is left as is; `GET` keeps working until the access token expires. |
|
||||
| 403 | `access_denied` | The user fails `allowedUsers` or `allowedRolesAndGroups`. |
|
||||
| 403 | `invalid_request` | Cross-origin request. |
|
||||
| 405 | `invalid_request` | Method other than `GET` or `POST`. |
|
||||
| 429 | `rate_limited` | `POST` from an external source over `perSourceLoginRateLimit`; `Retry-After: 1` is set and no refresh is attempted. |
|
||||
| 502 | `server_error` | The token endpoint was unreachable or failed on a `POST`, or on a `GET` whose access token had already expired; the session is kept. |
|
||||
|
||||
## SPA flow
|
||||
|
||||
Read the session once on load and keep the access token in memory. When the API
|
||||
answers `401` or `expires_at` is near, `POST` to get a fresh one. The endpoint
|
||||
never redirects: on any `401` from this endpoint (`invalid_session` or
|
||||
`backend_not_ready`), navigate the page to a protected URL so the normal login
|
||||
redirect runs. No page reload is needed otherwise.
|
||||
|
||||
## Not supported
|
||||
|
||||
`resource` and `scope` (token downscoping) are not supported in this version.
|
||||
Reference in New Issue
Block a user