Compare commits

...
25 Commits
Author SHA1 Message Date
github-actions[bot] 169a9f66f9 chore(release): v1.0.66 2026-11-21 04:45:49 +00:00
lukaszraczyloandGitHub f7b96344e4 fix(metadata): retry discovery HTTP errors and recover in the background (#169)
A provider behind the same Traefik answers 404 while its router is not
loaded, and 502 or 503 while it restarts. GetProviderMetadata returned
these statuses as a plain error, so the startup retries stopped at the
first attempt. After that, nothing retried until a request arrived, and
that request got the 503 page (#147).

- GetProviderMetadata returns a non-200 status as *HTTPError, so the
  startup retries apply to 429 and 5xx.
- RetryConfig gets RetryableStatusCodes. MetadataFetchRetryConfig sets
  it to 404, so only discovery retries a 404.
- If startup discovery fails, the init goroutine retries in the
  background (5 s, doubling up to 60 s, with jitter). It stops when
  metadata is adopted or when Close cancels the instance context.
- GetMetadataWithRecovery takes a context, so Close also ends the
  startup retries.
- Background attempts log at ERROR for the first three and every tenth,
  at DEBUG otherwise. A document with no usable issuer does not end
  recovery. A Close during the startup retries logs at DEBUG only.
- The 503 served while metadata is unavailable or initialization times
  out carries Retry-After: 10, and the startup error log names the
  middleware.

TestMetadataRecoveryOnProviderFailure and the issue152 cold-start test
now serve 400 for a failed discovery, because startup retries 500 and
503 and these tests need init to fail at once.
2026-11-21 04:42:32 +00:00
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
lukaszraczylo 2ceea0f617 fix(session): accept dotted opaque refresh tokens
Entra ID refresh tokens contain two dots but are not JWTs. The session
validator treated them as JWTs and rejected them. The session then lost
the refresh token, and users had to log in again after one hour.

A refresh token now falls back to opaque validation if its first segment
is not a JSON header with an alg member. A token that claims to be a JWT
keeps full JWT validation.

Fixes #167
2026-11-11 17:26:20 +00:00
lukaszraczylo 972993980e refactor(session): remove unreachable ChunkManager eviction code
ChunkManager.sessionMap is never written in this package, so the limit
and emergency eviction paths cannot run. Remove enforceSessionLimit,
findOldestSessions, CanCreateSession, EmergencyCleanup, GetSessionCount,
GetMemoryStats and globalMaxSessions, with the tests that only covered them.
The session/chunking package keeps its own copy.
2026-11-03 01:46:11 +00:00
lukaszraczylo 83da8e0bc2 fix(security): scope logout invalidation keys to the middleware instance
Back-channel logout keys for sub, sid and jti had no issuer or client
in them, in a cache shared by every instance. A logout for user u1 in
one realm logged out u1 in another, and an equal jti in two realms
looked like a replay. Keys now carry the instance prefix. An instance
without a prefix keeps the old key.
2026-11-03 01:31:35 +00:00
lukaszraczylo fd3fbbdbab fix(security): classify audience failures by sentinel error
The lenient-audience path chose itself when the verify error text
contained the word audience. The key lookup error embeds the kid from the
unverified token header. A kid of audience made a failed signature look
like an audience-only failure. verifyAudience now returns a sentinel and
the caller uses errors.Is.
2026-11-03 01:24:28 +00:00
lukaszraczylo 92c311fde1 fix(jwt): bind ECDSA curve to the algorithm and require fixed signature length
ES256, ES384 and ES512 verified against any curve and any even-length
signature. RFC 7518 fixes the curve per algorithm and the signature to
R||S at the curve's octet length. Verification now enforces both.
2026-11-03 01:21:01 +00:00
lukaszraczylo 2f0ee00e51 fix(security): scope introspection cache keys to the middleware instance
The introspection cache used the raw token as key in a shared cache.
Two instances with different providers or clients shared results. Keys
now use the same instance prefix as the verified-token cache.
2026-11-03 01:18:12 +00:00
lukaszraczylo 6e522fd212 fix(security): scope the verified-token cache to its middleware instance
The verified-token cache is one process-wide cache keyed by the raw
token. A verdict stored by one middleware instance satisfied any other
instance, so a token valid for one client or audience skipped the
issuer, audience and signature checks on another route. Each instance
now prefixes keys with its provider, client ID and audience. Dynamic
client registration updates the prefix.
2026-11-03 01:15:45 +00:00
lukaszraczylo 3ce5f428cf fix(session): keep old access token on failed store, cap incoming path, fold proto case
SetAccessToken cleared the old token before it found that no request
was available for the chunk cookies. The old token was lost.
The stored post-login path had no length bound and could bloat every
later Cookie header. It is now capped at 2048 bytes.
DetermineScheme compared X-Forwarded-Proto case-sensitively while the
cookie code did not, so HTTPS gave an http redirect_uri.
2026-11-03 01:10:36 +00:00
lukaszraczylo dc4da7b4c9 fix(security): drop client values for templated headers
A templated header skipped its Set when the render failed, came out
empty or failed sanitising. The client's own value of that header then
reached the backend. A client could forge a header such as X-Tenant by
using a token that lacks the claim. The middleware now removes the
inbound value first. Identity headers and Authorization are left alone.
2026-11-03 01:10:20 +00:00
lukaszraczylo 2cb42aa485 perf(logout): parse the ID token once for the invalidation check
With backchannel or frontchannel logout on, every authenticated request
parsed the ID token twice to read sid, sub and iat. One shared parse now
returns the same values. A test pins equality with the two separate
calls for valid, partial and malformed tokens. The gain is one parseJWT
call fewer per request. I did not measure it under yaegi.
2026-11-03 01:01:52 +00:00
lukaszraczylo 9ecd987416 fix(bearer): key the failure tracker by IPv6 /64
The bearer failure tracker keyed entries by the full source address.
One IPv6 host could create a new entry per request and grow the map for
window plus penalty seconds. It now shares one entry per /64, like the
login limiter. IPv4 keys do not change.
2026-11-03 00:59:16 +00:00
lukaszraczylo b1cf524bb4 fix(config): reject durations and sizes that overflow at startup
Several seconds settings became time.Duration with no upper bound, so
a large value wrapped negative or to zero. maxTokenAgeSeconds then
disabled the bearer age check, and a zero health check interval
panicked time.NewTicker. A circuit breaker threshold above MaxInt32
narrowed to a value that tripped on the first failure. A huge poolSize
allocated the connection channel up front. Validate now rejects these
values. Sane and default values are unchanged.
2026-11-03 00:53:12 +00:00
lukaszraczylo eec076f812 fix(resilience): recover from unhealthy and close half-open on successes
The health check promoted to healthy only when the fail counter was
above zero. The first success zeroed that counter, so a threshold of 2
or more never recovered. It now promotes on the status and the success
streak.

The breaker closed when admitted probes reached HalfOpenMaxRequests,
not when that many succeeded. A new counter tracks successes.
2026-11-03 00:46:46 +00:00
lukaszraczylo ac0fcfbe6a fix(redis): never send a zero or shortened expiry
Set and SetMany sent PSETEX with 0 for a TTL under 1ms, which Redis
rejects. They sent SETEX with truncated seconds for a fractional TTL,
so keys expired early. A shared helper now rounds up to a millisecond
and uses SETEX only for whole seconds.
2026-11-03 00:42:17 +00:00
lukaszraczylo 78db86b455 fix(security): treat trailing-dot hosts as their blocked names
validateHost and isLoopbackHost matched hostnames by exact string. The
spellings localhost. and metadata.google.internal. passed the SSRF
check. The check now drops the root dot and any IPv6 zone id first.
A bare IPv6 literal without a port no longer fails the host check.
2026-11-03 00:42:00 +00:00
lukaszraczylo 621f7993a8 fix(cache,jwt): bound grace, resize, memory cap and time claims
Grace extensions overwrote ExpiresAt, so a polled stale entry never hit
MaxGracePeriod. The bound now uses the first expiry.

SetMaxSize with a non-positive size spun the eviction loop forever. It
now clamps to 1.

One value larger than MaxMemoryBytes flushed every other entry and left
the cache over its cap. The cache now drops that value.

int64(float64) wrapped a far-future nbf or iat into the past, so the
token passed. Non-finite and out-of-range claims now fail.
2026-11-03 00:37:12 +00:00
lukaszraczylo a1b7059da1 fix(session): keep cooldown trackers and trim stale chunks by key
Cleanup evicted a refresh tracker by last attempt time alone. A tracker
could leave its cooldown early. Cleanup now also requires the cooldown
to be over.

The stale chunk trim deleted an index range derived from the chunk
count. A sparse key set kept stale high keys and failed the read. The
trim now deletes every key at or above token_total.
2026-11-03 00:15:52 +00:00
lukaszraczylo dae08b2c21 fix(refresh): reset window to zero attempts and admit one half-open probe
The window and cooldown resets set attempts to 1. The gate then counted
the same call again, so a reset window allowed one call fewer than a
fresh one. With a limit of 1 the session locked out at once. Resets now
start at 0.

The half-open breaker admitted every caller. It now admits one probe,
claimed with a compare-and-swap. A stale probe is replaced after
OpenDuration, so a lost probe cannot wedge the breaker.
2026-11-03 00:07:15 +00:00
lukaszraczylo 29a9b1f8f2 fix(ratelimit): key IPv6 sources by /64 prefix
The per-source limiter keyed buckets by the full IPv6 address. One host
holds a whole /64 and can mint 2^64 buckets. That host bypasses the
limit and grows the entries map. The limiter now shares one bucket per
/64. IPv4 keys do not change.
2026-11-03 00:02:07 +00:00
lukaszraczyloandGitHub 9ab7220828 fix(security): close confirmed findings from the 2026-10-15 hunt (#166)
Seven findings are fixed. Each fix has a regression test.

- Compare X-Forwarded-Host and the serving host case-insensitively, so a
  case variant cannot widen the session cookie Domain.
- Reject a future iat on the opaque introspection path.
- Serve the cached parsed JWKS inside the signature-refresh cooldown.
- Release the half-open circuit slot when a probe panics.
- Cap requests that wait for provider initialisation at 512. Extra
  requests receive 503 with Retry-After.
- Cap cookie deletion headers at 32 cookie names per response.
- Cap front-channel sid markers at 1000, so unauthenticated requests
  cannot evict backchannel or jti replay markers.
2026-10-16 00:47:35 +01:00
lukaszraczyloandGitHub f0af6282dc feat(templates): add toJson helper for object claims (#165)
Header templates can now emit an object or array claim as one JSON
header. Example: {{get .Claims "tenant" | toJson}}. The backend parses
the claim, so the middleware does not need to know its schema.

The helper adds no new access path. The validator treats toJson like
default and checks its arguments. A claim must be on the whitelist, and
a dump of the whole claims map is rejected. An absent or empty claim
skips the header. The JSON encoder escapes control characters.

A rendered header value over 8192 bytes is still dropped. The drop is
now logged at error level, with the header name and without the value.
Other sanitizer drops stay at debug level.

Tests cover value types, edge cases, whitelist bypass attempts, token
leaks and header injection. A new yaegi check runs the helper under the
interpreter. README, configuration docs and the plugin manifest show the
new helper.
2026-10-05 00:20:01 +01:00
lukaszraczylo 7c5a86f4e1 chore: remove dependabot config 2026-10-04 01:04:57 +01:00
69 changed files with 4395 additions and 470 deletions
-52
View File
@@ -1,52 +0,0 @@
version: 2
updates:
# Maintain dependencies for GitHub Actions
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
day: "monday"
time: "09:00"
open-pull-requests-limit: 5
commit-message:
prefix: "chore(deps)"
include: "scope"
labels:
- "dependencies"
- "github-actions"
reviewers:
- "lukaszraczylo"
# Maintain Go module dependencies
- package-ecosystem: "gomod"
directory: "/"
schedule:
interval: "weekly"
day: "monday"
time: "09:00"
open-pull-requests-limit: 10
commit-message:
prefix: "chore(deps)"
include: "scope"
labels:
- "dependencies"
- "go"
reviewers:
- "lukaszraczylo"
# Group patch updates together
groups:
patch-updates:
patterns:
- "*"
update-types:
- "patch"
minor-updates:
patterns:
- "*"
update-types:
- "minor"
# Ignore certain dependencies if needed
ignore:
# Example: ignore specific versions
# - dependency-name: "github.com/example/package"
# versions: ["1.x", "2.x"]
+7
View File
@@ -72,6 +72,13 @@ testData:
value: "{{.Claims.email}}"
- name: Authorization
value: "Bearer {{.AccessToken}}"
# Object/array claim as one JSON header; the claim must be whitelisted.
- name: X-Tenant
value: '{{get .Claims "tenant" | toJson}}'
# Extends the built-in claim whitelist for templated headers.
allowedClaims:
- tenant
# Security headers (default profile is enabled out of the box)
securityHeaders:
+19
View File
@@ -8,6 +8,12 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### 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](docs/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
@@ -121,6 +127,19 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Fixed
- **Provider metadata now recovers without a request (#147).** A discovery
response of `404`, `429` or `5xx` is now retried during startup. Traefik
answers `404` while the router of an IdP behind the same Traefik is not
loaded yet. During these retries, requests wait up to 30 s for
initialization, as they already do when the provider cannot be reached.
If startup discovery still fails, each middleware instance
retries in the background (5 s, doubling up to 60 s) until the provider
answers or the instance closes. Before this change, an instance stayed
broken until a request reached it. Background attempts log at ERROR for
the first three and then for every tenth, and at DEBUG otherwise. The
`503` served while metadata is unavailable or initialization times out
now carries `Retry-After: 10`. The startup error log names the
middleware.
- 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`
+30 -3
View File
@@ -126,7 +126,7 @@ Full reference in [docs/CONFIGURATION.md](docs/CONFIGURATION.md).
| `refreshGracePeriodSeconds` | `60` | Proactively refresh tokens this many seconds before expiry. |
| `maxRefreshTokenAgeSeconds` | `21600` | Heuristic max stored refresh-token lifetime (6h). Past this, the plugin treats the RT as expired without contacting the IdP — returns 401 to AJAX, full re-auth on navigations. Set `0` to disable. Tune to match your IdP's RT TTL. |
| `rateLimit` | `100` | Requests/sec. Min `10`. |
| `perSourceLoginRateLimit` | `0` (off) | Throttle OIDC auth events (authorization-code callback + login initiation) per external client source, auth events per minute. Keys and classifies the source by RemoteAddr only, never `X-Forwarded-For`, so a client cannot spoof it. Internal/loopback sources (proxies, in-cluster) are never throttled. `0` disables. RemoteAddr is the TCP peer. Behind a load balancer or CDN, the limiter keys on the proxy address: a private address is never throttled, and a public address puts every client in one shared bucket. |
| `perSourceLoginRateLimit` | `0` (off) | Throttle OIDC auth events (authorization-code callback, login initiation and forced refreshes at the `tmbSessionURL` endpoint) per external client source, auth events per minute. Keys and classifies the source by RemoteAddr only, never `X-Forwarded-For`, so a client cannot spoof it. Internal/loopback sources (proxies, in-cluster) are never throttled. `0` disables. RemoteAddr is the TCP peer. Behind a load balancer or CDN, the limiter keys on the proxy address: a private address is never throttled, and a public address puts every client in one shared bucket. |
| `logLevel` | `info` | `debug`, `info`, `error`. |
| `audience` | `clientID`, or `resource` if set | Custom access-token audience (Auth0 custom APIs). |
| `resource` | none | RFC 8707 resource indicator, alternative to `audience` for supporting IdPs (see [docs/RFC8707.md](docs/RFC8707.md)). |
@@ -151,6 +151,7 @@ Full reference in [docs/CONFIGURATION.md](docs/CONFIGURATION.md).
| `clientAssertionAlg` | `RS256` | JWS alg for `private_key_jwt`. Supported: `RS256/384/512`, `PS256/384/512`, `ES256/384/512`. |
| `enableBackchannelLogout` / `backchannelLogoutURL` | `false` / none | OIDC Back-Channel Logout (server-to-server). |
| `enableFrontchannelLogout` / `frontchannelLogoutURL` | `false` / none | OIDC Front-Channel Logout (iframe). |
| `tmbSessionURL` | none | Path (e.g. `/auth/session`) of an endpoint for SPAs, authenticated by the session cookie: `GET` returns session info and the access token, `POST` forces a refresh. Setting it enables the endpoint; `tmbClaims` lists extra ID-token claims to return. See [docs/TMB.md](docs/TMB.md). |
| `redis` | disabled | See [docs/REDIS.md](docs/REDIS.md). |
| `dynamicClientRegistration` | disabled | See [docs/DCR.md](docs/DCR.md). |
@@ -441,8 +442,34 @@ headers:
Rendering the whole context (`{{.}}`, `{{$}}`), the whole claims map
(`{{.Claims}}`), or any non-listed claim is rejected — this prevents a template
from accidentally forwarding raw tokens or unlisted claims. `range`/`with` must
target a specific listed claim (e.g. `{{range .Claims.groups}}`); `get`/`default`
are the only functions allowed.
target a specific listed claim (e.g. `{{range .Claims.groups}}`); `get`, `default`
and `toJson` are the only functions allowed.
### Forwarding an object claim as JSON
`toJson` serializes a claim (object, array or scalar) to compact JSON, so a
backend can parse the whole claim itself instead of the middleware flattening
it into one header per key:
```yaml
allowedClaims:
- tenant
headers:
- name: X-Tenant
value: '{{get .Claims "tenant" | toJson}}' # {"id":"t-1","plan":"pro"}
- name: X-Groups
value: "{{toJson .Claims.groups}}" # ["admin","users"]
```
- The claim must be on the whitelist (built-in or `allowedClaims`).
`{{toJson .Claims}}`, `{{toJson .}}` and non-listed claims are rejected.
- An absent or empty claim skips the header instead of sending `""`.
- Control characters are JSON-escaped, so a claim cannot inject extra header
lines.
- A rendered value over 8192 bytes, or one with bidi-override characters, is
dropped. The oversize case is logged at error level (header name only, never
the value); keep the claim small, since proxies commonly cap headers at
8-16 KB.
> **File-provider users: escape the braces.** Traefik's file provider runs
> every dynamic configuration file through Go templating before the plugin
+153
View File
@@ -0,0 +1,153 @@
package traefikoidc
import (
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestAccessTokenExpiry(t *testing.T) {
now := time.Unix(1_700_000_000, 0)
jwtWithExp := makeTestJWT(t, map[string]interface{}{"exp": float64(1_700_007_200)})
jwtNoExp := makeTestJWT(t, map[string]interface{}{"sub": "u"})
cases := []struct {
name string
tr *TokenResponse
want int64
}{
{"nil response", nil, 0},
{"expires_in from the response", &TokenResponse{AccessToken: "opaque-access-token-0123456789", ExpiresIn: 1800}, 1_700_001_800},
{"expires_in wins over the JWT exp", &TokenResponse{AccessToken: jwtWithExp, ExpiresIn: 60}, 1_700_000_060},
{"JWT exp when the response has no expires_in", &TokenResponse{AccessToken: jwtWithExp}, 1_700_007_200},
{"opaque token without expires_in", &TokenResponse{AccessToken: "opaque-access-token-0123456789"}, 0},
{"JWT without exp and no expires_in", &TokenResponse{AccessToken: jwtNoExp}, 0},
{"non-positive expires_in is ignored", &TokenResponse{AccessToken: jwtWithExp, ExpiresIn: -5}, 1_700_007_200},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
assert.Equal(t, c.want, accessTokenExpiry(c.tr, now))
})
}
}
// saveAndReload stores sd's state and loads it back through a fresh request,
// the way a following request would see it.
func saveAndReload(t *testing.T, sm *SessionManager, sd *SessionData) *SessionData {
t.Helper()
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
require.NoError(t, sd.Save(req, rec))
next := httptest.NewRequest(http.MethodGet, "/", nil)
for _, c := range rec.Result().Cookies() {
next.AddCookie(c)
}
loaded, err := sm.GetSession(next)
require.NoError(t, err)
return loaded
}
func TestSessionAccessTokenExpiresAt(t *testing.T) {
const tokenA = "test-access-token-0123456789abcdefghijklmnopqrstuvwxyz"
const tokenB = "other-access-token-0123456789abcdefghijklmnopqrstuvwxyz"
exp := time.Now().Add(30 * time.Minute).Unix()
for _, storage := range []struct {
name string
combined bool
}{{"combined cookie storage", true}, {"legacy cookie storage", false}} {
t.Run("survives a save and reload with "+storage.name, func(t *testing.T) {
sm := createTestSessionManager(t)
sd, err := sm.GetSession(httptest.NewRequest(http.MethodGet, "/", nil))
require.NoError(t, err)
sd.useCombinedStorage = storage.combined
sd.SetAccessToken(tokenA)
sd.SetAccessTokenExpiresAt(tokenA, exp)
loaded := saveAndReload(t, sm, sd)
assert.Equal(t, tokenA, loaded.GetAccessToken())
assert.Equal(t, exp, loaded.GetAccessTokenExpiresAt())
})
}
t.Run("a session saved without one reports unknown", func(t *testing.T) {
sm := createTestSessionManager(t)
sd, err := sm.GetSession(httptest.NewRequest(http.MethodGet, "/", nil))
require.NoError(t, err)
sd.SetAccessToken(tokenA)
assert.Zero(t, saveAndReload(t, sm, sd).GetAccessTokenExpiresAt())
})
t.Run("the expiry belongs to its token", func(t *testing.T) {
sm := createTestSessionManager(t)
sd, err := sm.GetSession(httptest.NewRequest(http.MethodGet, "/", nil))
require.NoError(t, err)
sd.SetAccessToken(tokenA)
sd.SetAccessTokenExpiresAt(tokenA, exp)
sd.SetAccessToken(tokenA) // unchanged token keeps its expiry
assert.Equal(t, exp, sd.GetAccessTokenExpiresAt())
sd.SetAccessToken(tokenB) // a different token drops it
assert.Zero(t, sd.GetAccessTokenExpiresAt())
sd.SetAccessTokenExpiresAt(tokenB, exp)
sd.SetAccessToken("") // clearing the token drops it
assert.Zero(t, sd.GetAccessTokenExpiresAt())
})
t.Run("a non-positive value clears it", func(t *testing.T) {
sm := createTestSessionManager(t)
sd, err := sm.GetSession(httptest.NewRequest(http.MethodGet, "/", nil))
require.NoError(t, err)
sd.SetAccessToken(tokenA)
sd.SetAccessTokenExpiresAt(tokenA, exp)
sd.SetAccessTokenExpiresAt(tokenA, 0)
assert.Zero(t, sd.GetAccessTokenExpiresAt())
})
t.Run("does not leak into the next user of a pooled session", func(t *testing.T) {
sm := createTestSessionManager(t)
sd, err := sm.GetSession(httptest.NewRequest(http.MethodGet, "/", nil))
require.NoError(t, err)
sd.SetAccessToken(tokenA)
sd.SetAccessTokenExpiresAt(tokenA, exp)
sd.Reset()
assert.Zero(t, sd.GetAccessTokenExpiresAt())
})
t.Run("a failed store keeps the previous token and its expiry", func(t *testing.T) {
sm := createTestSessionManager(t)
sd, err := sm.GetSession(httptest.NewRequest(http.MethodGet, "/", nil))
require.NoError(t, err)
sd.SetAccessToken(tokenA)
sd.SetAccessTokenExpiresAt(tokenA, exp)
oversized := incompressibleToken(200 * 1024)
sd.SetAccessToken(oversized) // too large even after compression: not stored
sd.SetAccessTokenExpiresAt(oversized, exp+3600)
assert.Equal(t, tokenA, sd.GetAccessToken())
assert.Equal(t, exp, sd.GetAccessTokenExpiresAt())
})
t.Run("an expiry for a token that is not stored is ignored", func(t *testing.T) {
sm := createTestSessionManager(t)
sd, err := sm.GetSession(httptest.NewRequest(http.MethodGet, "/", nil))
require.NoError(t, err)
sd.SetAccessToken(tokenA)
sd.SetAccessTokenExpiresAt(tokenB, exp)
assert.Zero(t, sd.GetAccessTokenExpiresAt())
sd.SetAccessTokenExpiresAt("", exp)
assert.Zero(t, sd.GetAccessTokenExpiresAt())
sd.SetAccessTokenExpiresAt(tokenA, exp)
sd.SetAccessTokenExpiresAt(tokenB, 0) // cannot clear another token's expiry
assert.Equal(t, exp, sd.GetAccessTokenExpiresAt())
})
}
+24
View File
@@ -0,0 +1,24 @@
package traefikoidc
import (
"errors"
"fmt"
"testing"
)
// Only a real audience mismatch may select the lenient-audience path; an
// error text that merely embeds the attacker-chosen kid must not.
func TestAudienceErrorClassifiedBySentinel(t *testing.T) {
if !errors.Is(fmt.Errorf("standard claim verification failed: %w", verifyAudience("x", "y")), errInvalidAudience) {
t.Fatal("audience mismatch not recognized through wrapping")
}
if errors.Is(verifyAudience("y", "y"), errInvalidAudience) {
t.Fatal("matching audience classified as mismatch")
}
for _, kid := range []string{"audience", "invalid audience"} {
err := fmt.Errorf("failed to get public key: no matching public key found for kid: %s", kid)
if errors.Is(err, errInvalidAudience) {
t.Errorf("kid %q fooled the audience classifier", kid)
}
}
}
+1
View File
@@ -444,6 +444,7 @@ func (t *TraefikOidc) handleCallback(rw http.ResponseWriter, req *http.Request,
session.SetUserIdentifier(userIdentifier)
session.SetIDToken(tokenResponse.IDToken)
session.SetAccessToken(tokenResponse.AccessToken)
session.SetAccessTokenExpiresAt(tokenResponse.AccessToken, accessTokenExpiry(tokenResponse, time.Now()))
session.SetRefreshToken(tokenResponse.RefreshToken)
session.SetCSRF("")
+55
View File
@@ -6,6 +6,7 @@ import (
"net/http/httptest"
"net/url"
"testing"
"time"
"github.com/stretchr/testify/suite"
)
@@ -685,6 +686,60 @@ func (s *AuthFlowBehaviourSuite) TestHandleCallback_SuccessfulAuthentication() {
mockVerifier.AssertVerifyTokenCalled(s.T())
}
// TestHandleCallback_RecordsAccessTokenExpiry checks that a successful login
// records the access token's expiry from the token response's expires_in.
func (s *AuthFlowBehaviourSuite) TestHandleCallback_RecordsAccessTokenExpiry() {
sessionManager, err := NewSessionManager("test-encryption-key-32-bytes-long!!", false, "", "", 0, s.logger)
s.Require().NoError(err)
defer sessionManager.Shutdown()
s.tOidc.sessionManager = sessionManager
s.tOidc.allowedUsers = nil
nonce := "test-nonce-12345"
idToken := "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwiZW1haWwiOiJ0ZXN0QGV4YW1wbGUuY29tIiwibm9uY2UiOiJ0ZXN0LW5vbmNlLTEyMzQ1IiwiaWF0IjoxNTE2MjM5MDIyfQ.signature"
const opaqueAccessToken = "opaque-access-token-0123456789abcdef"
s.tOidc.tokenExchanger = &EnhancedMockTokenExchanger{
ExchangeResponse: &TokenResponse{
AccessToken: opaqueAccessToken, // opaque: only expires_in can say when it expires
RefreshToken: "refresh-token-value-0123456789abcdef",
IDToken: idToken,
ExpiresIn: 1800,
},
}
s.tOidc.tokenVerifier = &EnhancedMockTokenVerifier{}
s.tOidc.extractClaimsFunc = func(token string) (map[string]interface{}, error) {
return map[string]interface{}{"sub": "1234567890", "email": "[email protected]", "nonce": nonce}, nil
}
csrfToken := "valid-csrf-token"
req := httptest.NewRequest(http.MethodGet, "/callback?code=auth-code&state="+csrfToken, nil)
rw := httptest.NewRecorder()
session, err := sessionManager.GetSession(req)
s.Require().NoError(err)
session.SetCSRF(csrfToken)
session.SetNonce(nonce)
s.Require().NoError(session.Save(req, rw))
session.returnToPoolSafely()
req2 := httptest.NewRequest(http.MethodGet, "/callback?code=auth-code&state="+csrfToken, nil)
for _, cookie := range rw.Result().Cookies() {
req2.AddCookie(cookie)
}
rw2 := httptest.NewRecorder()
s.tOidc.handleCallback(rw2, req2, "https://example.com/callback")
s.Require().Equal(http.StatusFound, rw2.Code)
req3 := httptest.NewRequest(http.MethodGet, "/", nil)
for _, cookie := range rw2.Result().Cookies() {
req3.AddCookie(cookie)
}
loaded, err := sessionManager.GetSession(req3)
s.Require().NoError(err)
s.Equal(opaqueAccessToken, loaded.GetAccessToken())
s.InDelta(time.Now().Add(30*time.Minute).Unix(), loaded.GetAccessTokenExpiresAt(), 5)
}
// TestHandleExpiredToken tests expired token handling
func (s *AuthFlowBehaviourSuite) TestHandleExpiredToken() {
sessionManager, err := NewSessionManager(
+12 -3
View File
@@ -223,6 +223,9 @@ func headerInjectionRuneReason(r rune) string {
return ""
}
// headerReasonTooLong is the headerValueReason result for an over-long value.
const headerReasonTooLong = "exceeds max length"
// headerValueReason reports why value is unsafe to forward as a free-form HTTP
// header value, or "" if acceptable. It rejects values over maxLen (maxLen<=0
// disables the check) and values containing control or bidi-override runes, but
@@ -230,7 +233,7 @@ func headerInjectionRuneReason(r rune) string {
// never includes the value, so it is safe to log.
func headerValueReason(value string, maxLen int) string {
if maxLen > 0 && len(value) > maxLen {
return "exceeds max length"
return headerReasonTooLong
}
for _, r := range value {
if reason := headerInjectionRuneReason(r); reason != "" {
@@ -368,6 +371,11 @@ func enforceIatAge(claims map[string]interface{}, maxAge time.Duration) *bearerE
if time.Since(iat) > maxAge {
return newBearerError(bearerErrInvalidToken, "token iat outside age bound")
}
// The opaque introspection path never runs jwt.Verify, so a future iat
// would otherwise defeat the age bound for the token's whole lifetime.
if time.Until(iat) > ClockSkewToleranceFuture {
return newBearerError(bearerErrInvalidToken, "token iat in the future")
}
return nil
}
@@ -550,9 +558,10 @@ func clientIPForBearer(req *http.Request) string {
}
host, _, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
return req.RemoteAddr
host = req.RemoteAddr
}
return host
// One IPv6 /64 shares a key, so a single host cannot mint 2^64 entries.
return limiterKey(host)
}
// --- Bearer auth entrypoint ---
+24
View File
@@ -0,0 +1,24 @@
package traefikoidc
import (
"net/http/httptest"
"testing"
)
// Addresses in one IPv6 /64 must share one failure-tracker key.
func TestClientIPForBearerCollapsesIPv6Prefix(t *testing.T) {
key := func(addr string) string {
r := httptest.NewRequest("GET", "/", nil)
r.RemoteAddr = addr
return clientIPForBearer(r)
}
if a, b := key("[2001:db8:1:2::1]:1"), key("[2001:db8:1:2:ffff::9]:2"); a != b {
t.Fatalf("same /64 got different keys: %q vs %q", a, b)
}
if a, b := key("[2001:db8:1:2::1]:1"), key("[2001:db8:1:3::1]:1"); a == b {
t.Fatalf("different /64 shared key %q", a)
}
if got := key("192.0.2.7:80"); got != "192.0.2.7" {
t.Fatalf("ipv4 key = %q", got)
}
}
+415
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"
)
@@ -128,6 +130,7 @@ func main() {
// reachable errors.As-replacement site directly under the interpreter.
runCheck("new01-retryexecutor-500-retried", checkNew01RetryExecutorHTTPError500Retried)
runCheck("new01-retryexecutor-400-not-retried", checkNew01RetryExecutorHTTPError400NotRetried)
runCheck("issue147-discovery-status-retried", checkIssue147DiscoveryStatusRetried)
runCheck("new01-retryexecutor-plain-error-no-panic", checkNew01RetryExecutorPlainErrorNoPanic)
runCheck("new01-internal-recovery-httperror-classification", checkNew01InternalRecoveryHTTPErrorClassification)
runCheck("new01-internal-recovery-oidcerror-classification", checkNew01InternalRecoveryOIDCErrorClassification)
@@ -139,7 +142,10 @@ func main() {
runCheck("middleware-erraborthandler-aborts-under-yaegi", checkErrAbortHandlerAbortsUnderYaegi)
runCheck("fix17-setifabsent-claims-once", checkSetIfAbsentUnderYaegi)
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")
}
@@ -389,6 +395,60 @@ func checkNew01RetryExecutorHTTPError400NotRetried() (string, error) {
return fmt.Sprintf(" calls=%d", calls), nil
}
// checkIssue147DiscoveryStatusRetried pins #147 under the interpreter: a
// discovery 404 and 502 come back from GetProviderMetadata as *HTTPError, and
// MetadataFetchRetryConfig retries both (RetryableStatusCodes for the 404,
// the 5xx rule for the 502) until the document is served.
func checkIssue147DiscoveryStatusRetried() (string, error) {
var hits int32
var srv *httptest.Server
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch atomic.AddInt32(&hits, 1) {
case 1:
w.WriteHeader(http.StatusNotFound)
return
case 2:
w.WriteHeader(http.StatusBadGateway)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(oidc.ProviderMetadata{
Issuer: srv.URL,
AuthURL: srv.URL + "/auth",
TokenURL: srv.URL + "/token",
JWKSURL: srv.URL + "/jwks",
})
}))
defer srv.Close()
cfg := oidc.MetadataFetchRetryConfig()
cfg.MaxAttempts = 4
cfg.InitialDelay = time.Millisecond
cfg.MaxDelay = time.Millisecond
re := oidc.NewRetryExecutor(cfg, oidc.NewLogger("error"))
mc := oidc.NewMetadataCacheWithLogger(nil, oidc.NewLogger("error"))
var issuer string
err := re.ExecuteWithContext(context.Background(), func() error {
metadata, fetchErr := mc.GetProviderMetadata(context.Background(), srv.URL, srv.Client())
if fetchErr != nil {
return fetchErr
}
issuer = metadata.Issuer
return nil
})
if err != nil {
return "", fmt.Errorf("discovery 404/502 were not retried to success: %v (requests=%d)", err, atomic.LoadInt32(&hits))
}
if issuer != srv.URL {
return "", fmt.Errorf("issuer = %q, want %q", issuer, srv.URL)
}
if got := atomic.LoadInt32(&hits); got != 3 {
return "", fmt.Errorf("requests = %d, want 3 (404, 502, 200)", got)
}
return " requests=3", nil
}
// checkNew01RetryExecutorPlainErrorNoPanic pins that a plain (non-HTTPError)
// error reaching isRetryableError's asHTTPError check never panics under
// yaegi -- the exact call shape that panicked pre-fix regardless of err's
@@ -807,6 +867,99 @@ func checkIssue162WebSocketHeaderTemplates() (string, error) {
return "", nil
}
// checkToJsonHeaderTemplate pins the toJson template helper under the
// interpreter: its (string, error) closure, json.Marshal of an object claim,
// the nil/absent-claim skip and the validator's rejection of a whole-claims dump.
func checkToJsonHeaderTemplate() (string, error) {
discovery := servers.NewOIDCServer(nil)
defer discovery.Close()
cfg := oidc.CreateConfig()
cfg.ProviderURL = discovery.URL
cfg.ClientID = "yaegi-check-tojson-client"
cfg.ClientSecret = "yaegi-check-tojson-secret"
cfg.CallbackURL = "/oauth2/callback"
cfg.SessionEncryptionKey = "0123456789abcdef0123456789abcdef"
cfg.AllowedClaims = []string{"tenant"}
cfg.Headers = []oidc.TemplatedHeader{
{Name: "X-Tenant", Value: `{{ get .Claims "tenant" | toJson }}`},
{Name: "X-Groups", Value: "{{ toJson .Claims.groups }}"},
{Name: "X-Missing", Value: "{{ toJson .Claims.department }}"},
}
if err := cfg.Validate(); err != nil {
return "", fmt.Errorf("toJson headers must validate: %w", err)
}
bad := oidc.CreateConfig()
*bad = *cfg
bad.Headers = []oidc.TemplatedHeader{{Name: "X-All", Value: "{{ toJson .Claims }}"}}
if err := bad.Validate(); err == nil {
return "", fmt.Errorf("toJson of the whole claims map must fail validation")
}
var seen http.Header
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
seen = r.Header.Clone()
})
h, err := oidc.New(context.Background(), next, cfg, "yaegi-check-tojson")
if err != nil {
return "", fmt.Errorf("New: %w", err)
}
if closer, ok := h.(interface{ Close() error }); ok {
defer closer.Close()
}
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", "/ws", 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]")
b64 := base64.RawURLEncoding.EncodeToString
sig := make([]byte, 32)
for i := range sig {
sig[i] = byte(i + 1)
}
session.SetIDToken(b64([]byte(`{"alg":"RS256","typ":"JWT"}`)) + "." + b64([]byte(`{"tenant":{"id":"t-1","plan":"pro"},"groups":["a","b"]}`)) + "." + b64(sig))
rec := httptest.NewRecorder()
if err := session.Save(setupReq, rec); err != nil {
return "", fmt.Errorf("session.Save: %w", err)
}
session.ReturnToPool()
req := httptest.NewRequest("GET", "/ws", nil)
for _, c := range rec.Result().Cookies() {
req.AddCookie(c)
}
req.Header.Set("Upgrade", "websocket")
req.Header.Set("Connection", "Upgrade")
rw := httptest.NewRecorder()
h.ServeHTTP(rw, req)
if seen == nil {
return "", fmt.Errorf("next was not reached (status %d)", rw.Code)
}
if got, want := seen.Get("X-Tenant"), `{"id":"t-1","plan":"pro"}`; got != want {
return "", fmt.Errorf("X-Tenant = %q, want %q", got, want)
}
if got, want := seen.Get("X-Groups"), `["a","b"]`; got != want {
return "", fmt.Errorf("X-Groups = %q, want %q", got, want)
}
if got := seen.Get("X-Missing"); got != "" {
return "", fmt.Errorf("X-Missing = %q, want header skipped", got)
}
return "", nil
}
// checkStreamingRefreshRevokedGrant drives streamingRefresh under the
// interpreter through the real RefreshCoordinator and token exchanger: an
// expired session whose refresh the IdP answers with invalid_grant must get
@@ -888,6 +1041,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
+2
View File
@@ -82,6 +82,8 @@ func (c Config) configToMap() map[string]interface{} {
result["cookiePath"] = c.CookiePath
result["enableBackchannelLogout"] = c.EnableBackchannelLogout
result["enableFrontchannelLogout"] = c.EnableFrontchannelLogout
result["tmbSessionURL"] = c.TMBSessionURL
result["tmbClaims"] = c.TMBClaims
result["backchannelLogoutURL"] = c.BackchannelLogoutURL
result["frontchannelLogoutURL"] = c.FrontchannelLogoutURL
result["caCertPath"] = c.CACertPath
+1 -78
View File
@@ -921,82 +921,6 @@ func TestMemoryTestOrchestrator_StopLeakDetection_CoverageBoost(t *testing.T) {
// CHUNK MANAGER TESTS
// =============================================================================
func TestChunkManager_GetSessionCount_CoverageBoost(t *testing.T) {
logger := NewLogger("debug")
cm := NewChunkManager(logger)
if cm == nil {
t.Fatal("Expected non-nil ChunkManager")
}
defer cm.Shutdown()
// Test GetSessionCount
count := cm.GetSessionCount()
if count != 0 {
t.Errorf("Expected 0 sessions, got %d", count)
}
}
func TestChunkManager_GetMemoryStats_CoverageBoost(t *testing.T) {
logger := NewLogger("debug")
cm := NewChunkManager(logger)
if cm == nil {
t.Fatal("Expected non-nil ChunkManager")
}
defer cm.Shutdown()
// Test GetMemoryStats
stats := cm.GetMemoryStats()
if stats == nil {
t.Fatal("Expected non-nil stats")
}
// Verify expected keys exist
if _, ok := stats["active_sessions"]; !ok {
t.Error("Expected active_sessions key in stats")
}
if _, ok := stats["max_sessions"]; !ok {
t.Error("Expected max_sessions key in stats")
}
if _, ok := stats["bytes_allocated"]; !ok {
t.Error("Expected bytes_allocated key in stats")
}
}
func TestChunkManager_CanCreateSession_CoverageBoost(t *testing.T) {
logger := NewLogger("debug")
cm := NewChunkManager(logger)
if cm == nil {
t.Fatal("Expected non-nil ChunkManager")
}
defer cm.Shutdown()
// Test CanCreateSession - should be true initially
canCreate, err := cm.CanCreateSession()
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if !canCreate {
t.Error("Expected CanCreateSession to return true when empty")
}
}
func TestChunkManager_EmergencyCleanup_CoverageBoost(t *testing.T) {
logger := NewLogger("debug")
cm := NewChunkManager(logger)
if cm == nil {
t.Fatal("Expected non-nil ChunkManager")
}
defer cm.Shutdown()
// Test EmergencyCleanup - should not panic on empty session map
cm.EmergencyCleanup()
// Verify no sessions exist
if cm.GetSessionCount() != 0 {
t.Error("Expected 0 sessions after cleanup")
}
}
func TestChunkManager_CleanupExpiredSessions_CoverageBoost(t *testing.T) {
logger := NewLogger("debug")
cm := NewChunkManager(logger)
@@ -1008,8 +932,7 @@ func TestChunkManager_CleanupExpiredSessions_CoverageBoost(t *testing.T) {
// Test CleanupExpiredSessions - should not panic on empty session map
cm.CleanupExpiredSessions()
// Verify no sessions exist
if cm.GetSessionCount() != 0 {
if len(cm.sessionMap) != 0 {
t.Error("Expected 0 sessions after cleanup")
}
}
+19 -2
View File
@@ -195,12 +195,14 @@ clientSecret: your-client-secret
| `clientAssertionKeyID` | string | none | `kid` header for `private_key_jwt` assertions. Required when `clientAuthMethod: private_key_jwt`. |
| `clientAssertionAlg` | string | `RS256` | Signing algorithm for `private_key_jwt`. One of `RS256/384/512`, `PS256/384/512`, `ES256/384/512`. |
| `extraAuthParams` | map | none | Extra query parameters appended to the authorization request (e.g. re-selective prompt). |
| `perSourceLoginRateLimit` | int | `0` (off) | Throttle OIDC auth events (callback + login initiation) per external client source, in auth events per minute. Keys and classifies the source by RemoteAddr only, never `X-Forwarded-For`, so a client cannot spoof it. Internal/loopback sources are never throttled. RemoteAddr is the TCP peer. Behind a load balancer or CDN, the limiter keys on the proxy address: a private address is never throttled, and a public address puts every client in one shared bucket. |
| `perSourceLoginRateLimit` | int | `0` (off) | Throttle OIDC auth events (callback, login initiation and forced refreshes at the `tmbSessionURL` endpoint) per external client source, in auth events per minute. Keys and classifies the source by RemoteAddr only, never `X-Forwarded-For`, so a client cannot spoof it. Internal/loopback sources are never throttled. RemoteAddr is the TCP peer. Behind a load balancer or CDN, the limiter keys on the proxy address: a private address is never throttled, and a public address puts every client in one shared bucket. |
| `stripAuthCookies` | bool | `false` | Strip OIDC session cookies from the hop to the backend (mitigates HTTP 431). |
| `enableBackchannelLogout` | bool | `false` | Enable OIDC back-channel logout (IdP-initiated, server-to-server). |
| `backchannelLogoutURL` | string | derived | Back-channel logout endpoint path. |
| `enableFrontchannelLogout` | bool | `false` | Enable OIDC front-channel logout (browser iframe logout). |
| `frontchannelLogoutURL` | string | derived | Front-channel logout endpoint path. |
| `tmbSessionURL` | string | none | Path of the token-mediating-backend endpoint, authenticated by the session cookie. `GET` returns user identifier, groups, roles, expiry, the claims listed in `tmbClaims` and the access token; `POST` forces a token refresh and returns the same. Setting it enables the endpoint. See [TMB.md](TMB.md). |
| `tmbClaims` | []string | none | ID-token claim names returned in the endpoint's `claims` object. Empty by default: nothing extra is exposed. |
| `caCertPath` / `caCertPEM` | string | none | Custom CA bundle for OIDC TLS verification (filesystem path, or inline PEM). Mutually exclusive with `insecureSkipVerify`. |
| `insecureSkipVerify` | bool | `false` | Disable TLS verification for the OIDC client (load balancer / mTLS edge). Emits a loud warning at startup. |
@@ -571,7 +573,7 @@ be emitted — the standard OIDC claims plus common provider claims (`email`,
`phone_number`, `email_verified`, `updated_at`; the authoritative list is
`safeClaimsFields` in `template_validation.go`). Rejected: rendering the whole
context (`{{.}}`, `{{$}}`) or the whole claims map (`{{.Claims}}`), any claim not
on the list, functions other than `get`/`default`, and `range`/`with` that do not
on the list, functions other than `get`/`default`/`toJson`, and `range`/`with` that do not
target a specific listed claim (e.g. `{{range .Claims}}` is rejected; `{{range
.Claims.groups}}` is allowed).
@@ -592,6 +594,21 @@ Listed names apply to both direct access (`{{.Claims.employee_id}}`) and
claim (e.g. `realm_access.roles`) are already accessible without listing them
individually.
**`toJson`** forwards an object or array claim as one JSON header:
```yaml
allowedClaims:
- tenant
headers:
- name: "X-Tenant"
value: "{{get .Claims \"tenant\" | toJson}}"
```
It only serializes values the template can already reach, so the whitelist
still applies; `{{toJson .Claims}}` is rejected. Control characters are
JSON-escaped, and values over 8192 bytes or with bidi-override characters are
dropped; an oversize value is logged at error level (header name only).
---
## Security Headers
+148
View File
@@ -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": "u@example.com", "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.
+16 -2
View File
@@ -9,6 +9,7 @@ import (
"math"
"math/rand/v2"
"net"
"net/http"
"strings"
"sync"
"sync/atomic"
@@ -476,6 +477,9 @@ func (cb *CircuitBreaker) GetMetrics() map[string]interface{} {
type RetryConfig struct {
// RetryableErrors defines error patterns that should trigger retries
RetryableErrors []string `json:"retryable_errors"`
// RetryableStatusCodes lists HTTP statuses retried even though they are
// below 500 and not 429
RetryableStatusCodes []int `json:"retryable_status_codes"`
// MaxAttempts is the maximum number of retry attempts
MaxAttempts int `json:"max_attempts"`
// InitialDelay is the delay before the first retry
@@ -528,6 +532,9 @@ func MetadataFetchRetryConfig() RetryConfig {
"x509",
"tls",
},
// Traefik answers 404 for a provider router that is not loaded yet
// (IdP behind the same Traefik, #147).
RetryableStatusCodes: []int{http.StatusNotFound},
}
}
@@ -766,8 +773,15 @@ func (re *RetryExecutor) isRetryableError(err error) bool {
// "EOF" (isEOFError), or a generic "timeout" — would be reclassified
// retryable and retried to MaxAttempts on a permanent error, repeating
// the failing request (R123, R157).
if statusHTTP, ok := asHTTPError(err); ok && statusHTTP.StatusCode != 0 && statusHTTP.StatusCode < 500 && statusHTTP.StatusCode != 429 {
return false
if statusHTTP, ok := asHTTPError(err); ok && statusHTTP.StatusCode != 0 {
for _, code := range re.config.RetryableStatusCodes {
if statusHTTP.StatusCode == code {
return true
}
}
if statusHTTP.StatusCode < 500 && statusHTTP.StatusCode != 429 {
return false
}
}
// Check for Traefik default certificate error (startup race condition)
+54
View File
@@ -0,0 +1,54 @@
package traefikoidc
import (
"net/http/httptest"
"testing"
"text/template"
)
func ownedHeaderOIDC(t *testing.T, names ...string) *TraefikOidc {
t.Helper()
m := map[string]*template.Template{}
for _, n := range names {
m[n] = template.Must(template.New(n).Option("missingkey=zero").Parse("{{.Claims.tenant}}"))
}
return &TraefikOidc{logger: NewLogger("error"), headerTemplates: m}
}
// A templated header the middleware owns must never carry a client value:
// an optional claim that renders empty must leave the header absent.
func TestTemplatedHeaderDropsClientSpoof(t *testing.T) {
o := ownedHeaderOIDC(t, "X-Tenant")
req := httptest.NewRequest("GET", "/", nil)
req.Header.Set("X-Tenant", "admin-corp")
o.applyHeaderTemplates(req, &principal{Claims: map[string]interface{}{"sub": "u"}})
if got := req.Header.Get("X-Tenant"); got != "" {
t.Fatalf("client-supplied X-Tenant reached the backend: %q", got)
}
}
func TestTemplatedHeaderRenderedValueWins(t *testing.T) {
o := ownedHeaderOIDC(t, "X-Tenant")
req := httptest.NewRequest("GET", "/", nil)
req.Header.Set("X-Tenant", "evil")
o.applyHeaderTemplates(req, &principal{Claims: map[string]interface{}{"tenant": "acme"}})
if got := req.Header.Get("X-Tenant"); got != "acme" {
t.Fatalf("X-Tenant = %q, want acme", got)
}
}
// Identity headers are injected before templates run; an empty render must
// not clobber them, and Authorization stays as received.
func TestTemplatedHeaderKeepsIdentityAndAuthorization(t *testing.T) {
o := ownedHeaderOIDC(t, "X-Forwarded-User", "Authorization")
req := httptest.NewRequest("GET", "/", nil)
req.Header.Set("X-Forwarded-User", "alice")
req.Header.Set("Authorization", "Bearer abc")
o.applyHeaderTemplates(req, &principal{Claims: map[string]interface{}{"sub": "u"}})
if got := req.Header.Get("X-Forwarded-User"); got != "alice" {
t.Fatalf("identity header clobbered: %q", got)
}
if got := req.Header.Get("Authorization"); got != "Bearer abc" {
t.Fatalf("Authorization changed: %q", got)
}
}
+59 -3
View File
@@ -13,6 +13,7 @@ import (
"net/http/cookiejar"
"net/url"
"strings"
"sync/atomic"
"time"
)
@@ -92,6 +93,34 @@ type TokenResponse struct {
ExpiresIn int `json:"expires_in"`
}
// jwtExpiry returns the exp claim of a JWT (unix seconds), or 0 when token is
// not a JWT or carries no numeric exp.
func jwtExpiry(token string) int64 {
parsed, err := parseJWT(token)
if err != nil {
return 0
}
exp, ok := parsed.Claims["exp"].(float64)
if !ok {
return 0
}
return int64(exp)
}
// accessTokenExpiry returns when the access token in a token response expires
// (unix seconds): from the response's expires_in when the IdP sent one,
// otherwise from the token's own exp claim. It returns 0 when neither is known
// (an opaque token without expires_in).
func accessTokenExpiry(tr *TokenResponse, now time.Time) int64 {
if tr == nil {
return 0
}
if tr.ExpiresIn > 0 {
return now.Unix() + int64(tr.ExpiresIn)
}
return jwtExpiry(tr.AccessToken)
}
// exchangeTokens performs OAuth 2.0 token exchange with the authorization server.
// It supports both authorization code and refresh token grant types with PKCE support.
// Parameters:
@@ -293,10 +322,37 @@ func extractClaims(tokenString string) (map[string]interface{}, error) {
// TokenCache provides a specialized cache for JWT tokens and their parsed claims.
// It wraps the UniversalCache with token-specific operations.
type TokenCache struct {
// ns scopes entries to one middleware instance (issuer|client|audience)
// so a verdict cached by one instance cannot satisfy another.
ns atomic.Value
// cache is the underlying universal cache implementation
cache *UniversalCache
}
// SetNamespace sets the verification context that scopes this cache's keys.
func (tc *TokenCache) SetNamespace(ns string) {
if tc == nil {
return
}
tc.ns.Store(ns)
}
// Namespace returns the scope set by SetNamespace, or "" when none is set.
func (tc *TokenCache) Namespace() string {
if tc == nil {
return ""
}
ns, _ := tc.ns.Load().(string)
return ns
}
func (tc *TokenCache) key(token string) string {
if ns, _ := tc.ns.Load().(string); ns != "" {
return "t-" + ns + "|" + token
}
return "t-" + token
}
// NewTokenCache creates and initializes a new TokenCache.
// It uses the global cache manager to ensure singleton behavior.
func NewTokenCache() *TokenCache {
@@ -313,7 +369,7 @@ func NewTokenCache() *TokenCache {
// - claims: Parsed claims from the token
// - expiration: The duration for which the cache entry should be valid
func (tc *TokenCache) Set(token string, claims map[string]interface{}, expiration time.Duration) {
token = "t-" + token
token = tc.key(token)
_ = tc.cache.Set(token, claims, expiration) // Safe to ignore: cache failures are non-critical
}
@@ -325,7 +381,7 @@ func (tc *TokenCache) Set(token string, claims map[string]interface{}, expiratio
// - map[string]interface{}: The cached claims if found
// - A boolean indicating whether the token was found in the cache (true if found, false otherwise)
func (tc *TokenCache) Get(token string) (map[string]interface{}, bool) {
token = "t-" + token
token = tc.key(token)
value, found := tc.cache.Get(token)
if !found {
return nil, false
@@ -338,7 +394,7 @@ func (tc *TokenCache) Get(token string) (map[string]interface{}, bool) {
// Parameters:
// - token: The raw token string to remove from the cache
func (tc *TokenCache) Delete(token string) {
token = "t-" + token
token = tc.key(token)
tc.cache.Delete(token)
}
+25
View File
@@ -0,0 +1,25 @@
package traefikoidc
import "testing"
func TestValidateHostCanonicalForms(t *testing.T) {
o := &TraefikOidc{}
blocked := []string{
"localhost.", "LOCALHOST.", "metadata.google.internal.", "metadata.google.internal",
"169.254.169.254.", "fe80::1%eth0", "[fe80::1]", "::1",
}
for _, h := range blocked {
if err := o.validateHost(h); err == nil {
t.Errorf("validateHost(%q) = nil, want blocked", h)
}
}
allowed := []string{"idp.example.com", "idp.example.com.", "2606:4700::1111"}
for _, h := range allowed {
if err := o.validateHost(h); err != nil {
t.Errorf("validateHost(%q) = %v, want allowed", h, err)
}
}
if !isLoopbackHost("localhost.") {
t.Error("isLoopbackHost(localhost.) = false")
}
}
+238
View File
@@ -0,0 +1,238 @@
package traefikoidc
import (
"context"
"crypto"
"crypto/rand"
"crypto/rsa"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestEnhanceSessionSecurity_CaseVariantForwardedHostStaysHostScoped(t *testing.T) {
cases := []struct {
name string
xfh string
}{
{name: "exact-case parent", xfh: "corp.example.com"},
{name: "upper-case parent", xfh: "CORP.example.com"},
{name: "mixed-case parent", xfh: "Corp.Example.COM"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
sm := createTestSessionManager(t)
t.Cleanup(func() { _ = sm.Shutdown() })
req := httptest.NewRequest(http.MethodGet, "https://app.corp.example.com/", nil)
req.Host = "app.corp.example.com"
req.Header.Set("X-Forwarded-Host", tc.xfh)
opts := sm.EnhanceSessionSecurity(nil, req)
if opts.Domain != "app.corp.example.com" {
t.Fatalf("Domain = %q, want host-scoped app.corp.example.com", opts.Domain)
}
})
}
t.Run("case-variant forwarded host equal to serving host is kept", func(t *testing.T) {
sm := createTestSessionManager(t)
t.Cleanup(func() { _ = sm.Shutdown() })
req := httptest.NewRequest(http.MethodGet, "https://internal.svc/", nil)
req.Host = "internal.svc"
req.Header.Set("X-Forwarded-Host", "App.Example.com")
opts := sm.EnhanceSessionSecurity(nil, req)
if opts.Domain != "app.example.com" {
t.Fatalf("Domain = %q, want app.example.com", opts.Domain)
}
})
}
func TestEnforceIatAge_RejectsFutureIat(t *testing.T) {
const maxAge = 24 * time.Hour
now := time.Now()
cases := []struct {
name string
iat time.Time
wantErr bool
}{
{name: "now", iat: now},
{name: "within future skew", iat: now.Add(ClockSkewToleranceFuture / 2)},
{name: "one hour ahead", iat: now.Add(time.Hour), wantErr: true},
{name: "just beyond skew", iat: now.Add(ClockSkewToleranceFuture + 10*time.Second), wantErr: true},
{name: "older than max age", iat: now.Add(-48 * time.Hour), wantErr: true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
err := enforceIatAge(map[string]interface{}{"iat": float64(tc.iat.Unix())}, maxAge)
if (err != nil) != tc.wantErr {
t.Fatalf("enforceIatAge err = %v, wantErr %v", err, tc.wantErr)
}
})
}
}
func TestJWKCache_CooldownServesParsedEntryWithoutReparse(t *testing.T) {
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatalf("keygen: %v", err)
}
c := NewJWKCache()
url := fmt.Sprintf("https://jwks.invalid/%d", time.Now().UnixNano())
// The raw set is empty, so only the pre-parsed entry can satisfy the lookup.
_ = c.cache.SetLocal(url, &JWKSet{}, time.Hour)
_ = c.cache.SetLocal(url+parsedKeysSuffix, &parsedJWKS{keys: map[string]crypto.PublicKey{"k1": &priv.PublicKey}}, time.Hour)
c.lastSignatureRefresh[url] = time.Now()
got, err := c.getPublicKeyFresh(context.Background(), url, "k1", http.DefaultClient)
if err != nil {
t.Fatalf("getPublicKeyFresh: %v", err)
}
if got != crypto.PublicKey(&priv.PublicKey) {
t.Fatal("cooldown branch did not serve the cached parsed key")
}
}
func TestFrontchannelLogout_FloodCannotEvictSignedMarkers(t *testing.T) {
cache := &CacheInterfaceWrapper{cache: NewUniversalCache(UniversalCacheConfig{
Type: CacheTypeSession,
MaxSize: 5000,
DefaultTTL: sessionInvalidationTTL,
Logger: NewLogger("error"),
SkipAutoCleanup: true,
MonotonicMarkers: true,
})}
oidc := &TraefikOidc{
logger: NewLogger("error"),
enableFrontchannelLogout: true,
sessionInvalidationCache: cache,
issuerURL: "https://idp.example.com",
}
t.Cleanup(func() { _ = cache.cache.Close() })
if err := oidc.invalidateSession("", "real-subject"); err != nil {
t.Fatalf("invalidateSession: %v", err)
}
if err := oidc.checkAndMarkLogoutJTIProcessed("real-jti", time.Now().Unix()); err != nil {
t.Fatalf("mark jti: %v", err)
}
for i := 0; i < 6000; i++ {
req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/fc?iss=https://idp.example.com&sid=flood-%d", i), nil)
rw := httptest.NewRecorder()
oidc.handleFrontchannelLogout(rw, req)
if rw.Code != http.StatusOK {
t.Fatalf("flood request %d: status %d", i, rw.Code)
}
}
if _, ok := cache.Get(oidc.buildSessionInvalidationKey("sub", "real-subject")); !ok {
t.Error("backchannel sub marker evicted by front-channel flood")
}
if err := oidc.checkAndMarkLogoutJTIProcessed("real-jti", time.Now().Unix()); err == nil {
t.Error("jti replay marker evicted by front-channel flood: replay accepted")
}
held := 0
for i := 0; i < 6000; i++ {
if _, ok := cache.Get(oidc.buildSessionInvalidationKey("sid", fmt.Sprintf("flood-%d", i))); ok {
held++
}
}
if held > maxFrontchannelMarkers {
t.Errorf("front-channel markers held = %d, want <= %d", held, maxFrontchannelMarkers)
}
if _, ok := cache.Get(oidc.buildSessionInvalidationKey("sid", "flood-5999")); !ok {
t.Error("most recent front-channel marker must remain")
}
}
func TestMarkerQuota_Admit(t *testing.T) {
var q markerQuota
if got := q.admit("a", 2); got != "" {
t.Errorf("admit a = %q, want none", got)
}
if got := q.admit("a", 2); got != "" {
t.Errorf("re-admit a = %q, want none", got)
}
if got := q.admit("b", 2); got != "" {
t.Errorf("admit b = %q, want none", got)
}
if got := q.admit("c", 2); got != "a" {
t.Errorf("admit c evicted %q, want a", got)
}
}
func TestServeHTTP_InitWaitQueueFullFailsFast(t *testing.T) {
oidc := &TraefikOidc{
logger: NewLogger("error"),
initComplete: make(chan struct{}),
sessionManager: createTestSessionManager(t),
firstRequestStarted: 1,
metadataRefreshStartedAtomic: 1,
}
oidc.initWaiters = maxInitWaiters
rw := httptest.NewRecorder()
start := time.Now()
oidc.ServeHTTP(rw, httptest.NewRequest(http.MethodGet, "/protected", nil))
if rw.Code != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want 503", rw.Code)
}
if rw.Header().Get("Retry-After") == "" {
t.Error("missing Retry-After header")
}
if time.Since(start) > 5*time.Second {
t.Errorf("rejected after %v, want immediate", time.Since(start))
}
if oidc.initWaiters != maxInitWaiters {
t.Errorf("initWaiters = %d, want unchanged %d", oidc.initWaiters, maxInitWaiters)
}
}
func TestServeHTTP_InitWaiterReleasedOnCancel(t *testing.T) {
oidc := &TraefikOidc{
logger: NewLogger("error"),
initComplete: make(chan struct{}),
sessionManager: createTestSessionManager(t),
firstRequestStarted: 1,
metadataRefreshStartedAtomic: 1,
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
req := httptest.NewRequest(http.MethodGet, "/protected", nil).WithContext(ctx)
oidc.ServeHTTP(httptest.NewRecorder(), req)
if oidc.initWaiters != 0 {
t.Fatalf("initWaiters = %d after canceled wait, want 0", oidc.initWaiters)
}
}
func TestCleanupOldCookies_CapsDeletionHeaders(t *testing.T) {
sm, err := NewSessionManager("test-encryption-key-32-bytes-long!!", false, "cookie.example.com", "testpref", 0, newNoOpLogger())
if err != nil {
t.Fatalf("session manager: %v", err)
}
t.Cleanup(func() { _ = sm.Shutdown() })
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Host = "a.b.example.com"
for i := 0; i < 180; i++ {
req.AddCookie(&http.Cookie{Name: fmt.Sprintf("testpref_%d", i), Value: "x"})
}
rw := httptest.NewRecorder()
sm.CleanupOldCookies(rw, req)
got := len(rw.Result().Cookies())
if got == 0 {
t.Fatal("expected deletion cookies for the first wave")
}
if limit := maxCleanupCookies * 4; got > limit {
t.Fatalf("deletion Set-Cookie headers = %d, want <= %d", got, limit)
}
for _, c := range rw.Result().Cookies() {
if !strings.HasPrefix(c.Name, "testpref_") {
t.Errorf("unexpected deletion cookie %q", c.Name)
}
}
}
+20 -18
View File
@@ -120,15 +120,8 @@ func (r *RedisBackend) Set(ctx context.Context, key string, value []byte, ttl ti
// Use PSETEX for millisecond precision, SETEX for second precision
if ttl > 0 {
ttlMillis := ttl.Milliseconds()
if ttlMillis < 1000 {
// Use PSETEX for sub-second TTLs (millisecond precision)
_, err = conn.Do("PSETEX", prefixedKey, fmt.Sprintf("%d", ttlMillis), string(value))
} else {
// Use SETEX for larger TTLs (second precision)
ttlSeconds := int(ttl.Seconds())
_, err = conn.Do("SETEX", prefixedKey, fmt.Sprintf("%d", ttlSeconds), string(value))
}
cmd, arg := ttlCommand(ttl)
_, err = conn.Do(cmd, prefixedKey, arg, string(value))
} else {
_, err = conn.Do("SET", prefixedKey, string(value))
}
@@ -624,6 +617,19 @@ func isRetryableError(err error) bool {
return false
}
// ttlCommand picks SETEX for whole seconds and PSETEX otherwise. The expiry is
// rounded up to a millisecond and is never zero, so a key never dies early.
func ttlCommand(ttl time.Duration) (cmd, arg string) {
ms := (ttl + time.Millisecond - 1).Milliseconds()
if ms < 1 {
ms = 1
}
if ms >= 1000 && ms%1000 == 0 {
return "SETEX", fmt.Sprintf("%d", ms/1000)
}
return "PSETEX", fmt.Sprintf("%d", ms)
}
// SetMany stores multiple values in Redis using pipelining for efficiency
// This reduces N round-trips to a single round-trip
func (r *RedisBackend) SetMany(ctx context.Context, items map[string][]byte, ttl time.Duration) error {
@@ -658,20 +664,16 @@ func (r *RedisBackend) SetMany(ctx context.Context, items map[string][]byte, ttl
pipeline := conn.NewPipeline()
// Queue all SET commands
ttlSeconds := int(ttl.Seconds())
ttlMillis := ttl.Milliseconds()
var ttlCmd, ttlArg string
if ttl > 0 {
ttlCmd, ttlArg = ttlCommand(ttl)
}
for key, value := range items {
prefixedKey := r.prefixKey(key)
if ttl > 0 {
if ttlMillis < 1000 {
// Use PSETEX for sub-second TTLs
pipeline.Queue("PSETEX", prefixedKey, fmt.Sprintf("%d", ttlMillis), string(value))
} else {
// Use SETEX for larger TTLs
pipeline.Queue("SETEX", prefixedKey, fmt.Sprintf("%d", ttlSeconds), string(value))
}
pipeline.Queue(ttlCmd, prefixedKey, ttlArg, string(value))
} else {
pipeline.Queue("SET", prefixedKey, string(value))
}
+45
View File
@@ -0,0 +1,45 @@
package backends
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestRedisSetTTLNeverZeroOrEarly(t *testing.T) {
mr := NewMiniredisServer(t)
b, err := NewRedisBackend(DefaultRedisConfig(mr.GetAddr()))
require.NoError(t, err)
defer b.Close()
ctx := context.Background()
t.Run("sub-millisecond ttl is accepted", func(t *testing.T) {
require.NoError(t, b.Set(ctx, "sub", []byte("v"), 500*time.Microsecond))
})
t.Run("sub-millisecond ttl accepted by SetMany", func(t *testing.T) {
require.NoError(t, b.SetMany(ctx, map[string][]byte{"sub-many": []byte("v")}, 500*time.Microsecond))
})
t.Run("fractional seconds are not rounded down", func(t *testing.T) {
require.NoError(t, b.Set(ctx, "frac", []byte("v"), 1999*time.Millisecond))
_, ttl, ok, err := b.Get(ctx, "frac")
require.NoError(t, err)
require.True(t, ok)
require.Greater(t, ttl, time.Second, "1999ms ttl must not be stored as 1s")
})
t.Run("fractional seconds SetMany", func(t *testing.T) {
require.NoError(t, b.SetMany(ctx, map[string][]byte{"frac-many": []byte("v")}, 1999*time.Millisecond))
_, ttl, ok, err := b.Get(ctx, "frac-many")
require.NoError(t, err)
require.True(t, ok)
require.Greater(t, ttl, time.Second)
})
t.Run("whole seconds still work", func(t *testing.T) {
require.NoError(t, b.Set(ctx, "whole", []byte("v"), 5*time.Second))
_, ttl, ok, err := b.Get(ctx, "whole")
require.NoError(t, err)
require.True(t, ok)
require.Greater(t, ttl, 3*time.Second)
})
}
+6 -3
View File
@@ -81,6 +81,7 @@ type CircuitBreaker struct {
stateMu sync.RWMutex
timeMu sync.RWMutex
halfOpenRequests atomic.Int32
halfOpenSuccesses atomic.Int32
consecutiveFailures atomic.Int32
state atomic.Int32
}
@@ -170,12 +171,12 @@ func (cb *CircuitBreaker) RecordSuccess() {
case StateHalfOpen:
// If we've had enough successful requests, close the circuit
successfulRequests := cb.halfOpenRequests.Load()
// #nosec G115 -- HalfOpenMaxRequests is a small config value that fits in int32
if successfulRequests >= int32(cb.config.HalfOpenMaxRequests) {
successfulRequests := cb.halfOpenSuccesses.Add(1)
if int64(successfulRequests) >= int64(cb.config.HalfOpenMaxRequests) {
cb.setState(StateClosed)
cb.consecutiveFailures.Store(0)
cb.halfOpenRequests.Store(0)
cb.halfOpenSuccesses.Store(0)
}
}
}
@@ -216,6 +217,7 @@ func (cb *CircuitBreaker) RecordFailure() {
func (cb *CircuitBreaker) openCircuit() {
cb.setState(StateOpen)
cb.halfOpenRequests.Store(0)
cb.halfOpenSuccesses.Store(0)
cb.timeMu.Lock()
cb.nextRetryTime = time.Now().Add(cb.config.Timeout)
@@ -251,6 +253,7 @@ func (cb *CircuitBreaker) Reset() {
cb.totalRequests.Store(0)
cb.totalFailures.Store(0)
cb.halfOpenRequests.Store(0)
cb.halfOpenSuccesses.Store(0)
cb.rejectedRequests.Store(0)
cb.stateTransitions.Store(0)
+4 -3
View File
@@ -168,11 +168,12 @@ func (h *HealthCheckBackend) IsHealthy() bool {
func (h *HealthCheckBackend) recordResult(success bool) {
// #nosec G115 -- threshold config values are small integers that fit in int32
if success {
fails := h.consecutiveFails.Swap(0)
h.consecutiveFails.Store(0)
oks := h.consecutiveOK.Add(1)
// Check if we should transition to healthy
if fails > 0 && oks >= int32(h.config.HealthyThreshold) {
// Promote on a success streak. Keyed on the status, not on the fail
// counter, which the first success of the streak already zeroed.
if HealthStatus(h.status.Load()) != HealthHealthy && oks >= int32(h.config.HealthyThreshold) {
oldStatus := HealthStatus(h.status.Swap(int32(HealthHealthy)))
if oldStatus != HealthHealthy && h.config.OnStatusChange != nil {
h.config.OnStatusChange(oldStatus, HealthHealthy)
+56
View File
@@ -0,0 +1,56 @@
package resilience
import (
"testing"
"time"
)
// With HealthyThreshold >= 2 an Unhealthy backend must recover once it
// answers HealthyThreshold times in a row.
func TestHealthCheckRecoversWithThresholdTwo(t *testing.T) {
h := &HealthCheckBackend{config: &HealthCheckConfig{HealthyThreshold: 2, UnhealthyThreshold: 3}}
for i := 0; i < 6; i++ {
h.recordResult(false)
}
if HealthStatus(h.status.Load()) != HealthUnhealthy {
t.Fatalf("precondition: status=%v, want unhealthy", HealthStatus(h.status.Load()))
}
for i := 0; i < 5; i++ {
h.recordResult(true)
}
if got := HealthStatus(h.status.Load()); got != HealthHealthy {
t.Fatalf("status after 5 successes = %v, want healthy", got)
}
}
// Half-open closes after HalfOpenMaxRequests successes, not admissions.
func TestHalfOpenClosesOnSuccessesNotAdmissions(t *testing.T) {
cb := NewCircuitBreaker(&CircuitBreakerConfig{
MaxFailures: 1, Timeout: time.Millisecond, HalfOpenMaxRequests: 3, ResetTimeout: time.Second,
})
cb.RecordFailure()
time.Sleep(20 * time.Millisecond)
for i := 0; i < 3; i++ {
if !cb.AllowRequest() {
t.Fatalf("probe %d rejected", i)
}
}
cb.RecordSuccess()
if cb.GetState() != StateHalfOpen {
t.Fatalf("closed after 1 of 3 probe successes; state=%v", cb.GetState())
}
cb.RecordFailure()
if cb.GetState() != StateOpen {
t.Fatalf("a failing probe must reopen; state=%v", cb.GetState())
}
time.Sleep(20 * time.Millisecond)
for i := 0; i < 3; i++ {
cb.AllowRequest()
}
for i := 0; i < 3; i++ {
cb.RecordSuccess()
}
if cb.GetState() != StateClosed {
t.Fatalf("state after 3 successes = %v, want closed", cb.GetState())
}
}
+9 -1
View File
@@ -93,8 +93,16 @@ func (cb *CircuitBreaker) ExecuteWithContext(ctx context.Context, fn func() erro
return fmt.Errorf("circuit breaker is open")
}
// Execute the function
// A panicking fn must still settle the breaker, otherwise a half-open
// probe slot leaks until the next open->half-open transition.
panicked := true
defer func() {
if panicked {
cb.recordFailure()
}
}()
err := fn()
panicked = false
if err != nil {
cb.recordFailure()
@@ -0,0 +1,40 @@
package recovery
import (
"context"
"errors"
"testing"
"time"
)
func TestCircuitBreaker_PanickingProbeReleasesHalfOpenSlot(t *testing.T) {
cb := NewCircuitBreaker(CircuitBreakerConfig{
FailureThreshold: 1,
SuccessThreshold: 1,
Timeout: 20 * time.Millisecond,
MaxRequests: 1,
}, &mockLogger{})
_ = cb.ExecuteWithContext(context.Background(), func() error { return errors.New("fail") })
time.Sleep(40 * time.Millisecond)
func() {
defer func() {
if recover() == nil {
t.Error("panic must still propagate to the caller")
}
}()
_ = cb.ExecuteWithContext(context.Background(), func() error { panic("boom") })
}()
if cb.GetState() != CircuitBreakerOpen {
t.Fatalf("state after panicking probe = %s, want open", cb.GetState())
}
time.Sleep(40 * time.Millisecond)
if err := cb.ExecuteWithContext(context.Background(), func() error { return nil }); err != nil {
t.Fatalf("probe after next timeout rejected: %v", err)
}
if cb.GetState() != CircuitBreakerClosed {
t.Fatalf("state = %s, want closed", cb.GetState())
}
}
+1 -1
View File
@@ -142,7 +142,7 @@ func DetermineScheme(req *http.Request, forceHTTPS bool) string {
// "X-Forwarded-Proto: ftp") would otherwise be emitted verbatim into
// redirect_uri as a broken or weakened scheme. Invalid values fall
// through to the TLS check (R103).
if scheme := req.Header.Get("X-Forwarded-Proto"); scheme == "https" || scheme == "http" {
if scheme := strings.ToLower(req.Header.Get("X-Forwarded-Proto")); scheme == "https" || scheme == "http" {
return scheme
}
+3 -1
View File
@@ -336,7 +336,9 @@ func TestIssue152NewWithContextWiring(t *testing.T) {
t.Run("discovery fails outright, cold-start seed holds", func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
// A status startup discovery does not retry (#147 retries 404,
// 429 and 5xx), so discovery fails at once.
w.WriteHeader(http.StatusBadRequest)
}))
defer srv.Close()
+7
View File
@@ -389,6 +389,13 @@ func (c *JWKCache) getPublicKeyFresh(ctx context.Context, jwksURL, kid string, h
if withinCooldown {
// Serve the cached keyset; do not fetch upstream again.
if v, found := c.cache.GetLocal(jwksURL + parsedKeysSuffix); found {
if pj, ok := v.(*parsedJWKS); ok {
if k, ok := pj.keys[kid]; ok {
return k, nil
}
}
}
if cached, found := c.cache.GetLocal(jwksURL); found {
if jwks, ok := cached.(*JWKSet); ok {
if k, ok := buildParsedJWKS(jwks).keys[kid]; ok {
+26 -3
View File
@@ -6,7 +6,9 @@ import (
"crypto/ecdsa"
"crypto/rsa"
"encoding/base64"
"errors"
"fmt"
"math"
"math/big"
"strings"
"time"
@@ -194,11 +196,16 @@ func (j *JWT) Verify(issuerURL, expectedAudience string) error {
//
// Returns:
// - An error if the claim type is invalid or the expected audience is not present
//
// errInvalidAudience marks a token whose aud does not match; callers match it
// with errors.Is, never by message text.
var errInvalidAudience = errors.New("invalid audience")
func verifyAudience(tokenAudience interface{}, expectedAudience string) error {
switch aud := tokenAudience.(type) {
case string:
if aud != expectedAudience {
return fmt.Errorf("invalid audience")
return errInvalidAudience
}
case []interface{}:
found := false
@@ -209,7 +216,7 @@ func verifyAudience(tokenAudience interface{}, expectedAudience string) error {
}
}
if !found {
return fmt.Errorf("invalid audience")
return errInvalidAudience
}
default:
return fmt.Errorf("invalid 'aud' claim type")
@@ -231,6 +238,9 @@ func verifyIssuer(tokenIssuer, expectedIssuer string) error {
return nil
}
// maxClaimUnix is 9999-12-31T23:59:59Z, the largest time claim accepted.
const maxClaimUnix = 253402300799
// verifyTimeConstraint validates time-based JWT claims with clock skew tolerance.
// It handles both future constraints (exp) and past constraints (iat, nbf).
// Parameters:
@@ -241,6 +251,10 @@ func verifyIssuer(tokenIssuer, expectedIssuer string) error {
// Returns:
// - An error describing the failure (e.g., "token has expired", "token used before issued")
func verifyTimeConstraint(unixTime float64, claimName string, future bool) error {
// int64(float64) wraps out of range, which put a far-future nbf/iat in the past.
if math.IsNaN(unixTime) || math.IsInf(unixTime, 0) || math.Abs(unixTime) > maxClaimUnix {
return fmt.Errorf("token %s claim out of range", claimName)
}
claimTime := time.Unix(int64(unixTime), 0)
now := time.Now()
@@ -314,6 +328,9 @@ func verifyTimeClaims(claims map[string]interface{}) error {
return nil
}
// ecdsaAlgBits maps an ES* algorithm to its curve size (RFC 7518 3.4).
var ecdsaAlgBits = map[string]int{"ES256": 256, "ES384": 384, "ES512": 521}
// verifySignatureWithKey verifies a JWT signature using an already-parsed
// public key, skipping the PEM-encode/decode round trip. This is the hot
// path used by VerifyJWTSignatureAndClaims and verifyLogoutTokenSignature.
@@ -361,7 +378,13 @@ func verifySignatureWithKey(tokenString string, pubKey crypto.PublicKey, alg str
if strings.HasPrefix(alg, "ES") {
var r, s big.Int
sigLen := len(signature)
if sigLen%2 != 0 {
// RFC 7518 3.4: the curve is fixed by the algorithm and the
// signature is R||S at exactly the curve's octet length.
bits := ecdsaAlgBits[alg]
if bits == 0 || pubKey.Curve.Params().BitSize != bits {
return fmt.Errorf("ECDSA key curve does not match algorithm %s", alg)
}
if sigLen != 2*((bits+7)/8) {
return fmt.Errorf("invalid ECDSA signature length")
}
r.SetBytes(signature[:sigLen/2])
+53
View File
@@ -0,0 +1,53 @@
package traefikoidc
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/sha512"
"encoding/base64"
"testing"
)
func signES(t *testing.T, key *ecdsa.PrivateKey, signed string, h256 bool, size int) (sigRS []byte) {
t.Helper()
var digest []byte
if h256 {
d := sha256.Sum256([]byte(signed))
digest = d[:]
} else {
d := sha512.Sum384([]byte(signed))
digest = d[:]
}
r, s, err := ecdsa.Sign(rand.Reader, key, digest)
if err != nil {
t.Fatal(err)
}
out := make([]byte, 2*size)
r.FillBytes(out[:size])
s.FillBytes(out[size:])
return out
}
func TestECDSAVerifyIsStrict(t *testing.T) {
const signed = "eyJhbGciOiJFUzI1NiJ9.eyJzdWIiOiJ1In0"
enc := base64.RawURLEncoding.EncodeToString
p256, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
p384, _ := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
if err := verifySignatureWithKey(signed+"."+enc(signES(t, p256, signed, true, 32)), &p256.PublicKey, "ES256"); err != nil {
t.Fatalf("valid ES256 rejected: %v", err)
}
if err := verifySignatureWithKey(signed+"."+enc(signES(t, p384, signed, false, 48)), &p384.PublicKey, "ES384"); err != nil {
t.Fatalf("valid ES384 rejected: %v", err)
}
// ES256 token verified against a P-384 key.
if err := verifySignatureWithKey(signed+"."+enc(signES(t, p384, signed, true, 48)), &p384.PublicKey, "ES256"); err == nil {
t.Error("ES256 accepted with a P-384 key")
}
// Zero-padded halves: 66 bytes for ES256.
if err := verifySignatureWithKey(signed+"."+enc(signES(t, p256, signed, true, 33)), &p256.PublicKey, "ES256"); err == nil {
t.Error("ES256 accepted a 66-byte signature")
}
}
+60
View File
@@ -51,8 +51,43 @@ const (
// sessionInvalidationTTL is how long to remember invalidated sessions
// Should be at least as long as your session max age
sessionInvalidationTTL = 25 * time.Hour
// maxFrontchannelMarkers caps the sid markers the unauthenticated
// front-channel endpoint may keep in the shared invalidation cache, so
// a flood cannot LRU-evict signed backchannel and jti replay markers.
maxFrontchannelMarkers = 1000
)
// markerQuota is a FIFO of cache keys written on behalf of one untrusted
// source. The zero value is ready to use.
type markerQuota struct {
set map[string]struct{}
keys []string
mu sync.Mutex
}
// admit records key and returns the oldest key to drop once more than limit
// keys are held, or "" when none must go. Re-admitting a held key is a no-op.
func (q *markerQuota) admit(key string, limit int) string {
q.mu.Lock()
defer q.mu.Unlock()
if q.set == nil {
q.set = make(map[string]struct{})
}
if _, ok := q.set[key]; ok {
return ""
}
q.set[key] = struct{}{}
q.keys = append(q.keys, key)
if len(q.keys) <= limit {
return ""
}
oldest := q.keys[0]
q.keys = q.keys[1:]
delete(q.set, oldest)
return oldest
}
// LogoutTokenClaims represents the claims in an OIDC logout token
// as defined in OpenID Connect Back-Channel Logout 1.0
type LogoutTokenClaims struct {
@@ -191,6 +226,10 @@ func (t *TraefikOidc) handleFrontchannelLogout(rw http.ResponseWriter, req *http
return
}
if evicted := t.frontchannelMarkers.admit(t.buildSessionInvalidationKey("sid", sid), maxFrontchannelMarkers); evicted != "" {
t.sessionInvalidationCache.Delete(evicted)
}
t.logger.Infof("Front-channel logout: successfully invalidated session (sid=%s)", sid)
// Return a minimal HTML response that's suitable for iframe loading
@@ -578,6 +617,11 @@ func (t *TraefikOidc) isSessionInvalidated(sid, sub string, sessionCreatedAt tim
// buildSessionInvalidationKey creates a cache key for session invalidation
func (t *TraefikOidc) buildSessionInvalidationKey(keyType, value string) string {
// sub, sid and jti are unique only within an issuer; the cache is shared by
// every instance, so scope the key to this instance's provider and client.
if ns := t.tokenCache.Namespace(); ns != "" {
return fmt.Sprintf("session_invalidation:%s|%s:%s", ns, keyType, value)
}
return fmt.Sprintf("session_invalidation:%s:%s", keyType, value)
}
@@ -600,6 +644,22 @@ func (t *TraefikOidc) sessionCreatedAtForInvalidation(idToken string, session *S
return time.Time{} // zero: treated as invalidated -> safe re-auth
}
// invalidationInputs returns sid, sub and the creation time for the IdP-logout
// check from one parseJWT call, with the same results as extractSessionInfo
// and sessionCreatedAtForInvalidation called separately.
func (t *TraefikOidc) invalidationInputs(idToken string, session *SessionData) (sid, sub string, createdAt time.Time) {
jwt, err := parseJWT(idToken)
if err != nil {
return "", "", t.sessionCreatedAtForInvalidation("", session)
}
sid, _ = jwt.Claims["sid"].(string)
sub, _ = jwt.Claims["sub"].(string)
if iat, ok := jwt.Claims["iat"].(float64); ok {
return sid, sub, time.Unix(int64(iat), 0)
}
return sid, sub, t.sessionCreatedAtForInvalidation("", session)
}
// extractSessionInfo extracts sid and sub from an ID token for session tracking
func (t *TraefikOidc) extractSessionInfo(idToken string) (sid, sub string, createdAt time.Time) {
if idToken == "" {
+34
View File
@@ -0,0 +1,34 @@
package traefikoidc
import (
"testing"
"github.com/gorilla/sessions"
)
// invalidationInputs must return exactly what extractSessionInfo and
// sessionCreatedAtForInvalidation return when called separately.
func TestInvalidationInputsMatchSeparateCalls(t *testing.T) {
oidc := &TraefikOidc{logger: newNoOpLogger()}
sess := &SessionData{mainSession: &sessions.Session{Values: map[interface{}]interface{}{"created_at": int64(1700000000)}}}
tokens := map[string]string{
"all claims": makeTestJWT(t, map[string]interface{}{"sid": "s1", "sub": "u1", "iat": float64(1700000100)}),
"no iat": makeTestJWT(t, map[string]interface{}{"sid": "s1", "sub": "u1"}),
"sid only": makeTestJWT(t, map[string]interface{}{"sid": "s1", "iat": float64(1700000200)}),
"sub only": makeTestJWT(t, map[string]interface{}{"sub": "u1"}),
"wrong types": makeTestJWT(t, map[string]interface{}{"sid": 5, "sub": true, "iat": "x"}),
"malformed": "not-a-jwt",
"empty": "",
}
for name, tok := range tokens {
t.Run(name, func(t *testing.T) {
wantSID, wantSub, _ := oidc.extractSessionInfo(tok)
wantAt := oidc.sessionCreatedAtForInvalidation(tok, sess)
gotSID, gotSub, gotAt := oidc.invalidationInputs(tok, sess)
if gotSID != wantSID || gotSub != wantSub || !gotAt.Equal(wantAt) {
t.Fatalf("got (%q,%q,%v) want (%q,%q,%v)", gotSID, gotSub, gotAt, wantSID, wantSub, wantAt)
}
})
}
}
+18
View File
@@ -0,0 +1,18 @@
package traefikoidc
import "testing"
func TestSessionInvalidationKeyScopedPerInstance(t *testing.T) {
a := &TraefikOidc{tokenCache: &TokenCache{}}
b := &TraefikOidc{tokenCache: &TokenCache{}}
a.tokenCache.SetNamespace("https://kc/realms/a|c|c")
b.tokenCache.SetNamespace("https://kc/realms/b|c|c")
for _, kind := range []string{"sub", "sid", "jti"} {
if a.buildSessionInvalidationKey(kind, "u1") == b.buildSessionInvalidationKey(kind, "u1") {
t.Errorf("%s key shared across issuers", kind)
}
}
if got := (&TraefikOidc{}).buildSessionInvalidationKey("sub", "u1"); got != "session_invalidation:sub:u1" {
t.Errorf("namespace-less key changed: %q", got)
}
}
+119 -7
View File
@@ -7,6 +7,7 @@ import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"net/http"
@@ -85,8 +86,10 @@ var defaultExcludedURLs = map[string]struct{}{
// headerTemplateFuncMap returns the function map available to custom header
// value templates, gated by the effective claims whitelist (built-in +
// config.AllowedClaims). It exposes exactly two helpers:
// config.AllowedClaims). It exposes exactly three helpers:
// - default: substitute a fallback when a value is nil/empty.
// - toJson: serialize a value (e.g. an object claim) to compact JSON; nil and
// "" yield "" so an absent claim skips the header instead of sending `""`.
// - get: safe map access RESTRICTED to whitelisted claim keys, so it cannot be
// used to read a non-whitelisted claim, a raw token, or the whole data map
// (issue #149 review). This is the sole runtime enforcement of the claims
@@ -102,6 +105,16 @@ func headerTemplateFuncMap(allowedClaims map[string]bool) template.FuncMap {
}
return val
},
"toJson": func(val interface{}) (string, error) {
if val == nil || val == "" {
return "", nil
}
b, err := json.Marshal(val)
if err != nil {
return "", err
}
return string(b), nil
},
"get": func(m interface{}, key string) interface{} {
if !allowedClaims[key] {
return ""
@@ -342,6 +355,8 @@ func NewWithContext(ctx context.Context, config *Config, next http.Handler, name
stripAuthCookies: config.StripAuthCookies,
enableBackchannelLogout: config.EnableBackchannelLogout,
enableFrontchannelLogout: config.EnableFrontchannelLogout,
tmbSessionURLPath: config.TMBSessionURL,
tmbClaims: config.TMBClaims,
backchannelLogoutPath: normalizeLogoutPath(config.BackchannelLogoutURL),
frontchannelLogoutPath: normalizeLogoutPath(config.FrontchannelLogoutURL),
sessionInvalidationCache: cacheManager.GetSharedSessionInvalidationCache(),
@@ -535,6 +550,7 @@ func NewWithContext(ctx context.Context, config *Config, next http.Handler, name
logger.Debugf("TraefikOidc.New: logoutURLPath configured as: %q", t.logoutURLPath)
t.providerURL = config.ProviderURL
t.tokenCache.SetNamespace(t.tokenCacheNamespace())
// Use singleton resource manager for metadata initialization
rm := GetResourceManager()
@@ -558,7 +574,7 @@ func NewWithContext(ctx context.Context, config *Config, next http.Handler, name
t.safeLogErrorf("Initialize metadata goroutine panic recovered: %v", r)
}
}()
t.initializeMetadata(config.ProviderURL)
t.runMetadataInit(config.ProviderURL, metadataRecoveryBackoff())
}()
// Setup cleanup hook for when context is canceled
@@ -573,12 +589,97 @@ func NewWithContext(ctx context.Context, config *Config, next http.Handler, name
return t, nil
}
// metadataRecoveryFetchTimeout bounds one background discovery request.
const metadataRecoveryFetchTimeout = 15 * time.Second
// metadataRecoveryBackoff paces background discovery after startup discovery
// fails: 5s, doubling up to 60s, with jitter.
func metadataRecoveryBackoff() RetryConfig {
return RetryConfig{
InitialDelay: 5 * time.Second,
MaxDelay: 60 * time.Second,
BackoffFactor: 2,
EnableJitter: true,
}
}
// runMetadataInit runs startup discovery and, if it fails, keeps retrying in
// the background, so an instance recovers once the provider answers without
// waiting for a request to trigger recovery (#147).
func (t *TraefikOidc) runMetadataInit(providerURL string, backoff RetryConfig) {
if t.initializeMetadata(providerURL) || providerURL == "" {
return
}
t.recoverMetadataInBackground(providerURL, backoff)
}
// recoverMetadataInBackground retries discovery with backoff until it
// succeeds, another path has adopted metadata, or the instance closes.
// Instances that share providerURL also share the metadata cache, so after the
// first success the others adopt the cached document without a fetch.
func (t *TraefikOidc) recoverMetadataInBackground(providerURL string, backoff RetryConfig) {
if t.metadataCache == nil || t.httpClient == nil {
return
}
ctx := t.lifecycleCtx()
pacer := NewRetryExecutor(backoff, t.logger)
for attempt := 1; ; attempt++ {
timer := time.NewTimer(pacer.calculateDelay(attempt))
select {
case <-ctx.Done():
timer.Stop()
return
case <-timer.C:
}
if t.metadataReady() {
return
}
fetchCtx, cancel := context.WithTimeout(ctx, metadataRecoveryFetchTimeout)
metadata, err := t.metadataCache.GetProviderMetadata(fetchCtx, providerURL, t.httpClient)
cancel()
if err != nil || metadata == nil {
t.logMetadataRecoveryFailure(attempt, err)
continue
}
t.updateMetadataEndpoints(metadata)
if !t.metadataReady() {
t.logMetadataRecoveryFailure(attempt, fmt.Errorf("discovery document has no usable issuer"))
continue
}
t.safeLogInfo(fmt.Sprintf("Recovered OIDC provider metadata for middleware %q in the background", t.name))
return
}
}
// Background recovery logs the first metadataRecoveryLoudAttempts failures and
// then every metadataRecoveryLogEvery-th at ERROR, the rest at DEBUG, so a
// permanently wrong providerURL does not flood the log.
const (
metadataRecoveryLoudAttempts = 3
metadataRecoveryLogEvery = 10
)
// metadataRecoveryLogLoud reports whether a failed background attempt logs at ERROR.
func metadataRecoveryLogLoud(attempt int) bool {
return attempt <= metadataRecoveryLoudAttempts || attempt%metadataRecoveryLogEvery == 0
}
func (t *TraefikOidc) logMetadataRecoveryFailure(attempt int, err error) {
if metadataRecoveryLogLoud(attempt) {
t.safeLogErrorf("Provider metadata for middleware %q still unavailable (background attempt %d): %v", t.name, attempt, err)
return
}
t.safeLogDebugf("Provider metadata for middleware %q still unavailable (background attempt %d): %v", t.name, attempt, err)
}
// initializeMetadata initializes OIDC provider metadata by fetching configuration.
// It retrieves the provider's .well-known/openid-configuration and updates
// internal endpoint URLs. Uses error recovery if available for resilient fetching.
// It reports whether metadata was adopted.
// Parameters:
// - providerURL: The base URL of the OIDC provider.
func (t *TraefikOidc) initializeMetadata(providerURL string) {
func (t *TraefikOidc) initializeMetadata(providerURL string) bool {
t.safeLogDebug("Starting provider metadata discovery")
// Ensure initComplete is always closed, even on failure
@@ -595,22 +696,27 @@ func (t *TraefikOidc) initializeMetadata(providerURL string) {
var metadata *ProviderMetadata
var err error
if t.errorRecoveryManager != nil {
metadata, err = t.metadataCache.GetMetadataWithRecovery(providerURL, t.httpClient, t.logger, t.errorRecoveryManager)
metadata, err = t.metadataCache.GetMetadataWithRecovery(t.lifecycleCtx(), providerURL, t.httpClient, t.logger, t.errorRecoveryManager)
} else {
metadata, err = t.metadataCache.GetMetadata(providerURL, t.httpClient, t.logger)
}
if err != nil {
t.safeLogErrorf("Failed to get provider metadata: %v", err)
return
if t.lifecycleCtx().Err() != nil {
t.safeLogDebugf("Provider metadata discovery for middleware %q stopped: instance closed", t.name)
return false
}
t.safeLogErrorf("Failed to get provider metadata for middleware %q: %v", t.name, err)
return false
}
if metadata != nil {
t.safeLogDebug("Successfully initialized provider metadata")
t.updateMetadataEndpoints(metadata)
return
return true
}
t.safeLogError("Received nil metadata during initialization")
return false
}
// Discovered-endpoint names. jwks_uri, authorization and token have no
@@ -931,6 +1037,7 @@ func (t *TraefikOidc) performDynamicClientRegistration() {
if t.audience == "" {
t.audience = resp.ClientID // Default audience to client ID
}
t.tokenCache.SetNamespace(t.tokenCacheNamespace())
// R162: DCR can provision a client whose method is private_key_jwt
// (RFC 7591 ClientMetadata.TokenEndpointAuthMethod) even when the
// static config did not set ClientAuthMethod=private_key_jwt. In that
@@ -1070,3 +1177,8 @@ func buildFullURL(scheme, host, path string) string {
return fmt.Sprintf("%s://%s%s", scheme, host, path)
}
// tokenCacheNamespace identifies the verification context of this instance.
func (t *TraefikOidc) tokenCacheNamespace() string {
return t.providerURL + "|" + t.clientID + "|" + t.audience
}
+4 -1
View File
@@ -2647,7 +2647,10 @@ func TestMetadataRecoveryOnProviderFailure(t *testing.T) {
mu.Unlock()
if !available {
w.WriteHeader(http.StatusServiceUnavailable)
// A status startup discovery does not retry, so init fails at
// once and the test can drive request-path recovery (#147
// retries 404, 429 and 5xx at startup).
w.WriteHeader(http.StatusBadRequest)
return
}
+10 -8
View File
@@ -138,7 +138,8 @@ func (mc *MetadataCache) GetProviderMetadata(ctx context.Context, providerURL st
defer func() { _ = resp.Body.Close() }() // Safe to ignore: closing body on defer
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("metadata fetch returned status %d", resp.StatusCode)
// Typed so the retry classification can read the status.
return nil, &HTTPError{StatusCode: resp.StatusCode, Message: "metadata fetch failed"}
}
var metadata ProviderMetadata
@@ -212,10 +213,11 @@ func (mc *MetadataCache) GetMetadata(providerURL string, httpClient *http.Client
// GetMetadataWithRecovery fetches metadata with retry support for startup scenarios.
// This handles the race condition where Traefik initializes the plugin before the
// OIDC provider routes are fully established, or before TLS certificates are loaded.
// Uses aggressive retry settings (10 attempts, 1s intervals) to give the infrastructure
// time to stabilize during cold starts.
// It makes up to 10 attempts with backoff from 1s, x1.5, capped at 10s (about 51s
// of delay), so the infrastructure has time to stabilize during cold starts.
// The retries stop when ctx ends.
// See: https://github.com/lukaszraczylo/traefikoidc/issues/90
func (mc *MetadataCache) GetMetadataWithRecovery(providerURL string, httpClient *http.Client, logger *Logger, errorRecoveryManager *ErrorRecoveryManager) (*ProviderMetadata, error) {
func (mc *MetadataCache) GetMetadataWithRecovery(ctx context.Context, providerURL string, httpClient *http.Client, logger *Logger, errorRecoveryManager *ErrorRecoveryManager) (*ProviderMetadata, error) {
// Check cache first - if we have valid cached metadata, use it
if metadata, exists := mc.Get(providerURL); exists {
return metadata, nil
@@ -229,13 +231,13 @@ func (mc *MetadataCache) GetMetadataWithRecovery(providerURL string, httpClient
var lastErr error
// Use context with overall timeout for the entire retry sequence
// 10 attempts * ~10s max delay = ~100s worst case, so use 2 minute timeout
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
// About 51s of delay plus up to 15s per attempt, so use a 2 minute timeout
retryCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)
defer cancel()
err := retryExecutor.ExecuteWithContext(ctx, func() error {
err := retryExecutor.ExecuteWithContext(retryCtx, func() error {
// Create per-attempt context with shorter timeout
attemptCtx, attemptCancel := context.WithTimeout(ctx, 15*time.Second)
attemptCtx, attemptCancel := context.WithTimeout(retryCtx, 15*time.Second)
defer attemptCancel()
var fetchErr error
+307
View File
@@ -0,0 +1,307 @@
package traefikoidc
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// newFlakyDiscovery serves failStatus for the first failures discovery
// requests, then a valid document whose endpoints share the server's host.
// The returned provider URL is unique to the test, so the process-wide
// metadata cache never answers with another test's document.
func newFlakyDiscovery(t *testing.T, failStatus int, failures int32) (*httptest.Server, string, *atomic.Int32) {
t.Helper()
hits := &atomic.Int32{}
var srv *httptest.Server
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if hits.Add(1) <= failures {
w.WriteHeader(failStatus)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(ProviderMetadata{
Issuer: srv.URL,
AuthURL: srv.URL + "/auth",
TokenURL: srv.URL + "/token",
JWKSURL: srv.URL + "/jwks",
})
}))
t.Cleanup(srv.Close)
return srv, srv.URL + "/" + strings.ReplaceAll(t.Name(), "/", "_"), hits
}
// fastRetry shrinks a retry config's delays so a test runs in milliseconds.
func fastRetry(cfg RetryConfig, attempts int) RetryConfig {
cfg.MaxAttempts = attempts
cfg.InitialDelay = time.Millisecond
cfg.MaxDelay = time.Millisecond
return cfg
}
// newRecoveryTestOIDC builds an instance whose provider metadata is not yet
// known and whose startup gate is still open, as New leaves it before init.
func newRecoveryTestOIDC(t *testing.T, srv *httptest.Server, providerURL string) *TraefikOidc {
t.Helper()
return newTestOIDC(t, func(o *TraefikOidc) {
o.issuerURL = ""
o.initComplete = make(chan struct{})
o.providerURL = providerURL
o.httpClient = srv.Client()
o.metadataCache = NewMetadataCacheWithLogger(nil, NewLogger("error"))
})
}
func TestMetadataDiscovery_StatusRetryClassification(t *testing.T) {
cases := []struct {
name string
cfg RetryConfig
status int
wantCalls int32
}{
{"discovery 404 is a routing race and is retried", MetadataFetchRetryConfig(), http.StatusNotFound, 3},
{"discovery 502 is retried", MetadataFetchRetryConfig(), http.StatusBadGateway, 3},
{"discovery 503 is retried", MetadataFetchRetryConfig(), http.StatusServiceUnavailable, 3},
{"discovery 429 is retried", MetadataFetchRetryConfig(), http.StatusTooManyRequests, 3},
{"discovery 400 is terminal", MetadataFetchRetryConfig(), http.StatusBadRequest, 1},
{"discovery 401 is terminal", MetadataFetchRetryConfig(), http.StatusUnauthorized, 1},
{"discovery 403 is terminal", MetadataFetchRetryConfig(), http.StatusForbidden, 1},
{"other configs keep 404 terminal", DefaultRetryConfig(), http.StatusNotFound, 1},
{"other configs retry 502", DefaultRetryConfig(), http.StatusBadGateway, 3},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
srv, providerURL, hits := newFlakyDiscovery(t, c.status, 1<<20)
mc := NewMetadataCacheWithLogger(nil, NewLogger("error"))
re := NewRetryExecutor(fastRetry(c.cfg, 3), NewLogger("error"))
err := re.ExecuteWithContext(context.Background(), func() error {
_, fetchErr := mc.GetProviderMetadata(context.Background(), providerURL, srv.Client())
return fetchErr
})
require.Error(t, err)
assert.Equal(t, c.wantCalls, hits.Load())
})
}
}
func TestGetProviderMetadata_NonOKStatusIsHTTPError(t *testing.T) {
srv, providerURL, _ := newFlakyDiscovery(t, http.StatusBadGateway, 1)
mc := NewMetadataCacheWithLogger(nil, NewLogger("error"))
_, err := mc.GetProviderMetadata(context.Background(), providerURL, srv.Client())
require.Error(t, err)
httpErr, ok := asHTTPError(err)
require.True(t, ok, "a non-200 discovery response must carry its status: %v", err)
assert.Equal(t, http.StatusBadGateway, httpErr.StatusCode)
assert.Contains(t, err.Error(), "HTTP 502")
}
func TestGetMetadataWithRecovery_RetriesStartupNotFound(t *testing.T) {
srv, providerURL, hits := newFlakyDiscovery(t, http.StatusNotFound, 2)
mc := NewMetadataCacheWithLogger(nil, NewLogger("error"))
metadata, err := mc.GetMetadataWithRecovery(context.Background(), providerURL, srv.Client(), NewLogger("error"), nil)
require.NoError(t, err)
assert.Equal(t, srv.URL, metadata.Issuer)
assert.Equal(t, int32(3), hits.Load())
}
func TestGetMetadataWithRecovery_StopsWhenContextEnds(t *testing.T) {
srv, providerURL, _ := newFlakyDiscovery(t, http.StatusNotFound, 1<<20)
mc := NewMetadataCacheWithLogger(nil, NewLogger("error"))
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
start := time.Now()
_, err := mc.GetMetadataWithRecovery(ctx, providerURL, srv.Client(), NewLogger("error"), nil)
require.Error(t, err)
assert.Less(t, time.Since(start), 5*time.Second, "a canceled context must end the startup retries")
}
func TestRunMetadataInit_RecoversInBackgroundWithoutRequest(t *testing.T) {
srv, providerURL, hits := newFlakyDiscovery(t, http.StatusNotFound, 3)
oidc := newRecoveryTestOIDC(t, srv, providerURL)
done := make(chan struct{})
go func() {
oidc.runMetadataInit(providerURL, fastRetry(metadataRecoveryBackoff(), 0))
close(done)
}()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("background recovery did not finish")
}
select {
case <-oidc.initComplete:
default:
t.Fatal("initComplete must be closed after the first failed attempt")
}
assert.True(t, oidc.metadataReady())
assert.Equal(t, srv.URL, oidc.issuerURL)
assert.Equal(t, int32(4), hits.Load(), "one startup attempt, two failed background attempts, one success")
}
func TestRunMetadataInit_OpensTheGateBeforeBackgroundRetries(t *testing.T) {
srv, providerURL, hits := newFlakyDiscovery(t, http.StatusNotFound, 1<<20)
oidc := newRecoveryTestOIDC(t, srv, providerURL)
ctx, cancel := context.WithCancel(context.Background())
oidc.ctx = ctx
done := make(chan struct{})
go func() {
oidc.runMetadataInit(providerURL, fastRetry(metadataRecoveryBackoff(), 0))
close(done)
}()
select {
case <-oidc.initComplete:
case <-time.After(5 * time.Second):
t.Fatal("requests must not wait on initComplete while recovery retries")
}
require.Eventually(t, func() bool { return hits.Load() >= 3 }, 5*time.Second, 5*time.Millisecond)
assert.False(t, oidc.metadataReady())
cancel()
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("background recovery must stop when the instance context ends")
}
}
func TestRecoverMetadataInBackground_StopsOnCancelDuringDelay(t *testing.T) {
srv, providerURL, hits := newFlakyDiscovery(t, http.StatusNotFound, 1<<20)
oidc := newRecoveryTestOIDC(t, srv, providerURL)
ctx, cancel := context.WithCancel(context.Background())
oidc.ctx = ctx
backoff := metadataRecoveryBackoff()
backoff.InitialDelay = time.Hour
done := make(chan struct{})
go func() {
oidc.recoverMetadataInBackground(providerURL, backoff)
close(done)
}()
cancel()
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("background recovery must stop when the instance context ends")
}
assert.Zero(t, hits.Load())
}
func TestRecoverMetadataInBackground_SkipsWhenAlreadyRecovered(t *testing.T) {
srv, providerURL, hits := newFlakyDiscovery(t, http.StatusNotFound, 1<<20)
oidc := newRecoveryTestOIDC(t, srv, providerURL)
oidc.issuerURL = srv.URL // the request path recovered it first
oidc.recoverMetadataInBackground(providerURL, fastRetry(metadataRecoveryBackoff(), 0))
assert.Zero(t, hits.Load())
}
func TestServeHTTP_MetadataUnavailableSetsRetryAfter(t *testing.T) {
oidc := newTestOIDC(t, func(o *TraefikOidc) { o.issuerURL = "" })
req := httptest.NewRequest(http.MethodGet, "/app", nil)
req.Header.Set("Accept", "text/html")
rec := httptest.NewRecorder()
oidc.ServeHTTP(rec, req)
assert.Equal(t, http.StatusServiceUnavailable, rec.Code)
assert.Equal(t, metadataUnavailableRetryAfter, rec.Header().Get("Retry-After"))
assert.True(t, strings.Contains(rec.Body.String(), "metadata"))
}
func TestMetadataRecoveryLogLoud(t *testing.T) {
cases := []struct {
attempt int
want bool
}{
{1, true}, {3, true}, {4, false}, {9, false}, {10, true}, {11, false}, {20, true},
}
for _, c := range cases {
assert.Equal(t, c.want, metadataRecoveryLogLoud(c.attempt), "attempt %d", c.attempt)
}
}
func TestRecoverMetadataInBackground_KeepsRetryingWithoutIssuer(t *testing.T) {
hits := &atomic.Int32{}
var srv *httptest.Server
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hits.Add(1)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(ProviderMetadata{
AuthURL: srv.URL + "/auth",
TokenURL: srv.URL + "/token",
JWKSURL: srv.URL + "/jwks",
})
}))
t.Cleanup(srv.Close)
providerURL := srv.URL + "/" + t.Name()
oidc := newRecoveryTestOIDC(t, srv, providerURL)
ctx, cancel := context.WithCancel(context.Background())
oidc.ctx = ctx
done := make(chan struct{})
go func() {
oidc.recoverMetadataInBackground(providerURL, fastRetry(metadataRecoveryBackoff(), 0))
close(done)
}()
require.Eventually(t, func() bool { return hits.Load() >= 1 }, 5*time.Second, time.Millisecond)
select {
case <-done:
t.Fatal("a document without an issuer must not end recovery")
case <-time.After(100 * time.Millisecond):
}
assert.False(t, oidc.metadataReady())
cancel()
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("background recovery must stop when the instance context ends")
}
}
func TestNew_CloseStopsStartupRetries(t *testing.T) {
if testing.Short() {
t.Skip("drives New through the real startup retry delays")
}
srv, _, hits := newFlakyDiscovery(t, http.StatusNotFound, 1<<20)
config := &Config{
ProviderURL: srv.URL,
ClientID: "test-client",
ClientSecret: "test-secret",
CallbackURL: "/callback",
SessionEncryptionKey: "test-encryption-key-thats-long-enough",
RateLimit: 100,
}
handler, err := New(context.Background(), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}), config, "issue147-close")
require.NoError(t, err)
m, ok := handler.(*TraefikOidc)
require.True(t, ok)
// The first retry delay is 1s, so a second request proves the retries run.
require.Eventually(t, func() bool { return hits.Load() >= 2 }, 10*time.Second, 10*time.Millisecond)
start := time.Now()
require.NoError(t, m.Close())
assert.Less(t, time.Since(start), 5*time.Second, "Close must not wait for the startup retries")
stopped := hits.Load()
time.Sleep(2 * time.Second)
assert.Equal(t, stopped, hits.Load(), "no discovery request may follow Close")
}
+65 -5
View File
@@ -158,6 +158,15 @@ func (w *optionsPreflightWriter) Write(b []byte) (int, error) {
return len(b), nil
}
const (
// maxInitWaiters bounds requests parked on initComplete so a boot-time
// flood with the IdP down cannot hold unbounded connections for 30s each.
maxInitWaiters = 512
// initWaitRetryAfter is the Retry-After value (seconds) sent when the
// init-wait queue is full.
initWaitRetryAfter = "5"
)
// bypassReason describes why a request is being forwarded without OIDC auth.
// It is only used for logging and to decide whether extra side-effects
// (propagating the user header from an existing session) should run.
@@ -195,6 +204,12 @@ func isWebSocketUpgrade(req *http.Request) bool {
// This must be called BEFORE waiting on t.initComplete so excluded, SSE and
// WebSocket traffic is never blocked by a slow/broken provider.
func (t *TraefikOidc) shouldBypassAuth(req *http.Request) (bool, string) {
// The token-mediating endpoint authenticates itself, so no bypass (excluded
// URL, SSE, WebSocket, preflight) may forward a request to the backend
// instead of answering it.
if t.isTMBPath(req.URL.Path) {
return false, ""
}
if t.determineExcludedURL(req.URL.Path) {
return true, bypassReasonExcluded
}
@@ -451,6 +466,11 @@ func (t *TraefikOidc) bypassSessionClaims(session *SessionData) (map[string]inte
return claims, err
}
// metadataUnavailableRetryAfter is the Retry-After value (seconds) of the 503
// served while provider metadata is unavailable or initialization times out.
// Background recovery retries every 5 to 60 seconds.
const metadataUnavailableRetryAfter = "10"
// ServeHTTP implements the main middleware logic for processing HTTP requests.
// It handles the complete OIDC authentication flow including:
// - Excluded URL bypass
@@ -701,6 +721,13 @@ func (t *TraefikOidc) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
// Log waiting for initialization to help diagnose hanging requests
t.logger.Debug("Waiting for OIDC provider initialization...")
if atomic.AddInt32(&t.initWaiters, 1) > maxInitWaiters {
atomic.AddInt32(&t.initWaiters, -1)
rw.Header().Set("Retry-After", initWaitRetryAfter)
t.sendErrorResponse(rw, req, "OIDC provider initialization in progress - please try again later", http.StatusServiceUnavailable)
return
}
// time.NewTimer + Stop avoids leaking a goroutine+channel for 30s on every
// request when initComplete fires quickly (would happen with time.After).
initTimer := time.NewTimer(30 * time.Second)
@@ -708,6 +735,7 @@ func (t *TraefikOidc) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
select {
case <-t.initComplete:
atomic.AddInt32(&t.initWaiters, -1)
// Read issuerURL via atomic snapshot when available — replaces the
// metadataMu.RLock that previously fired on every non-bypass request.
// Under Yaegi each RLock acquisition costs 1-5ms of interpreter
@@ -740,15 +768,19 @@ func (t *TraefikOidc) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
}
t.logger.Error("OIDC provider metadata initialization failed or incomplete")
rw.Header().Set("Retry-After", metadataUnavailableRetryAfter)
t.sendErrorResponse(rw, req, "OIDC provider metadata initialization failed - please check provider availability and configuration", http.StatusServiceUnavailable)
return
}
case <-req.Context().Done():
atomic.AddInt32(&t.initWaiters, -1)
t.logger.Debug("Request canceled while waiting for OIDC initialization")
t.sendErrorResponse(rw, req, "Request canceled", http.StatusRequestTimeout)
return
case <-initTimer.C:
atomic.AddInt32(&t.initWaiters, -1)
t.logger.Error("Timeout waiting for OIDC initialization")
rw.Header().Set("Retry-After", metadataUnavailableRetryAfter)
t.sendErrorResponse(rw, req, "Timeout waiting for OIDC provider initialization - please try again later", http.StatusServiceUnavailable)
return
}
@@ -756,6 +788,14 @@ func (t *TraefikOidc) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
// Bypass checks already ran before the init wait; no need to repeat them.
t.sessionManager.CleanupOldCookies(rw, req)
// Token-mediating endpoints (opt-in by path): session-cookie only, so
// they are handled before the bearer branch and never fall into the
// redirect flow below.
if t.isTMBPath(req.URL.Path) {
t.handleTMB(rw, req)
return
}
// Bearer-token auth (opt-in). Runs after init (we need issuer+JWKs+aud
// available) and after bypass (excluded URLs always win). Cookie-vs-
// bearer precedence is configurable; the safe default is cookie-wins.
@@ -1035,8 +1075,7 @@ func (t *TraefikOidc) processAuthorizedRequestRS(rw http.ResponseWriter, req *ht
idToken := rs.idToken
if t.enableBackchannelLogout || t.enableFrontchannelLogout {
if idToken != "" {
sid, sub, _ := t.extractSessionInfo(idToken)
createdAt := t.sessionCreatedAtForInvalidation(idToken, session)
sid, sub, createdAt := t.invalidationInputs(idToken, session)
if t.isSessionInvalidated(sid, sub, createdAt) {
t.logger.Infof("Session for user %s has been invalidated via IdP-initiated logout", userIdentifier)
if err := session.Clear(req, rw); err != nil {
@@ -1128,8 +1167,7 @@ func (t *TraefikOidc) processAuthorizedRequest(rw http.ResponseWriter, req *http
if t.enableBackchannelLogout || t.enableFrontchannelLogout {
idToken := session.GetIDToken()
if idToken != "" {
sid, sub, _ := t.extractSessionInfo(idToken)
createdAt := t.sessionCreatedAtForInvalidation(idToken, session)
sid, sub, createdAt := t.invalidationInputs(idToken, session)
if t.isSessionInvalidated(sid, sub, createdAt) {
t.logger.Infof("Session for user %s has been invalidated via IdP-initiated logout", userIdentifier)
// Clear the session and redirect to login
@@ -1324,6 +1362,23 @@ func joinBoundedClaimHeader(values []string) string {
return b.String()
}
// dropInboundTemplated removes a client-supplied value for a header the
// middleware owns, so a skipped render leaves it absent instead of forwarding
// the client's. Identity headers (already stripped and re-injected) and
// Authorization (the inbound bearer credential) are left alone.
func dropInboundTemplated(req *http.Request, name string) {
canon := http.CanonicalHeaderKey(name)
if canon == "Authorization" {
return
}
for _, h := range identityHeaders {
if canon == http.CanonicalHeaderKey(h) {
return
}
}
req.Header.Del(canon)
}
// applyHeaderTemplates renders the configured header templates for p onto req.
func (t *TraefikOidc) applyHeaderTemplates(req *http.Request, p *principal) {
if len(t.headerTemplates) == 0 {
@@ -1342,6 +1397,7 @@ func (t *TraefikOidc) applyHeaderTemplates(req *http.Request, p *principal) {
}
for headerName, tmpl := range t.headerTemplates {
dropInboundTemplated(req, headerName)
var buf bytes.Buffer
if err := tmpl.Execute(&buf, templateData); err != nil {
t.logger.Errorf("Failed to execute template for header %s: %v", headerName, err)
@@ -1371,7 +1427,11 @@ func (t *TraefikOidc) applyHeaderTemplates(req *http.Request, p *principal) {
// forwarding a tainted value. Do not log the value (it commonly
// carries the access token); log only name + reason.
if reason := headerValueReason(headerValue, headerTemplateMaxLen); reason != "" {
t.logger.Debugf("Dropping templated header %s: value failed sanitization (%s)", headerName, reason)
if reason == headerReasonTooLong {
t.logger.Errorf("Dropping templated header %s: rendered value exceeds %d bytes", headerName, headerTemplateMaxLen)
} else {
t.logger.Debugf("Dropping templated header %s: value failed sanitization (%s)", headerName, reason)
}
continue
}
req.Header.Set(headerName, headerValue)
+19 -2
View File
@@ -62,10 +62,11 @@ func (l *perSourceAuthLimiter) allow(req *http.Request) bool {
if now.Sub(l.lastSweep) >= time.Minute {
l.sweep(now)
}
e := l.entries[ip]
key := limiterKey(ip)
e := l.entries[key]
if e == nil {
e = &perSourceAuthEntry{limiter: rate.NewLimiter(l.limit, l.burst)}
l.entries[ip] = e
l.entries[key] = e
}
e.lastSeen = now
return e.limiter.Allow()
@@ -115,3 +116,19 @@ func isInternalSource(ip string) bool {
return p.IsLoopback() || p.IsPrivate() || p.IsLinkLocalUnicast() ||
p.IsLinkLocalMulticast() || p.IsUnspecified()
}
// ipv6PrefixBits is the IPv6 prefix that shares one bucket: a host holds a
// whole /64, so per-address keys would give it 2^64 buckets.
const ipv6PrefixBits = 64
// limiterKey maps a source IP to its bucket key (IPv6 collapses to its /64).
func limiterKey(ip string) string {
p := net.ParseIP(ip)
if p == nil {
return ip
}
if p.To4() != nil {
return p.String()
}
return (&net.IPNet{IP: p.Mask(net.CIDRMask(ipv6PrefixBits, 128)), Mask: net.CIDRMask(ipv6PrefixBits, 128)}).String()
}
+49
View File
@@ -0,0 +1,49 @@
package traefikoidc
import (
"fmt"
"net/http/httptest"
"testing"
)
// An IPv6 /64 holder must share one bucket; per-address keys let one host
// mint 2^64 buckets and bypass the throttle.
func TestPerSourceLimiter_IPv6SamePrefixSharesBucket(t *testing.T) {
const burst = 3
l := newPerSourceAuthLimiter(burst)
allowed := 0
for i := 0; i < 50; i++ {
req := httptest.NewRequest("GET", "/", nil)
req.RemoteAddr = fmt.Sprintf("[2001:db8:1:2::%x]:1234", i+1)
if l.allow(req) {
allowed++
}
}
if allowed > burst {
t.Fatalf("one /64 got %d allows, want <= %d", allowed, burst)
}
}
func TestPerSourceLimiter_IPv6DifferentPrefixIndependent(t *testing.T) {
l := newPerSourceAuthLimiter(1)
a := httptest.NewRequest("GET", "/", nil)
a.RemoteAddr = "[2001:db8:1:2::1]:1"
b := httptest.NewRequest("GET", "/", nil)
b.RemoteAddr = "[2001:db8:1:3::1]:1"
if !l.allow(a) || !l.allow(b) {
t.Fatal("distinct /64 prefixes must have independent buckets")
}
}
func TestLimiterKey(t *testing.T) {
cases := map[string]string{
"192.0.2.1": "192.0.2.1",
"2001:db8:1:2::9": "2001:db8:1:2::/64",
"::ffff:192.0.2.1": "192.0.2.1",
}
for in, want := range cases {
if got := limiterKey(in); got != want {
t.Errorf("limiterKey(%q)=%q want %q", in, got, want)
}
}
}
+49
View File
@@ -0,0 +1,49 @@
package traefikoidc
import (
"testing"
"time"
"github.com/gorilla/sessions"
)
// Cleanup must not evict a tracker whose cooldown is still running.
func TestRefreshCleanupKeepsTrackerInCooldown(t *testing.T) {
cfg := DefaultRefreshCoordinatorConfig()
cfg.MaxRefreshAttempts = 2
cfg.RefreshAttemptWindow = 20 * time.Millisecond
cfg.RefreshCooldownPeriod = time.Hour
rc := NewRefreshCoordinator(cfg, GetSingletonNoOpLogger())
defer rc.Shutdown()
rc.recordRefreshAttempt("s")
rc.recordRefreshAttempt("s")
if !rc.isInCooldown("s") {
t.Fatal("precondition: session must enter cooldown")
}
time.Sleep(80 * time.Millisecond)
rc.cleanupStaleEntries()
if !rc.isInCooldown("s") {
t.Fatal("cleanup evicted a tracker still in cooldown")
}
}
// Stale chunks above token_total must be dropped by key, even when the key
// set is sparse.
func TestChunkTrimDropsStaleSparseKeys(t *testing.T) {
cm := NewChunkManager(newNoOpLogger())
mk := func(s string, total interface{}) *sessions.Session {
v := map[interface{}]interface{}{"token_chunk": s}
if total != nil {
v["token_total"] = total
}
return &sessions.Session{Values: v}
}
chunks := map[int]*sessions.Session{
0: mk("Zq8xK2mP", 3), 1: mk("r7TnB4wY", nil), 2: mk("c9LdG5sH", nil), 7: mk("stale", nil),
}
res := cm.processChunkedToken(chunks, RefreshTokenConfig)
if res.Error != nil || res.Token != "Zq8xK2mPr7TnB4wYc9LdG5sH" {
t.Fatalf("token=%q err=%v, want Zq8xK2mPr7TnB4wYc9LdG5sH", res.Token, res.Error)
}
}
+23 -13
View File
@@ -672,7 +672,6 @@ func (rc *RefreshCoordinator) isInCooldown(sessionID string) bool {
}
return &attemptState{
windowStartNano: nowNano,
attempts: 1,
}
})
return false
@@ -686,7 +685,7 @@ func (rc *RefreshCoordinator) isInCooldown(sessionID string) bool {
}
next := *s
next.windowStartNano = nowNano
next.attempts = 1
next.attempts = 0
return &next
})
return false
@@ -824,13 +823,16 @@ func (rc *RefreshCoordinator) cleanupRoutine() {
// cleanupStaleEntries removes outdated tracking entries. Lock-free iteration
// via sync.Map.Range; safe to race with concurrent reads/writes.
func (rc *RefreshCoordinator) cleanupStaleEntries() {
cutoff := time.Now().Add(-2 * rc.config.RefreshAttemptWindow).UnixNano()
now := time.Now()
cutoff := now.Add(-2 * rc.config.RefreshAttemptWindow).UnixNano()
nowNano := now.UnixNano()
rc.sessionRefreshAttempts.Range(func(key, value interface{}) bool {
tracker := trackerFromMapValue(value)
if tracker == nil {
return true
}
if tracker.stateOf().lastAttemptNano < cutoff {
st := tracker.stateOf()
if st.lastAttemptNano < cutoff && st.cooldownEndNano <= nowNano {
// Compare-and-delete to avoid evicting a tracker that was just
// re-used by a concurrent caller. We compare by pointer identity.
rc.sessionRefreshAttempts.CompareAndDelete(key, value)
@@ -939,20 +941,28 @@ func (cb *RefreshCircuitBreaker) AllowRequest() bool {
return true
case 1: // open
lastFail := atomic.LoadInt64(&cb.lastFailureNano)
if time.Duration(time.Now().UnixNano()-lastFail) > cb.config.OpenDuration {
// Transition to half-open; first CAS winner gets the probe.
if atomic.CompareAndSwapInt32(&cb.state, 1, 2) {
return true
}
}
return false
case 2: // half-open
return true
return cb.claimProbe(lastFail)
case 2: // half-open: one probe at a time; a stale probe is replaced
return cb.claimProbe(atomic.LoadInt64(&cb.lastFailureNano))
default:
return false
}
}
// claimProbe admits one probe when OpenDuration has passed since lastFail.
// The CAS on lastFailureNano makes the claim exclusive and restarts the clock.
func (cb *RefreshCircuitBreaker) claimProbe(lastFail int64) bool {
now := time.Now().UnixNano()
if time.Duration(now-lastFail) <= cb.config.OpenDuration {
return false
}
if !atomic.CompareAndSwapInt64(&cb.lastFailureNano, lastFail, now) {
return false
}
atomic.StoreInt32(&cb.state, 2)
return true
}
// RecordSuccess records a successful operation. Lock-free.
func (cb *RefreshCircuitBreaker) RecordSuccess() {
switch atomic.LoadInt32(&cb.state) {
+54
View File
@@ -0,0 +1,54 @@
package traefikoidc
import (
"strings"
"testing"
"time"
)
// Entra ID refresh tokens start with "1." and contain two dots, but are not JWTs.
func TestRefreshTokenWithDotsIsOpaque(t *testing.T) {
cm := NewChunkManager(NewLogger(""))
entra := "1.AXwAbCdEfGhIjKlMnOpQrStUvWxYz0123456789_-" +
"." + strings.Repeat("Ab9_-xYz+/", 40) +
"." + strings.Repeat("Qw3rTy7u!~", 40)
t.Run("refresh config accepts dotted opaque token", func(t *testing.T) {
if res := cm.validateToken(entra, RefreshTokenConfig); res.Error != nil {
t.Fatalf("refresh token rejected: %v", res.Error)
}
})
t.Run("access config still validates dotted token as JWT", func(t *testing.T) {
res := cm.validateToken(entra, AccessTokenConfig)
if res.Error == nil {
t.Fatal("malformed JWT-shaped access token was accepted")
}
})
t.Run("refresh config still rejects control characters", func(t *testing.T) {
bad := strings.Replace(entra, "AXwA", "AX\x01A", 1)
if res := cm.validateToken(bad, RefreshTokenConfig); res.Error == nil {
t.Fatal("refresh token with control character was accepted")
}
})
t.Run("valid JWT refresh token keeps JWT validation", func(t *testing.T) {
future := time.Now().Add(time.Hour).Unix()
jwt := tokenWithGroups(t, map[string]interface{}{"sub": "a", "exp": float64(future + 3600), "iat": float64(future)})
res := cm.validateToken(jwt, RefreshTokenConfig)
if res.Error == nil || !strings.Contains(res.Error.Error(), "issued in future") {
t.Fatalf("error = %v, want issued-in-future from the JWT path", res.Error)
}
})
t.Run("malformed JWT refresh token stays rejected", func(t *testing.T) {
future := time.Now().Add(time.Hour).Unix()
jwt := tokenWithGroups(t, map[string]interface{}{"sub": "a", "exp": float64(future + 3600), "iat": float64(time.Now().Unix())})
parts := strings.Split(jwt, ".")
corrupt := parts[0] + "." + parts[1] + ".!!!not-base64!!!"
if res := cm.validateToken(corrupt, RefreshTokenConfig); res.Error == nil {
t.Fatal("JWT with a corrupt signature was accepted as opaque")
}
})
}
+93
View File
@@ -0,0 +1,93 @@
package traefikoidc
import (
"sync"
"sync/atomic"
"testing"
"time"
)
// After a window reset the tracker must allow the full MaxRefreshAttempts,
// the same as a fresh tracker.
func TestRefreshWindowResetAllowsFullQuota(t *testing.T) {
cfg := DefaultRefreshCoordinatorConfig()
cfg.MaxRefreshAttempts = 3
cfg.RefreshAttemptWindow = 50 * time.Millisecond
cfg.RefreshCooldownPeriod = time.Hour
rc := NewRefreshCoordinator(cfg, GetSingletonNoOpLogger())
defer rc.Shutdown()
pass := func() int {
n := 0
for i := 0; i < 10; i++ {
if rc.isInCooldown("s") {
break
}
rc.recordRefreshAttempt("s")
n++
}
return n
}
if got := pass(); got != 3 {
t.Fatalf("fresh window passes=%d want 3", got)
}
// Window expiry alone cannot reset while in cooldown, so use a new
// session that never hits the cap: record 1, wait out the window.
rc.recordRefreshAttempt("w")
time.Sleep(80 * time.Millisecond)
n := 0
for i := 0; i < 10; i++ {
if rc.isInCooldown("w") {
break
}
rc.recordRefreshAttempt("w")
n++
}
if n != 3 {
t.Fatalf("post-reset window passes=%d want 3", n)
}
}
// Half-open admits a single probe until it reports.
func TestRefreshBreakerHalfOpenSingleProbe(t *testing.T) {
cb := &RefreshCircuitBreaker{config: RefreshCircuitBreakerConfig{
MaxFailures: 1, OpenDuration: 20 * time.Millisecond, HalfOpenRequests: 1,
}}
cb.RecordFailure()
time.Sleep(40 * time.Millisecond)
var admitted int32
var wg sync.WaitGroup
for i := 0; i < 20; i++ {
wg.Add(1)
go func() {
defer wg.Done()
if cb.AllowRequest() {
atomic.AddInt32(&admitted, 1)
}
}()
}
wg.Wait()
if admitted != 1 {
t.Fatalf("half-open admitted %d, want 1", admitted)
}
cb.RecordSuccess()
if !cb.AllowRequest() {
t.Fatal("breaker must close after probe success")
}
}
// A probe that never reports must not wedge the breaker.
func TestRefreshBreakerHalfOpenProbeTimeout(t *testing.T) {
cb := &RefreshCircuitBreaker{config: RefreshCircuitBreakerConfig{
MaxFailures: 1, OpenDuration: 20 * time.Millisecond, HalfOpenRequests: 1,
}}
cb.RecordFailure()
time.Sleep(40 * time.Millisecond)
if !cb.AllowRequest() || cb.AllowRequest() {
t.Fatal("want exactly one probe")
}
time.Sleep(40 * time.Millisecond)
if !cb.AllowRequest() {
t.Fatal("stale probe must allow a new one")
}
}
+5
View File
@@ -39,6 +39,10 @@ type requestState struct {
userIdentifier string
createdAtUnixSec int64
// accessTokenExpiresAt is the recorded access-token expiry (unix); 0 when
// unknown.
accessTokenExpiresAt int64
// Output: scheme/host/redirect path determined at top of ServeHTTP.
scheme string
host string
@@ -66,6 +70,7 @@ func (rs *requestState) captureSession(sd *SessionData) *requestState {
rs.refreshToken = sd.getRefreshTokenUnsafe()
rs.userIdentifier = sd.getUserIdentifierUnsafe()
rs.createdAtUnixSec = sd.getCreatedAtUnsafe()
rs.accessTokenExpiresAt = sd.getAccessTokenExpiresAtUnsafe()
sd.sessionMutex.RUnlock()
return rs
}
-13
View File
@@ -2,8 +2,6 @@ package traefikoidc
import (
"context"
"crypto/rand"
"encoding/base64"
"net/http/httptest"
"sync"
"sync/atomic"
@@ -13,17 +11,6 @@ import (
// R154 review-round regressions.
// incompressibleToken returns a base64 blob too large to fit a single
// cookie after compression, so Set*Token takes the chunked path. Random
// bytes are (nearly) incompressible, unlike repeated chars.
func incompressibleToken(size int) string {
buf := make([]byte, size)
if _, err := rand.Read(buf); err != nil {
panic(err)
}
return base64.RawStdEncoding.EncodeToString(buf)
}
// TestSetRefreshToken_AbortPreservesPrevious covers the commit-on-success
// rewrite of SetRefreshToken (session.go). Setting a new chunked refresh
// token on a session whose request is nil (so the chunk write aborts)
+92 -1
View File
@@ -116,6 +116,10 @@ const (
defaultCookiePrefix = "_oidc_raczylo_"
)
// maxCleanupCookies bounds the cookie names CleanupOldCookies emits deletion
// headers for per response (up to 4 Set-Cookie headers each).
const maxCleanupCookies = 32
const (
// maxCookieSize is the maximum raw data size per chunk before securecookie encoding.
//
@@ -149,6 +153,7 @@ type combinedSessionPayload struct {
Ip string `json:"ip,omitempty"`
Ru string `json:"ru,omitempty"` // redirect_uri used at initiate; reused at callback so a per-request rebuild can't drift (R136)
Ca int64 `json:"ca,omitempty"`
Ea int64 `json:"ea,omitempty"` // access-token expiry (unix); a dedicated field because JSON would turn an int64 in X into a float64
Rc int `json:"rc,omitempty"`
Au bool `json:"au,omitempty"`
}
@@ -168,8 +173,15 @@ var knownSessionKeys = map[string]bool{
"redirect_url": true,
"created_at": true,
"redirect_count": true,
"access_token_expires_at": true,
}
// accessTokenExpiresAtKey holds the access token's expiry (unix seconds) in
// mainSession.Values. It describes the stored access token only and is dropped
// whenever that token changes (see SetAccessToken).
const accessTokenExpiresAtKey = "access_token_expires_at"
// compressCombinedPayload compresses the combined session payload using gzip.
// It serializes the payload to JSON, compresses it, and returns base64-encoded data.
// Returns the compressed string and any error encountered.
@@ -937,6 +949,9 @@ func (sm *SessionManager) EnhanceSessionSecurity(options *sessions.Options, r *h
// service). Keep it unless it is a strict parent of the serving
// host, which would scope the token-bearing cookie to sibling
// subdomains — then fall back to the serving host.
// DNS names and the cookie Domain attribute are case-insensitive.
host = strings.ToLower(host)
fh = strings.ToLower(fh)
if !strings.HasSuffix(host, "."+fh) {
host = fh
}
@@ -1024,6 +1039,7 @@ func (sm *SessionManager) CleanupOldCookies(w http.ResponseWriter, r *http.Reque
}
processedCookies := make(map[string]bool)
deletedCookies := 0
for _, cookie := range cookies {
// Check if cookie belongs to this middleware instance using the configured prefix
@@ -1037,7 +1053,8 @@ func (sm *SessionManager) CleanupOldCookies(w http.ResponseWriter, r *http.Reque
shouldCleanup := currentDomain != "" && !sm.cleanupDone
sm.cleanupMutex.RUnlock()
if shouldCleanup {
if shouldCleanup && deletedCookies < maxCleanupCookies {
deletedCookies++
for _, domain := range domainsToClean {
if domain == currentDomain || domain == "."+currentDomain || "."+domain == currentDomain {
continue
@@ -1296,6 +1313,9 @@ func (sm *SessionManager) loadFromCombinedCookies(r *http.Request, sessionData *
sessionData.mainSession.Values["redirect_url"] = payload.Ru
sessionData.mainSession.Values["created_at"] = payload.Ca
sessionData.mainSession.Values["redirect_count"] = payload.Rc
if payload.Ea > 0 {
sessionData.mainSession.Values[accessTokenExpiresAtKey] = payload.Ea
}
// Restore extra custom session values
for key, val := range payload.X {
@@ -1510,6 +1530,7 @@ func (sd *SessionData) saveCombined(r *http.Request, w http.ResponseWriter, opti
Ip: sd.getIncomingPathUnsafe(),
Ru: sd.getRedirectURLUnsafe(),
Ca: sd.getCreatedAtUnsafe(),
Ea: sd.getAccessTokenExpiresAtUnsafe(),
Rc: sd.getRedirectCountUnsafe(),
}
// Persist the refresh token's issued_at so maxRefreshTokenAge keeps
@@ -2225,6 +2246,7 @@ func (sd *SessionData) SetAccessToken(token string) {
sd.accessSession.Values["compressed"] = false
}
sd.clearAccessTokenChunks()
sd.clearAccessTokenExpiryUnsafe()
return
}
@@ -2254,6 +2276,7 @@ func (sd *SessionData) SetAccessToken(token string) {
if len(compressed) <= maxCookieSize {
sd.clearAccessTokenChunks()
sd.clearAccessTokenExpiryUnsafe()
if sd.accessSession != nil {
sd.accessSession.Values["token"] = compressed
sd.accessSession.Values["compressed"] = (compressed != token)
@@ -2293,9 +2316,17 @@ func (sd *SessionData) SetAccessToken(token string) {
return
}
// Chunk cookies bind to the request; without one the store cannot
// complete, so keep the previous token.
if sd.request == nil {
sd.manager.logger.Error("SetAccessToken: sd.request is nil, cannot create chunk sessions")
return
}
// Validation passed: now it is safe to clear the existing token
// before storing the new chunked one.
sd.clearAccessTokenChunks()
sd.clearAccessTokenExpiryUnsafe()
if sd.accessSession != nil {
sd.accessSession.Values["token"] = ""
sd.accessSession.Values["compressed"] = (compressed != token)
@@ -2928,6 +2959,9 @@ func (sd *SessionData) GetIncomingPath() string {
return path
}
// maxIncomingPathLen bounds the post-login redirect path kept in the session.
const maxIncomingPathLen = 2048
// SetIncomingPath stores the original request URI for post-authentication redirect.
// This allows the user to be redirected to their originally requested resource
// after completing the authentication flow.
@@ -2936,6 +2970,11 @@ func (sd *SessionData) GetIncomingPath() string {
func (sd *SessionData) SetIncomingPath(path string) {
sd.sessionMutex.Lock()
defer sd.sessionMutex.Unlock()
// The path becomes cookie bytes on every later request; an oversized one
// would bloat the Cookie header or fail the save. Fall back to "/".
if len(path) > maxIncomingPathLen {
path = ""
}
currentVal, _ := sd.mainSession.Values["incoming_path"].(string)
if currentVal != path {
sd.mainSession.Values["incoming_path"] = path
@@ -3122,6 +3161,58 @@ func (sd *SessionData) getCreatedAtUnsafe() int64 {
return createdAt
}
// getAccessTokenExpiresAtUnsafe returns the stored access-token expiry (unix
// seconds), or 0 when none is known, without acquiring locks.
func (sd *SessionData) getAccessTokenExpiresAtUnsafe() int64 {
if sd.mainSession == nil {
return 0
}
exp, _ := sd.mainSession.Values[accessTokenExpiresAtKey].(int64)
return exp
}
// GetAccessTokenExpiresAt returns when the stored access token expires (unix
// seconds), as recorded from the token response or the token's own exp claim
// at login or refresh. It returns 0 when unknown, e.g. for sessions created
// before the expiry was recorded.
func (sd *SessionData) GetAccessTokenExpiresAt() int64 {
sd.sessionMutex.RLock()
defer sd.sessionMutex.RUnlock()
return sd.getAccessTokenExpiresAtUnsafe()
}
// SetAccessTokenExpiresAt records when token expires (unix seconds), but only
// if token is the stored access token: when SetAccessToken could not store it,
// the previous token keeps its own expiry. A value <= 0 clears it.
func (sd *SessionData) SetAccessTokenExpiresAt(token string, expiresAt int64) {
sd.sessionMutex.Lock()
defer sd.sessionMutex.Unlock()
if sd.mainSession == nil || sd.accessSession == nil || token == "" {
return
}
if !constantTimeStringCompare(sd.getAccessTokenUnsafe(), token) {
return
}
if sd.getAccessTokenExpiresAtUnsafe() == expiresAt {
return
}
sd.dirty = true
if expiresAt <= 0 {
sd.clearAccessTokenExpiryUnsafe()
return
}
sd.mainSession.Values[accessTokenExpiresAtKey] = expiresAt
}
// clearAccessTokenExpiryUnsafe drops the recorded expiry, without acquiring
// locks. Call it whenever the stored access token is replaced or cleared.
func (sd *SessionData) clearAccessTokenExpiryUnsafe() {
if sd.mainSession != nil {
delete(sd.mainSession.Values, accessTokenExpiresAtKey)
}
}
// getRedirectCountUnsafe retrieves the redirect count without acquiring locks.
func (sd *SessionData) getRedirectCountUnsafe() int {
count, _ := sd.mainSession.Values["redirect_count"].(int)
+36
View File
@@ -0,0 +1,36 @@
package traefikoidc
import (
"crypto/rand"
"encoding/base64"
"net/http/httptest"
"testing"
)
// A chunked store that cannot run (no request to bind chunk cookies to) must
// leave the previous access token intact.
func TestSetAccessTokenNilRequestKeepsOldToken(t *testing.T) {
sm, err := NewSessionManager("test-encryption-key-32-characters", false, "", "", 0, NewLogger("error"))
if err != nil {
t.Fatal(err)
}
sess, err := sm.GetSession(httptest.NewRequest("GET", "/", nil))
if err != nil {
t.Fatal(err)
}
t.Cleanup(sess.returnToPoolSafely)
const old = "smallaccesstokenvaluevaluevalue"
sess.SetAccessToken(old)
blob := make([]byte, 3000)
if _, err := rand.Read(blob); err != nil {
t.Fatal(err)
}
sess.request = nil
sess.SetAccessToken(base64.StdEncoding.EncodeToString(blob))
if got := sess.GetAccessToken(); got != old {
t.Fatalf("old access token lost after a failed chunked store: %q", got)
}
}
+49 -233
View File
@@ -5,6 +5,7 @@ import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"strings"
"sync"
@@ -27,12 +28,43 @@ type TokenConfig struct {
MaxChunkSize int
AllowOpaqueTokens bool
RequireJWTFormat bool
// AlwaysOpaque skips JWT checks even when the value contains dots.
AlwaysOpaque bool
// FallbackToOpaque validates a dotted token as opaque when it fails JWT
// validation. Entra ID refresh tokens have two dots but are not JWTs.
FallbackToOpaque bool
}
// claimsJWT reports whether the first segment decodes to a JSON header with an
// "alg" member. A token that does so claims to be a JWT, so a malformed one
// must stay rejected rather than fall back to opaque validation.
func claimsJWT(token string) bool {
seg, _, _ := strings.Cut(token, ".")
raw, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(seg, "="))
if err != nil {
return false
}
var header map[string]any
if json.Unmarshal(raw, &header) != nil {
return false
}
_, ok := header["alg"]
return ok
}
// jwtShaped reports whether token must pass JWT validation.
func (c TokenConfig) jwtShaped(token string) bool {
return c.RequireJWTFormat || (c.AllowOpaqueTokens && !c.AlwaysOpaque && strings.Contains(token, "."))
}
// opaqueShaped reports whether token must pass opaque-token validation.
func (c TokenConfig) opaqueShaped(token string) bool {
return c.AllowOpaqueTokens && (c.AlwaysOpaque || !strings.Contains(token, "."))
}
// Global session tracking to prevent memory leaks across all instances
var (
globalSessionCount int64 = 0
globalMaxSessions int64 = 5000 // CRITICAL FIX: Global limit of 5000 total sessions
)
// ResetGlobalSessionCounters resets global session tracking for testing
@@ -64,6 +96,7 @@ var (
MaxChunkSize: maxCookieSize,
AllowOpaqueTokens: true,
RequireJWTFormat: false,
FallbackToOpaque: true,
}
IDTokenConfig = TokenConfig{
@@ -300,6 +333,9 @@ func (cm *ChunkManager) processSingleToken(token string, compressed bool, config
// Returns:
// - TokenRetrievalResult with the validated token or validation error.
func (cm *ChunkManager) validateToken(token string, config TokenConfig) TokenRetrievalResult {
if config.FallbackToOpaque && strings.Contains(token, ".") && !claimsJWT(token) {
config.AlwaysOpaque = true
}
// Content-only checks depend on the token string alone, so a token that
// passed them once skips them. Expiry and freshness always run.
key := contentValidKey(token, config)
@@ -315,7 +351,9 @@ func (cm *ChunkManager) validateToken(token string, config TokenConfig) TokenRet
if contentErr := cm.validateTokenContent(token, config); contentErr != nil {
return TokenRetrievalResult{Token: "", Error: contentErr}
}
times = cm.tokenTimesOf(token)
if !config.AlwaysOpaque {
times = cm.tokenTimesOf(token)
}
}
if expErr := cm.validateTokenExpiration(times, config); expErr != nil {
@@ -332,8 +370,7 @@ func (cm *ChunkManager) validateToken(token string, config TokenConfig) TokenRet
return TokenRetrievalResult{Token: token, Error: nil}
}
dotCount := strings.Count(token, ".")
isJWT := dotCount == 2
isJWT := strings.Count(token, ".") == 2 && !config.AlwaysOpaque
if config.RequireJWTFormat && !config.AllowOpaqueTokens {
// Only accept JWT format tokens
@@ -445,9 +482,10 @@ func (cm *ChunkManager) processChunkedToken(chunks map[int]*sessions.Session, co
// not clear cookies above n). token_total is the authoritative
// count; drop the excess rather than failing — which forced a
// re-auth and discarded the still-valid new token (R129).
n := len(chunks)
for i := total; i < n; i++ {
delete(chunks, i)
for i := range chunks {
if i >= total {
delete(chunks, i)
}
}
}
if len(chunks) < total {
@@ -684,7 +722,7 @@ func (cm *ChunkManager) validateTokenSize(token string, config TokenConfig) erro
return err
}
if config.RequireJWTFormat || (config.AllowOpaqueTokens && strings.Contains(token, ".")) {
if config.jwtShaped(token) {
parts := strings.Split(token, ".")
if len(parts) == 3 {
headerLen := len(parts[0])
@@ -708,7 +746,7 @@ func (cm *ChunkManager) validateTokenSize(token string, config TokenConfig) erro
}
}
if config.AllowOpaqueTokens && !strings.Contains(token, ".") {
if config.opaqueShaped(token) {
if tokenLen > config.MaxLength {
err := fmt.Errorf("%s opaque token unusually large (%d bytes)", config.Type, tokenLen)
return err
@@ -751,13 +789,13 @@ func (cm *ChunkManager) validateTokenContent(token string, config TokenConfig) e
return err
}
if config.RequireJWTFormat || (config.AllowOpaqueTokens && strings.Contains(token, ".")) {
if config.jwtShaped(token) {
if err := cm.validateJWTContent(token, config); err != nil {
return err
}
}
if config.AllowOpaqueTokens && !strings.Contains(token, ".") {
if config.opaqueShaped(token) {
if err := cm.validateOpaqueTokenContent(token, config); err != nil {
return err
}
@@ -1242,226 +1280,4 @@ func (cm *ChunkManager) CleanupExpiredSessions(force ...bool) {
cm.logger.Debugf("Cleaned up %d expired sessions, freed %d bytes",
len(expiredKeys), totalBytesFreed)
}
// Enforce max sessions limit
if len(cm.sessionMap) > cm.maxSessions {
cm.enforceSessionLimit()
}
}
// enforceSessionLimit removes oldest sessions when limit is exceeded
// Uses partial sort (O(n) for finding k smallest) instead of full sort (O(n log n))
func (cm *ChunkManager) enforceSessionLimit() {
currentLocal := len(cm.sessionMap)
currentGlobal := atomic.LoadInt64(&globalSessionCount)
// CRITICAL FIX: Aggressive eviction when approaching limits
shouldEvict := false
targetCapacity := cm.maxSessions
// Check global limit first (more critical)
if currentGlobal >= globalMaxSessions {
shouldEvict = true
targetCapacity = cm.maxSessions / 4 // Aggressive reduction to 25%
} else if currentGlobal >= globalMaxSessions*8/10 { // 80% of global
shouldEvict = true
targetCapacity = cm.maxSessions / 2 // Reduce to 50%
} else if currentLocal >= cm.maxSessions {
shouldEvict = true
targetCapacity = cm.maxSessions * 3 / 4 // Reduce to 75%
}
if !shouldEvict {
return
}
// Calculate how many sessions to remove
excessCount := currentLocal - targetCapacity
if excessCount <= 0 {
return
}
// Use partial selection instead of full sort for better performance
// For finding k oldest sessions, we only need O(n) operations
keysToRemove := cm.findOldestSessions(excessCount)
totalBytesFreed := int64(0)
removedCount := int64(0)
for _, key := range keysToRemove {
if entry, exists := cm.sessionMap[key]; exists {
totalBytesFreed += entry.SizeEstimate
atomic.AddInt64(&cm.bytesAllocated, -entry.SizeEstimate)
removedCount++
}
delete(cm.sessionMap, key)
}
// Update global count
if removedCount > 0 {
atomic.AddInt64(&globalSessionCount, -removedCount)
}
cm.logger.Infof("Enforced session limit: removed %d excess sessions, freed %d bytes",
len(keysToRemove), totalBytesFreed)
}
// findOldestSessions returns keys of the k oldest sessions efficiently
// Uses a simple approach: find the kth oldest timestamp, then collect all older entries
func (cm *ChunkManager) findOldestSessions(k int) []string {
if k <= 0 || len(cm.sessionMap) == 0 {
return nil
}
if k >= len(cm.sessionMap) {
// Remove all sessions
keys := make([]string, 0, len(cm.sessionMap))
for key := range cm.sessionMap {
keys = append(keys, key)
}
return keys
}
// Collect all timestamps with keys
type sessionAge struct {
lastUsed time.Time
key string
}
sessions := make([]sessionAge, 0, len(cm.sessionMap))
for key, entry := range cm.sessionMap {
sessions = append(sessions, sessionAge{key: key, lastUsed: entry.LastUsed})
}
// Partial sort: get the k smallest elements using selection
// This is O(n*k) which is better than O(n log n) when k << n
for i := 0; i < k; i++ {
minIdx := i
for j := i + 1; j < len(sessions); j++ {
if sessions[j].lastUsed.Before(sessions[minIdx].lastUsed) {
minIdx = j
}
}
if minIdx != i {
sessions[i], sessions[minIdx] = sessions[minIdx], sessions[i]
}
}
// Return the k oldest
result := make([]string, k)
for i := 0; i < k; i++ {
result[i] = sessions[i].key
}
return result
}
// CanCreateSession checks if a new session can be created within limits
func (cm *ChunkManager) CanCreateSession() (bool, error) {
cm.mutex.RLock()
currentCount := len(cm.sessionMap)
cm.mutex.RUnlock()
// Hard limit check - never exceed maxSessions
if currentCount >= cm.maxSessions {
cm.logger.Error("Cannot create session: at maximum limit (%d)", cm.maxSessions)
return false, fmt.Errorf("session storage at maximum capacity (%d sessions)", cm.maxSessions)
}
// Emergency cleanup at 90% capacity
emergencyThreshold := int(float64(cm.maxSessions) * 0.9)
if currentCount >= emergencyThreshold {
cm.logger.Info("Session storage at %d%% capacity, triggering emergency cleanup",
(currentCount*100)/cm.maxSessions)
cm.EmergencyCleanup()
// Recheck after cleanup
cm.mutex.RLock()
newCount := len(cm.sessionMap)
cm.mutex.RUnlock()
if newCount >= cm.maxSessions {
return false, fmt.Errorf("session storage full even after emergency cleanup (%d sessions)", newCount)
}
}
return true, nil
}
// EmergencyCleanup performs aggressive session cleanup when approaching limits
func (cm *ChunkManager) EmergencyCleanup() {
cm.mutex.Lock()
defer cm.mutex.Unlock()
now := time.Now()
removed := 0
// Remove any expired sessions first
expiredKeys := make([]string, 0)
for key, entry := range cm.sessionMap {
if now.After(entry.ExpiresAt) || now.Sub(entry.LastUsed) > cm.sessionTTL {
expiredKeys = append(expiredKeys, key)
}
}
for _, key := range expiredKeys {
if entry, exists := cm.sessionMap[key]; exists {
atomic.AddInt64(&cm.bytesAllocated, -entry.SizeEstimate)
}
delete(cm.sessionMap, key)
removed++
}
// If still over 80% capacity, remove oldest sessions more aggressively
targetCapacity := int(float64(cm.maxSessions) * 0.8)
if len(cm.sessionMap) > targetCapacity {
excessCount := len(cm.sessionMap) - targetCapacity
// Use efficient partial sort to find oldest sessions
keysToRemove := cm.findOldestSessions(excessCount)
for _, key := range keysToRemove {
if entry, exists := cm.sessionMap[key]; exists {
atomic.AddInt64(&cm.bytesAllocated, -entry.SizeEstimate)
}
delete(cm.sessionMap, key)
removed++
}
}
cm.lastCleanup = now
cm.logger.Infof("Emergency cleanup completed: removed %d sessions, %d remaining",
removed, len(cm.sessionMap))
// Log memory stats after emergency cleanup (read only, no forced GC)
cm.logger.Infof("Sessions after emergency cleanup: %d, Tracked bytes: %d",
len(cm.sessionMap), atomic.LoadInt64(&cm.bytesAllocated))
}
// GetSessionCount returns the current number of active sessions (for monitoring)
func (cm *ChunkManager) GetSessionCount() int {
cm.mutex.RLock()
defer cm.mutex.RUnlock()
return len(cm.sessionMap)
}
// GetMemoryStats returns memory usage statistics for monitoring
func (cm *ChunkManager) GetMemoryStats() map[string]interface{} {
cm.mutex.RLock()
sessionCount := len(cm.sessionMap)
cm.mutex.RUnlock()
stats := make(map[string]interface{})
stats["active_sessions"] = sessionCount
stats["max_sessions"] = cm.maxSessions
stats["bytes_allocated"] = atomic.LoadInt64(&cm.bytesAllocated)
stats["peak_sessions"] = atomic.LoadInt64(&cm.peakSessions)
stats["cleanup_count"] = atomic.LoadInt64(&cm.cleanupCount)
stats["session_ttl_hours"] = cm.sessionTTL.Hours()
// Update peak sessions
if int64(sessionCount) > atomic.LoadInt64(&cm.peakSessions) {
atomic.StoreInt64(&cm.peakSessions, int64(sessionCount))
}
return stats
}
+41
View File
@@ -0,0 +1,41 @@
package traefikoidc
import (
"net/http/httptest"
"strings"
"testing"
"github.com/lukaszraczylo/traefikoidc/internal/utils"
)
// A deep link longer than the cap must not be persisted into the cookies.
func TestSetIncomingPathCapsLength(t *testing.T) {
sm, err := NewSessionManager("test-encryption-key-32-characters", false, "", "", 0, NewLogger("error"))
if err != nil {
t.Fatal(err)
}
sess, err := sm.GetSession(httptest.NewRequest("GET", "/", nil))
if err != nil {
t.Fatal(err)
}
t.Cleanup(sess.returnToPoolSafely)
sess.SetIncomingPath("/ok?a=1")
if got := sess.GetIncomingPath(); got != "/ok?a=1" {
t.Fatalf("short path changed: %q", got)
}
sess.SetIncomingPath("/x?" + strings.Repeat("q", maxIncomingPathLen+1))
if got := sess.GetIncomingPath(); got != "" {
t.Fatalf("oversized path stored (%d bytes)", len(got))
}
}
func TestDetermineSchemeCaseInsensitive(t *testing.T) {
for in, want := range map[string]string{"HTTPS": "https", "Https": "https", "HTTP": "http", "https": "https"} {
r := httptest.NewRequest("GET", "/", nil)
r.Header.Set("X-Forwarded-Proto", in)
if got := utils.DetermineScheme(r, false); got != want {
t.Errorf("X-Forwarded-Proto %q -> %q, want %q", in, got, want)
}
}
}
+17
View File
@@ -0,0 +1,17 @@
package traefikoidc
import (
"crypto/rand"
"encoding/base64"
)
// incompressibleToken returns a base64 blob too large to fit a single
// cookie after compression, so Set*Token takes the chunked path. Random
// bytes are (nearly) incompressible, unlike repeated chars.
func incompressibleToken(size int) string {
buf := make([]byte, size)
if _, err := rand.Read(buf); err != nil {
panic(err)
}
return base64.RawStdEncoding.EncodeToString(buf)
}
+93 -1
View File
@@ -91,7 +91,8 @@ type Config struct {
SessionMaxAge int `json:"sessionMaxAge"`
RateLimit int `json:"rateLimit"`
// PerSourceLoginRateLimit throttles OIDC authentication events
// (authorization-code callback + login initiation) per client source IP,
// (authorization-code callback, login initiation and forced refreshes at
// the token-mediating endpoint) per client source IP,
// for external (non-internal) sources only. Internal / loopback /
// link-local sources (reverse proxies, in-cluster callers) are trusted
// and never throttled. Value = max auth events per minute per external
@@ -132,6 +133,16 @@ type Config struct {
EnableFrontchannelLogout bool `json:"enableFrontchannelLogout,omitempty"`
BackchannelLogoutURL string `json:"backchannelLogoutURL,omitempty"`
FrontchannelLogoutURL string `json:"frontchannelLogoutURL,omitempty"`
// TMBSessionURL is the path of the token-mediating backend endpoint
// (draft-ietf-oauth-browser-based-apps), authenticated by the session
// cookie: GET returns session information and the access token, POST
// forces a token refresh first. Setting it enables the endpoint; unset
// (default) leaves it off. See docs/TMB.md.
TMBSessionURL string `json:"tmbSessionURL,omitempty"`
// TMBClaims lists the ID-token claims the endpoint returns in `claims`.
// Default empty: nothing beyond user_identifier (userIdentifierClaim),
// groups and roles (groupClaimName, roleClaimName) and expires_at.
TMBClaims []string `json:"tmbClaims,omitempty"`
// CACertPath is an optional filesystem path to a PEM-encoded CA bundle used
// to verify the OIDC provider's TLS certificate. Use this when the provider
// is signed by an internal/private CA that is not in the system trust store.
@@ -517,6 +528,42 @@ func (c *Config) Validate() error {
}
}
for _, name := range c.TMBClaims {
if name == "" || len(name) > 128 {
return fmt.Errorf("tmbClaims entries must be non-empty claim names of at most 128 characters")
}
}
// The token-mediating endpoint path is matched by exact request-path
// comparison, so it must be a bare absolute path and must not shadow
// another endpoint of this middleware.
if c.TMBSessionURL != "" {
if !strings.HasPrefix(c.TMBSessionURL, "/") {
return fmt.Errorf("tmbSessionURL must start with /")
}
if strings.ContainsAny(c.TMBSessionURL, "?#\\") || strings.HasPrefix(c.TMBSessionURL, "//") {
return fmt.Errorf("tmbSessionURL must be a plain absolute path: no query string, fragment, backslash or leading //")
}
// The logout, back-channel and front-channel handlers run before the
// TMB endpoint, so a path they own would silently never reach it.
// Compare against the effective logout path (its default derives
// from callbackURL) and the normalized channel paths.
logoutPath := c.LogoutURL
if logoutPath == "" {
logoutPath = c.CallbackURL + "/logout"
}
for _, owned := range []string{
c.CallbackURL,
logoutPath,
normalizeLogoutPath(c.BackchannelLogoutURL),
normalizeLogoutPath(c.FrontchannelLogoutURL),
} {
if owned != "" && c.TMBSessionURL == owned {
return fmt.Errorf("tmbSessionURL %q is already used by the callback, logout, back-channel or front-channel logout endpoint", c.TMBSessionURL)
}
}
}
// Validate client credentials. With Dynamic Client Registration (RFC 7591)
// enabled, clientID (and typically clientSecret) are not known at
// construction time — the provider provisions them at registration. Skip
@@ -659,6 +706,24 @@ func (c *Config) Validate() error {
return fmt.Errorf("sessionMaxAge is too large; must be at most %d seconds", math.MaxInt64/int64(time.Second))
}
// Bearer durations are int64 seconds * time.Second at startup (main.go); an
// unbounded value wraps negative or to zero and disables the age check
// and failure throttle.
for name, v := range map[string]int64{
"maxTokenAgeSeconds": c.MaxTokenAgeSeconds,
"bearerFailureWindowSeconds": int64(c.BearerFailureWindowSeconds),
"bearerFailurePenaltySeconds": int64(c.BearerFailurePenaltySeconds),
} {
if v > maxDurationSeconds {
return fmt.Errorf("%s is too large; must be at most %d seconds", name, maxDurationSeconds)
}
}
// The throttle sweep cutoff adds window and penalty.
if int64(c.BearerFailureWindowSeconds) > 0 && int64(c.BearerFailurePenaltySeconds) > 0 &&
int64(c.BearerFailureWindowSeconds)+int64(c.BearerFailurePenaltySeconds) > maxDurationSeconds {
return fmt.Errorf("bearerFailureWindowSeconds plus bearerFailurePenaltySeconds is too large")
}
// Validate audience if specified
if c.Audience != "" {
// Validate audience format - should be a valid identifier or URL
@@ -954,6 +1019,7 @@ func isValidSecureURL(s string) bool {
// isLoopbackHost reports whether host is "localhost" or a loopback IP literal
// (127.0.0.0/8 or ::1).
func isLoopbackHost(host string) bool {
host = canonicalHost(host)
if strings.EqualFold(host, "localhost") {
return true
}
@@ -1227,6 +1293,14 @@ func (c *Config) GetSecurityHeadersApplier() func(http.ResponseWriter, *http.Req
}
// isOriginAllowed checks if an origin is in the allowed list
const (
// maxDurationSeconds is the largest whole-second value whose
// time.Duration product with time.Second does not overflow int64.
maxDurationSeconds = math.MaxInt64 / int64(time.Second)
// maxRedisPoolSize bounds the eagerly allocated connection channel.
maxRedisPoolSize = 10000
)
// Validate checks if the Redis configuration is valid
func (rc *RedisConfig) Validate() error {
if !rc.Enabled {
@@ -1253,6 +1327,9 @@ func (rc *RedisConfig) Validate() error {
if rc.PoolSize < 0 {
return fmt.Errorf("pool size cannot be negative")
}
if rc.PoolSize > maxRedisPoolSize {
return fmt.Errorf("pool size is too large; must be at most %d", maxRedisPoolSize)
}
if rc.ConnectTimeout < 0 {
return fmt.Errorf("connect timeout cannot be negative")
}
@@ -1286,6 +1363,21 @@ func (rc *RedisConfig) Validate() error {
return fmt.Errorf("health check interval cannot be negative")
}
// Seconds become time.Duration (x * time.Second) and the threshold is
// narrowed to int32 in the breaker; out-of-range values wrap, which
// panics time.NewTicker or trips the breaker on the first failure.
for name, v := range map[string]int{
"health check interval": rc.HealthCheckInterval,
"circuit breaker timeout": rc.CircuitBreakerTimeout,
} {
if int64(v) > maxDurationSeconds {
return fmt.Errorf("%s is too large; must be at most %d seconds", name, maxDurationSeconds)
}
}
if rc.CircuitBreakerThreshold > math.MaxInt32 {
return fmt.Errorf("circuit breaker threshold is too large; must be at most %d", math.MaxInt32)
}
return nil
}
+73
View File
@@ -0,0 +1,73 @@
package traefikoidc
import (
"math"
"testing"
"time"
)
func boundsTestConfig() *Config {
cfg := CreateConfig()
cfg.ProviderURL = "https://auth.example.com"
cfg.CallbackURL = "/callback"
cfg.ClientID = "test-client"
cfg.ClientSecret = "test-client-secret"
cfg.SessionEncryptionKey = "test-encryption-key-32-bytes-long!!"
return cfg
}
const maxWholeSeconds = math.MaxInt64 / int64(time.Second)
func TestConfigValidateRejectsDurationOverflow(t *testing.T) {
cases := map[string]func(c *Config){
"maxTokenAgeSeconds wraps negative": func(c *Config) { c.MaxTokenAgeSeconds = maxWholeSeconds + 1 },
"maxTokenAgeSeconds wraps to zero": func(c *Config) { c.MaxTokenAgeSeconds = 1 << 55 },
"bearerFailureWindowSeconds": func(c *Config) { c.BearerFailureWindowSeconds = int(maxWholeSeconds + 1) },
"bearerFailurePenaltySeconds": func(c *Config) { c.BearerFailurePenaltySeconds = int(maxWholeSeconds + 1) },
}
for name, mutate := range cases {
t.Run(name, func(t *testing.T) {
cfg := boundsTestConfig()
mutate(cfg)
if err := cfg.Validate(); err == nil {
t.Fatal("Validate accepted an overflowing duration")
}
})
}
t.Run("max exact value still valid", func(t *testing.T) {
cfg := boundsTestConfig()
cfg.MaxTokenAgeSeconds = maxWholeSeconds
if err := cfg.Validate(); err != nil {
t.Fatalf("boundary value rejected: %v", err)
}
})
}
func TestRedisConfigValidateRejectsOverflowAndHugePool(t *testing.T) {
base := func() *RedisConfig {
rc := &RedisConfig{Enabled: true, Address: "localhost:6379"}
return rc
}
cases := map[string]func(rc *RedisConfig){
"healthCheckInterval wraps to zero": func(rc *RedisConfig) { rc.HealthCheckInterval = 1 << 55 },
"circuitBreakerTimeout wraps": func(rc *RedisConfig) { rc.CircuitBreakerTimeout = int(maxWholeSeconds + 1) },
"circuitBreakerThreshold narrows": func(rc *RedisConfig) { rc.CircuitBreakerThreshold = math.MaxInt32 + 1 },
"poolSize absurd": func(rc *RedisConfig) { rc.PoolSize = 1_000_000_000 },
}
for name, mutate := range cases {
t.Run(name, func(t *testing.T) {
rc := base()
mutate(rc)
if err := rc.Validate(); err == nil {
t.Fatal("Validate accepted an unsafe value")
}
})
}
t.Run("defaults and sane values stay valid", func(t *testing.T) {
rc := base()
rc.PoolSize, rc.CircuitBreakerThreshold, rc.HealthCheckInterval = 50, 5, 30
if err := rc.Validate(); err != nil {
t.Fatalf("sane config rejected: %v", err)
}
})
}
+5 -2
View File
@@ -22,6 +22,7 @@ var allowedRootTokenFields = map[string]bool{
var validateTemplateParseFuncs = map[string]any{
"get": struct{}{},
"default": struct{}{},
"toJson": struct{}{},
}
// claimsWhitelist returns the effective set of claim field names a header
@@ -183,12 +184,14 @@ func (v *templateValidator) validateCommand(cmd *parse.CommandNode, dotIsRoot bo
return nil
}
// validateFunctionCall allows only get/default. get's map argument must be a
// validateFunctionCall allows only get/default/toJson. get's map argument must be a
// claims reference (never the root) and default's arguments are validated as
// values; the runtime get additionally enforces the key whitelist.
func (v *templateValidator) validateFunctionCall(name string, args []parse.Node, dotIsRoot bool) error {
switch name {
case "default":
case "default", "toJson":
// toJson only serializes what its (validated) arguments or piped input
// already expose; it cannot reach anything a direct reference could not.
for _, arg := range args {
if err := v.validateValue(arg, dotIsRoot); err != nil {
return err
+288
View File
@@ -0,0 +1,288 @@
package traefikoidc
import (
"encoding/json"
"net/http"
"net/url"
"strings"
"time"
"github.com/lukaszraczylo/traefikoidc/internal/utils"
)
// Token-mediating backend endpoint (draft-ietf-oauth-browser-based-apps,
// "Token-Mediating Backend"). The spec defines no paths or formats, so the
// endpoint is served only at the path configured in tmbSessionURL,
// authenticated by the regular session cookie, and is never reachable by
// bearer auth. GET reads the session and its access token; POST forces a
// refresh first and returns the same body.
// isTMBPath reports whether path is the configured token-mediating endpoint.
func (t *TraefikOidc) isTMBPath(path string) bool {
return t.tmbSessionURLPath != "" && path == t.tmbSessionURLPath
}
func writeTMBJSON(rw http.ResponseWriter, status int, body map[string]interface{}) {
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(status)
_ = json.NewEncoder(rw).Encode(body) // Safe to ignore: response write
}
func writeTMBError(rw http.ResponseWriter, status int, code, description string) {
body := map[string]interface{}{"error": code}
if description != "" {
body["error_description"] = description
}
writeTMBJSON(rw, status, body)
}
// tmbCrossSite reports whether the request was issued from another origin.
// Browsers label cross-origin requests with Sec-Fetch-Site and Origin, and no
// CORS headers are ever emitted. Requests carrying neither header
// (non-browser clients) pass.
func tmbCrossSite(req *http.Request) bool {
switch strings.ToLower(req.Header.Get("Sec-Fetch-Site")) {
case "cross-site", "same-site":
return true
}
if origin := req.Header.Get("Origin"); origin != "" {
u, err := url.Parse(origin)
if err != nil || !strings.EqualFold(u.Host, utils.DetermineHost(req)) {
return true
}
}
return false
}
// handleTMB serves the token-mediating endpoint. Callers must have verified
// isTMBPath.
func (t *TraefikOidc) handleTMB(rw http.ResponseWriter, req *http.Request) {
h := rw.Header()
h.Set("Cache-Control", "no-store")
h.Set("X-Content-Type-Options", "nosniff")
h.Set("Cross-Origin-Resource-Policy", "same-origin")
// The endpoint is same-origin only. The middleware-wide security headers
// may already have added CORS headers (securityHeaders.corsEnabled); drop
// them so a cross-origin page can never be granted read access.
for name := range h {
if strings.HasPrefix(strings.ToLower(name), "access-control-") {
h.Del(name)
}
}
if req.Method != http.MethodGet && req.Method != http.MethodPost {
h.Set("Allow", "GET, POST")
writeTMBError(rw, http.StatusMethodNotAllowed, "invalid_request", "only GET and POST are supported")
return
}
if tmbCrossSite(req) {
writeTMBError(rw, http.StatusForbidden, "invalid_request", "cross-origin requests are not allowed")
return
}
session, err := t.sessionManager.GetSession(req)
if err != nil || session == nil {
t.logger.Errorf("Token-mediating endpoint: no usable session: %v", err)
writeTMBError(rw, http.StatusUnauthorized, "invalid_session", "")
return
}
gen := session.ownerGeneration()
defer session.returnToPoolIfOwner(gen)
rs := (&requestState{metadata: t.metadataSnap()}).captureSession(session)
refreshed, ok := t.tmbEstablishSession(rw, req, session, rs)
if !ok {
return
}
claims, groups, roles, ok := t.tmbAuthorize(rw, session)
if !ok {
return
}
// POST forces a refresh, unless this request already refreshed. The
// refresh runs only after the user passed the authorization gates, and
// the gates are re-applied to the refreshed token's claims.
if req.Method == http.MethodPost && !refreshed {
// Each forced refresh is an IdP round trip, so it shares the optional
// per-source throttle of the other auth gates (perSourceLoginRateLimit).
if t.perSourceLimiter != nil && !t.perSourceLimiter.allow(req) {
rw.Header().Set("Retry-After", "1")
writeTMBError(rw, http.StatusTooManyRequests, "rate_limited", "too many refresh requests, try again shortly")
return
}
if !t.tmbForceRefresh(rw, req, session, rs) {
return
}
if claims, groups, roles, ok = t.tmbAuthorize(rw, session); !ok {
return
}
}
t.writeTMBSession(rw, session, rs, claims, groups, roles)
}
// tmbEstablishSession ensures the session holds a valid, authenticated token
// set, refreshing it when due, and updates rs to match. It reports whether a
// refresh happened. It answers invalid_session itself and returns ok=false
// when no valid session exists. It never redirects: this endpoint is for
// XHR/fetch.
//
// The plugin's own refresh decision follows the ID token when the access token
// is opaque, so it can hand out an access token that has already expired. This
// endpoint returns the access token, so it also refreshes when the recorded
// access-token expiry is inside refreshGracePeriod, and it never answers 200
// with an access token known to be expired.
func (t *TraefikOidc) tmbEstablishSession(rw http.ResponseWriter, req *http.Request, session *SessionData, rs *requestState) (refreshed, ok bool) {
authenticated, needsRefresh, expired := t.isUserAuthenticatedRS(rs)
if expired {
writeTMBError(rw, http.StatusUnauthorized, "invalid_session", "")
return false, false
}
now := time.Now()
exp := tmbAccessTokenExpiry(rs)
accessDue := exp > 0 && time.Unix(exp, 0).Sub(now) <= t.refreshGracePeriod
accessExpired := exp > 0 && exp <= now.Unix()
attempted := false
if (needsRefresh || accessDue) && rs.refreshToken != "" && !t.isRefreshTokenExpired(session) &&
!(authenticated && !accessDue && t.shouldSkipGraceRefresh(session)) {
attempted = true
if t.refreshToken(rw, req, session) {
rs.captureSession(session)
authenticated, refreshed = true, true
}
}
if !authenticated {
writeTMBError(rw, http.StatusUnauthorized, "invalid_session", "")
return false, false
}
if accessExpired && !refreshed {
switch {
case !attempted || !session.GetAuthenticated():
// Nothing to renew it with, or the IdP rejected the refresh token.
writeTMBError(rw, http.StatusUnauthorized, "invalid_session", "")
default:
writeTMBError(rw, http.StatusBadGateway, "server_error", "access token expired and could not be refreshed")
}
return false, false
}
return refreshed, true
}
// tmbForceRefresh runs a refresh-token grant through the existing refresh
// path and updates rs. It answers the error itself and returns false on
// failure.
func (t *TraefikOidc) tmbForceRefresh(rw http.ResponseWriter, req *http.Request, session *SessionData, rs *requestState) bool {
if rs.refreshToken == "" {
writeTMBError(rw, http.StatusUnauthorized, "backend_not_ready", "")
return false
}
if !t.refreshToken(rw, req, session) {
// A rejected refresh token clears the session; any other failure
// (IdP unreachable, 5xx) leaves it intact.
if !session.GetAuthenticated() {
writeTMBError(rw, http.StatusUnauthorized, "invalid_session", "")
} else {
writeTMBError(rw, http.StatusBadGateway, "server_error", "token refresh failed")
}
return false
}
rs.captureSession(session)
return true
}
// tmbAuthorize applies the same post-authentication gates as the normal
// request path (identifier present, allowed user, IdP-initiated logout
// invalidation, allowed roles/groups) and returns the token claims.
func (t *TraefikOidc) tmbAuthorize(rw http.ResponseWriter, session *SessionData) (map[string]interface{}, []string, []string, bool) {
identifier := session.GetUserIdentifier()
if identifier == "" {
writeTMBError(rw, http.StatusUnauthorized, "invalid_session", "")
return nil, nil, nil, false
}
if !t.isAllowedUser(identifier) {
writeTMBError(rw, http.StatusForbidden, "access_denied", "")
return nil, nil, nil, false
}
idToken := session.GetIDToken()
if idToken != "" && (t.enableBackchannelLogout || t.enableFrontchannelLogout) {
sid, sub, createdAt := t.invalidationInputs(idToken, session)
if t.isSessionInvalidated(sid, sub, createdAt) {
writeTMBError(rw, http.StatusUnauthorized, "invalid_session", "")
return nil, nil, nil, false
}
}
// A claims parse error leaves claims nil, which the roles/groups gate
// below rejects when it is configured.
claims, _ := t.bypassSessionClaims(session)
var groups, roles []string
if claims != nil {
var err error
groups, roles, err = t.extractGroupsAndRolesFromClaims(claims)
if err != nil && len(t.allowedRolesAndGroups) > 0 {
writeTMBError(rw, http.StatusForbidden, "access_denied", "")
return nil, nil, nil, false
}
}
if len(t.allowedRolesAndGroups) > 0 {
allowed := false
for _, g := range append(append([]string{}, groups...), roles...) {
if _, ok := t.allowedRolesAndGroups[g]; ok {
allowed = true
break
}
}
if !allowed {
writeTMBError(rw, http.StatusForbidden, "access_denied", "")
return nil, nil, nil, false
}
}
return claims, groups, roles, true
}
// tmbAccessTokenExpiry returns when the session's access token expires (unix
// seconds): the expiry recorded at login or refresh (from the token response),
// else the token's own exp claim for sessions that predate the record. It
// returns 0 when unknown (an opaque token with no recorded expiry).
func tmbAccessTokenExpiry(rs *requestState) int64 {
if rs.accessTokenExpiresAt > 0 {
return rs.accessTokenExpiresAt
}
return jwtExpiry(rs.accessToken)
}
// writeTMBSession answers 200 with the session information and the access
// token.
func (t *TraefikOidc) writeTMBSession(rw http.ResponseWriter, session *SessionData, rs *requestState, claims map[string]interface{}, groups, roles []string) {
out := map[string]interface{}{
"authenticated": true,
"user_identifier": session.GetUserIdentifier(),
}
// Only the claims the operator listed in tmbClaims, as they appear in the
// token; absent or null claims are left out.
shown := map[string]interface{}{}
for _, name := range t.tmbClaims {
if v, ok := claims[name]; ok && v != nil {
shown[name] = v
}
}
if len(shown) > 0 {
out["claims"] = shown
}
if len(groups) > 0 {
out["groups"] = groups
}
if len(roles) > 0 {
out["roles"] = roles
}
if rs.accessToken != "" {
out["access_token"] = rs.accessToken
if exp := tmbAccessTokenExpiry(rs); exp > 0 {
out["expires_at"] = exp
}
}
writeTMBJSON(rw, http.StatusOK, out)
}
+683
View File
@@ -0,0 +1,683 @@
package traefikoidc
import (
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Example path used as the configured value in these tests.
const tmbPath = "/auth/session"
const (
tmbTestRefresh = "tmb-refresh-token-0123456789abcdefghijklmnopqrstuvwxyz"
tmbTestRotated = "tmb-rotated-token-0123456789abcdefghijklmnopqrstuvwxyz"
)
// tmbIdP is a fake token endpoint recording each form it receives.
type tmbIdP struct {
mu sync.Mutex
forms []url.Values
status int
body string
}
func (p *tmbIdP) ServeHTTP(w http.ResponseWriter, r *http.Request) {
_ = r.ParseForm()
p.mu.Lock()
p.forms = append(p.forms, r.PostForm)
status, body := p.status, p.body
p.mu.Unlock()
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_, _ = w.Write([]byte(body))
}
func (p *tmbIdP) calls() int {
p.mu.Lock()
defer p.mu.Unlock()
return len(p.forms)
}
func (p *tmbIdP) last(t *testing.T) url.Values {
t.Helper()
p.mu.Lock()
defer p.mu.Unlock()
require.NotEmpty(t, p.forms, "token endpoint was not called")
return p.forms[len(p.forms)-1]
}
type tmbEnv struct {
oidc *TraefikOidc
idp *tmbIdP
cookies []*http.Cookie
access string // the session's access token
newAccess string // what a refresh grant returns
newID string // the ID token a refresh grant returns
}
func newTMBEnv(t *testing.T, opts ...func(*TraefikOidc)) *tmbEnv {
t.Helper()
claims := map[string]interface{}{
"sub": "user-1", "email": "[email protected]", "name": "U One",
"groups": []interface{}{"admins"},
"exp": float64(time.Now().Add(time.Hour).Unix()),
"iat": float64(time.Now().Unix()),
}
newClaims := map[string]interface{}{
"sub": "user-1", "email": "[email protected]", "name": "U One",
"groups": []interface{}{"admins"},
"exp": float64(time.Now().Add(2 * time.Hour).Unix()),
"iat": float64(time.Now().Unix()),
}
access := tokenWithGroups(t, claims)
id := tokenWithGroups(t, claims)
newAccess := tokenWithGroups(t, newClaims)
newID := tokenWithGroups(t, newClaims)
refreshBody, err := json.Marshal(map[string]interface{}{
"access_token": newAccess,
"id_token": newID,
"refresh_token": tmbTestRotated,
"expires_in": 7200,
})
require.NoError(t, err)
idp := &tmbIdP{status: http.StatusOK, body: string(refreshBody)}
srv := httptest.NewServer(idp)
t.Cleanup(srv.Close)
oidc := newTestOIDC(t, func(o *TraefikOidc) {
o.tmbSessionURLPath = tmbPath
o.tmbClaims = []string{"email", "name"}
o.tokenCache = NewTokenCache()
o.tokenVerifier = o // real VerifyToken; the seeded cache short-circuits it
o.tokenExchanger = o
o.extractClaimsFunc = extractClaims
o.tokenURL = srv.URL + "/token"
o.clientSecret = "secret"
o.tokenHTTPClient = srv.Client()
o.userIdentifierClaim = "sub"
o.groupClaimName, o.roleClaimName = "groups", "roles"
o.refreshGracePeriod = time.Minute
o.allowedRolesAndGroups = map[string]struct{}{}
o.next = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Error("token-mediating request must not reach the backend")
})
})
for _, opt := range opts {
opt(oidc)
}
seedVerified(t, oidc, access, claims)
seedVerified(t, oidc, id, claims)
seedVerified(t, oidc, newAccess, newClaims)
seedVerified(t, oidc, newID, newClaims)
base := httptest.NewRequest(http.MethodGet, "https://app.example.com/", nil)
rec := httptest.NewRecorder()
session, err := oidc.sessionManager.GetSession(base)
require.NoError(t, err)
require.NoError(t, session.SetAuthenticated(true))
session.SetAccessToken(access)
session.SetIDToken(id)
session.SetRefreshToken(tmbTestRefresh)
session.SetUserIdentifier("user-1")
require.NoError(t, session.Save(base, rec))
return &tmbEnv{oidc: oidc, idp: idp, cookies: rec.Result().Cookies(), access: access, newAccess: newAccess, newID: newID}
}
func requestWithCookies(cs []*http.Cookie) *http.Request {
r := httptest.NewRequest(http.MethodGet, "https://app.example.com/", nil)
for _, c := range cs {
r.AddCookie(c)
}
return r
}
func (e *tmbEnv) do(method, path string, mutate func(*http.Request)) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, "https://app.example.com"+path, nil)
for _, c := range e.cookies {
req.AddCookie(c)
}
if mutate != nil {
mutate(req)
}
rec := httptest.NewRecorder()
e.oidc.ServeHTTP(rec, req)
return rec
}
func (e *tmbEnv) get(path string, mutate func(*http.Request)) *httptest.ResponseRecorder {
return e.do(http.MethodGet, path, mutate)
}
func (e *tmbEnv) post(path string, mutate func(*http.Request)) *httptest.ResponseRecorder {
return e.do(http.MethodPost, path, mutate)
}
func decodeTMB(t *testing.T, rec *httptest.ResponseRecorder) map[string]interface{} {
t.Helper()
var m map[string]interface{}
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &m), "body: %s", rec.Body.String())
return m
}
func TestTMBGet_ReturnsSessionAndAccessToken(t *testing.T) {
e := newTMBEnv(t)
rec := e.get(tmbPath, nil)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
body := decodeTMB(t, rec)
assert.Equal(t, true, body["authenticated"])
assert.Equal(t, "user-1", body["user_identifier"])
assert.Equal(t, []interface{}{"admins"}, body["groups"])
assert.Equal(t, map[string]interface{}{"email": "[email protected]", "name": "U One"}, body["claims"])
assert.Contains(t, body, "expires_at")
assert.Equal(t, e.access, body["access_token"])
assert.InDelta(t, time.Now().Add(time.Hour).Unix(), body["expires_at"], 5, "the access token's expiry")
assert.NotContains(t, body, "expires_in", "expiry is reported once, as an absolute time")
assert.NotContains(t, rec.Body.String(), tmbTestRefresh, "the refresh token must never be returned")
h := rec.Header()
assert.Equal(t, "application/json", h.Get("Content-Type"))
assert.Equal(t, "no-store", h.Get("Cache-Control"))
assert.Equal(t, "nosniff", h.Get("X-Content-Type-Options"))
assert.Equal(t, "same-origin", h.Get("Cross-Origin-Resource-Policy"))
assert.Empty(t, h.Get("Access-Control-Allow-Origin"))
assert.Zero(t, e.idp.calls(), "GET does not call the IdP while the token is fresh")
}
// setRefreshResponse makes the fake token endpoint answer the next grants with
// the given access token and expires_in (the refreshed ID token is valid).
func (e *tmbEnv) setRefreshResponse(t *testing.T, accessToken string, expiresIn int) {
t.Helper()
body, err := json.Marshal(map[string]interface{}{
"access_token": accessToken,
"id_token": e.newID,
"refresh_token": tmbTestRotated,
"expires_in": expiresIn,
})
require.NoError(t, err)
e.idp.mu.Lock()
e.idp.body = string(body)
e.idp.mu.Unlock()
}
func TestTMB_ReportsTheAccessTokenExpiry(t *testing.T) {
t.Run("a session without a recorded expiry falls back to the token's exp claim", func(t *testing.T) {
e := newTMBEnv(t)
body := decodeTMB(t, e.get(tmbPath, nil))
assert.InDelta(t, time.Now().Add(time.Hour).Unix(), body["expires_at"], 5)
})
t.Run("a recorded expiry wins over the token's exp claim", func(t *testing.T) {
e := newTMBEnv(t)
want := time.Now().Add(2 * time.Minute).Unix()
session, err := e.oidc.sessionManager.GetSession(requestWithCookies(e.cookies))
require.NoError(t, err)
session.SetAccessTokenExpiresAt(session.GetAccessToken(), want)
saved := httptest.NewRecorder()
require.NoError(t, session.Save(requestWithCookies(e.cookies), saved))
e.cookies = saved.Result().Cookies()
body := decodeTMB(t, e.get(tmbPath, nil))
assert.EqualValues(t, want, body["expires_at"], "the ID token and the JWT expire in an hour; the recorded value is used")
})
t.Run("POST reports the token response's expires_in and the next GET keeps it", func(t *testing.T) {
e := newTMBEnv(t)
e.setRefreshResponse(t, e.newAccess, 1800) // the refreshed JWT itself is good for 2 h
rec := e.post(tmbPath, nil)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
body := decodeTMB(t, rec)
assert.InDelta(t, time.Now().Add(30*time.Minute).Unix(), body["expires_at"], 5)
next := requestWithCookies(e.cookies)
for _, c := range rec.Result().Cookies() {
next.AddCookie(c)
}
session, err := e.oidc.sessionManager.GetSession(next)
require.NoError(t, err)
assert.InDelta(t, time.Now().Add(30*time.Minute).Unix(), session.GetAccessTokenExpiresAt(), 5)
})
t.Run("an opaque access token gets its expiry from expires_in", func(t *testing.T) {
e := newTMBEnv(t)
e.setRefreshResponse(t, "opaque-access-token-0123456789abcdef", 1800)
body := decodeTMB(t, e.post(tmbPath, nil))
assert.Equal(t, "opaque-access-token-0123456789abcdef", body["access_token"])
assert.InDelta(t, time.Now().Add(30*time.Minute).Unix(), body["expires_at"], 5)
})
t.Run("an opaque token with no expiry information reports none", func(t *testing.T) {
e := newTMBEnv(t)
e.setRefreshResponse(t, "opaque-access-token-0123456789abcdef", 0)
body := decodeTMB(t, e.post(tmbPath, nil))
assert.Equal(t, "opaque-access-token-0123456789abcdef", body["access_token"])
assert.NotContains(t, body, "expires_at")
})
}
// mutateSession rewrites the session behind the env's cookies.
func (e *tmbEnv) mutateSession(t *testing.T, fn func(*SessionData)) {
t.Helper()
session, err := e.oidc.sessionManager.GetSession(requestWithCookies(e.cookies))
require.NoError(t, err)
fn(session)
saved := httptest.NewRecorder()
require.NoError(t, session.Save(requestWithCookies(e.cookies), saved))
e.cookies = saved.Result().Cookies()
}
// An opaque access token is judged by the ID token (valid for an hour here), so
// the plugin's own refresh logic keeps serving it; the endpoint hands out the
// access token and must look at the access token's own expiry.
func TestTMB_RefreshesAnAccessTokenThatIsDue(t *testing.T) {
const opaque = "opaque-access-token-0123456789abcdef"
setup := func(t *testing.T, remaining time.Duration, opts ...func(*SessionData)) *tmbEnv {
e := newTMBEnv(t)
e.mutateSession(t, func(sd *SessionData) {
sd.SetAccessToken(opaque)
sd.SetAccessTokenExpiresAt(opaque, time.Now().Add(remaining).Unix())
for _, opt := range opts {
opt(sd)
}
})
return e
}
t.Run("a token with plenty of life left is served as is", func(t *testing.T) {
e := setup(t, 30*time.Minute)
rec := e.get(tmbPath, nil)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
assert.Equal(t, opaque, decodeTMB(t, rec)["access_token"])
assert.Zero(t, e.idp.calls())
})
t.Run("one inside the grace window is refreshed before being returned", func(t *testing.T) {
e := setup(t, 20*time.Second) // the env's grace period is one minute
rec := e.get(tmbPath, nil)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
assert.Equal(t, e.newAccess, decodeTMB(t, rec)["access_token"])
assert.Equal(t, 1, e.idp.calls())
assert.Equal(t, "refresh_token", e.idp.last(t).Get("grant_type"))
})
t.Run("one that has already expired is refreshed too", func(t *testing.T) {
e := setup(t, -10*time.Second)
rec := e.get(tmbPath, nil)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
assert.Equal(t, e.newAccess, decodeTMB(t, rec)["access_token"])
})
t.Run("an expired token the IdP cannot refresh right now is never served", func(t *testing.T) {
e := setup(t, -10*time.Second)
e.idp.status, e.idp.body = http.StatusInternalServerError, `oops`
rec := e.get(tmbPath, nil)
assert.Equal(t, http.StatusBadGateway, rec.Code)
assert.Equal(t, "server_error", decodeTMB(t, rec)["error"])
assert.NotContains(t, rec.Body.String(), "access_token")
})
t.Run("an expired token with no refresh token means logging in again", func(t *testing.T) {
e := setup(t, -10*time.Second, func(sd *SessionData) { sd.SetRefreshToken("") })
rec := e.get(tmbPath, nil)
assert.Equal(t, http.StatusUnauthorized, rec.Code)
assert.Equal(t, "invalid_session", decodeTMB(t, rec)["error"])
assert.NotContains(t, rec.Body.String(), "access_token")
assert.Zero(t, e.idp.calls())
})
t.Run("an expired token whose refresh token is rejected ends the session", func(t *testing.T) {
e := setup(t, -10*time.Second)
e.idp.status, e.idp.body = http.StatusBadRequest, `{"error":"invalid_grant"}`
rec := e.get(tmbPath, nil)
assert.Equal(t, http.StatusUnauthorized, rec.Code)
assert.Equal(t, "invalid_session", decodeTMB(t, rec)["error"])
assert.NotContains(t, rec.Body.String(), "access_token")
})
t.Run("a token due inside the grace window is still served if the refresh fails", func(t *testing.T) {
e := setup(t, 20*time.Second)
e.idp.status, e.idp.body = http.StatusInternalServerError, `oops`
rec := e.get(tmbPath, nil)
require.Equal(t, http.StatusOK, rec.Code, "the token is still valid, so the failed early refresh is not fatal")
assert.Equal(t, opaque, decodeTMB(t, rec)["access_token"])
})
}
func TestTMB_ClaimsAreOptIn(t *testing.T) {
t.Run("nothing is returned by default", func(t *testing.T) {
e := newTMBEnv(t, func(o *TraefikOidc) { o.tmbClaims = nil })
body := decodeTMB(t, e.get(tmbPath, nil))
assert.NotContains(t, body, "claims")
assert.Equal(t, "user-1", body["user_identifier"], "identity comes from userIdentifierClaim, not tmbClaims")
assert.Equal(t, []interface{}{"admins"}, body["groups"], "groups come from groupClaimName, not tmbClaims")
})
t.Run("only listed claims, as they appear in the token", func(t *testing.T) {
e := newTMBEnv(t, func(o *TraefikOidc) { o.tmbClaims = []string{"groups", "email", "absent"} })
body := decodeTMB(t, e.get(tmbPath, nil))
assert.Equal(t, map[string]interface{}{
"groups": []interface{}{"admins"},
"email": "[email protected]",
}, body["claims"], "a non-scalar claim passes through; an absent claim is omitted; unlisted ones are not leaked")
})
t.Run("claims of a refreshed token are returned after POST", func(t *testing.T) {
e := newTMBEnv(t)
body := decodeTMB(t, e.post(tmbPath, nil))
assert.Equal(t, map[string]interface{}{"email": "[email protected]", "name": "U One"}, body["claims"])
})
}
func TestTMBGet_IgnoresParametersAndNeverForcesRefresh(t *testing.T) {
e := newTMBEnv(t)
rec := e.get(tmbPath+"?refresh=true&scope=read&resource="+url.QueryEscape("https://api.example.com"), nil)
require.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, e.access, decodeTMB(t, rec)["access_token"])
assert.Zero(t, e.idp.calls(), "a GET must have no side effect on the session")
}
func TestTMBPost_ForcesRefresh(t *testing.T) {
e := newTMBEnv(t)
rec := e.post(tmbPath, nil)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
body := decodeTMB(t, rec)
assert.Equal(t, e.newAccess, body["access_token"])
assert.InDelta(t, time.Now().Add(2*time.Hour).Unix(), body["expires_at"], 5)
assert.Equal(t, "user-1", body["user_identifier"], "POST returns the same body shape as GET")
assert.Equal(t, []interface{}{"admins"}, body["groups"])
require.Equal(t, 1, e.idp.calls())
form := e.idp.last(t)
assert.Equal(t, "refresh_token", form.Get("grant_type"))
assert.Equal(t, tmbTestRefresh, form.Get("refresh_token"))
assert.Empty(t, form.Get("scope"))
// The refreshed tokens are persisted for later requests.
next := requestWithCookies(e.cookies)
for _, c := range rec.Result().Cookies() {
next.AddCookie(c)
}
session, err := e.oidc.sessionManager.GetSession(next)
require.NoError(t, err)
assert.Equal(t, e.newAccess, session.GetAccessToken())
assert.Equal(t, tmbTestRotated, session.GetRefreshToken())
}
func TestTMBPost_ErrorsAnswerWithoutLeakingTokens(t *testing.T) {
t.Run("rejected refresh token ends the session", func(t *testing.T) {
e := newTMBEnv(t)
e.idp.status, e.idp.body = http.StatusBadRequest, `{"error":"invalid_grant"}`
rec := e.post(tmbPath, nil)
assert.Equal(t, http.StatusUnauthorized, rec.Code)
assert.Equal(t, "invalid_session", decodeTMB(t, rec)["error"])
assert.NotContains(t, rec.Body.String(), "access_token")
})
t.Run("idp failure keeps the session and answers 502", func(t *testing.T) {
e := newTMBEnv(t)
e.idp.status, e.idp.body = http.StatusInternalServerError, `oops`
rec := e.post(tmbPath, nil)
assert.Equal(t, http.StatusBadGateway, rec.Code)
assert.Equal(t, "server_error", decodeTMB(t, rec)["error"])
assert.NotContains(t, rec.Body.String(), "access_token")
assert.Equal(t, http.StatusOK, e.get(tmbPath, nil).Code, "the session still works")
})
t.Run("no refresh token is backend_not_ready", func(t *testing.T) {
e := newTMBEnv(t)
session, err := e.oidc.sessionManager.GetSession(requestWithCookies(e.cookies))
require.NoError(t, err)
session.SetRefreshToken("")
rec0 := httptest.NewRecorder()
require.NoError(t, session.Save(requestWithCookies(e.cookies), rec0))
e.cookies = rec0.Result().Cookies()
rec := e.post(tmbPath, nil)
assert.Equal(t, http.StatusUnauthorized, rec.Code)
assert.Equal(t, "backend_not_ready", decodeTMB(t, rec)["error"])
assert.Zero(t, e.idp.calls())
})
}
func TestTMB_NoSessionIsInvalidSession(t *testing.T) {
for _, method := range []string{http.MethodGet, http.MethodPost} {
e := newTMBEnv(t)
e.cookies = nil
rec := e.do(method, tmbPath, nil)
assert.Equal(t, http.StatusUnauthorized, rec.Code, method)
assert.Equal(t, "invalid_session", decodeTMB(t, rec)["error"], method)
assert.Empty(t, rec.Header().Get("Location"), "must not redirect")
assert.Zero(t, e.idp.calls())
}
}
func TestTMB_RejectsOtherMethods(t *testing.T) {
e := newTMBEnv(t)
for _, m := range []string{http.MethodPut, http.MethodDelete, http.MethodPatch, http.MethodOptions, http.MethodHead} {
rec := e.do(m, tmbPath, nil)
assert.Equal(t, http.StatusMethodNotAllowed, rec.Code, m)
assert.Equal(t, "GET, POST", rec.Header().Get("Allow"), m)
}
assert.Zero(t, e.idp.calls())
}
func TestTMB_CrossOriginRequestsRejected(t *testing.T) {
e := newTMBEnv(t)
cases := map[string]func(*http.Request){
"sec-fetch cross-site": func(r *http.Request) { r.Header.Set("Sec-Fetch-Site", "cross-site") },
"sec-fetch same-site": func(r *http.Request) { r.Header.Set("Sec-Fetch-Site", "same-site") },
"foreign origin": func(r *http.Request) { r.Header.Set("Origin", "https://evil.example") },
"null origin": func(r *http.Request) { r.Header.Set("Origin", "null") },
}
for name, mutate := range cases {
for _, method := range []string{http.MethodGet, http.MethodPost} {
rec := e.do(method, tmbPath, mutate)
assert.Equal(t, http.StatusForbidden, rec.Code, name+" "+method)
}
}
assert.Zero(t, e.idp.calls(), "a cross-origin request must not trigger a refresh")
for name, mutate := range map[string]func(*http.Request){
"same-origin fetch": func(r *http.Request) { r.Header.Set("Sec-Fetch-Site", "same-origin") },
"same origin header": func(r *http.Request) { r.Header.Set("Origin", "https://app.example.com") },
"address bar": func(r *http.Request) { r.Header.Set("Sec-Fetch-Site", "none") },
} {
assert.Equal(t, http.StatusOK, e.get(tmbPath, mutate).Code, name)
}
}
func TestTMB_ConfiguredPathEnablesEndpoint(t *testing.T) {
t.Run("unset path leaves the endpoint off", func(t *testing.T) {
e := newTMBEnv(t, func(o *TraefikOidc) { o.tmbSessionURLPath = "" })
for _, p := range []string{tmbPath, ""} {
assert.False(t, e.oidc.isTMBPath(p), p)
}
})
t.Run("custom path is served and others are not", func(t *testing.T) {
e := newTMBEnv(t, func(o *TraefikOidc) { o.tmbSessionURLPath = "/api/me" })
rec := e.get("/api/me", nil)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
assert.Equal(t, e.access, decodeTMB(t, rec)["access_token"])
assert.False(t, e.oidc.isTMBPath(tmbPath))
})
}
func TestConfigValidate_TMBPath(t *testing.T) {
valid := func() *Config {
c := CreateConfig()
c.ProviderURL = "https://provider.example.com"
c.ClientID = "id"
c.ClientSecret = "secret"
c.CallbackURL = "/callback"
c.SessionEncryptionKey = "0123456789abcdef0123456789abcdef"
return c
}
require.NoError(t, valid().Validate())
ok := valid()
ok.TMBSessionURL = tmbPath
require.NoError(t, ok.Validate())
cases := map[string]func(*Config){
"no leading slash": func(c *Config) { c.TMBSessionURL = "session" },
"query": func(c *Config) { c.TMBSessionURL = "/s?x=1" },
"fragment": func(c *Config) { c.TMBSessionURL = "/s#x" },
"equals callback": func(c *Config) { c.TMBSessionURL = "/callback" },
"equals logout": func(c *Config) { c.LogoutURL = "/out"; c.TMBSessionURL = "/out" },
"empty claim name": func(c *Config) { c.TMBClaims = []string{"email", ""} },
"equals the derived default logout path": func(c *Config) { c.TMBSessionURL = "/callback/logout" },
"equals back-channel path, written without a slash": func(c *Config) {
c.BackchannelLogoutURL, c.TMBSessionURL = "bc/logout", "/bc/logout"
},
"equals front-channel path": func(c *Config) {
c.FrontchannelLogoutURL, c.TMBSessionURL = "/fc/logout", "/fc/logout"
},
"leading //": func(c *Config) { c.TMBSessionURL = "//auth/session" },
"backslash": func(c *Config) { c.TMBSessionURL = "/auth\\session" },
}
for name, mutate := range cases {
t.Run(name, func(t *testing.T) {
c := valid()
mutate(c)
assert.Error(t, c.Validate())
})
}
}
// The endpoint authenticates itself, so none of the bypasses may forward a
// request on its path to the backend (newTMBEnv's next fails the test).
func TestTMB_NoBypassForwardsToBackend(t *testing.T) {
cases := map[string]struct {
opt func(*TraefikOidc)
mutate func(*http.Request)
method string
}{
"excluded URL": {
opt: func(o *TraefikOidc) { o.excludedURLs = map[string]struct{}{tmbPath: {}} },
method: http.MethodGet,
},
"SSE accept header": {
mutate: func(r *http.Request) { r.Header.Set("Accept", "text/event-stream") },
method: http.MethodGet,
},
"WebSocket upgrade": {
mutate: func(r *http.Request) {
r.Header.Set("Upgrade", "websocket")
r.Header.Set("Connection", "Upgrade")
},
method: http.MethodGet,
},
"unauthenticated preflight allowed": {
opt: func(o *TraefikOidc) { o.allowUnauthenticatedPreflight = true },
mutate: func(r *http.Request) {
r.Header.Set("Origin", "https://app.example.com")
r.Header.Set("Access-Control-Request-Method", "POST")
},
method: http.MethodOptions,
},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
var opts []func(*TraefikOidc)
if c.opt != nil {
opts = append(opts, c.opt)
}
e := newTMBEnv(t, opts...)
rec := e.do(c.method, tmbPath, c.mutate)
if c.method == http.MethodOptions {
assert.Equal(t, http.StatusMethodNotAllowed, rec.Code)
return
}
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
assert.Equal(t, e.access, decodeTMB(t, rec)["access_token"])
})
}
}
func TestTMBPost_SharesThePerSourceThrottle(t *testing.T) {
t.Run("forced refreshes are limited, reads are not", func(t *testing.T) {
e := newTMBEnv(t, func(o *TraefikOidc) { o.perSourceLimiter = newPerSourceAuthLimiter(2) })
assert.Equal(t, http.StatusOK, e.post(tmbPath, nil).Code)
assert.Equal(t, http.StatusOK, e.post(tmbPath, nil).Code)
callsBefore := e.idp.calls()
rec := e.post(tmbPath, nil)
assert.Equal(t, http.StatusTooManyRequests, rec.Code)
assert.Equal(t, "rate_limited", decodeTMB(t, rec)["error"])
assert.Equal(t, "1", rec.Header().Get("Retry-After"))
assert.NotContains(t, rec.Body.String(), "access_token")
assert.Equal(t, callsBefore, e.idp.calls(), "a throttled POST must not reach the IdP")
assert.Equal(t, http.StatusOK, e.get(tmbPath, nil).Code, "GET stays available while throttled")
})
t.Run("no limiter configured means no throttling", func(t *testing.T) {
e := newTMBEnv(t)
for i := 0; i < 5; i++ {
assert.Equal(t, http.StatusOK, e.post(tmbPath, nil).Code)
}
})
t.Run("internal sources are never throttled", func(t *testing.T) {
e := newTMBEnv(t, func(o *TraefikOidc) { o.perSourceLimiter = newPerSourceAuthLimiter(1) })
for i := 0; i < 3; i++ {
rec := e.post(tmbPath, func(r *http.Request) { r.RemoteAddr = "10.1.2.3:4567" })
assert.Equal(t, http.StatusOK, rec.Code)
}
})
}
func TestTMB_NeverEmitsCORSHeaders(t *testing.T) {
e := newTMBEnv(t, func(o *TraefikOidc) {
// What securityHeaders.corsEnabled does at the top of ServeHTTP.
o.securityHeadersApplier = func(rw http.ResponseWriter, _ *http.Request) {
rw.Header().Set("Access-Control-Allow-Origin", "https://evil.example")
rw.Header().Set("Access-Control-Allow-Credentials", "true")
rw.Header().Set("access-control-allow-headers", "x-anything")
rw.Header().Set("X-Frame-Options", "DENY")
}
})
for _, rec := range []*httptest.ResponseRecorder{
e.get(tmbPath, nil),
e.post(tmbPath, nil),
e.get(tmbPath, func(r *http.Request) { r.Header.Set("Sec-Fetch-Site", "cross-site") }),
e.do(http.MethodPut, tmbPath, nil),
} {
for name := range rec.Header() {
assert.NotContains(t, name, "Access-Control", "response %d", rec.Code)
}
assert.Equal(t, "DENY", rec.Header().Get("X-Frame-Options"), "unrelated security headers are kept")
}
}
func TestTMB_AuthorizationGates(t *testing.T) {
t.Run("user not in allowlist", func(t *testing.T) {
e := newTMBEnv(t, func(o *TraefikOidc) { o.allowedUsers = map[string]struct{}{"someone-else": {}} })
for _, method := range []string{http.MethodGet, http.MethodPost} {
rec := e.do(method, tmbPath, nil)
assert.Equal(t, http.StatusForbidden, rec.Code, method)
assert.Equal(t, "access_denied", decodeTMB(t, rec)["error"])
assert.NotContains(t, rec.Body.String(), "access_token")
}
assert.Zero(t, e.idp.calls(), "an unauthorized user must not trigger a refresh")
})
t.Run("missing required group", func(t *testing.T) {
e := newTMBEnv(t, func(o *TraefikOidc) { o.allowedRolesAndGroups = map[string]struct{}{"staff": {}} })
assert.Equal(t, http.StatusForbidden, e.get(tmbPath, nil).Code)
assert.Equal(t, http.StatusForbidden, e.post(tmbPath, nil).Code)
assert.Zero(t, e.idp.calls(), "an unauthorized user must not trigger a refresh")
})
t.Run("required group present", func(t *testing.T) {
e := newTMBEnv(t, func(o *TraefikOidc) { o.allowedRolesAndGroups = map[string]struct{}{"admins": {}} })
assert.Equal(t, http.StatusOK, e.get(tmbPath, nil).Code)
assert.Equal(t, http.StatusOK, e.post(tmbPath, nil).Code)
})
}
func TestTMB_BearerHeaderDoesNotBypassSessionCheck(t *testing.T) {
e := newTMBEnv(t, func(o *TraefikOidc) { o.enableBearerAuth = true })
e.cookies = nil
rec := e.get(tmbPath, func(r *http.Request) { r.Header.Set("Authorization", "Bearer a.b.c") })
assert.Equal(t, http.StatusUnauthorized, rec.Code)
assert.Equal(t, "invalid_session", decodeTMB(t, rec)["error"])
}
+286
View File
@@ -0,0 +1,286 @@
package traefikoidc
import (
"encoding/json"
"net/http/httptest"
"strings"
"testing"
"text/template"
)
// renderHeaderTemplate runs tmplStr through the same validator, funcMap and
// applyHeaderTemplates path production uses. validateErr is the static-validation
// error; got is the forwarded header value ("" when absent or dropped).
func renderHeaderTemplate(t *testing.T, tmplStr string, extraClaims []string, claims map[string]interface{}) (got string, validateErr error) {
t.Helper()
allowed := claimsWhitelist(extraClaims)
if err := validateTemplateSecure(tmplStr, allowed); err != nil {
return "", err
}
tmpl, err := template.New("X-Test").Funcs(headerTemplateFuncMap(allowed)).Option("missingkey=zero").Parse(tmplStr)
if err != nil {
t.Fatalf("validated template failed to parse: %v", err)
}
o := &TraefikOidc{logger: NewLogger("error"), headerTemplates: map[string]*template.Template{"X-Test": tmpl}}
req := httptest.NewRequest("GET", "/", nil)
o.applyHeaderTemplates(req, &principal{Claims: claims, AccessToken: "AT-SECRET", IDToken: "IDT-SECRET", RefreshToken: "RT-SECRET"})
return req.Header.Get("X-Test"), nil
}
func TestToJson_ObjectClaimRoundTrips(t *testing.T) {
claims := map[string]interface{}{
"tenant": map[string]interface{}{"id": "t-1", "plan": "pro", "flags": []interface{}{"a", "b"}, "n": 3.0, "ok": true, "nil": nil},
}
for _, tmpl := range []string{
`{{ get .Claims "tenant" | toJson }}`,
`{{ toJson (get .Claims "tenant") }}`,
`{{ toJson .Claims.tenant }}`,
`{{ with .Claims.tenant }}{{ toJson . }}{{ end }}`,
`{{ $t := .Claims.tenant }}{{ toJson $t }}`,
`{{ toJson $.Claims.tenant }}`,
} {
got, err := renderHeaderTemplate(t, tmpl, []string{"tenant"}, claims)
if err != nil {
t.Fatalf("%s: unexpected validation error: %v", tmpl, err)
}
var back map[string]interface{}
if err := json.Unmarshal([]byte(got), &back); err != nil {
t.Fatalf("%s: output %q is not valid JSON: %v", tmpl, got, err)
}
if back["id"] != "t-1" || back["plan"] != "pro" || back["n"] != 3.0 || back["ok"] != true {
t.Fatalf("%s: round trip mismatch: %q", tmpl, got)
}
}
}
func TestToJson_ValueTypes(t *testing.T) {
claims := map[string]interface{}{
"groups": []interface{}{"admin", "users"},
"email": "[email protected]",
"exp": 1700000000.0,
"role": "",
}
cases := []struct{ name, tmpl, want string }{
{"array", `{{ toJson .Claims.groups }}`, `["admin","users"]`},
{"string", `{{ toJson .Claims.email }}`, `"[email protected]"`},
{"number", `{{ toJson .Claims.exp }}`, `1700000000`},
{"missing claim skips header", `{{ toJson .Claims.department }}`, ``},
{"missing via get skips header", `{{ get .Claims "department" | toJson }}`, ``},
{"empty string skips header", `{{ toJson .Claims.role }}`, ``},
{"literal string", `{{ toJson "x" }}`, `"x"`},
{"literal number", `{{ toJson 5 }}`, `5`},
{"composes with surrounding text", `v={{ toJson .Claims.groups }};`, `v=["admin","users"];`},
}
for _, c := range cases {
got, err := renderHeaderTemplate(t, c.tmpl, nil, claims)
if err != nil {
t.Fatalf("%s: unexpected validation error: %v", c.name, err)
}
if got != c.want {
t.Errorf("%s: got %q want %q", c.name, got, c.want)
}
}
}
func TestToJson_EmptyAndNilContainers(t *testing.T) {
claims := map[string]interface{}{
"realm_access": map[string]interface{}{},
"groups": []interface{}{},
}
if got, _ := renderHeaderTemplate(t, `{{ toJson .Claims.realm_access }}`, nil, claims); got != `{}` {
t.Errorf("empty object: got %q", got)
}
if got, _ := renderHeaderTemplate(t, `{{ toJson .Claims.groups }}`, nil, claims); got != `[]` {
t.Errorf("empty array: got %q", got)
}
if got, _ := renderHeaderTemplate(t, `{{ toJson .Claims.groups }}`, nil, nil); got != `` {
t.Errorf("nil claims: got %q", got)
}
}
func TestToJson_UnmarshalableValueDropsHeader(t *testing.T) {
fn := headerTemplateFuncMap(nil)["toJson"].(func(interface{}) (string, error))
if _, err := fn(make(chan int)); err == nil {
t.Fatal("expected error for unmarshalable value")
}
// A non-finite float is the only way a claim map could carry one in.
if _, err := fn(map[string]interface{}{"x": func() {}}); err == nil {
t.Fatal("expected error for func value")
}
}
// Security: toJson must not widen what a template can reach.
func TestToJson_SecurityBoundary(t *testing.T) {
claims := map[string]interface{}{
"email": "[email protected]",
"secret": "NOT-WHITELISTED",
"tenant": map[string]interface{}{"id": "t"},
}
rejected := []string{
`{{ toJson . }}`,
`{{ toJson $ }}`,
`{{ toJson .Claims }}`,
`{{ toJson $.Claims }}`,
`{{ .Claims | toJson }}`,
`{{ toJson .Claims.secret }}`,
`{{ toJson $.Claims.secret }}`,
`{{ toJson .AccessToken }}{{ toJson .Claims }}`,
`{{ get .Claims "secret" | toJson }}`,
`{{ toJson (get . "AccessToken") }}`,
`{{ get . "Claims" | toJson }}`,
`{{ with .Claims }}{{ toJson . }}{{ end }}`,
`{{ range .Claims }}{{ toJson . }}{{ end }}`,
`{{ toJson (index .Claims "secret") }}`,
`{{ toJson (printf "%v" .Claims) }}`,
`{{ toJson (call .Claims) }}`,
`{{ tojson .Claims.email }}`,
`{{ toJSON .Claims.email }}`,
`{{ toJson | js }}`,
}
for _, tmpl := range rejected {
if got, err := renderHeaderTemplate(t, tmpl, nil, claims); err == nil {
t.Errorf("%s: must be rejected by validation, rendered %q", tmpl, got)
}
}
// Dynamic key: static validation cannot see it, the runtime whitelist must.
dyn := `{{ get .Claims .Claims.email | toJson }}`
if got, err := renderHeaderTemplate(t, dyn, nil, map[string]interface{}{"email": "secret", "secret": "LEAK"}); err != nil || strings.Contains(got, "LEAK") {
t.Errorf("dynamic key leaked a non-whitelisted claim: err=%v got=%q", err, got)
}
}
// Security: tokens and the claims map never appear in output, even from a
// validated template that serializes a whitelisted claim.
func TestToJson_NoTokenLeak(t *testing.T) {
claims := map[string]interface{}{"tenant": map[string]interface{}{"id": "t"}}
got, err := renderHeaderTemplate(t, `{{ toJson .Claims.tenant }}`, []string{"tenant"}, claims)
if err != nil {
t.Fatal(err)
}
for _, s := range []string{"AT-SECRET", "IDT-SECRET", "RT-SECRET"} {
if strings.Contains(got, s) {
t.Fatalf("token %s leaked into %q", s, got)
}
}
}
// Security: a non-whitelisted claim stays unreachable until the operator opts
// in via allowedClaims, with or without toJson.
func TestToJson_RequiresAllowedClaims(t *testing.T) {
claims := map[string]interface{}{"tenant": map[string]interface{}{"id": "t"}}
if _, err := renderHeaderTemplate(t, `{{ toJson .Claims.tenant }}`, nil, claims); err == nil {
t.Error("direct reference to non-whitelisted claim must be rejected")
}
got, err := renderHeaderTemplate(t, `{{ get .Claims "tenant" | toJson }}`, nil, claims)
if err == nil {
t.Errorf("literal get key outside whitelist must be rejected, rendered %q", got)
}
}
// Security: hostile claim content must not produce header injection.
func TestToJson_HeaderInjectionHardening(t *testing.T) {
cases := []struct {
name string
value interface{}
// forwarded reports whether the header is expected to reach upstream.
forwarded bool
}{
{"CRLF is escaped to \\r\\n", map[string]interface{}{"x": "a\r\nX-Evil: 1"}, true},
{"NUL and control chars escaped", map[string]interface{}{"x": "a\x00\x07b"}, true},
{"LS/PS escaped", map[string]interface{}{"x": "a

b"}, true},
{"HTML chars escaped", map[string]interface{}{"x": "<script>&"}, true},
{"quote and backslash escaped", map[string]interface{}{"x": `"\`}, true},
{"bidi override dropped by sanitizer", map[string]interface{}{"x": "a\u202Eb"}, false},
{"bidi isolate dropped by sanitizer", map[string]interface{}{"x": "a\u2066b"}, false},
{"oversize dropped by sanitizer", map[string]interface{}{"x": strings.Repeat("A", headerTemplateMaxLen)}, false},
}
for _, c := range cases {
got, err := renderHeaderTemplate(t, `{{ toJson .Claims.realm_access }}`, nil, map[string]interface{}{"realm_access": c.value})
if err != nil {
t.Fatalf("%s: %v", c.name, err)
}
if !c.forwarded {
if got != "" {
t.Errorf("%s: tainted value must be dropped, got %d bytes", c.name, len(got))
}
continue
}
if got == "" {
t.Errorf("%s: safe escaped JSON must be forwarded", c.name)
continue
}
for _, r := range got {
if r < 0x20 || r == 0x7f || r == 0x2028 || r == 0x2029 {
t.Errorf("%s: raw control rune %U in %q", c.name, r, got)
}
}
if strings.ContainsAny(got, "<>&") {
t.Errorf("%s: unescaped HTML char in %q", c.name, got)
}
var back map[string]interface{}
if err := json.Unmarshal([]byte(got), &back); err != nil {
t.Errorf("%s: not valid JSON: %v", c.name, err)
}
}
}
// Default-preserving: existing templates are unaffected and toJson is not
// available to anything but validated header templates.
func TestToJson_ExistingTemplatesUnchanged(t *testing.T) {
claims := map[string]interface{}{"email": "[email protected]", "groups": []interface{}{"x", "y"}}
got, err := renderHeaderTemplate(t, `{{ .Claims.email }}|{{range $i, $e := .Claims.groups}}{{if $i}},{{end}}{{$e}}{{end}}|{{ default "d" .Claims.role }}`, nil, claims)
if err != nil || got != "[email protected]|x,y|d" {
t.Fatalf("got %q err=%v", got, err)
}
if _, ok := headerTemplateFuncMap(nil)["toJson"]; !ok {
t.Fatal("toJson missing from func map")
}
for _, name := range []string{"env", "expandenv", "printf", "call", "index", "js"} {
if _, ok := headerTemplateFuncMap(nil)[name]; ok {
t.Errorf("%s must not be exposed", name)
}
}
}
func TestToJson_ConfigValidate(t *testing.T) {
cfg := issue149BaseConfig()
cfg.AllowedClaims = []string{"tenant"}
cfg.Headers = []TemplatedHeader{{Name: "X-Tenant", Value: `{{ get .Claims "tenant" | toJson }}`}}
if err := cfg.Validate(); err != nil {
t.Fatalf("toJson header must validate: %v", err)
}
cfg.Headers = []TemplatedHeader{{Name: "X-All", Value: `{{ toJson .Claims }}`}}
if err := cfg.Validate(); err == nil {
t.Fatal("toJson of whole Claims must fail validation")
}
}
// Oversize output is operator-actionable, so it logs at error level (name and
// size limit only, never the value); other sanitizer drops stay at debug.
func TestToJson_OversizeLogsError(t *testing.T) {
run := func(claim map[string]interface{}) string {
var buf strings.Builder
logger := NewLogger("debug")
logger.logError.SetOutput(&buf)
tmpl := template.Must(template.New("X-Test").Funcs(headerTemplateFuncMap(nil)).Parse(`{{ toJson .Claims.realm_access }}`))
o := &TraefikOidc{logger: logger, headerTemplates: map[string]*template.Template{"X-Test": tmpl}}
req := httptest.NewRequest("GET", "/", nil)
o.applyHeaderTemplates(req, &principal{Claims: map[string]interface{}{"realm_access": claim}})
if req.Header.Get("X-Test") != "" {
t.Fatal("tainted header must be dropped")
}
return buf.String()
}
big := strings.Repeat("S3CRET", headerTemplateMaxLen)
out := run(map[string]interface{}{"x": big})
if !strings.Contains(out, "X-Test") || !strings.Contains(out, "exceeds") {
t.Errorf("oversize must log an error naming the header, got %q", out)
}
if strings.Contains(out, "S3CRET") {
t.Error("error log must not contain the value")
}
if out := run(map[string]interface{}{"x": "a\u202Eb"}); out != "" {
t.Errorf("non-length sanitizer drop must not log at error level, got %q", out)
}
}
+69
View File
@@ -0,0 +1,69 @@
package traefikoidc
import (
"testing"
"time"
)
func newNSCache(t *testing.T) *UniversalCache {
t.Helper()
c := NewUniversalCache(UniversalCacheConfig{Type: CacheTypeToken, MaxSize: 100, DefaultTTL: time.Hour, CleanupInterval: time.Hour})
t.Cleanup(func() { _ = c.Close() })
return c
}
// A verdict stored by one middleware instance must not satisfy another
// instance that verifies against a different client or audience.
func TestTokenCacheIsolatedPerInstanceNamespace(t *testing.T) {
shared := newNSCache(t)
a := &TokenCache{cache: shared}
b := &TokenCache{cache: shared}
a.SetNamespace("https://idp|app-a|app-a")
b.SetNamespace("https://idp|app-b|app-b")
a.Set("tok", map[string]interface{}{"sub": "u"}, time.Minute)
if _, ok := b.Get("tok"); ok {
t.Fatal("instance B hit a verdict cached by instance A")
}
if _, ok := a.Get("tok"); !ok {
t.Fatal("instance A lost its own verdict")
}
a.Delete("tok")
if _, ok := a.Get("tok"); ok {
t.Fatal("Delete did not remove the namespaced entry")
}
}
func TestTokenCacheNamespaceFollowsDCR(t *testing.T) {
shared := newNSCache(t)
tc := &TokenCache{cache: shared}
tc.SetNamespace("p|old|old")
tc.Set("tok", map[string]interface{}{"sub": "u"}, time.Minute)
tc.SetNamespace("p|new|new")
if _, ok := tc.Get("tok"); ok {
t.Fatal("verdict cached under the old client survived a namespace change")
}
}
func TestTokenCacheEmptyNamespaceKeepsLegacyKey(t *testing.T) {
shared := newNSCache(t)
a := &TokenCache{cache: shared}
b := &TokenCache{cache: shared}
a.Set("tok", map[string]interface{}{"sub": "u"}, time.Minute)
if _, ok := b.Get("tok"); !ok {
t.Fatal("namespace-less caches must keep sharing the legacy key")
}
}
func TestIntrospectionKeyScopedPerInstance(t *testing.T) {
a := &TraefikOidc{tokenCache: &TokenCache{}}
b := &TraefikOidc{tokenCache: &TokenCache{}}
a.tokenCache.SetNamespace("p|app-a|app-a")
b.tokenCache.SetNamespace("p|app-b|app-b")
if a.introspectionKey("tok") == b.introspectionKey("tok") {
t.Fatal("different instances share an introspection cache key")
}
if got := (&TraefikOidc{}).introspectionKey("tok"); got != "tok" {
t.Fatalf("namespace-less key = %q, want raw token", got)
}
}
+11 -2
View File
@@ -53,7 +53,7 @@ type IntrospectionResponse struct {
func (t *TraefikOidc) introspectToken(token string) (*IntrospectionResponse, error) {
// Check cache first
if t.introspectionCache != nil {
if cached, found := t.introspectionCache.Get(token); found {
if cached, found := t.introspectionCache.Get(t.introspectionKey(token)); found {
if response, ok := cached.(*IntrospectionResponse); ok {
t.logger.Debugf("Using cached introspection result for token")
return response, nil
@@ -173,7 +173,7 @@ func (t *TraefikOidc) introspectToken(token string) (*IntrospectionResponse, err
cacheDuration = untilExp
}
}
t.introspectionCache.Set(token, &introspectionResp, cacheDuration)
t.introspectionCache.Set(t.introspectionKey(token), &introspectionResp, cacheDuration)
t.logger.Debugf("Cached introspection result for %v", cacheDuration)
}
@@ -280,3 +280,12 @@ func (t *TraefikOidc) validateOpaqueToken(token string) error {
t.logger.Debugf("Opaque token validation successful via introspection")
return nil
}
// introspectionKey scopes an introspection verdict to this instance's
// provider, client and audience, like the verified-token cache.
func (t *TraefikOidc) introspectionKey(token string) string {
if ns := t.tokenCache.Namespace(); ns != "" {
return ns + "|" + token
}
return token
}
+2 -1
View File
@@ -622,6 +622,7 @@ func (t *TraefikOidc) refreshToken(rw http.ResponseWriter, req *http.Request, se
session.SetIDToken(newToken.IDToken)
session.SetAccessToken(newToken.AccessToken)
session.SetAccessTokenExpiresAt(newToken.AccessToken, accessTokenExpiry(newToken, time.Now()))
if newToken.RefreshToken != "" {
t.logger.Debug("Received new refresh token from provider")
@@ -812,7 +813,7 @@ func (t *TraefikOidc) RevokeToken(token string) {
// from the introspection cache after revocation. Next request
// re-introspects and sees active=false.
if t.introspectionCache != nil {
t.introspectionCache.Delete(token)
t.introspectionCache.Delete(t.introspectionKey(token))
}
d := blacklistDuration(token)
+2 -2
View File
@@ -15,6 +15,7 @@ package traefikoidc
import (
"encoding/base64"
"encoding/json"
"errors"
"strings"
"time"
)
@@ -266,8 +267,7 @@ func (t *TraefikOidc) validateStandardTokensRS(rs *requestState) (bool, bool, bo
var accessVerifyErr error
if err := t.verifyToken(rs.accessToken); err != nil {
accessVerifyErr = err
errMsg := err.Error()
if strings.Contains(errMsg, "invalid audience") || strings.Contains(errMsg, "audience") {
if errors.Is(err, errInvalidAudience) {
if t.strictAudienceValidation {
if rs.refreshToken != "" {
return false, true, false
+6
View File
@@ -111,6 +111,9 @@ type TraefikOidc struct {
// 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
@@ -224,11 +227,14 @@ type TraefikOidc struct {
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
+38 -2
View File
@@ -380,6 +380,10 @@ func (c *UniversalCache) setLocalLocked(key string, value interface{}, ttl time.
growth = size - existing.Size
}
if c.rejectOversized(key, size) {
return
}
// Check memory limits
if c.config.MaxMemoryBytes > 0 {
// Evict items if necessary to make room
@@ -712,6 +716,9 @@ func (c *UniversalCache) getLocal(key string) (interface{}, bool) {
if gracePeriod, ok := item.Metadata["grace_period_active"].(bool); ok && gracePeriod {
if c.shouldExtendGracePeriod(item, now) {
newExpiry := c.calculateNewExpiry(item, now)
if _, set := item.Metadata[graceOriginKey]; !set {
item.Metadata[graceOriginKey] = item.ExpiresAt
}
item.ExpiresAt = newExpiry
c.logger.Infof("UniversalCache[%s]: Extended grace period for key=%s until %v",
c.config.Type, key, newExpiry)
@@ -915,11 +922,29 @@ func (c *UniversalCache) evictOldest() {
}
}
// rejectOversized drops a value larger than the whole memory cap instead of
// flushing every other entry to fit it. A stale copy under the key is removed.
// Caller holds c.mu.
func (c *UniversalCache) rejectOversized(key string, size int64) bool {
if c.config.MaxMemoryBytes <= 0 || size <= c.config.MaxMemoryBytes {
return false
}
if existing, ok := c.items[key]; ok {
c.removeItem(key, existing)
}
c.logger.Infof("UniversalCache[%s]: dropped oversized value key=%s size=%d cap=%d",
c.config.Type, key, size, c.config.MaxMemoryBytes)
return true
}
// SetMaxSize sets the maximum size and evicts items if necessary
func (c *UniversalCache) SetMaxSize(newSize int) {
c.mu.Lock()
defer c.mu.Unlock()
if newSize < 1 {
newSize = 1 // a non-positive bound would spin the eviction loop forever
}
oldSize := c.config.MaxSize
c.config.MaxSize = newSize
@@ -1021,6 +1046,9 @@ func (c *UniversalCache) estimateSize(value interface{}) int64 {
}
}
// graceOriginKey holds the item's first expiry once grace has started.
const graceOriginKey = "grace_origin"
// shouldExtendGracePeriod determines if grace period should be extended
func (c *UniversalCache) shouldExtendGracePeriod(item *CacheItem, now time.Time) bool {
if c.config.MetadataConfig == nil {
@@ -1040,8 +1068,12 @@ func (c *UniversalCache) shouldExtendGracePeriod(item *CacheItem, now time.Time)
}
}
// Calculate how long since the item originally expired
timeSinceExpiry := now.Sub(item.ExpiresAt)
// Measure from the first expiry: later extensions overwrite ExpiresAt.
origin := item.ExpiresAt
if o, ok := item.Metadata[graceOriginKey].(time.Time); ok {
origin = o
}
timeSinceExpiry := now.Sub(origin)
return timeSinceExpiry <= maxGrace
}
@@ -1523,6 +1555,10 @@ func (c *UniversalCache) updateLocalCache(key string, value interface{}, ttl tim
growth = size - existing.Size
}
if c.rejectOversized(key, size) {
return nil
}
// Check memory limits
if c.config.MaxMemoryBytes > 0 {
for c.currentMemory+growth > c.config.MaxMemoryBytes && c.lruList.Len() > 0 {
+88
View File
@@ -0,0 +1,88 @@
package traefikoidc
import (
"math"
"testing"
"time"
)
func newBoundsCache(t *testing.T, cfg UniversalCacheConfig) *UniversalCache {
t.Helper()
cfg.CleanupInterval = time.Hour
if cfg.DefaultTTL == 0 {
cfg.DefaultTTL = time.Hour
}
c := NewUniversalCache(cfg)
t.Cleanup(func() { _ = c.Close() })
return c
}
// Grace extensions must stay within MaxGracePeriod of the ORIGINAL expiry.
func TestGraceNeverServesPastOriginalExpiryBound(t *testing.T) {
c := newBoundsCache(t, UniversalCacheConfig{
Type: CacheTypeMetadata, MaxSize: 10,
MetadataConfig: &MetadataCacheConfig{
GracePeriod: 20 * time.Millisecond, ExtendedGracePeriod: 20 * time.Millisecond,
MaxGracePeriod: 100 * time.Millisecond, SecurityCriticalMaxGracePeriod: 100 * time.Millisecond,
},
})
if err := c.Set("k", "v", 10*time.Millisecond); err != nil {
t.Fatal(err)
}
c.ActivateGracePeriod("k")
deadline := time.Now().Add(600 * time.Millisecond)
for time.Now().Before(deadline) {
time.Sleep(10 * time.Millisecond)
if _, ok := c.Get("k"); !ok {
return
}
}
t.Fatal("stale entry still served 600ms after a 100ms max grace")
}
func TestSetMaxSizeNegativeTerminates(t *testing.T) {
c := newBoundsCache(t, UniversalCacheConfig{Type: CacheTypeGeneral, MaxSize: 10})
for _, k := range []string{"a", "b", "c"} {
_ = c.Set(k, "v", time.Hour)
}
done := make(chan struct{})
go func() { c.SetMaxSize(-1); close(done) }()
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("SetMaxSize(-1) did not return")
}
}
// One oversized value must not flush the other live entries.
func TestOversizedValueDoesNotFlushCache(t *testing.T) {
c := newBoundsCache(t, UniversalCacheConfig{
Type: CacheTypeGeneral, MaxSize: 10, MaxMemoryBytes: 1000, EnableMemoryLimit: true,
})
_ = c.Set("live", "x", time.Hour)
_ = c.Set("big", make([]byte, 5000), time.Hour)
if _, ok := c.Get("live"); !ok {
t.Fatal("oversized insert evicted a live entry")
}
c.mu.RLock()
mem := c.currentMemory
c.mu.RUnlock()
if mem > 1000 {
t.Fatalf("currentMemory=%d exceeds cap 1000", mem)
}
}
// Out-of-range or non-finite nbf/iat must be rejected, not wrapped into the past.
func TestTimeClaimsRejectOutOfRange(t *testing.T) {
for _, v := range []float64{1e19, 1e300, math.Inf(1), math.Inf(-1), math.NaN()} {
if verifyNotBefore(v) == nil {
t.Errorf("nbf=%v accepted", v)
}
if verifyIssuedAt(v) == nil {
t.Errorf("iat=%v accepted", v)
}
if verifyExpiration(v) == nil {
t.Errorf("exp=%v accepted", v)
}
}
}
+13 -3
View File
@@ -453,6 +453,15 @@ func sameHost(a, b string) bool {
return strings.EqualFold(ua.Host, ub.Host)
}
// canonicalHost drops the root dot ("localhost." is localhost) and an IPv6
// zone id so the blocklists see one spelling per host.
func canonicalHost(host string) string {
if i := strings.IndexByte(host, '%'); i > 0 && net.ParseIP(host[:i]) != nil {
host = host[:i]
}
return strings.TrimRight(host, ".")
}
// validateHost validates a hostname or IP address for security.
// It prevents access to localhost, private networks, and known metadata endpoints.
// When allowPrivateIPAddresses is enabled, private IP checks are skipped.
@@ -462,13 +471,14 @@ func sameHost(a, b string) bool {
// Returns:
// - An error if the host is dangerous or not allowed, nil if safe.
func (t *TraefikOidc) validateHost(host string) error {
hostname := host
if strings.Contains(host, ":") {
hostname := canonicalHost(host)
if net.ParseIP(hostname) == nil && strings.Contains(hostname, ":") {
var err error
hostname, _, err = net.SplitHostPort(host)
hostname, _, err = net.SplitHostPort(hostname)
if err != nil {
return fmt.Errorf("invalid host format: %w", err)
}
hostname = canonicalHost(hostname)
}
ip := net.ParseIP(hostname)
+21
View File
@@ -3,6 +3,7 @@
package traefikoidc
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
@@ -28,6 +29,26 @@ func (t *TraefikOidc) metadataSnap() *MetadataSnapshot {
return s
}
// metadataReady reports whether provider metadata has been adopted, read the
// same way ServeHTTP reads it: the snapshot, else issuerURL under metadataMu.
func (t *TraefikOidc) metadataReady() bool {
if snap := t.metadataSnap(); snap != nil {
return snap.IssuerURL != ""
}
t.metadataMu.RLock()
defer t.metadataMu.RUnlock()
return t.issuerURL != ""
}
// lifecycleCtx returns the instance context, which Close cancels, or
// context.Background for instances built without New.
func (t *TraefikOidc) lifecycleCtx() context.Context {
if t.ctx != nil {
return t.ctx
}
return context.Background()
}
// safeLogDebug provides nil-safe logging for debug messages
func (t *TraefikOidc) safeLogDebug(msg string) {
if t.logger != nil {
+1 -1
View File
@@ -14,4 +14,4 @@ const devPluginVersion = "0.0.0-dev"
// from build info at runtime (debug.ReadBuildInfo sees Traefik's build graph,
// not the interpreted plugin). This build-stamped constant is therefore the
// single source of truth for the version reported by anonymous usage telemetry.
const traefikoidcPluginVersion = "0.0.0-dev"
const traefikoidcPluginVersion = "1.0.66"