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:
Alex Sedov
2026-11-21 04:00:18 +00:00
committed by GitHub
co-authored by lukaszraczylo
parent 2ceea0f617
commit a8ae9fa49b
21 changed files with 1791 additions and 16 deletions
+266
View File
@@ -24,6 +24,7 @@ package main
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
@@ -39,6 +40,7 @@ import (
oidc "github.com/lukaszraczylo/traefikoidc"
recovery "github.com/lukaszraczylo/traefikoidc/internal/recovery"
fixtures "github.com/lukaszraczylo/traefikoidc/internal/testutil/fixtures"
servers "github.com/lukaszraczylo/traefikoidc/internal/testutil/servers"
)
@@ -141,6 +143,8 @@ func main() {
runCheck("issue162-websocket-forwards-header-templates", checkIssue162WebSocketHeaderTemplates)
runCheck("tojson-header-template", checkToJsonHeaderTemplate)
runCheck("streaming-refresh-revoked-grant-rejected", checkStreamingRefreshRevokedGrant)
runCheck("tmb-endpoints-invalid-session", checkTMBEndpointsUnderYaegi)
runCheck("tmb-endpoint-get-and-forced-refresh", checkTMBSuccessUnderYaegi)
fmt.Println("OK: all yaegi regression checks passed")
}
@@ -982,6 +986,268 @@ func checkStreamingRefreshRevokedGrant() (string, error) {
return "", nil
}
// checkTMBEndpointsUnderYaegi drives the token-mediating endpoints through the real
// middleware under the interpreter: with no session cookie, and with a
// session whose refresh the IdP rejects (invalid_grant), both endpoints must
// answer a JSON 401 invalid_session, never redirect and never reach next.
func checkTMBEndpointsUnderYaegi() (string, error) {
idpCfg := servers.DefaultConfig()
idpCfg.RefreshError = &servers.OIDCError{Error: "invalid_grant"}
idp := servers.NewOIDCServer(idpCfg)
defer idp.Close()
cfg := oidc.CreateConfig()
cfg.ProviderURL = idp.URL
cfg.ClientID = "yaegi-check-tmb-client"
cfg.ClientSecret = "yaegi-check-tmb-secret"
cfg.CallbackURL = "/oauth2/callback"
cfg.SessionEncryptionKey = "0123456789abcdef0123456789abcdef"
cfg.TMBSessionURL = "/auth/session"
reached := false
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reached = true
})
h, err := oidc.New(context.Background(), next, cfg, "yaegi-check-tmb")
if err != nil {
return "", fmt.Errorf("New: %w", err)
}
if closer, ok := h.(interface{ Close() error }); ok {
defer closer.Close()
}
// A normal request first, so provider metadata (token endpoint) is known.
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/", nil))
reached = false
expect := func(label string, req *http.Request) error {
rw := httptest.NewRecorder()
h.ServeHTTP(rw, req)
if reached {
return fmt.Errorf("%s: next reached", label)
}
if rw.Code != http.StatusUnauthorized {
return fmt.Errorf("%s: status = %d, want 401 (body %q)", label, rw.Code, rw.Body.String())
}
if loc := rw.Header().Get("Location"); loc != "" {
return fmt.Errorf("%s: unexpected redirect to %q", label, loc)
}
var body map[string]interface{}
if err := json.Unmarshal(rw.Body.Bytes(), &body); err != nil {
return fmt.Errorf("%s: body is not JSON: %v", label, err)
}
if body["error"] != "invalid_session" {
return fmt.Errorf("%s: error = %v, want invalid_session", label, body["error"])
}
return nil
}
for _, method := range []string{"GET", "POST"} {
if err := expect("no-cookie "+method, httptest.NewRequest(method, "/auth/session", nil)); err != nil {
return "", err
}
}
sm, err := oidc.NewSessionManager(cfg.SessionEncryptionKey, cfg.ForceHTTPS, cfg.CookieDomain, cfg.CookiePrefix, time.Duration(cfg.SessionMaxAge)*time.Second, oidc.NewLogger("error"))
if err != nil {
return "", fmt.Errorf("NewSessionManager: %w", err)
}
defer sm.Shutdown()
setupReq := httptest.NewRequest("GET", "/", nil)
session, err := sm.GetSession(setupReq)
if err != nil {
return "", fmt.Errorf("GetSession: %w", err)
}
if err := session.SetAuthenticated(true); err != nil {
return "", fmt.Errorf("SetAuthenticated: %w", err)
}
session.SetUserIdentifier("[email protected]")
// Built at runtime because a JWT literal trips the pre-commit secret scanner.
b64 := base64.RawURLEncoding.EncodeToString
sig := make([]byte, 32)
for i := range sig {
sig[i] = byte(i + 1)
}
payload := fmt.Sprintf(`{"email":"[email protected]","exp":%d}`, time.Now().Add(-time.Minute).Unix())
session.SetAccessToken(b64([]byte(`{"alg":"RS256","typ":"JWT"}`)) + "." + b64([]byte(payload)) + "." + b64(sig))
session.SetRefreshToken("yaegi-check-bff-refresh-token")
rec := httptest.NewRecorder()
if err := session.Save(setupReq, rec); err != nil {
return "", fmt.Errorf("session.Save: %w", err)
}
session.ReturnToPool()
cookies := rec.Result().Cookies()
for _, method := range []string{"GET", "POST"} {
req := httptest.NewRequest(method, "/auth/session", nil)
for _, c := range cookies {
req.AddCookie(c)
}
if err := expect("revoked-refresh "+method, req); err != nil {
return "", err
}
}
return "", nil
}
// checkTMBSuccessUnderYaegi drives the 200 paths of the token-mediating
// endpoint under the interpreter, with tokens the fake IdP's JWKS really
// verifies: GET builds the body (claim extraction, groups, expires_at, JSON
// encoding), POST forces a refresh grant against the fake IdP, and the
// refreshed tokens are served by the next GET from the rotated cookie.
func checkTMBSuccessUnderYaegi() (string, error) {
const clientID = "yaegi-check-tmb-ok-client"
fx, err := fixtures.NewTokenFixture()
if err != nil {
return "", fmt.Errorf("NewTokenFixture: %w", err)
}
idpCfg := servers.DefaultConfig()
idpCfg.TokenFixture = fx
idp := servers.NewOIDCServer(idpCfg)
defer idp.Close()
fx.Issuer = idp.Config.Issuer
fx.Audience = clientID
mint := func(jtiSuffix string) (string, error) {
return fx.ValidToken(map[string]interface{}{
"email": "[email protected]",
"groups": []string{"admins"},
"jti": "yaegi-tmb-" + jtiSuffix,
})
}
accessTok, err := mint("access")
if err != nil {
return "", fmt.Errorf("mint access: %w", err)
}
idTok, err := mint("id")
if err != nil {
return "", fmt.Errorf("mint id: %w", err)
}
newAccessTok, err := mint("access-new")
if err != nil {
return "", fmt.Errorf("mint new access: %w", err)
}
newIDTok, err := mint("id-new")
if err != nil {
return "", fmt.Errorf("mint new id: %w", err)
}
idp.Config.RefreshResponse = map[string]interface{}{
"access_token": newAccessTok,
"id_token": newIDTok,
"refresh_token": "yaegi-check-tmb-rotated-refresh-token-0123456789",
"token_type": "Bearer",
"expires_in": 3600,
}
cfg := oidc.CreateConfig()
cfg.ProviderURL = idp.URL
cfg.ClientID = clientID
cfg.ClientSecret = "yaegi-check-tmb-ok-secret"
cfg.CallbackURL = "/oauth2/callback"
cfg.SessionEncryptionKey = "0123456789abcdef0123456789abcdef"
cfg.TMBSessionURL = "/auth/session"
cfg.TMBClaims = []string{"email"}
reached := false
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { reached = true })
h, err := oidc.New(context.Background(), next, cfg, "yaegi-check-tmb-ok")
if err != nil {
return "", fmt.Errorf("New: %w", err)
}
if closer, ok := h.(interface{ Close() error }); ok {
defer closer.Close()
}
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/", nil))
reached = false
sm, err := oidc.NewSessionManager(cfg.SessionEncryptionKey, cfg.ForceHTTPS, cfg.CookieDomain, cfg.CookiePrefix, time.Duration(cfg.SessionMaxAge)*time.Second, oidc.NewLogger("error"))
if err != nil {
return "", fmt.Errorf("NewSessionManager: %w", err)
}
defer sm.Shutdown()
setupReq := httptest.NewRequest("GET", "/", nil)
session, err := sm.GetSession(setupReq)
if err != nil {
return "", fmt.Errorf("GetSession: %w", err)
}
if err := session.SetAuthenticated(true); err != nil {
return "", fmt.Errorf("SetAuthenticated: %w", err)
}
session.SetUserIdentifier("[email protected]")
session.SetAccessToken(accessTok)
session.SetIDToken(idTok)
session.SetRefreshToken("yaegi-check-tmb-refresh-token-0123456789")
rec := httptest.NewRecorder()
if err := session.Save(setupReq, rec); err != nil {
return "", fmt.Errorf("session.Save: %w", err)
}
session.ReturnToPool()
cookies := rec.Result().Cookies()
call := func(method string, jar []*http.Cookie) (map[string]interface{}, []*http.Cookie, error) {
req := httptest.NewRequest(method, "/auth/session", nil)
for _, c := range jar {
req.AddCookie(c)
}
rw := httptest.NewRecorder()
h.ServeHTTP(rw, req)
if reached {
return nil, nil, fmt.Errorf("%s: next reached", method)
}
if rw.Code != http.StatusOK {
return nil, nil, fmt.Errorf("%s: status = %d, want 200 (body %q)", method, rw.Code, rw.Body.String())
}
var body map[string]interface{}
if err := json.Unmarshal(rw.Body.Bytes(), &body); err != nil {
return nil, nil, fmt.Errorf("%s: body is not JSON: %v", method, err)
}
return body, rw.Result().Cookies(), nil
}
body, _, err := call("GET", cookies)
if err != nil {
return "", err
}
if body["access_token"] != accessTok || body["user_identifier"] != "[email protected]" {
return "", fmt.Errorf("GET: unexpected identity/token in %v", body)
}
claims, _ := body["claims"].(map[string]interface{})
if len(claims) != 1 || claims["email"] != "[email protected]" {
return "", fmt.Errorf("GET: claims = %v, want only the configured email", body["claims"])
}
groups, _ := body["groups"].([]interface{})
if len(groups) != 1 || groups[0] != "admins" {
return "", fmt.Errorf("GET: groups = %v, want [admins]", body["groups"])
}
left := body["expires_at"].(float64) - float64(time.Now().Unix())
if left < 3000 || left > 3700 {
return "", fmt.Errorf("GET: expires_at = %v, want about an hour from now", body["expires_at"])
}
if _, found := body["expires_in"]; found {
return "", fmt.Errorf("GET: expires_in must not be returned")
}
for _, k := range []string{"refresh_token", "id_token"} {
if _, found := body[k]; found {
return "", fmt.Errorf("GET: %s must never be returned", k)
}
}
body, rotated, err := call("POST", cookies)
if err != nil {
return "", err
}
if body["access_token"] != newAccessTok {
return "", fmt.Errorf("POST: access_token was not the refreshed one")
}
body, _, err = call("GET", append(append([]*http.Cookie{}, cookies...), rotated...))
if err != nil {
return "", err
}
if body["access_token"] != newAccessTok {
return "", fmt.Errorf("GET after POST: refreshed token was not persisted in the session")
}
return "", nil
}
// checkErrAbortHandlerAbortsUnderYaegi guards the re-review finding on
// ServeHTTP's ErrAbortHandler branch (middleware.go): under yaegi v0.16.1,
// `r == http.ErrAbortHandler` only ever matches a panic raised by COMPILED