Files
traefikoidc/types.go
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

272 lines
12 KiB
Go

// Package traefikoidc provides OIDC authentication middleware for Traefik.
package traefikoidc
import (
"context"
"net/http"
"sync"
"sync/atomic"
"text/template"
"time"
"golang.org/x/time/rate"
)
// CacheInterface defines the common cache operations
type CacheInterface interface {
Set(key string, value any, ttl time.Duration)
Get(key string) (any, bool)
Delete(key string)
SetMaxSize(size int)
Size() int
Clear()
Cleanup()
Close()
GetStats() map[string]any // For testing and monitoring
}
// AtomicSetIfAbsentCache is an optional capability a CacheInterface
// implementation can provide: an atomic check-and-set, in place of a
// separate Get followed by a Set. CacheInterface itself is not widened to
// require it — most of the CacheInterface test doubles across the suite
// have no need for it, and every one of them would otherwise need a new
// method — so a caller that wants the atomic primitive type-asserts a
// CacheInterface value to this interface instead (see logout.go's
// checkAndMarkLogoutJTIProcessed, FIX-17). CacheInterfaceWrapper (backed by
// UniversalCache) implements it.
type AtomicSetIfAbsentCache interface {
// SetIfAbsent stores value under key only if key is not already
// present, and reports whether this call performed the store.
SetIfAbsent(key string, value any, ttl time.Duration) (bool, error)
}
// TokenVerifier interface defines token verification capabilities.
// Implementations should validate token format, signature, and claims.
type TokenVerifier interface {
VerifyToken(token string) error
}
// JWTVerifier interface defines JWT-specific verification capabilities.
// Implementations should validate JWT structure, signature using JWKs, and standard claims.
type JWTVerifier interface {
VerifyJWTSignatureAndClaims(jwt *JWT, token string) error
}
// TokenExchanger interface defines OAuth 2.0 and OpenID Connect token exchange capabilities.
// Implementations should handle authorization code exchange, refresh tokens, and revocation
// according to the OAuth 2.0 and OpenID Connect specifications.
type TokenExchanger interface {
ExchangeCodeForToken(ctx context.Context, grantType string, codeOrToken string, redirectURL string, codeVerifier string) (*TokenResponse, error)
GetNewTokenWithRefreshToken(refreshToken string) (*TokenResponse, error)
RevokeTokenWithProvider(token, tokenType string) error
}
// ProviderMetadata represents OIDC provider configuration data.
// This data is typically retrieved from the provider's .well-known/openid-configuration endpoint
// and contains essential URLs for authentication, token exchange, and key retrieval.
type ProviderMetadata struct {
Issuer string `json:"issuer"`
AuthURL string `json:"authorization_endpoint"`
TokenURL string `json:"token_endpoint"`
JWKSURL string `json:"jwks_uri"`
RevokeURL string `json:"revocation_endpoint"`
EndSessionURL string `json:"end_session_endpoint"`
IntrospectionURL string `json:"introspection_endpoint,omitempty"`
RegistrationURL string `json:"registration_endpoint,omitempty"`
ScopesSupported []string `json:"scopes_supported,omitempty"`
}
// TraefikOidc is the main middleware struct that implements OIDC authentication for Traefik.
// It integrates with various OIDC providers, manages sessions, caches tokens, and handles
// the complete authentication flow. It's designed to work seamlessly with Traefik's
// plugin system and provides flexible configuration options.
// MetadataSnapshot is an immutable bundle of provider-metadata URLs that the
// plugin needs on the hot request path. Published atomically via
// TraefikOidc.metadataSnapshot; readers do exactly one atomic.Value.Load to
// access all fields. Replaces 3 per-request metadataMu.RLock acquisitions
// in middleware.ServeHTTP + token_manager paths, each of which paid
// 1-5ms of Yaegi-dispatch overhead.
//
// The fields are a strict subset of the metadataMu-guarded TraefikOidc
// fields; the legacy fields are still written under metadataMu for
// less-frequent code paths that have not been migrated.
type MetadataSnapshot struct {
IssuerURL string
JWKSURL string
TokenURL string
AuthURL string
RevocationURL string
EndSessionURL string
IntrospectionURL string
RegistrationURL string
}
type TraefikOidc struct {
// metadataSnapshot atomically publishes the read-mostly URL bundle.
// Hot-path readers (middleware.ServeHTTP, token verification) load it
// directly; less-frequent paths still acquire metadataMu.RLock and
// read the individual fields below.
metadataSnapshot atomic.Value
// lastMetadataRetryNano is the UnixNano timestamp of the last metadata
// recovery attempt. Stored atomically so the hot ServeHTTP path can
// throttle retries without acquiring metadataRetryMutex on every request.
lastMetadataRetryNano int64
// initWaiters counts requests parked on initComplete; bounded by
// maxInitWaiters so a boot-time flood cannot hold unbounded connections.
initWaiters int32
// firstRequestStarted is 0 until the very first non-health request fires
// the background-task bootstrap; then it flips to 1 via CAS. Replaces the
// firstRequestMutex + firstRequestReceived combo which previously took
// a write lock on every non-health request forever.
firstRequestStarted int32
// metadataRefreshStartedAtomic is the CAS-only variant of the old
// metadataRefreshStarted bool. Both flags live under the same atomic so
// concurrent first-request goroutines race exactly once.
metadataRefreshStartedAtomic int32
jwkCache JWKCacheInterface
jwtVerifier JWTVerifier
ctx context.Context
tokenVerifier TokenVerifier
next http.Handler
tokenExchanger TokenExchanger
tokenBlacklist CacheInterface
tokenTypeCache CacheInterface
introspectionCache CacheInterface
initComplete chan struct{}
limiter *rate.Limiter
perSourceLimiter *perSourceAuthLimiter // optional per-external-source auth throttle (R185), nil when disabled
headerTemplates map[string]*template.Template
sessionManager *SessionManager
tokenCleanupStopChan chan struct{}
excludedURLs map[string]struct{}
extractClaimsFunc func(tokenString string) (map[string]any, error)
initiateAuthenticationFunc func(rw http.ResponseWriter, req *http.Request, session *SessionData, redirectURL string)
metadataCache *MetadataCache
allowedRolesAndGroups map[string]struct{}
allowedUsers map[string]struct{}
allowedUserDomains map[string]struct{}
tokenCache *TokenCache
httpClient *http.Client
tokenHTTPClient *http.Client
logger *Logger
metadataRefreshStopChan chan struct{}
cancelFunc context.CancelFunc
errorRecoveryManager *ErrorRecoveryManager
tokenResilienceManager *TokenResilienceManager
refreshCoordinator *RefreshCoordinator
goroutineWG *sync.WaitGroup
dcrConfig *DynamicClientRegistrationConfig
dynamicClientRegistrar *DynamicClientRegistrar
scopeFilter *ScopeFilter
securityHeadersApplier func(http.ResponseWriter, *http.Request)
userIdentifierClaim string
revocationURL string
name string
redirURLPath string
logoutURLPath string
tokenURL string
authURL string
endSessionURL string
postLogoutRedirectURI string
jwksURL string
issuerURL string
groupClaimName string
introspectionURL string
providerURL string
roleClaimName string
audience string
clientID string
clientSecret string
clientAuthMethod string
clientAssertion *ClientAssertionSigner
// clientSecretExpiresAt is the RFC 7591 userinfo client_secret_expires_at
// (unix seconds) returned at DCR registration, or 0 when the IdP
// grants a non-expiring secret. Guarded by metadataMu like the other
// DCR-installed credential fields; used by dcrRegistrationNeeded to
// re-register a client whose secret has lapsed (R180).
clientSecretExpiresAt int64
// dcrClientAssertionBuilder lazily builds a client-assertion signer
// from the static config's key material. Used when DCR provisions a
// private_key_jwt client but no signer was built at construction
// (because the static ClientAuthMethod was not private_key_jwt); see
// R162 / updateMetadataEndpoints.
dcrClientAssertionBuilder func() (*ClientAssertionSigner, error)
registrationURL string
// configRevocationURL, configEndSessionURL, and configIntrospectionURL
// hold operator-configured endpoint overrides (Config.RevocationURL,
// Config.OIDCEndSessionURL, Config.IntrospectionURL). They are set once at
// construction and never mutated afterwards, so they are read lock-free,
// the same contract as providerURL, which updateMetadataEndpoints already
// reads unlocked. A manual override always wins over discovery; an empty
// string means use the discovered value.
configRevocationURL string
configEndSessionURL string
configIntrospectionURL string
backchannelLogoutPath string
frontchannelLogoutPath string
scopesSupported []string
scopes []string
extraAuthParams map[string]string
// resource holds the RFC 8707 resource indicator from Config.Resource
// (Config.Validate() already guarantees it is either empty or a
// non-empty absolute URI). Sent as the `resource` param on the
// authorization request and on both the authorization_code and
// refresh_token grants.
resource string
// explicitAudience mirrors Config.Audience verbatim, with no
// resource- or clientID-based defaulting applied. audience (below) does
// carry that defaulting, for token-validation purposes; explicitAudience
// exists so buildAuthURL can decide whether to send the non-standard
// `audience` request parameter without that default leaking onto the
// wire.
explicitAudience string
refreshGracePeriod time.Duration
maxRefreshTokenAge time.Duration
metadataMu sync.RWMutex
dcrMu sync.Mutex
shutdownOnce sync.Once
sessionInvalidationCache CacheInterface
frontchannelMarkers markerQuota
refreshResultCache CacheInterface
minimalHeaders bool
stripAuthCookies bool
enableBackchannelLogout bool
enableFrontchannelLogout bool
tmbSessionURLPath string
tmbClaims []string
requireTokenIntrospection bool
allowPrivateIPAddresses bool
// allowUnauthenticatedPreflight mirrors Config.AllowUnauthenticatedPreflight
// (default false): gates whether shouldBypassAuth's genuine-preflight
// check (middleware.go) bypasses OIDC auth at all.
allowUnauthenticatedPreflight bool
// streamingRefresh mirrors Config.StreamingRefresh (default false).
streamingRefresh bool
// allowLoopbackHosts permits loopback/localhost hosts in outbound URL
// validation (validateHost). Derived at construction time from a loopback
// providerURL (local development), never operator-set directly. Mirrors
// the allowLoopback derivation in updateMetadataEndpoints.
allowLoopbackHosts bool
disableReplayDetection bool
allowOpaqueTokens bool
strictAudienceValidation bool
overrideScopes bool
enablePKCE bool
forceHTTPS bool
suppressDiagnosticLogs bool
// Bearer-auth runtime state (populated only when EnableBearerAuth=true).
bearerIdentifierClaim string
bearerFailureTracker *bearerFailureTracker
maxTokenAge time.Duration
maxIdentifierLength int
bearerFailureThreshold int
bearerFailureWindow time.Duration
bearerFailurePenalty time.Duration
enableBearerAuth bool
stripAuthorizationHeader bool
bearerEmitWWWAuthenticate bool
bearerOverridesCookie bool
}