feat(auth): admit oidc bearer tokens as virtual users (#27)

* feat(auth): add oidc config and per-identity overrides

Add Config.OIDC with issuer, audiences, claim and group-map settings.
The constructor validates the settings and applies defaults.

A users-config entry with oidcIdentity is now a per-identity override.
It sets the accounting name and the limits for one OIDC identity.
It must not set an API key, groups, grants or admin.

The admin config view sanitizes the issuer URL like a base URL.

* feat(auth): verify oidc jwt access tokens locally

Add a stdlib-only JWS verifier for OIDC access tokens. It accepts
RS256, RS384, RS512, PS256, ES256 and ES384 only. It rejects "none",
HMAC algorithms and a header algorithm that does not match the key.

The verifier checks iss, exp and nbf with 60 seconds of skew, aud or
azp against the configured audiences, and email_verified on request.
JWKS parsing skips encryption keys and unsupported key types. It
rejects an EC point that is not on its curve.

* feat(auth): fetch oidc discovery, jwks and userinfo

Add the OIDC provider client. It reads the discovery document on first
use and checks that its issuer equals the configured issuer. It caches
the JWKS and refreshes it every jwksRefresh.

An unknown kid starts a refetch at most once per 60 seconds. A failed
fetch is held for 5 seconds, and the last good keys stay in use. One
fetch runs at a time, and each IdP response is capped at 1 MiB.

* feat(auth): map oidc claims to cached virtual users

Add the OIDC authenticator. It verifies a JWT locally, or an opaque
token at the userinfo endpoint when that path is on. It then maps the
group claim to configured gateway groups.

A valid token with no mapped group gets a forbidden verdict. The
virtual user is named "oidc:<identity>", or takes the override name.
Its limits merge the override with the group memberLimits per field.

Verdicts are cached until the token expires or cacheTTL ends. A
refusal is cached for 30 seconds. An IdP outage is not cached. Virtual
users are held in an LRU bounded by maxUsers.

* feat(auth): admit oidc bearer tokens as virtual users

With oidc configured, a Bearer token that matches no configured key
goes to the OIDC authenticator. A configured key always wins first,
and the anonymous fallbacks keep their previous order.

A valid token without a mapped group gets 403 permission_error, in
the route's own error shape. An invalid token gets 401 as before. The
admin API and the metrics route stay key-only.

All routes now use one requireAuth helper. The auth failure log line
names the OIDC refusal reason. The yaegi-check harness signs RS256,
PS256 and ES256 tokens and runs them through the interpreted plugin.

* feat(admin): list oidc virtual users across replicas

The admin snapshot now lists OIDC virtual users with source "oidc".
Each one counts in the memberCount of every mapped group. Scope checks
and the rejection prune after a users-file reload see them too.

With Redis configured, each replica records the users it admits in the
llmgw:oidc:users hash, at most once per minute per user. The snapshot
reads the hash at most once every two seconds. It hides users whose
groups are all gone, and users not seen for 32 days. Without Redis the
list holds only the users this replica has seen.

* feat(admin): badge oidc users

The user panel shows an "OIDC" badge for a virtual user that an OIDC
bearer token admitted. The consumer source type now includes "oidc".

* docs(auth): document oidc virtual users

Add the "OIDC users (Open WebUI)" section and the OIDCConfig reference
table. The section covers precedence, 401 against 403, the oidc: name
prefix, per-person overrides, the token cache, the Redis registry and
the userinfo audience limit. It also lists the Open WebUI connection
steps.

* fix(auth): harden oidc key fetch, userinfo and jwks handling

The discovery and JWKS fetch now runs on its own 5s deadline, so one
caller's cancel cannot fail it for every request. Discovery failures
now use the same 5s retry hold on the userinfo path.

Userinfo calls are capped at 16 in flight. Only an IdP 401 or 403 is
cached as a rejection. Timeouts, 5xx and 429 are not cached. Refused
tokens use their own cache, so a flood cannot evict valid verdicts.
An unknown kid is not cached, because the keys can be stale.

A disallowed alg is refused before any key fetch. The jwks_uri and
userinfo_endpoint must be https or loopback http. A malformed key, or
an RSA key under 2048 bits, is skipped instead of failing the set.

The identity is case-folded only for the email claim. IdP failure
causes are logged, rate-gated, and the no_group reason names the
identity. The Redis registry deletes records past the 32-day retention.

* fix(auth): close oidc audit leads on azp and userinfo slots

A JWT now passes the audience check only when aud names a configured
audience. The azp claim counts only with the new acceptAzp option,
because a token that the client obtained for another service carries
the same azp.

Concurrent requests with one cold token now share one verification.
A userinfo call waits up to 2s for a free slot instead of failing at
once, and it no longer waits on the key fetch lock once discovery is
cached.

The IdP client does not follow redirects. A bearer over 16384 bytes
and an identity over 256 bytes get 401. Email identities fold only
ASCII A-Z, so a look-alike character stays a separate identity.
This commit is contained in:
2026-12-02 01:22:30 +00:00
committed by GitHub
parent f1b198bce4
commit 6805253f91
32 changed files with 4367 additions and 169 deletions
+178 -1
View File
@@ -419,6 +419,7 @@ config accepts them as YAML, which decodes to the same JSON shape.
| `mcpServers` | `map[string]TargetConfig` | `{}` | MCP server registry; see [MCP/A2A](#mcp-and-a2a). |
| `agents` | `map[string]AgentConfig` | `{}` | A2A agent registry; see [MCP/A2A](#mcp-and-a2a). |
| `users` | `UsersConfig` | — | Inline and/or file-backed API-key holders. With none configured, every request is unauthenticated and gets 401. |
| `oidc` | `*OIDCConfig` | `nil` (disabled) | Admit OIDC bearer tokens as per-person virtual users — see [OIDC users (Open WebUI)](#oidc-users-open-webui). `nil` keeps key-only authentication. |
| `redis` | `RedisConfig` | — | Distributed limit-counter backend. Omitted means in-process counters only (per-replica, approximate across multiple Traefik instances). |
| `retry` | `RetryConfig` | `{}` (disabled) | Same-provider retry for transient upstream failures — see [Retry](#retry). Omitted or `enabled: false` means no retry: every request makes exactly one upstream attempt, byte-identical to a gateway built before this field existed. |
| `failover` | `FailoverConfig` | `{}` (disabled) | Cross-provider failover for a bare model id more than one configured provider serves — see [Failover](#failover). Omitted or `enabled: false` means no failover, byte-identical to a gateway built before this field existed. `enabled: true` opts in; a deployment with no overlapping providers behaves exactly as before regardless of this setting either way. |
@@ -793,6 +794,160 @@ sets each to a pattern that matches no name (`-none-`) to deny them.
Set group `limits` and `memberLimits`, and restrict who can reach the route
at the proxy.
#### OIDC users (Open WebUI)
You can let people who sign in to a separate app through OIDC use the
gateway without a key per person. Open WebUI is the main case. The gateway
verifies the person's access token and serves the request as a virtual
user. A virtual user exists for accounting and limits only. It shows in the
admin dashboard with an `OIDC` badge.
```yaml
groups:
staff:
providers: ["openai"]
memberLimits: { requestsPerDay: 500 }
power:
memberLimits: { requestsPerDay: 5000 }
oidc:
issuer: https://idp.example.com/realms/main
audiences: ["openwebui"]
groupClaim: groups
groupMap:
llm-users: staff
llm-power: power
users:
inline:
- name: alice
oidcIdentity: alice@example.com
limits: { requestsPerDay: 2000 }
```
How the gateway reads a request:
1. A key that matches a configured user always wins. The gateway does not
contact the IdP.
2. If `oidc` is set and the request has `Authorization: Bearer <token>`, the
gateway verifies the token. A token in `x-api-key` is never treated as an
OIDC token.
3. A valid token whose group claim maps to at least one gateway group runs
as that person's virtual user.
4. A valid token with no mapped group gets **403** `permission_error`
("token has no group mapped for this gateway"). This also applies when
`users.anonymousAcceptAnyKey` is set. A 403 does not count toward the
auth-failure throttle.
5. An invalid token gets **401**, as a wrong key does, and counts toward
the throttle. With `users.anonymousAcceptAnyKey`, it runs as
`anonymous` instead. This also applies to a valid token while the IdP
cannot be reached: the person then runs with `anonymous` limits.
On `/v1/messages`, the 401 and 403 bodies use the Anthropic error shape.
The admin API and the metrics key fallback accept only keys.
How the gateway verifies a token:
- **JWT.** The gateway fetches `{issuer}/.well-known/openid-configuration`
on the first token, then the JWKS. The `issuer` in that document must
equal `oidc.issuer` exactly. The gateway refreshes the keys every
`jwksRefresh`. An unknown `kid` causes at most one refetch per minute.
If a refresh fails, the old keys stay in use. The gateway skips a
malformed key and an RSA key under 2048 bits, and uses the other keys.
- The gateway accepts RS256, RS384, RS512, PS256, ES256 and ES384 only. It
checks `iss`, `exp` and `nbf` with 60 seconds of clock skew. The `aud`
claim must name one of `audiences`.
- The `azp` claim counts only when you set `acceptAzp: true`. `azp` names
the client that asked for the token, not the service it is for. With
`acceptAzp`, a token that Open WebUI obtained for another service also
passes, and that service can replay it to the gateway. Prefer an
audience mapper in the IdP that puts the gateway audience in `aud`. In
Keycloak, add an "Audience" mapper to the Open WebUI client.
- The gateway does not check the `typ` header, so an ID token whose `aud`
names one of `audiences` also passes.
- A bearer token over 16384 bytes gets 401 before any parse or IdP call.
- **Opaque token.** Only with `userinfo: true`, the gateway sends the token
to the IdP's `userinfo_endpoint` and reads the claims from a 200 reply.
At most 16 userinfo calls run at once. A request over that limit waits up
to 2 seconds for a free slot, then gets 401, and the result is not
cached. Concurrent requests with the same token share one userinfo call.
This path runs before any authentication, so put a rate limit in front
of the gateway (for example Traefik `rateLimit` or `inFlightReq`): a
flood of unique bearers can still fill the 16 slots.
- In userinfo mode, a bearer that matches no static key goes to the IdP.
A mistyped static key therefore reaches the IdP userinfo endpoint.
- `jwks_uri` and `userinfo_endpoint` from discovery must be `https`, or
`http` on a loopback host. The gateway refuses any other endpoint, and
it does not follow redirects from the IdP.
- The identity claim must be a non-empty string of at most 256 bytes. The
gateway trims it. For the `email` claim only, it changes ASCII `A`-`Z`
to lower case. It does not fold other characters, so a look-alike such
as U+212A (Kelvin sign) stays a different identity. When the
identity claim is `email`, `email_verified` must be true unless you set
`requireEmailVerified: false`.
- **Use an identity claim that the IdP controls and the user cannot
change**, such as `sub` or a verified `email`. Some IdPs let users edit
`preferred_username`. A user who renames to another person's name gets
that person's override and usage.
The virtual user's name is `oidc:<identity>`, for example
`oidc:[email protected]`. Its limits are the `memberLimits` of its mapped
groups, merged as for a keyed user in several groups. Usage counters use
that name, like any other user. While `oidc` is set, an inline or file user
whose name starts with `oidc:` is a config error.
To change one person's limits or accounting name, add an entry with
`oidcIdentity` to `users.inline` or to the users file. The entry's `name`
replaces `oidc:<identity>`. Its `limits` override the group `memberLimits`
per field. The token's group claim still decides membership. Two entries
with the same `oidcIdentity` are a config error. A users-file entry
replaces an inline entry with the same identity, and a reload applies the
change on the next request.
Caching and its limits:
- The gateway keeps a verified token until its `exp` or for `cacheTTL`,
whichever comes first. A token that the IdP revokes stays valid at the
gateway until then.
- A rejected token is kept for 30 seconds, so a bad token cannot cause one
IdP call per request. Rejected tokens use a separate cache, so they
cannot push out verified ones. An IdP outage, a userinfo error other than
401 or 403, and an unknown `kid` are not cached.
- The gateway keeps at most `maxUsers` virtual users in memory and drops
the least recently used. Usage counters are not affected.
- The `scope_id` label on `/metrics` holds `oidc:<identity>`, for example
an email address. Any scraper in `metrics.allowedCIDRs` can read it.
- The userinfo path cannot check the audience. Any live access token from
the same issuer passes, and `groupMap` is the only gate. Keep
`userinfo: false` unless your IdP issues opaque tokens.
With `redis` configured, each replica records the virtual users it admits
in the Redis hash `llmgw:oidc:users`, at most once per minute per user.
Every replica then lists the same users in the admin dashboard, and the
list survives a restart. The list hides a user not seen for 32 days, or
whose mapped groups no longer exist. Without Redis, each replica lists only
the users it has seen since it started.
When a token is refused, the auth failure log line names the reason, for
example `auth failed: POST "/v1/chat/completions" from 10.0.0.5:4312 (oidc:
aud)`. For `no_group`, the line also names the identity. When the IdP
cannot be reached, a separate error line gives the cause, for example an
issuer mismatch. The gateway writes that line at most once per 30 seconds. The reasons are `expired`, `not_yet_valid`, `bad_sig`, `bad_alg`,
`issuer`, `aud`, `unknown_kid`, `malformed`, `no_identity`, `no_group`,
`email_unverified`, `userinfo_rejected`, `opaque_disabled` and
`idp_unavailable`. The gateway never logs the token.
To connect Open WebUI:
1. Use Open WebUI 0.9.0 or later, with OIDC sign-in configured.
2. Make sure that the IdP issues refresh tokens to Open WebUI, for example
with the `offline_access` scope. Open WebUI uses them to keep the access
token current.
3. Add the gateway as an OpenAI-compatible connection with the base URL
`https://<gateway>/v1`. Set the connection's auth type to
`system_oauth`. Open WebUI then sends each person's access token as
`Authorization: Bearer`, also on `GET /v1/models`.
4. Add the Open WebUI client ID to `oidc.audiences`, or the audience your
IdP puts in access tokens for it.
### `UserConfig`
| Field | Type | Default | Semantics |
@@ -801,6 +956,7 @@ at the proxy.
| `group` | `string` | — | The user's primary group. May be left empty when `groups` below names at least one group instead — see `groups` for the "at least one" rule. Any non-empty value here or in `groups` must reference a configured group, or construction fails. |
| `groups` | `[]string` | `[]` | Further member groups, alongside `group` — see [`GroupConfig`](#groupconfig) for the full multi-group authorization/limits/cache contract. Effective membership is `group` first (when non-empty), then `groups`, de-duplicated, order preserved. At least one group, from either field, is required — a user naming none at all fails construction. |
| `apiKey` | `string` | — | Secret form (see [Secret forms](#secret-forms)); must resolve non-empty and unique across every inline **and** file-sourced user. |
| `oidcIdentity` | `string` | — | Makes this entry a per-person override for an OIDC virtual user, not a keyed user — see [OIDC users (Open WebUI)](#oidc-users-open-webui). Needs `oidc`. The entry must not set `apiKey`, `group`, `groups`, `providers`, `models` or `admin`. |
| `providers` | `[]string` | `[]` | This user's own personal grant — access beyond whatever their group(s) already allow, glob-matched exactly like a group's own `providers`. Set alone (with `models` left empty), it grants **every** model on those providers — the same empty-`models`-means-all-models contract a group's own `models` carries. The personal grant exists at all only when `providers` is non-empty — leaving it empty/omitted never means "allow everything" on its own, regardless of `models`. |
| `models` | `[]string` | `[]` | The personal grant's own model glob, narrowing `providers` above — same semantics as a group's own `models`. Requires `providers` to be non-empty too: a `models`-only personal grant (no `providers`) would reach every configured provider, not just the ones already covered — a construction error naming the user. |
| `limits` | `*LimitsConfig` | `nil` (governed by group's limits alone) | Overrides the groups' `memberLimits` per non-zero field (see [Group, member and user limits](#group-member-and-user-limits)). When set, enforced alongside — not instead of — every member group's own limits (one independent scope per member group); the request is refused by whichever scope is breached first. The personal grant above carries no limits of its own. |
@@ -810,6 +966,22 @@ A user belonging to exactly one group (`group` alone, `groups` empty)
with no personal grant (`providers`/`models` both empty) behaves
byte-identically to before multi-group support existed.
### `OIDCConfig`
| Field | Type | Default | Semantics |
|---|---|---|---|
| `issuer` | `string` | — | Required. The IdP issuer URL. Must be `https`, or `http` on a loopback host only. |
| `audiences` | `[]string` | — | Required, at least one. A JWT's `aud` must name one of them. |
| `acceptAzp` | `bool` | `false` | Also accept a JWT whose `azp` names one of `audiences` when `aud` does not. A token the client obtained for another service then passes too. |
| `groupClaim` | `string` | — | Required. The claim that holds the person's groups or roles, as a dotted path, for example `realm_access.roles`. A string or an array of strings. |
| `groupMap` | `map[string]string` | — | Required, at least one entry. Claim value to gateway group. Every target must be a configured group. |
| `identityClaim` | `string` | `email` | The claim that names the person, for example `sub`. Use a claim the user cannot change. The value is case-folded only for `email`. |
| `requireEmailVerified` | `*bool` | `true` when `identityClaim` is `email`, else `false` | Require `email_verified` to be true. |
| `userinfo` | `bool` | `false` | Verify opaque tokens through the IdP's userinfo endpoint. See the audience limit in [OIDC users (Open WebUI)](#oidc-users-open-webui). |
| `cacheTTL` | `string` (Go duration) | `5m` | The longest time a verified token stays cached. The token's `exp` always applies too. |
| `jwksRefresh` | `string` (Go duration) | `1h` | How often the gateway refetches the IdP signing keys. |
| `maxUsers` | `int` | `10000` | The most virtual users held in memory. Negative is a config error. |
### `RedisConfig`
| Field | Type | Default | Semantics |
@@ -987,11 +1159,16 @@ Secret (`users_file.go`):
"apiKey": "env:LLMGW_KEY_CAROL",
"providers": ["gx10"],
"models": ["gx10/GLM-5.3-Flash-EXL3"]
}
},
{"name": "dave", "oidcIdentity": "dave@example.com", "limits": {"requestsPerDay": 50}}
]
}
```
Dave has no key. His entry changes the limits and accounting name of the
OIDC virtual user for `[email protected]` — see
[OIDC users (Open WebUI)](#oidc-users-open-webui).
Carol belongs to both `engineering` and `friends` (each group's own
grant authorizes her independently — see [`GroupConfig`](#groupconfig)),
**plus** a personal grant adding exactly one `gx10` model — an addition
+1 -1
View File
@@ -135,7 +135,7 @@ func (g *Gateway) handleAdmin(sw *statusTrackingWriter, r *http.Request) {
// shared, resource cost.
func (g *Gateway) handleAdminAPI(sw *statusTrackingWriter, r *http.Request) {
u, _, ok := g.auth.identifyKeyed(r)
g.logAuthEvent(ok, authEventUserName(u), r)
g.logAuthEvent(ok, authEventUserName(u), r, "")
if !ok {
writeOAIError(sw, http.StatusUnauthorized, "authentication_error", "invalid or missing API key")
return
+58 -58
View File
File diff suppressed because one or more lines are too long
+1
View File
@@ -63,6 +63,7 @@ var hiddenConfigKeys = map[string]bool{
var baseURLLikeConfigKeys = map[string]bool{
"baseUrl": true,
"url": true,
"issuer": true,
}
// redactConfig returns a redacted map[string]any view of cfg, safe to
+1
View File
@@ -17,6 +17,7 @@ var nonSecretConfigKeys = map[string]bool{
"probeInterval": true, "providers": true, "requestTimeout": true,
"ttl": true, "type": true,
"cachedInputPerM": true, "cacheWritePerM": true, "defaultTier": true, "toolsMinTier": true, "classifier": true, "shadowClassifier": true, "intentTiers": true, "keywords": true, "selection": true, "tier": true, "header": true, "mode": true, "firstByteTimeout": true, "provider": true, "timeout": true, "sharedState": true,
"identityClaim": true, "jwksRefresh": true, "oidcIdentity": true, "groupMap": true, "groupClaim": true, "audiences": true,
}
func collectStringKeys(t reflect.Type, seen map[reflect.Type]bool, out map[string]bool) {
+139 -61
View File
@@ -22,6 +22,9 @@ type user struct {
// limitSources maps each non-zero limits field to its origin.
limitSources map[string]string
name, groupName string
// oidcIdentity is the normalized token identity of an OIDC virtual
// user; empty for keyed and anonymous users.
oidcIdentity string
// groupNames is this user's full, de-duplicated, order-preserving
// member group list (effectiveGroupNames, below) — groupName above
// keeps only the first, for back-compat display; groupNames is the
@@ -731,13 +734,26 @@ type authStore struct {
inline map[[32]byte]*authEntry
// anonymous is the principal for keyless requests; nil unless
// UsersConfig.AnonymousGroup is set.
anonymous *authEntry
anonymous *authEntry
// oidc is the validated OIDC config; nil when Config.OIDC is unset.
oidc *oidcSettings
// oidcAuth verifies bearer tokens as OIDC virtual users; nil when off.
oidcAuth *oidcAuthenticator
// oidcRegistry shares seen virtual users through Redis; nil without
// Redis or OIDC.
oidcRegistry *oidcRegistry
// oidcInline and oidcOverrides are the OIDC per-identity overrides,
// keyed by normalizeIdentity: the inline set, and the live set
// (inline merged with the users file), the latter guarded by mu.
oidcInline map[string]*oidcOverride
oidcOverrides map[string]*oidcOverride
lastReloadErrMsg string
failureLog logGate
throttleLog logGate
fileUserCount int
// anonymousAnyKey admits an unknown key as anonymous instead of 401.
anonymousAnyKey bool
oidcEnabled bool
mu sync.RWMutex
buildMu sync.Mutex
reloadMu sync.Mutex
@@ -818,30 +834,40 @@ func newAuthStore(cfg *Config) (*authStore, error) {
return nil, fmt.Errorf("llmgateway: users.anonymousAcceptAnyKey needs users.anonymousGroup")
}
if cfg.Users != nil {
// seenNames rejects two INLINE users sharing the same name
// (security audit finding 5, 2026-08-22) — scoped to inline only,
// not cross-checked against a later file-sourced set: replaceFileUsers
// intentionally allows a file user to override an inline user of the
// same name (its own doc comment), so "duplicate name" only ever
// means "duplicate within the same source".
seenNames := make(map[string]bool, len(cfg.Users.Inline))
for _, uc := range cfg.Users.Inline {
entry, err := a.buildEntry(uc)
if err != nil {
return nil, err
if cfg.OIDC != nil {
settings, err := parseOIDCConfig(cfg.OIDC, a.groups)
if err != nil {
return nil, err
}
a.oidc = settings
a.oidcEnabled = true
now := func() time.Time { return a.nowFn() }
provider := newOIDCProvider(settings, &http.Client{Timeout: oidcHTTPTimeout}, now)
a.oidcAuth = newOIDCAuthenticator(settings, provider, a.groups, now)
// a.log is set after construction, so it is read per call.
a.oidcAuth.logf = func(msg string) {
if a.log != nil {
a.log.errorf("%s", msg)
}
if seenNames[entry.user.name] {
return nil, fmt.Errorf("llmgateway: duplicate user name %q", entry.user.name)
}
seenNames[entry.user.name] = true
if _, exists := a.inline[entry.digest]; exists {
return nil, fmt.Errorf("llmgateway: duplicate API key for user %q", uc.Name)
}
a.inline[entry.digest] = entry
a.byDigest[entry.digest] = entry
}
}
a.oidcInline = map[string]*oidcOverride{}
if cfg.Users != nil {
// buildUserSet rejects duplicate names within the inline source only;
// a file user may still override an inline user of the same name
// (replaceFileUsers).
set, err := a.buildUserSet(cfg.Users.Inline)
if err != nil {
return nil, err
}
for digest, entry := range set.keyed {
a.inline[digest] = entry
a.byDigest[digest] = entry
}
a.oidcInline = set.overrides
}
a.oidcOverrides = a.oidcInline
return a, nil
}
@@ -1017,11 +1043,8 @@ func (a *authStore) buildEntry(uc *UserConfig) (*authEntry, error) {
if uc == nil {
return nil, fmt.Errorf("llmgateway: user config entry must not be nil")
}
if uc.Name == "" {
return nil, fmt.Errorf("llmgateway: user config entry must have a non-empty name")
}
if a.anonymous != nil && uc.Name == anonymousUserName {
return nil, fmt.Errorf("llmgateway: user name %q is reserved while users.anonymousGroup is set", uc.Name)
if err := a.checkUserName(uc.Name); err != nil {
return nil, err
}
groupNames := effectiveGroupNames(uc.Group, uc.Groups)
if len(groupNames) == 0 {
@@ -1106,43 +1129,39 @@ func (a *authStore) replaceFileUsers(us []*UserConfig) error {
a.buildMu.Lock()
defer a.buildMu.Unlock()
fileNames := make(map[string]bool, len(us))
for _, uc := range us {
if uc != nil {
fileNames[uc.Name] = true
}
// buildUserSet rejects duplicate names within the file only: a file user
// overriding an inline user of the same name is intended (doc above).
set, err := a.buildUserSet(us)
if err != nil {
return err
}
next := make(map[[32]byte]*authEntry, len(a.inline)+len(us))
next := make(map[[32]byte]*authEntry, len(a.inline)+len(set.keyed))
for digest, entry := range a.inline {
if fileNames[entry.user.name] {
if set.names[entry.user.name] {
continue // a file user of the same name overrides this inline user
}
next[digest] = entry
}
// seenFileNames rejects two FILE users sharing the same name (security
// audit finding 5, 2026-08-22) — scoped to this call's own us slice
// only, never checked against a.inline: a file user overriding an
// inline user of the same name is this function's own documented,
// intentional behavior (doc comment above), not a duplicate.
seenFileNames := make(map[string]bool, len(us))
for _, uc := range us {
entry, err := a.buildEntry(uc)
if err != nil {
return err
for digest, entry := range set.keyed {
if _, exists := next[digest]; exists {
return fmt.Errorf("llmgateway: duplicate API key for user %q", entry.user.name)
}
if seenFileNames[entry.user.name] {
return fmt.Errorf("llmgateway: duplicate user name %q", entry.user.name)
next[digest] = entry
}
overrides := make(map[string]*oidcOverride, len(a.oidcInline)+len(set.overrides))
for identity, ov := range a.oidcInline {
if _, replaced := set.overrides[identity]; replaced || set.names[ov.name] {
continue
}
seenFileNames[entry.user.name] = true
if _, exists := next[entry.digest]; exists {
return fmt.Errorf("llmgateway: duplicate API key for user %q", uc.Name)
}
next[entry.digest] = entry
overrides[identity] = ov
}
for identity, ov := range set.overrides {
overrides[identity] = ov
}
a.mu.Lock()
a.byDigest = next
a.oidcOverrides = overrides
a.fileUserCount = len(us)
a.mu.Unlock()
return nil
@@ -1281,19 +1300,56 @@ func (a *authStore) shouldLogThrottleEngaged() (log bool, suppressed int64) {
// — there is no separate secret-bytes compare here for a non-constant-time
// implementation to leak timing from).
func (a *authStore) identify(r *http.Request) (*user, *group, bool) {
if a.anonymous == nil {
return a.identifyKeyed(r)
}
u, g, st := a.authenticate(r)
return u, g, st == authOK
}
// authenticate resolves r to a principal: a configured key first, then an
// OIDC bearer token, then the anonymous fallbacks. A valid OIDC token with
// no mapped group is authForbidden and never falls back to anonymous.
func (a *authStore) authenticate(r *http.Request) (*user, *group, authStatus) {
u, g, st, _ := a.authenticateDetail(r)
return u, g, st
}
// authenticateDetail is authenticate plus the OIDC refusal reason, which
// is safe to log.
func (a *authStore) authenticateDetail(r *http.Request) (*user, *group, authStatus, string) {
if !hasCredentialHeader(r.Header) {
return a.anonymous.user, a.anonymous.group, true
}
if !a.anonymousAnyKey {
return a.identifyKeyed(r)
if a.anonymous != nil {
return a.anonymous.user, a.anonymous.group, authOK, ""
}
a.recordAuthFailure(clientIP(r))
return nil, nil, authUnauthorized, ""
}
if entry, ok := a.lookupKey(r); ok {
return entry.user, entry.group, true
return entry.user, entry.group, authOK, ""
}
return a.anonymous.user, a.anonymous.group, true
var reason string
if token, ok := bearerToken(r.Header); ok && a.oidcAuth != nil {
a.mu.RLock()
overrides := a.oidcOverrides
a.mu.RUnlock()
var (
entry *authEntry
st authStatus
)
entry, st, reason = a.oidcAuth.authenticate(r.Context(), token, overrides)
switch st {
case authOK:
if a.oidcRegistry != nil {
a.oidcRegistry.touch(entry.user.name, entry.user.oidcIdentity, entry.user.groupNames)
}
return entry.user, entry.group, authOK, ""
case authForbidden:
return nil, nil, authForbidden, reason
}
}
if a.anonymous != nil && a.anonymousAnyKey {
return a.anonymous.user, a.anonymous.group, authOK, ""
}
a.recordAuthFailure(clientIP(r))
return nil, nil, authUnauthorized, reason
}
// identifyKeyed is identify without the anonymous fallback: the request
@@ -1353,6 +1409,17 @@ func (a *authStore) anonymousEntry(groupName string) (*authEntry, error) {
}, nil
}
// bearerToken returns the Authorization Bearer credential only: an OIDC
// token never arrives in x-api-key.
func bearerToken(h http.Header) (string, bool) {
scheme, rest, found := strings.Cut(h.Get("Authorization"), " ")
if !found || !strings.EqualFold(scheme, "bearer") {
return "", false
}
token := strings.TrimSpace(rest)
return token, token != ""
}
// presentedKey extracts the API key from r's Authorization Bearer header or
// its x-api-key header. Bearer takes priority when both are set.
func presentedKey(r *http.Request) (string, bool) {
@@ -1476,6 +1543,17 @@ func (a *authStore) snapshot() ([]userSummary, []groupSummary) {
}
}
a.mu.RUnlock()
// oidcSummaries takes a.mu itself, so it runs after the unlock.
listed := make(map[string]bool, len(users))
for _, u := range users {
listed[u.name] = true
}
for _, s := range a.oidcSummaries(listed) {
users = append(users, s)
for _, name := range s.groups {
memberCounts[name]++
}
}
sort.Slice(users, func(i, j int) bool { return users[i].name < users[j].name })
groups := make([]groupSummary, 0, len(a.groups))
+244
View File
@@ -0,0 +1,244 @@
package traefikllmgateway
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// oidcGatewayFixture is a Gateway with OIDC on, a fake IdP and a fake
// OpenAI-compatible upstream that answers every chat call.
type oidcGatewayFixture struct {
idp *fakeIDP
gw *Gateway
h http.Handler
cfg *Config
}
// jwtShapedStaticKey is a configured API key that parses as a JWT header,
// to prove a static key wins before any OIDC check.
var jwtShapedStaticKey = b64([]byte(`{"alg":"RS256","kid":"rsa"}`)) + ".c3RhdGlj.a2V5"
func oidcGatewayConfig(issuer, upstream string) *Config {
cfg := CreateConfig()
cfg.Admin = &AdminConfig{Enabled: true}
cfg.Providers = map[string]*ProviderConfig{
"openai": {Type: "openai", BaseURL: upstream, APIKey: "sk-up", Models: []string{"gpt-test"}},
}
cfg.Groups = map[string]*GroupConfig{"default": {MemberLimits: &LimitsConfig{RequestsPerMinute: 50}}}
cfg.Users = &UsersConfig{Inline: []*UserConfig{
{Name: "admin1", Group: "default", APIKey: "sk-admin1", Admin: true},
{Name: "dotted", Group: "default", APIKey: jwtShapedStaticKey},
}}
cfg.OIDC = &OIDCConfig{
Issuer: issuer,
Audiences: []string{"openwebui"},
GroupClaim: "groups",
GroupMap: map[string]string{"llm-users": "default"},
}
return cfg
}
func newOIDCGateway(t *testing.T, mutate func(cfg *Config)) *oidcGatewayFixture {
t.Helper()
idp := newFakeIDP(t)
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"id":"c1","object":"chat.completion","model":"gpt-test","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5}}`))
}))
t.Cleanup(upstream.Close)
cfg := oidcGatewayConfig(idp.srv.URL, upstream.URL)
if mutate != nil {
mutate(cfg)
}
h, gw := newAdminGatewayHandle(t, cfg)
return &oidcGatewayFixture{idp: idp, gw: gw, h: h, cfg: cfg}
}
func (fx *oidcGatewayFixture) token(t *testing.T, mutate func(c map[string]any)) string {
t.Helper()
c := baseClaims(fx.gw.auth.nowFn())
c["iss"] = fx.idp.srv.URL
if mutate != nil {
mutate(c)
}
return signTestJWT(t, "RS256", "rsa", oidcKeys(t), nil, c)
}
func (fx *oidcGatewayFixture) chat(t *testing.T, bearer string) *httptest.ResponseRecorder {
t.Helper()
body := map[string]any{"model": "gpt-test", "messages": []any{map[string]any{"role": "user", "content": "hi"}}}
rec := httptest.NewRecorder()
fx.h.ServeHTTP(rec, newUnifiedRequest(t, http.MethodPost, "/v1/chat/completions", bearer, body))
return rec
}
func (fx *oidcGatewayFixture) userRequests(name string) int64 {
u := fx.gw.limiter.currentUsage([]limitScope{{kind: "user", id: name}})
return u[0].requestsPerDay
}
func TestIdentify_StaticKeyBeatsOIDC(t *testing.T) {
fx := newOIDCGateway(t, nil)
if !looksLikeJWT(jwtShapedStaticKey) {
t.Fatal("fixture must look like a JWT")
}
rec := fx.chat(t, jwtShapedStaticKey)
if rec.Code != http.StatusOK {
t.Fatalf("status %d body %s", rec.Code, rec.Body.String())
}
if fx.userRequests("dotted") != 1 {
t.Fatal("request must be accounted to the keyed user")
}
if d, j := fx.idp.discoveryHits.Load(), fx.idp.jwksHits.Load(); d != 0 || j != 0 {
t.Fatalf("IdP hits discovery %d jwks %d, want 0", d, j)
}
}
func TestOIDC_ChatCompletionAccounted(t *testing.T) {
fx := newOIDCGateway(t, nil)
rec := fx.chat(t, fx.token(t, nil))
if rec.Code != http.StatusOK {
t.Fatalf("status %d body %s", rec.Code, rec.Body.String())
}
if got := fx.userRequests("oidc:[email protected]"); got != 1 {
t.Fatalf("user requests = %d, want 1", got)
}
}
func TestOIDC_Models(t *testing.T) {
fx := newOIDCGateway(t, nil)
rec := httptest.NewRecorder()
fx.h.ServeHTTP(rec, adminRequest(http.MethodGet, "/v1/models", fx.token(t, nil)))
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "gpt-test") {
t.Fatalf("status %d body %s", rec.Code, rec.Body.String())
}
}
func TestOIDC_NoGroup403(t *testing.T) {
fx := newOIDCGateway(t, nil)
tok := fx.token(t, func(c map[string]any) { c["groups"] = []string{"other"} })
rec := fx.chat(t, tok)
if rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), `"permission_error"`) {
t.Fatalf("status %d body %s", rec.Code, rec.Body.String())
}
body := map[string]any{"model": "gpt-test", "max_tokens": 5, "messages": []any{map[string]any{"role": "user", "content": "hi"}}}
rec = httptest.NewRecorder()
fx.h.ServeHTTP(rec, newUnifiedRequest(t, http.MethodPost, messagesPath, tok, body))
if rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), `"type":"error"`) {
t.Fatalf("messages: status %d body %s", rec.Code, rec.Body.String())
}
if n := fx.gw.auth.failures.get("192.0.2.1"); n != 0 {
t.Fatalf("a valid identity without a group is not an auth failure; failures = %d", n)
}
}
func TestOIDC_InvalidToken401(t *testing.T) {
fx := newOIDCGateway(t, nil)
tok := fx.token(t, func(c map[string]any) { c["aud"] = "someone-else" })
rec := fx.chat(t, tok)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("status %d", rec.Code)
}
if n := fx.gw.auth.failures.get("192.0.2.1"); n != 1 {
t.Fatalf("auth failures = %d, want 1", n)
}
}
func TestOIDC_AdminRejected(t *testing.T) {
fx := newOIDCGateway(t, nil)
rec := httptest.NewRecorder()
fx.h.ServeHTTP(rec, adminRequest(http.MethodGet, adminUsagePath, fx.token(t, nil)))
if rec.Code != http.StatusUnauthorized {
t.Fatalf("status %d, want 401", rec.Code)
}
}
func TestOIDC_OverrideReload(t *testing.T) {
fx := newOIDCGateway(t, nil)
tok := fx.token(t, nil)
if err := fx.gw.auth.replaceFileUsers([]*UserConfig{{Name: "alice", OIDCIdentity: "[email protected]", Limits: &LimitsConfig{RequestsPerMinute: 5}}}); err != nil {
t.Fatal(err)
}
u, _, st := fx.gw.auth.authenticate(adminRequest(http.MethodPost, "/v1/chat/completions", tok))
if st != authOK || u.name != "alice" || u.limits.RequestsPerMinute != 5 {
t.Fatalf("status %v user %+v", st, u)
}
if err := fx.gw.auth.replaceFileUsers([]*UserConfig{{Name: "alice", OIDCIdentity: "[email protected]", Limits: &LimitsConfig{RequestsPerMinute: 9}}}); err != nil {
t.Fatal(err)
}
u, _, st = fx.gw.auth.authenticate(adminRequest(http.MethodPost, "/v1/chat/completions", tok))
if st != authOK || u.limits.RequestsPerMinute != 9 {
t.Fatalf("status %v limits %+v, want the reloaded override", st, u.limits)
}
if err := fx.gw.auth.replaceFileUsers(nil); err != nil {
t.Fatal(err)
}
u, _, _ = fx.gw.auth.authenticate(adminRequest(http.MethodPost, "/v1/chat/completions", tok))
if u.name != "oidc:[email protected]" || u.limits.RequestsPerMinute != 50 {
t.Fatalf("removed override must fall back: %+v", u)
}
}
func TestIdentify_OIDCWithAnonymous(t *testing.T) {
anonGroup := func(anyKey bool) func(cfg *Config) {
return func(cfg *Config) {
cfg.Groups["public"] = &GroupConfig{}
cfg.Users.AnonymousGroup = "public"
cfg.Users.AnonymousAcceptAnyKey = anyKey
}
}
fx := newOIDCGateway(t, anonGroup(false))
cases := []struct {
name string
bearer string
want string
status authStatus
}{
{name: "valid token", bearer: fx.token(t, nil), want: "oidc:[email protected]", status: authOK},
{name: "bad token", bearer: fx.token(t, func(c map[string]any) { c["iss"] = "https://evil" }), status: authUnauthorized},
{name: "no header", want: anonymousUserName, status: authOK},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
u, _, st := fx.gw.auth.authenticate(adminRequest(http.MethodPost, "/v1/chat/completions", tc.bearer))
if st != tc.status || (st == authOK && u.name != tc.want) {
t.Fatalf("status %v user %v", st, u)
}
})
}
fx = newOIDCGateway(t, anonGroup(true))
u, _, st := fx.gw.auth.authenticate(adminRequest(http.MethodPost, "/v1/chat/completions", fx.token(t, func(c map[string]any) { c["iss"] = "https://evil" })))
if st != authOK || u.name != anonymousUserName {
t.Fatalf("any-key anonymous must still take a bad token: %v %v", st, u)
}
u, _, st = fx.gw.auth.authenticate(adminRequest(http.MethodPost, "/v1/chat/completions", fx.token(t, func(c map[string]any) { c["groups"] = []string{"other"} })))
if st != authForbidden {
t.Fatalf("a valid token without a group is 403 even with any-key anonymous: %v %v", st, u)
}
}
func TestOIDC_Disabled(t *testing.T) {
fx := newOIDCGateway(t, func(cfg *Config) { cfg.OIDC = nil })
rec := fx.chat(t, fx.token(t, nil))
if rec.Code != http.StatusUnauthorized {
t.Fatalf("status %d, want 401", rec.Code)
}
if d := fx.idp.discoveryHits.Load(); d != 0 {
t.Fatalf("discovery hits = %d, want 0", d)
}
}
func TestOIDC_XAPIKeyNotTreatedAsToken(t *testing.T) {
fx := newOIDCGateway(t, nil)
req := httptest.NewRequest(http.MethodGet, "/v1/models", nil)
req.Header.Set("x-api-key", fx.token(t, nil))
if _, _, st := fx.gw.auth.authenticate(req); st != authUnauthorized {
t.Fatalf("status %v, want 401 for a JWT in x-api-key", st)
}
if d := fx.idp.discoveryHits.Load(); d != 0 {
t.Fatalf("discovery hits = %d, want 0", d)
}
}
+23
View File
@@ -0,0 +1,23 @@
package traefikllmgateway
import "net/http"
// requireAuth authenticates r, logs the outcome and, on refusal, writes the
// 401 or 403 in the route's error shape (Anthropic when anthropic is true).
func (g *Gateway) requireAuth(w http.ResponseWriter, r *http.Request, anthropic bool) (*user, *group, bool) {
u, grp, st, reason := g.auth.authenticateDetail(r)
g.logAuthEvent(st == authOK, authEventUserName(u), r, reason)
write := writeOAIError
if anthropic {
write = writeAnthropicError
}
switch st {
case authOK:
return u, grp, true
case authForbidden:
write(w, http.StatusForbidden, "permission_error", "token has no group mapped for this gateway")
default:
write(w, http.StatusUnauthorized, "authentication_error", "invalid or missing API key")
}
return nil, nil, false
}
+22 -27
View File
@@ -49,7 +49,10 @@ type Config struct {
MCPServers map[string]*TargetConfig `json:"mcpServers,omitempty"`
Agents map[string]*AgentConfig `json:"agents,omitempty"`
Users *UsersConfig `json:"users,omitempty"`
Groups map[string]*GroupConfig `json:"groups,omitempty"`
// OIDC admits verified OIDC bearer tokens as per-identity virtual users
// (oidc_config.go). Nil keeps every route key-only.
OIDC *OIDCConfig `json:"oidc,omitempty"`
Groups map[string]*GroupConfig `json:"groups,omitempty"`
// ModelAliases maps an operator-defined alias id to a target model id
// (spec §5, v0.2) — e.g. {"aliased/coding": "anthropic/claude-sonnet-4-5"}.
// An exact alias match wins resolution before any other rule
@@ -422,6 +425,10 @@ type UserConfig struct {
// (effectiveGroup's own back-compat rule, auth.go).
Groups []string `json:"groups,omitempty"`
APIKey string `json:"apiKey"`
// OIDCIdentity turns this entry into a per-user override for the OIDC
// virtual user with that identity: only Name and Limits apply, and the
// token's group mapping decides membership.
OIDCIdentity string `json:"oidcIdentity,omitempty"`
// Providers and Models together describe this user's own PERSONAL
// grant — access beyond whatever their member group(s) already allow,
// with the identical glob semantics a group's own Providers/Models
@@ -1221,6 +1228,10 @@ func newGateway(ctx context.Context, next http.Handler, config *Config, name str
// providerAttemptSpawnCap semaphore) rather than a second one, so an
// event-feed write storm and a provider-attempt write storm compete
// for the identical bounded pool instead of two independent ones.
if redisClient != nil && auth.oidcAuth != nil {
// spawn reads lim.spawn per call, so a later swap of it applies.
auth.oidcRegistry = newOIDCRegistry(redisClient, func() time.Time { return auth.nowFn() }, func(f func()) { lim.spawn(f) }, g.errorf, 4*auth.oidc.maxUsers)
}
g.events = &eventLog{
ring: &eventRing{},
client: redisClient,
@@ -1511,10 +1522,8 @@ func (g *Gateway) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
if r.Method == http.MethodPost && (r.URL.Path == "/v1/chat/completions" || r.URL.Path == "/v1/embeddings") {
u, grp, ok := g.auth.identify(r)
g.logAuthEvent(ok, authEventUserName(u), r)
u, grp, ok := g.requireAuth(sw, r, false)
if !ok {
writeOAIError(sw, http.StatusUnauthorized, "authentication_error", "invalid or missing API key")
return
}
if r.URL.Path == "/v1/chat/completions" {
@@ -1534,10 +1543,8 @@ func (g *Gateway) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// makes. A failed auth gets the Anthropic error shape
// (writeAnthropicError, routes_messages.go), not writeOAIError's
// — the one thing that differs from every route above.
u, grp, ok := g.auth.identify(r)
g.logAuthEvent(ok, authEventUserName(u), r)
u, grp, ok := g.requireAuth(sw, r, true)
if !ok {
writeAnthropicError(sw, http.StatusUnauthorized, "authentication_error", "invalid or missing API key")
return
}
g.handleMessages(sw, r, u, grp)
@@ -1545,10 +1552,8 @@ func (g *Gateway) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
if r.Method == http.MethodPost && (r.URL.Path == imagesGenerationsPath || r.URL.Path == audioSpeechPath || r.URL.Path == audioTranscriptionsPath) {
u, grp, ok := g.auth.identify(r)
g.logAuthEvent(ok, authEventUserName(u), r)
u, grp, ok := g.requireAuth(sw, r, false)
if !ok {
writeOAIError(sw, http.StatusUnauthorized, "authentication_error", "invalid or missing API key")
return
}
switch r.URL.Path {
@@ -1581,10 +1586,8 @@ func (g *Gateway) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
if r.Method == http.MethodGet && (r.URL.Path == "/v1/mcp/servers" || r.URL.Path == "/v1/agents") {
u, grp, ok := g.auth.identify(r)
g.logAuthEvent(ok, authEventUserName(u), r)
_, grp, ok := g.requireAuth(sw, r, false)
if !ok {
writeOAIError(sw, http.StatusUnauthorized, "authentication_error", "invalid or missing API key")
return
}
if r.URL.Path == "/v1/mcp/servers" {
@@ -1617,10 +1620,8 @@ func (g *Gateway) ServeHTTP(w http.ResponseWriter, r *http.Request) {
writeOAIError(sw, http.StatusMethodNotAllowed, "invalid_request_error", "method not allowed")
return
}
u, grp, ok := g.auth.identify(r)
g.logAuthEvent(ok, authEventUserName(u), r)
u, grp, ok := g.requireAuth(sw, r, false)
if !ok {
writeOAIError(sw, http.StatusUnauthorized, "authentication_error", "invalid or missing API key")
return
}
g.handleMCPFederated(sw, r, u, grp)
@@ -1628,20 +1629,16 @@ func (g *Gateway) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
if name, rest, ok := targetRoute(r.URL.EscapedPath(), targetKindMCP); ok {
u, grp, authOK := g.auth.identify(r)
g.logAuthEvent(authOK, authEventUserName(u), r)
if !authOK {
writeOAIError(sw, http.StatusUnauthorized, "authentication_error", "invalid or missing API key")
u, grp, authed := g.requireAuth(sw, r, false)
if !authed {
return
}
g.handleTargetProxy(sw, r, u, grp, targetKindMCP, name, rest)
return
}
if name, rest, ok := targetRoute(r.URL.EscapedPath(), targetKindAgent); ok {
u, grp, authOK := g.auth.identify(r)
g.logAuthEvent(authOK, authEventUserName(u), r)
if !authOK {
writeOAIError(sw, http.StatusUnauthorized, "authentication_error", "invalid or missing API key")
u, grp, authed := g.requireAuth(sw, r, false)
if !authed {
return
}
g.handleTargetProxy(sw, r, u, grp, targetKindAgent, name, rest)
@@ -1655,10 +1652,8 @@ func (g *Gateway) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// request falls through to the same unknown-route 404 below,
// without even reaching auth.identify.
if _, known := g.adapters[providerName]; known && providerPassthroughEnabled(g.cfg, providerName) {
u, grp, ok := g.auth.identify(r)
g.logAuthEvent(ok, authEventUserName(u), r)
u, grp, ok := g.requireAuth(sw, r, false)
if !ok {
writeOAIError(sw, http.StatusUnauthorized, "authentication_error", "invalid or missing API key")
return
}
g.handlePassthrough(sw, r, u, grp, providerName, rest)
+7 -2
View File
@@ -149,7 +149,9 @@ func (g *Gateway) pricingWarn(msg string) {
// appends that count to the line when non-zero. The success line stays
// completely unbounded — see shouldLogAuthFailure's own doc comment for
// why that is safe.
func (g *Gateway) logAuthEvent(ok bool, userName string, r *http.Request) {
// detail, when non-empty, names why an OIDC token was refused; it never
// holds the token.
func (g *Gateway) logAuthEvent(ok bool, userName string, r *http.Request, detail string) {
if !ok {
ip := clientIP(r)
if g.auth.authThrottled(ip) {
@@ -159,7 +161,10 @@ func (g *Gateway) logAuthEvent(ok bool, userName string, r *http.Request) {
return
}
if log, suppressed := g.auth.shouldLogAuthFailure(); log {
g.logf("auth failed: %s %q from %s%s", r.Method, r.URL.Path, r.RemoteAddr, suppressedSuffix(suppressed))
if detail != "" {
detail = " (oidc: " + detail + ")"
}
g.logf("auth failed: %s %q from %s%s%s", r.Method, r.URL.Path, r.RemoteAddr, detail, suppressedSuffix(suppressed))
}
return
}
+9 -9
View File
@@ -70,7 +70,7 @@ func TestLogAuthEvent_Failure_RateLimited(t *testing.T) {
out := captureStderr(t, func() {
for i := 0; i < 5; i++ {
gw.logAuthEvent(false, "", r)
gw.logAuthEvent(false, "", r, "")
}
})
@@ -91,9 +91,9 @@ func TestLogAuthEvent_Failure_LogsAgainAfterIntervalElapses(t *testing.T) {
r.RemoteAddr = "203.0.113.9:1234"
out := captureStderr(t, func() {
gw.logAuthEvent(false, "", r)
gw.logAuthEvent(false, "", r, "")
clock.Advance(authFailureLogEvery + time.Second)
gw.logAuthEvent(false, "", r)
gw.logAuthEvent(false, "", r, "")
})
if n := strings.Count(out, "auth failed:"); n != 2 {
@@ -115,7 +115,7 @@ func TestLogAuthEvent_Success_NeverRateLimited(t *testing.T) {
out := captureStderr(t, func() {
for i := 0; i < 5; i++ {
gw.logAuthEvent(true, "alice", r)
gw.logAuthEvent(true, "alice", r, "")
}
})
@@ -141,7 +141,7 @@ func TestLogAuthEvent_ThrottleEngaged_DistinctLine(t *testing.T) {
}
out := captureStderr(t, func() {
gw.logAuthEvent(false, "", r)
gw.logAuthEvent(false, "", r, "")
})
if !strings.Contains(out, "auth throttle:") {
@@ -167,14 +167,14 @@ func TestLogAuthEvent_Failure_SuppressedCountReported(t *testing.T) {
r.RemoteAddr = "203.0.113.9:1234"
captureStderr(t, func() {
gw.logAuthEvent(false, "", r) // logged (first call on a fresh gate)
gw.logAuthEvent(false, "", r) // suppressed #1
gw.logAuthEvent(false, "", r) // suppressed #2
gw.logAuthEvent(false, "", r, "") // logged (first call on a fresh gate)
gw.logAuthEvent(false, "", r, "") // suppressed #1
gw.logAuthEvent(false, "", r, "") // suppressed #2
})
clock.Advance(authFailureLogEvery + time.Second)
out := captureStderr(t, func() {
gw.logAuthEvent(false, "", r)
gw.logAuthEvent(false, "", r, "")
})
if !strings.Contains(out, "2 more suppressed since last log") {
+1 -1
View File
@@ -131,7 +131,7 @@ func (g *Gateway) handleMetrics(sw *statusTrackingWriter, r *http.Request) {
return
}
u, _, ok := g.auth.identifyKeyed(r)
g.logAuthEvent(ok, authEventUserName(u), r)
g.logAuthEvent(ok, authEventUserName(u), r, "")
if !ok {
writeOAIError(sw, http.StatusUnauthorized, "authentication_error", "invalid or missing API key")
return
+163
View File
@@ -0,0 +1,163 @@
package traefikllmgateway
import (
"context"
"strings"
"sync"
"testing"
"time"
)
func TestVerifyJWT_AcceptAzpOptIn(t *testing.T) {
k := oidcKeys(t)
set, err := parseJWKS(testJWKS(t, k))
if err != nil {
t.Fatal(err)
}
now := time.Unix(1_800_000_000, 0)
c := baseClaims(now)
c["aud"] = []string{"other-api"}
c["azp"] = "openwebui"
tok := signTestJWT(t, "RS256", "rsa", k, nil, c)
s := testSettings()
if _, err := verifyJWT(tok, set, s, now); err != errTokenAudience {
t.Fatalf("aud for another service with azp=openwebui: err = %v, want errTokenAudience", err)
}
s.acceptAzp = true
if _, err := verifyJWT(tok, set, s, now); err != nil {
t.Fatalf("acceptAzp opt-in: err = %v", err)
}
}
func TestOIDCConfig_AcceptAzp(t *testing.T) {
cfg := oidcAuthCfg()
cfg.OIDC.AcceptAzp = true
a, err := newAuthStore(cfg)
if err != nil {
t.Fatal(err)
}
if !a.oidc.acceptAzp {
t.Fatal("acceptAzp not carried into settings")
}
}
func TestAuthenticate_SingleFlightPerToken(t *testing.T) {
fx := opaqueFixture(t)
fx.idp.delay.Store(int64(100 * time.Millisecond))
const n = 20
var wg sync.WaitGroup
errs := make(chan string, n)
for i := 0; i < n; i++ {
wg.Add(1)
go func() {
defer wg.Done()
if _, st, reason := fx.auth.authenticate(context.Background(), "opaque-burst", nil); st != authOK {
errs <- reason
}
}()
}
wg.Wait()
close(errs)
for r := range errs {
t.Errorf("concurrent request refused: %q", r)
}
if h := fx.idp.userinfoHits.Load(); h != 1 {
t.Fatalf("userinfo hits = %d, want 1 for one token", h)
}
}
func TestProvider_UserinfoWaitsForSlot(t *testing.T) {
f := newFakeIDP(t)
f.userinfo.Store(map[string]any{"email": "[email protected]"})
p := newTestProvider(f, newFakeClock())
p.queueWait = 2 * time.Second
for i := 0; i < cap(p.userinfoSlots); i++ {
p.userinfoSlots <- struct{}{}
}
go func() {
time.Sleep(50 * time.Millisecond)
<-p.userinfoSlots
}()
if _, err := p.userinfo(context.Background(), "opaque"); err != nil {
t.Fatalf("a slot freed inside the wait must admit the call: %v", err)
}
}
func TestProvider_UserinfoSkipsFetchLockWhenDiscovered(t *testing.T) {
f := newFakeIDP(t)
f.userinfo.Store(map[string]any{"email": "[email protected]"})
p := newTestProvider(f, newFakeClock())
if _, err := p.userinfo(context.Background(), "opaque"); err != nil {
t.Fatal(err)
}
p.fetchMu.Lock()
defer p.fetchMu.Unlock()
done := make(chan error, 1)
go func() {
_, err := p.userinfo(context.Background(), "opaque")
done <- err
}()
select {
case err := <-done:
if err != nil {
t.Fatal(err)
}
case <-time.After(2 * time.Second):
t.Fatal("userinfo waited on fetchMu although discovery was cached")
}
}
func TestProvider_RefusesRedirect(t *testing.T) {
f := newFakeIDP(t)
f.jwksURI.Store(f.srv.URL + "/redirect-jwks")
if _, err := newTestProvider(f, newFakeClock()).keysFor("rsa"); err == nil {
t.Fatal("a redirected JWKS fetch must fail")
}
if h := f.jwksHits.Load(); h != 0 {
t.Fatalf("redirect was followed: jwks hits = %d", h)
}
}
func TestAuthenticate_TokenTooLarge(t *testing.T) {
fx := opaqueFixture(t)
_, st, reason := fx.run(t, strings.Repeat("a", oidcMaxTokenBytes+1), nil)
if st != authUnauthorized || reason != oidcReasonTokenTooLarge {
t.Fatalf("%v %q", st, reason)
}
if h := fx.idp.userinfoHits.Load() + fx.idp.discoveryHits.Load(); h != 0 {
t.Fatalf("oversized token reached the IdP: %d calls", h)
}
if _, st, _ := fx.run(t, strings.Repeat("a", oidcMaxTokenBytes), nil); st != authOK {
t.Fatalf("a token at the cap must be verified: %v", st)
}
}
func TestAuthenticate_IdentityTooLong(t *testing.T) {
fx := newAuthFixture(t, nil)
long := strings.Repeat("a", oidcMaxIdentityBytes-5) + "@x.com"
_, st, reason := fx.run(t, fx.token(t, func(c map[string]any) { c["email"] = long }), nil)
if st != authUnauthorized || reason != oidcReasonIdentityTooLong {
t.Fatalf("%v %q", st, reason)
}
}
func TestNormalizeIdentity_ASCIIFoldOnly(t *testing.T) {
tests := []struct{ raw, want string }{
{raw: " [email protected] ", want: "[email protected]"},
{raw: "K[email protected]", want: "K[email protected]"},
{raw: "É[email protected]", want: "É[email protected]"},
}
for _, tc := range tests {
if got := normalizeIdentity("email", tc.raw); got != tc.want {
t.Errorf("normalizeIdentity(%q) = %q, want %q", tc.raw, got, tc.want)
}
}
}
// TestOIDCAuditConstants pins the values that formal/Gateway/OidcHardening.lean
// (maxToken, maxIdentity) and the README state.
func TestOIDCAuditConstants(t *testing.T) {
if oidcMaxTokenBytes != 16384 || oidcMaxIdentityBytes != 256 || oidcUserinfoMaxInFlight != 16 || oidcUserinfoQueueWait != 2*time.Second {
t.Fatal("constant drifted from the Lean model and README")
}
}
+427
View File
@@ -0,0 +1,427 @@
package traefikllmgateway
import (
"container/list"
"context"
"crypto/sha256"
"errors"
"sort"
"strconv"
"strings"
"sync"
"time"
)
// authStatus is the outcome of authenticating one request.
type authStatus int
const (
authOK authStatus = iota
authUnauthorized
authForbidden
)
// oidcNegativeTTL holds a rejected token's verdict, so a garbage bearer
// cannot turn every request into an IdP call.
const oidcNegativeTTL = 30 * time.Second
const (
// oidcMaxTokenBytes caps a bearer before any parse or IdP call.
oidcMaxTokenBytes = 16384
// oidcMaxIdentityBytes caps the identity that becomes a Redis field,
// a metric label and a log value.
oidcMaxIdentityBytes = 256
)
// Reasons logged for an OIDC verdict. They never contain the token.
const (
oidcReasonTokenTooLarge = "token_too_large"
oidcReasonIdentityTooLong = "identity_too_long"
oidcReasonNoGroup = "no_group"
oidcReasonNoIdentity = "no_identity"
oidcReasonOpaqueDisabled = "opaque_disabled"
oidcReasonUserinfo = "userinfo_rejected"
oidcReasonIDPUnavailable = "idp_unavailable"
oidcReasonEmailUnverified = "email_unverified"
)
// oidcCall is one verification in flight; waiters read slot after done.
type oidcCall struct {
done chan struct{}
slot *oidcSlot
cacheable bool
}
// oidcSlot is one entry of an oidcAuthenticator cache. A token slot holds a
// verdict (identity and mapped groups, or a negative reason) until expires;
// a user slot holds the virtual principal built for an identity.
type oidcSlot struct {
expires time.Time
entry *authEntry
override *oidcOverride
identity string
groupsKey string
reason string
groups []string
status authStatus
}
// lruCache is a size-bounded map with least-recently-used eviction. The
// caller serializes access.
type lruCache struct {
ll *list.List
items map[string]*list.Element
max int
}
type lruItem struct {
slot *oidcSlot
key string
}
func newLRU(maxEntries int) *lruCache {
return &lruCache{ll: list.New(), items: make(map[string]*list.Element), max: maxEntries}
}
func (c *lruCache) get(key string) (*oidcSlot, bool) {
el, ok := c.items[key]
if !ok {
return nil, false
}
c.ll.MoveToFront(el)
return el.Value.(*lruItem).slot, true
}
func (c *lruCache) put(key string, slot *oidcSlot) {
if el, ok := c.items[key]; ok {
el.Value.(*lruItem).slot = slot
c.ll.MoveToFront(el)
return
}
c.items[key] = c.ll.PushFront(&lruItem{key: key, slot: slot})
for c.ll.Len() > c.max {
oldest := c.ll.Back()
c.ll.Remove(oldest)
delete(c.items, oldest.Value.(*lruItem).key)
}
}
func (c *lruCache) remove(key string) {
if el, ok := c.items[key]; ok {
c.ll.Remove(el)
delete(c.items, key)
}
}
// slots returns every slot, most recently used first.
func (c *lruCache) slots() []*oidcSlot {
out := make([]*oidcSlot, 0, c.ll.Len())
for el := c.ll.Front(); el != nil; el = el.Next() {
out = append(out, el.Value.(*lruItem).slot)
}
return out
}
// oidcAuthenticator turns a bearer token into a virtual user.
type oidcAuthenticator struct {
now func() time.Time
settings *oidcSettings
provider *oidcProvider
groups map[string]*group
// tokens holds verified tokens; rejects holds refused ones apart, so a
// flood of bad tokens cannot evict valid verdicts.
tokens *lruCache
rejects *lruCache
principals *lruCache
// calls holds the verification in flight per token digest, so a burst
// of one cold token makes one IdP call.
calls map[string]*oidcCall
// logf receives IdP failure causes; it never sees a token.
logf func(string)
logGate logGate
mu sync.Mutex
}
func newOIDCAuthenticator(s *oidcSettings, p *oidcProvider, groups map[string]*group, now func() time.Time) *oidcAuthenticator {
return &oidcAuthenticator{
now: now,
settings: s,
provider: p,
groups: groups,
tokens: newLRU(2 * s.maxUsers),
rejects: newLRU(s.maxUsers),
principals: newLRU(s.maxUsers),
calls: map[string]*oidcCall{},
logf: func(string) {},
}
}
// authenticate verifies token and returns its virtual user. overrides is the
// live per-identity override set; a changed override rebuilds the user. The
// reason names why a token was refused and is safe to log.
func (o *oidcAuthenticator) authenticate(ctx context.Context, token string, overrides map[string]*oidcOverride) (*authEntry, authStatus, string) {
if len(token) > oidcMaxTokenBytes {
return nil, authUnauthorized, oidcReasonTokenTooLarge
}
digest := sha256.Sum256([]byte(token))
key := string(digest[:])
now := o.now()
o.mu.Lock()
for _, c := range []*lruCache{o.tokens, o.rejects} {
slot, ok := c.get(key)
if !ok {
continue
}
if now.Before(slot.expires) {
defer o.mu.Unlock()
if slot.status != authOK {
return nil, slot.status, slot.reason
}
return o.userFor(slot, overrides[slot.identity]), authOK, ""
}
c.remove(key)
}
call, waiting := o.calls[key]
if !waiting {
call = &oidcCall{done: make(chan struct{})}
o.calls[key] = call
}
o.mu.Unlock()
if waiting {
select {
case <-call.done:
case <-ctx.Done():
return nil, authUnauthorized, oidcReasonIDPUnavailable
}
} else {
// The verification serves every waiter, so no single caller's
// cancel may abort it; the provider bounds it with its own timeout.
call.slot, call.cacheable = o.verify(context.Background(), token, now)
}
slot := call.slot
o.mu.Lock()
defer o.mu.Unlock()
if !waiting {
delete(o.calls, key)
close(call.done)
if call.cacheable {
if slot.status == authOK {
o.tokens.put(key, slot)
} else {
o.rejects.put(key, slot)
}
}
}
if slot.status != authOK {
return nil, slot.status, slot.reason
}
return o.userFor(slot, overrides[slot.identity]), authOK, ""
}
// verify checks token at the IdP or locally and returns its verdict as a
// token slot. cacheable is false for an IdP outage and for an unknown kid,
// which must not pin a refusal on a valid token.
func (o *oidcAuthenticator) verify(ctx context.Context, token string, now time.Time) (*oidcSlot, bool) {
expires := now.Add(o.settings.cacheTTL)
var claims map[string]any
switch {
case looksLikeJWT(token):
kid, err := jwtKid(token)
if err != nil {
return o.refuse(authUnauthorized, oidcErrorReason(err), now), true
}
keys, err := o.provider.keysFor(kid)
if err != nil {
o.warn("oidc: signing keys unavailable: " + err.Error())
return o.refuse(authUnauthorized, oidcReasonIDPUnavailable, now), false
}
if claims, err = verifyJWT(token, keys, o.settings, now); err != nil {
// Keys can be stale during an IdP outage or the refetch
// throttle, so an unknown kid may be valid moments later.
return o.refuse(authUnauthorized, oidcErrorReason(err), now), !errors.Is(err, errTokenUnknownKid)
}
case o.settings.userinfo:
var err error
if claims, err = o.provider.userinfo(ctx, token); err != nil {
if errors.Is(err, errIDPRejected) {
return o.refuse(authUnauthorized, oidcReasonUserinfo, now), true
}
o.warn("oidc: userinfo unavailable: " + err.Error())
return o.refuse(authUnauthorized, oidcReasonIDPUnavailable, now), false
}
if o.settings.requireEmailVerified && !emailVerified(claims) {
return o.refuse(authUnauthorized, oidcReasonEmailUnverified, now), true
}
default:
return o.refuse(authUnauthorized, oidcReasonOpaqueDisabled, now), false
}
if exp, ok := numericClaim(claims, "exp"); ok {
if tokenExp := time.Unix(exp, 0); tokenExp.Before(expires) {
expires = tokenExp
}
}
raw, ok := claimString(claims, []string{o.settings.identityClaim})
identity := normalizeIdentity(o.settings.identityClaim, raw)
if !ok || identity == "" {
return o.refuse(authUnauthorized, oidcReasonNoIdentity, now), true
}
if len(identity) > oidcMaxIdentityBytes {
return o.refuse(authUnauthorized, oidcReasonIdentityTooLong, now), true
}
groups := o.mapGroups(claimStrings(claims, o.settings.groupClaim))
if len(groups) == 0 {
return o.refuse(authForbidden, oidcReasonNoGroup+" identity="+strconv.Quote(identity), now), true
}
return &oidcSlot{
expires: expires,
identity: identity,
groups: groups,
groupsKey: strings.Join(groups, ","),
status: authOK,
}, true
}
// warn logs an IdP failure cause, rate-gated so an outage cannot flood the
// log. msg never holds a token.
func (o *oidcAuthenticator) warn(msg string) {
if log, suppressed := o.logGate.shouldLog(o.now()); log {
o.logf(msg + suppressedSuffix(suppressed))
}
}
func (o *oidcAuthenticator) refuse(status authStatus, reason string, now time.Time) *oidcSlot {
return &oidcSlot{expires: now.Add(oidcNegativeTTL), status: status, reason: reason}
}
// mapGroups returns the sorted, de-duplicated gateway groups that values map to.
func (o *oidcAuthenticator) mapGroups(values []string) []string {
seen := make(map[string]bool, len(values))
var out []string
for _, v := range values {
g, ok := o.settings.groupMap[v]
if !ok || seen[g] {
continue
}
seen[g] = true
out = append(out, g)
}
sort.Strings(out)
return out
}
// userFor returns the cached virtual user for slot's identity, rebuilding it
// when its groups or its override changed. The caller holds mu.
func (o *oidcAuthenticator) userFor(slot *oidcSlot, ov *oidcOverride) *authEntry {
if u, ok := o.principals.get(slot.identity); ok && u.groupsKey == slot.groupsKey && u.override == ov {
return u.entry
}
members := make([]*group, len(slot.groups))
for i, name := range slot.groups {
members[i] = o.groups[name]
}
var own *LimitsConfig
name := oidcNamePrefix + slot.identity
if ov != nil {
own, name = ov.limits, ov.name
}
limits, sources := effectiveUserLimits(own, members)
entry := &authEntry{
user: &user{
limits: limits,
limitSources: sources,
groupNames: append([]string(nil), slot.groups...),
name: name,
groupName: slot.groups[0],
oidcIdentity: slot.identity,
},
group: effectiveGroup(members, nil),
}
o.principals.put(slot.identity, &oidcSlot{entry: entry, override: ov, identity: slot.identity, groupsKey: slot.groupsKey})
return entry
}
// users returns the cached virtual users, most recently used first.
func (o *oidcAuthenticator) users() []*authEntry {
o.mu.Lock()
defer o.mu.Unlock()
slots := o.principals.slots()
out := make([]*authEntry, len(slots))
for i, s := range slots {
out[i] = s.entry
}
return out
}
// oidcErrorReason maps a verification error to a log reason.
func oidcErrorReason(err error) string {
switch {
case errors.Is(err, errTokenExpired):
return "expired"
case errors.Is(err, errTokenNotYetValid):
return "not_yet_valid"
case errors.Is(err, errTokenBadSignature):
return "bad_sig"
case errors.Is(err, errTokenBadAlg):
return "bad_alg"
case errors.Is(err, errTokenIssuer):
return "issuer"
case errors.Is(err, errTokenAudience):
return "aud"
case errors.Is(err, errTokenUnknownKid):
return "unknown_kid"
case errors.Is(err, errEmailNotVerified):
return oidcReasonEmailUnverified
}
return "malformed"
}
// claimValue walks a dotted claim path through nested JSON objects.
func claimValue(claims map[string]any, path []string) (any, bool) {
var cur any = claims
for _, seg := range path {
m, ok := cur.(map[string]any)
if !ok {
return nil, false
}
if cur, ok = m[seg]; !ok {
return nil, false
}
}
return cur, true
}
// claimString returns the string at path.
func claimString(claims map[string]any, path []string) (string, bool) {
v, ok := claimValue(claims, path)
if !ok {
return "", false
}
s, ok := v.(string)
return s, ok
}
// claimStrings returns the string, or the strings of the array, at path.
// Non-string array members are skipped.
func claimStrings(claims map[string]any, path []string) []string {
v, ok := claimValue(claims, path)
if !ok {
return nil
}
switch t := v.(type) {
case string:
return []string{t}
case []any:
var out []string
for _, e := range t {
if s, ok := e.(string); ok {
out = append(out, s)
}
}
return out
}
return nil
}
+269
View File
@@ -0,0 +1,269 @@
package traefikllmgateway
import (
"context"
"fmt"
"net/http"
"reflect"
"strings"
"testing"
"time"
)
func oidcAuthTestGroups(t *testing.T) map[string]*group {
t.Helper()
a, err := newAuthStore(&Config{
Providers: map[string]*ProviderConfig{"openai": {Type: "openai", APIKey: "k"}},
Groups: map[string]*GroupConfig{
"staff": {MemberLimits: &LimitsConfig{RequestsPerMinute: 10, TokensPerDay: 500}},
"power": {MemberLimits: &LimitsConfig{RequestsPerMinute: 20}},
},
})
if err != nil {
t.Fatal(err)
}
return a.groups
}
type authFixture struct {
idp *fakeIDP
clock *fakeClock
auth *oidcAuthenticator
}
func newAuthFixture(t *testing.T, mutate func(s *oidcSettings)) *authFixture {
t.Helper()
f := newFakeIDP(t)
clock := newFakeClock()
s := f.settings()
s.groupMap = map[string]string{"llm-users": "staff", "llm-power": "power"}
if mutate != nil {
mutate(s)
}
p := newOIDCProvider(s, &http.Client{Timeout: 5 * time.Second}, clock.Now)
return &authFixture{idp: f, clock: clock, auth: newOIDCAuthenticator(s, p, oidcAuthTestGroups(t), clock.Now)}
}
func (fx *authFixture) token(t *testing.T, mutate func(c map[string]any)) string {
t.Helper()
c := baseClaims(fx.clock.Now())
c["iss"] = fx.idp.srv.URL
if mutate != nil {
mutate(c)
}
return signTestJWT(t, "RS256", "rsa", oidcKeys(t), nil, c)
}
func (fx *authFixture) run(t *testing.T, tok string, overrides map[string]*oidcOverride) (*authEntry, authStatus, string) {
t.Helper()
return fx.auth.authenticate(context.Background(), tok, overrides)
}
func TestClaims_GroupShapes(t *testing.T) {
tests := []struct {
mutateClaims func(c map[string]any)
name string
groupClaim []string
}{
{name: "string", groupClaim: []string{"groups"}, mutateClaims: func(c map[string]any) { c["groups"] = "llm-users" }},
{name: "array", groupClaim: []string{"groups"}, mutateClaims: func(c map[string]any) { c["groups"] = []string{"x", "llm-users"} }},
{name: "nested path", groupClaim: []string{"realm_access", "roles"}, mutateClaims: func(c map[string]any) {
delete(c, "groups")
c["realm_access"] = map[string]any{"roles": []string{"llm-users"}}
}},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
fx := newAuthFixture(t, func(s *oidcSettings) { s.groupClaim = tc.groupClaim })
entry, st, reason := fx.run(t, fx.token(t, tc.mutateClaims), nil)
if st != authOK {
t.Fatalf("status %v reason %q", st, reason)
}
if !reflect.DeepEqual(entry.user.groupNames, []string{"staff"}) {
t.Fatalf("groups = %v", entry.user.groupNames)
}
})
}
}
func TestClaimStrings_IgnoresNonStrings(t *testing.T) {
claims := map[string]any{"a": map[string]any{"b": []any{"x", 3.0, true, "y"}}, "n": 5.0}
if got := claimStrings(claims, []string{"a", "b"}); !reflect.DeepEqual(got, []string{"x", "y"}) {
t.Fatalf("claimStrings = %v", got)
}
if got := claimStrings(claims, []string{"a", "missing"}); got != nil {
t.Fatalf("missing path = %v", got)
}
if _, ok := claimString(claims, []string{"n"}); ok {
t.Fatal("a number is not an identity string")
}
}
func TestAuthenticate_NoMappedGroup(t *testing.T) {
fx := newAuthFixture(t, nil)
_, st, reason := fx.run(t, fx.token(t, func(c map[string]any) { c["groups"] = []string{"other"} }), nil)
if st != authForbidden || !strings.HasPrefix(reason, oidcReasonNoGroup) {
t.Fatalf("status %v reason %q", st, reason)
}
}
func TestAuthenticate_MultiGroup(t *testing.T) {
fx := newAuthFixture(t, nil)
entry, st, _ := fx.run(t, fx.token(t, func(c map[string]any) { c["groups"] = []string{"llm-users", "llm-power", "llm-users"} }), nil)
if st != authOK {
t.Fatal(st)
}
if !reflect.DeepEqual(entry.user.groupNames, []string{"power", "staff"}) {
t.Fatalf("groupNames = %v", entry.user.groupNames)
}
if entry.user.limits.RequestsPerMinute != 10 || entry.user.limits.TokensPerDay != 500 {
t.Fatalf("limits = %+v, want the per-field minimum", entry.user.limits)
}
}
func TestAuthenticate_VirtualName(t *testing.T) {
fx := newAuthFixture(t, nil)
tok := fx.token(t, nil)
entry, st, _ := fx.run(t, tok, nil)
if st != authOK || entry.user.name != "oidc:[email protected]" {
t.Fatalf("status %v name %q", st, entry.user.name)
}
if entry.digest != ([32]byte{}) {
t.Fatal("a virtual user must have no key digest")
}
overrides := map[string]*oidcOverride{"[email protected]": {name: "alice", limits: &LimitsConfig{RequestsPerMinute: 3}}}
entry, st, _ = fx.run(t, tok, overrides)
if st != authOK || entry.user.name != "alice" {
t.Fatalf("status %v name %q", st, entry.user.name)
}
if entry.user.limits.RequestsPerMinute != 3 || entry.user.limitSources["requestsPerMinute"] != "user" {
t.Fatalf("limits %+v sources %v", entry.user.limits, entry.user.limitSources)
}
if entry.user.limits.TokensPerDay != 500 {
t.Fatalf("unset override fields must fall back to memberLimits: %+v", entry.user.limits)
}
}
func TestAuthenticate_IdentityCaseFolded(t *testing.T) {
fx := newAuthFixture(t, nil)
overrides := map[string]*oidcOverride{"[email protected]": {name: "alice"}}
entry, st, _ := fx.run(t, fx.token(t, func(c map[string]any) { c["email"] = "[email protected]" }), overrides)
if st != authOK || entry.user.name != "alice" {
t.Fatalf("status %v name %q", st, entry.user.name)
}
}
func TestAuthenticate_MissingIdentityClaim(t *testing.T) {
fx := newAuthFixture(t, nil)
_, st, reason := fx.run(t, fx.token(t, func(c map[string]any) { delete(c, "email") }), nil)
if st != authUnauthorized || reason != "no_identity" {
t.Fatalf("status %v reason %q", st, reason)
}
}
func TestAuthenticate_InvalidTokenReasons(t *testing.T) {
fx := newAuthFixture(t, nil)
_, st, reason := fx.run(t, fx.token(t, func(c map[string]any) { c["aud"] = "other" }), nil)
if st != authUnauthorized || reason != "aud" {
t.Fatalf("status %v reason %q", st, reason)
}
_, st, reason = fx.run(t, fx.token(t, func(c map[string]any) { c["exp"] = fx.clock.Now().Add(-2 * time.Minute).Unix() }), nil)
if st != authUnauthorized || reason != "expired" {
t.Fatalf("status %v reason %q", st, reason)
}
}
func TestAuthenticate_TokenCacheHit(t *testing.T) {
fx := newAuthFixture(t, func(s *oidcSettings) { s.jwksRefresh = time.Minute })
tok := fx.token(t, nil)
if _, st, _ := fx.run(t, tok, nil); st != authOK {
t.Fatal(st)
}
// Rotate the IdP keys and let the JWKS go stale: only a cache hit can
// still admit the token without a JWKS fetch.
fx.idp.jwks.Store([]byte(`{"keys":[]}`))
fx.clock.Advance(2 * time.Minute)
if _, st, reason := fx.run(t, tok, nil); st != authOK {
t.Fatalf("cached token rejected: %v %q", st, reason)
}
if j := fx.idp.jwksHits.Load(); j != 1 {
t.Fatalf("jwks hits = %d, want 1", j)
}
}
func TestAuthenticate_CacheClampedToExp(t *testing.T) {
fx := newAuthFixture(t, nil)
tok := fx.token(t, func(c map[string]any) { c["exp"] = fx.clock.Now().Add(30 * time.Second).Unix() })
if _, st, _ := fx.run(t, tok, nil); st != authOK {
t.Fatal(st)
}
fx.clock.Advance(91 * time.Second)
if _, st, reason := fx.run(t, tok, nil); st != authUnauthorized || reason != "expired" {
t.Fatalf("status %v reason %q, want expired once past exp", st, reason)
}
}
func TestAuthenticate_NegativeCache(t *testing.T) {
fx := newAuthFixture(t, nil)
for range 2 {
if _, st, _ := fx.run(t, "opaque-garbage", nil); st != authUnauthorized {
t.Fatal(st)
}
}
if h := fx.idp.userinfoHits.Load(); h != 1 {
t.Fatalf("userinfo hits = %d, want 1 within the negative TTL", h)
}
fx.clock.Advance(31 * time.Second)
if _, st, _ := fx.run(t, "opaque-garbage", nil); st != authUnauthorized {
t.Fatal(st)
}
if h := fx.idp.userinfoHits.Load(); h != 2 {
t.Fatalf("userinfo hits = %d, want 2 after the negative TTL", h)
}
}
func TestAuthenticate_OpaqueAccepted(t *testing.T) {
fx := newAuthFixture(t, nil)
fx.idp.userinfo.Store(map[string]any{"email": "[email protected]", "email_verified": true, "groups": []string{"llm-users"}})
entry, st, reason := fx.run(t, "opaque-ok", nil)
if st != authOK || entry.user.name != "oidc:[email protected]" {
t.Fatalf("status %v reason %q", st, reason)
}
fx.idp.userinfo.Store(map[string]any{"email": "[email protected]", "email_verified": false, "groups": []string{"llm-users"}})
if _, st, reason := fx.run(t, "opaque-unverified", nil); st != authUnauthorized || reason != "email_unverified" {
t.Fatalf("status %v reason %q", st, reason)
}
}
func TestAuthenticate_OpaqueDisabled(t *testing.T) {
fx := newAuthFixture(t, func(s *oidcSettings) { s.userinfo = false })
if _, st, reason := fx.run(t, "opaque-token", nil); st != authUnauthorized || reason != "opaque_disabled" {
t.Fatalf("status %v reason %q", st, reason)
}
if d, u := fx.idp.discoveryHits.Load(), fx.idp.userinfoHits.Load(); d != 0 || u != 0 {
t.Fatalf("IdP hits discovery %d userinfo %d, want 0", d, u)
}
}
func TestAuthenticate_LRUBound(t *testing.T) {
fx := newAuthFixture(t, func(s *oidcSettings) { s.maxUsers = 3 })
for i := range 5 {
tok := fx.token(t, func(c map[string]any) { c["email"] = fmt.Sprintf("u%[email protected]", i) })
if _, st, _ := fx.run(t, tok, nil); st != authOK {
t.Fatal(st)
}
}
users := fx.auth.users()
if len(users) != 3 {
t.Fatalf("users = %d, want 3", len(users))
}
got := map[string]bool{}
for _, u := range users {
got[u.user.name] = true
}
for _, want := range []string{"oidc:[email protected]", "oidc:[email protected]", "oidc:[email protected]"} {
if !got[want] {
t.Fatalf("most recent users missing %q: %v", want, got)
}
}
}
+325
View File
@@ -0,0 +1,325 @@
package traefikllmgateway
import (
"fmt"
"net/url"
"sort"
"strings"
"time"
)
// OIDCConfig admits OIDC bearer tokens (for example the access token Open
// WebUI forwards with auth_type "system_oauth") as per-identity virtual
// users whose groups come from a token claim.
type OIDCConfig struct {
// RequireEmailVerified rejects a token whose email_verified claim is
// not true. Nil defaults to true when IdentityClaim is "email".
RequireEmailVerified *bool `json:"requireEmailVerified,omitempty"`
// GroupMap maps a GroupClaim value to a configured gateway group.
GroupMap map[string]string `json:"groupMap"`
// Issuer is the OIDC issuer URL; discovery is read from
// {Issuer}/.well-known/openid-configuration.
Issuer string `json:"issuer"`
// IdentityClaim names the claim that identifies the user. Default "email".
IdentityClaim string `json:"identityClaim,omitempty"`
// GroupClaim is a dotted claim path, for example "groups" or
// "realm_access.roles".
GroupClaim string `json:"groupClaim"`
// CacheTTL caps how long a verified token is trusted without a new
// check (a Go duration, default 5m); a token's own exp always wins.
CacheTTL string `json:"cacheTTL,omitempty"`
// JWKSRefresh is how often the signing keys are re-read (default 1h).
JWKSRefresh string `json:"jwksRefresh,omitempty"`
// Audiences lists accepted aud (or azp) values for JWT access tokens.
Audiences []string `json:"audiences"`
// MaxUsers bounds the virtual users kept in memory (default 10000).
MaxUsers int `json:"maxUsers,omitempty"`
// Userinfo verifies opaque (non-JWT) tokens at the IdP userinfo
// endpoint. That path cannot check the audience.
Userinfo bool `json:"userinfo,omitempty"`
// AcceptAzp also accepts a JWT whose azp, not aud, names one of
// Audiences. Off by default: azp names the client that asked for the
// token, not the service it was issued for.
AcceptAzp bool `json:"acceptAzp,omitempty"`
}
const (
oidcDefaultIdentityClaim = "email"
oidcDefaultCacheTTL = 5 * time.Minute
oidcDefaultJWKSRefresh = time.Hour
oidcDefaultMaxUsers = 10000
// oidcNamePrefix marks a virtual user's accounting name, so it can never
// collide with a configured user or the reserved anonymous principal.
oidcNamePrefix = "oidc:"
)
// oidcSettings is OIDCConfig validated and defaulted.
type oidcSettings struct {
audiences map[string]bool
groupMap map[string]string
issuer string
identityClaim string
groupClaim []string
cacheTTL time.Duration
jwksRefresh time.Duration
maxUsers int
requireEmailVerified bool
userinfo bool
acceptAzp bool
}
// oidcOverride is a users-config entry with OIDCIdentity set: the accounting
// name and per-user limits for one OIDC identity.
type oidcOverride struct {
limits *LimitsConfig
name string
}
// parseOIDCConfig validates c against the configured groups and applies
// defaults.
func parseOIDCConfig(c *OIDCConfig, groups map[string]*group) (*oidcSettings, error) {
issuer, err := validateIssuer(c.Issuer)
if err != nil {
return nil, err
}
s := &oidcSettings{
issuer: issuer,
audiences: make(map[string]bool, len(c.Audiences)),
groupMap: make(map[string]string, len(c.GroupMap)),
cacheTTL: oidcDefaultCacheTTL,
jwksRefresh: oidcDefaultJWKSRefresh,
maxUsers: oidcDefaultMaxUsers,
userinfo: c.Userinfo,
acceptAzp: c.AcceptAzp,
}
if len(c.Audiences) == 0 {
return nil, fmt.Errorf("llmgateway: oidc.audiences must list at least one audience")
}
for _, aud := range c.Audiences {
if strings.TrimSpace(aud) == "" {
return nil, fmt.Errorf("llmgateway: oidc.audiences must not contain a blank value")
}
s.audiences[aud] = true
}
s.identityClaim = c.IdentityClaim
if s.identityClaim == "" {
s.identityClaim = oidcDefaultIdentityClaim
} else if strings.TrimSpace(s.identityClaim) != s.identityClaim {
return nil, fmt.Errorf("llmgateway: oidc.identityClaim %q must be a claim name without spaces", c.IdentityClaim)
}
s.requireEmailVerified = s.identityClaim == oidcDefaultIdentityClaim
if c.RequireEmailVerified != nil {
s.requireEmailVerified = *c.RequireEmailVerified
}
if s.groupClaim, err = parseClaimPath(c.GroupClaim); err != nil {
return nil, err
}
if len(c.GroupMap) == 0 {
return nil, fmt.Errorf("llmgateway: oidc.groupMap must map at least one claim value to a group")
}
values := make([]string, 0, len(c.GroupMap))
for v := range c.GroupMap {
values = append(values, v)
}
sort.Strings(values)
for _, v := range values {
target := c.GroupMap[v]
if v == "" {
return nil, fmt.Errorf("llmgateway: oidc.groupMap must not have an empty claim value")
}
if _, ok := groups[target]; !ok {
return nil, fmt.Errorf("llmgateway: oidc.groupMap[%q] references unknown group %q", v, target)
}
s.groupMap[v] = target
}
if c.MaxUsers < 0 {
return nil, fmt.Errorf("llmgateway: oidc.maxUsers must not be negative")
}
if c.MaxUsers > 0 {
s.maxUsers = c.MaxUsers
}
if s.cacheTTL, err = positiveDuration("cacheTTL", c.CacheTTL, oidcDefaultCacheTTL); err != nil {
return nil, err
}
if s.jwksRefresh, err = positiveDuration("jwksRefresh", c.JWKSRefresh, oidcDefaultJWKSRefresh); err != nil {
return nil, err
}
return s, nil
}
// validateIssuer requires https, except for a loopback host, so a token is
// never verified against keys fetched over plain HTTP from the network.
func validateIssuer(raw string) (string, error) {
if raw == "" {
return "", fmt.Errorf("llmgateway: oidc.issuer is required")
}
u, err := url.Parse(raw)
if err != nil {
return "", fmt.Errorf("llmgateway: oidc.issuer: %w", err)
}
switch {
case u.Scheme == "https" && u.Host != "":
case u.Scheme == "http" && isLoopbackHost(u.Hostname()):
default:
return "", fmt.Errorf("llmgateway: oidc.issuer %q must be an https URL", raw)
}
return raw, nil
}
// secureIDPURL reports whether raw is an https URL, or http on a loopback
// host, so no token or key travels over plain HTTP on the network.
func secureIDPURL(raw string) bool {
u, err := url.Parse(raw)
if err != nil || u.Host == "" {
return false
}
return u.Scheme == "https" || (u.Scheme == "http" && isLoopbackHost(u.Hostname()))
}
func isLoopbackHost(h string) bool {
return h == "localhost" || h == "127.0.0.1" || h == "::1"
}
func parseClaimPath(raw string) ([]string, error) {
if raw == "" {
return nil, fmt.Errorf("llmgateway: oidc.groupClaim is required")
}
path := strings.Split(raw, ".")
for _, seg := range path {
if seg == "" || strings.TrimSpace(seg) != seg {
return nil, fmt.Errorf("llmgateway: oidc.groupClaim %q has an empty or padded path segment", raw)
}
}
return path, nil
}
func positiveDuration(field, raw string, def time.Duration) (time.Duration, error) {
if raw == "" {
return def, nil
}
d, err := time.ParseDuration(raw)
if err != nil {
return 0, fmt.Errorf("llmgateway: oidc.%s: %w", field, err)
}
if d <= 0 {
return 0, fmt.Errorf("llmgateway: oidc.%s must be positive, got %s", field, raw)
}
return d, nil
}
// normalizeIdentity folds case and trims, because IdPs differ in the case
// they return for the same email.
// normalizeIdentity trims raw and folds case only for the email claim:
// other claims, such as sub, can be case-sensitive.
func normalizeIdentity(claim, raw string) string {
id := strings.TrimSpace(raw)
if claim == oidcDefaultIdentityClaim {
id = asciiLower(id)
}
return id
}
// asciiLower folds only A-Z. Unicode folding maps distinct characters onto
// ASCII (U+212A KELVIN SIGN to k), which would merge two mailboxes.
func asciiLower(s string) string {
b := []byte(s)
for i, c := range b {
if c >= 'A' && c <= 'Z' {
b[i] = c + ('a' - 'A')
}
}
return string(b)
}
// buildOIDCOverride validates a users-config entry with OIDCIdentity set.
func (a *authStore) buildOIDCOverride(uc *UserConfig) (string, *oidcOverride, error) {
if !a.oidcEnabled {
return "", nil, fmt.Errorf("llmgateway: user %q: oidcIdentity needs oidc to be configured", uc.Name)
}
if err := a.checkUserName(uc.Name); err != nil {
return "", nil, err
}
identity := normalizeIdentity(a.oidc.identityClaim, uc.OIDCIdentity)
if identity == "" {
return "", nil, fmt.Errorf("llmgateway: user %q: oidcIdentity must not be blank", uc.Name)
}
switch {
case uc.APIKey != "":
return "", nil, fmt.Errorf("llmgateway: user %q: an oidcIdentity entry must not set apiKey", uc.Name)
case uc.Group != "" || len(uc.Groups) > 0:
return "", nil, fmt.Errorf("llmgateway: user %q: an oidcIdentity entry must not set group or groups; the token's groupMap decides membership", uc.Name)
case len(uc.Providers) > 0:
return "", nil, fmt.Errorf("llmgateway: user %q: an oidcIdentity entry must not set providers", uc.Name)
case len(uc.Models) > 0:
return "", nil, fmt.Errorf("llmgateway: user %q: an oidcIdentity entry must not set models", uc.Name)
case uc.Admin:
return "", nil, fmt.Errorf("llmgateway: user %q: an oidcIdentity entry must not set admin", uc.Name)
}
if err := uc.Limits.validate(); err != nil {
return "", nil, fmt.Errorf("llmgateway: user %q: %w", uc.Name, err)
}
return identity, &oidcOverride{name: uc.Name, limits: uc.Limits}, nil
}
// checkUserName rejects names that would collide with a built-in principal.
func (a *authStore) checkUserName(name string) error {
if name == "" {
return fmt.Errorf("llmgateway: user config entry must have a non-empty name")
}
if a.anonymous != nil && name == anonymousUserName {
return fmt.Errorf("llmgateway: user name %q is reserved while users.anonymousGroup is set", name)
}
if a.oidcEnabled && strings.HasPrefix(name, oidcNamePrefix) {
return fmt.Errorf("llmgateway: user name %q: the %q prefix is reserved for OIDC virtual users", name, oidcNamePrefix)
}
return nil
}
// userSet is one users-config source split into keyed users and OIDC
// overrides, validated for duplicate names, keys and identities.
type userSet struct {
keyed map[[32]byte]*authEntry
overrides map[string]*oidcOverride
names map[string]bool
}
func (a *authStore) buildUserSet(us []*UserConfig) (*userSet, error) {
set := &userSet{
keyed: make(map[[32]byte]*authEntry, len(us)),
overrides: make(map[string]*oidcOverride),
names: make(map[string]bool, len(us)),
}
for _, uc := range us {
if uc != nil && uc.OIDCIdentity != "" {
identity, ov, err := a.buildOIDCOverride(uc)
if err != nil {
return nil, err
}
if set.names[ov.name] {
return nil, fmt.Errorf("llmgateway: duplicate user name %q", ov.name)
}
if _, dup := set.overrides[identity]; dup {
return nil, fmt.Errorf("llmgateway: duplicate oidcIdentity %q (user %q)", identity, ov.name)
}
set.names[ov.name] = true
set.overrides[identity] = ov
continue
}
entry, err := a.buildEntry(uc)
if err != nil {
return nil, err
}
if set.names[entry.user.name] {
return nil, fmt.Errorf("llmgateway: duplicate user name %q", entry.user.name)
}
set.names[entry.user.name] = true
if _, exists := set.keyed[entry.digest]; exists {
return nil, fmt.Errorf("llmgateway: duplicate API key for user %q", uc.Name)
}
set.keyed[entry.digest] = entry
}
return set, nil
}
+248
View File
@@ -0,0 +1,248 @@
package traefikllmgateway
import (
"net/url"
"reflect"
"strings"
"testing"
"time"
)
func validOIDCConfig() *OIDCConfig {
return &OIDCConfig{
Issuer: "https://idp.example.com/realms/main",
Audiences: []string{"openwebui"},
GroupClaim: "groups",
GroupMap: map[string]string{"llm-users": "staff"},
}
}
func oidcTestGroups() map[string]*group {
return map[string]*group{"staff": {name: "staff"}, "power": {name: "power"}}
}
func TestParseOIDCConfig(t *testing.T) {
tests := []struct {
mutate func(c *OIDCConfig)
name string
wantErr string
}{
{name: "empty issuer", mutate: func(c *OIDCConfig) { c.Issuer = "" }, wantErr: "issuer"},
{name: "plain http issuer", mutate: func(c *OIDCConfig) { c.Issuer = "http://idp.example.com" }, wantErr: "issuer"},
{name: "unparsable issuer", mutate: func(c *OIDCConfig) { c.Issuer = "https://%zz" }, wantErr: "issuer"},
{name: "empty audiences", mutate: func(c *OIDCConfig) { c.Audiences = nil }, wantErr: "audiences"},
{name: "blank audience", mutate: func(c *OIDCConfig) { c.Audiences = []string{" "} }, wantErr: "audiences"},
{name: "empty groupClaim", mutate: func(c *OIDCConfig) { c.GroupClaim = "" }, wantErr: "groupClaim"},
{name: "groupClaim empty segment", mutate: func(c *OIDCConfig) { c.GroupClaim = "a..b" }, wantErr: "groupClaim"},
{name: "empty groupMap", mutate: func(c *OIDCConfig) { c.GroupMap = nil }, wantErr: "groupMap"},
{name: "unknown group", mutate: func(c *OIDCConfig) { c.GroupMap = map[string]string{"x": "nope"} }, wantErr: `unknown group "nope"`},
{name: "negative maxUsers", mutate: func(c *OIDCConfig) { c.MaxUsers = -1 }, wantErr: "maxUsers"},
{name: "bad cacheTTL", mutate: func(c *OIDCConfig) { c.CacheTTL = "soon" }, wantErr: "cacheTTL"},
{name: "zero cacheTTL", mutate: func(c *OIDCConfig) { c.CacheTTL = "0s" }, wantErr: "cacheTTL"},
{name: "bad jwksRefresh", mutate: func(c *OIDCConfig) { c.JWKSRefresh = "-1m" }, wantErr: "jwksRefresh"},
{name: "empty identityClaim path segment", mutate: func(c *OIDCConfig) { c.IdentityClaim = " " }, wantErr: "identityClaim"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
c := validOIDCConfig()
tc.mutate(c)
_, err := parseOIDCConfig(c, oidcTestGroups())
if err == nil || !strings.Contains(err.Error(), tc.wantErr) {
t.Fatalf("err = %v, want containing %q", err, tc.wantErr)
}
})
}
}
func TestParseOIDCConfig_Defaults(t *testing.T) {
s, err := parseOIDCConfig(validOIDCConfig(), oidcTestGroups())
if err != nil {
t.Fatal(err)
}
if s.identityClaim != "email" || !s.requireEmailVerified || s.userinfo {
t.Fatalf("identity defaults: %+v", s)
}
if s.cacheTTL != 5*time.Minute || s.jwksRefresh != time.Hour || s.maxUsers != 10000 {
t.Fatalf("duration/size defaults: %+v", s)
}
if !s.audiences["openwebui"] || len(s.audiences) != 1 {
t.Fatalf("audiences = %v", s.audiences)
}
if !reflect.DeepEqual(s.groupClaim, []string{"groups"}) {
t.Fatalf("groupClaim = %v", s.groupClaim)
}
}
func TestParseOIDCConfig_Overrides(t *testing.T) {
c := validOIDCConfig()
c.Issuer = "http://127.0.0.1:8080/"
c.IdentityClaim = "sub"
c.GroupClaim = "realm_access.roles"
c.CacheTTL = "30s"
c.JWKSRefresh = "10m"
c.MaxUsers = 3
c.Userinfo = true
s, err := parseOIDCConfig(c, oidcTestGroups())
if err != nil {
t.Fatal(err)
}
if s.issuer != "http://127.0.0.1:8080/" {
t.Fatalf("issuer = %q", s.issuer)
}
if s.identityClaim != "sub" || s.requireEmailVerified {
t.Fatalf("non-email identity must not require email_verified by default: %+v", s)
}
if !reflect.DeepEqual(s.groupClaim, []string{"realm_access", "roles"}) {
t.Fatalf("groupClaim = %v", s.groupClaim)
}
if s.cacheTTL != 30*time.Second || s.jwksRefresh != 10*time.Minute || s.maxUsers != 3 || !s.userinfo {
t.Fatalf("overrides: %+v", s)
}
off := false
c.IdentityClaim = "email"
c.RequireEmailVerified = &off
s, err = parseOIDCConfig(c, oidcTestGroups())
if err != nil {
t.Fatal(err)
}
if s.requireEmailVerified {
t.Fatal("explicit requireEmailVerified=false must win")
}
}
func oidcAuthCfg(users ...*UserConfig) *Config {
return &Config{
Providers: map[string]*ProviderConfig{"openai": {Type: "openai", APIKey: "k"}},
Groups: map[string]*GroupConfig{
"staff": {MemberLimits: &LimitsConfig{RequestsPerMinute: 10}},
"power": {},
},
OIDC: validOIDCConfig(),
Users: &UsersConfig{Inline: users},
}
}
func TestNewAuthStore_OIDCOverrides(t *testing.T) {
a, err := newAuthStore(oidcAuthCfg(
&UserConfig{Name: "bob", Group: "staff", APIKey: "sk-bob"},
&UserConfig{Name: "alice", OIDCIdentity: "[email protected]", Limits: &LimitsConfig{RequestsPerMinute: 5}},
))
if err != nil {
t.Fatal(err)
}
ov, ok := a.oidcOverrides["[email protected]"]
if !ok || ov.name != "alice" || ov.limits.RequestsPerMinute != 5 {
t.Fatalf("override index = %+v", a.oidcOverrides)
}
if len(a.byDigest) != 1 {
t.Fatalf("override must not be a keyed user; byDigest has %d entries", len(a.byDigest))
}
if !a.oidcEnabled {
t.Fatal("oidcEnabled must be set when cfg.OIDC is set")
}
bad := []struct {
uc *UserConfig
name string
wantErr string
}{
{name: "apiKey", uc: &UserConfig{Name: "c", OIDCIdentity: "c@x", APIKey: "k"}, wantErr: "apiKey"},
{name: "group", uc: &UserConfig{Name: "c", OIDCIdentity: "c@x", Group: "staff"}, wantErr: "group"},
{name: "groups", uc: &UserConfig{Name: "c", OIDCIdentity: "c@x", Groups: []string{"staff"}}, wantErr: "group"},
{name: "providers", uc: &UserConfig{Name: "c", OIDCIdentity: "c@x", Providers: []string{"openai"}}, wantErr: "providers"},
{name: "models", uc: &UserConfig{Name: "c", OIDCIdentity: "c@x", Models: []string{"m"}}, wantErr: "models"},
{name: "admin", uc: &UserConfig{Name: "c", OIDCIdentity: "c@x", Admin: true}, wantErr: "admin"},
{name: "no name", uc: &UserConfig{OIDCIdentity: "c@x"}, wantErr: "name"},
{name: "bad limits", uc: &UserConfig{Name: "c", OIDCIdentity: "c@x", Limits: &LimitsConfig{RequestsPerMinute: -1}}, wantErr: `"c"`},
{name: "oidc prefix on keyed user", uc: &UserConfig{Name: "oidc:bob", Group: "staff", APIKey: "k2"}, wantErr: "oidc:"},
{name: "oidc prefix on override", uc: &UserConfig{Name: "oidc:c", OIDCIdentity: "c@x"}, wantErr: "oidc:"},
{name: "duplicate identity", uc: &UserConfig{Name: "alice2", OIDCIdentity: "[email protected]"}, wantErr: "duplicate oidcIdentity"},
{name: "name clashes with keyed user", uc: &UserConfig{Name: "bob", OIDCIdentity: "b@x"}, wantErr: "duplicate user name"},
{name: "name clashes with override", uc: &UserConfig{Name: "alice", OIDCIdentity: "other@x"}, wantErr: "duplicate user name"},
}
for _, tc := range bad {
t.Run(tc.name, func(t *testing.T) {
_, err := newAuthStore(oidcAuthCfg(
&UserConfig{Name: "bob", Group: "staff", APIKey: "sk-bob"},
&UserConfig{Name: "alice", OIDCIdentity: "[email protected]"},
tc.uc,
))
if err == nil || !strings.Contains(err.Error(), tc.wantErr) {
t.Fatalf("err = %v, want containing %q", err, tc.wantErr)
}
})
}
}
func TestNewAuthStore_OIDCIdentityNeedsOIDC(t *testing.T) {
cfg := oidcAuthCfg(&UserConfig{Name: "alice", OIDCIdentity: "[email protected]"})
cfg.OIDC = nil
_, err := newAuthStore(cfg)
if err == nil || !strings.Contains(err.Error(), "oidcIdentity needs oidc") {
t.Fatalf("err = %v", err)
}
}
func TestNewAuthStore_OIDCPrefixAllowedWithoutOIDC(t *testing.T) {
cfg := oidcAuthCfg(&UserConfig{Name: "oidc:legacy", Group: "staff", APIKey: "k"})
cfg.OIDC = nil
if _, err := newAuthStore(cfg); err != nil {
t.Fatalf("a keyed user named oidc:* must stay valid while oidc is off: %v", err)
}
}
func TestReplaceFileUsers_OIDCOverrides(t *testing.T) {
a, err := newAuthStore(oidcAuthCfg(
&UserConfig{Name: "bob", Group: "staff", APIKey: "sk-bob"},
&UserConfig{Name: "alice", OIDCIdentity: "[email protected]", Limits: &LimitsConfig{RequestsPerMinute: 5}},
&UserConfig{Name: "carol", OIDCIdentity: "[email protected]"},
))
if err != nil {
t.Fatal(err)
}
err = a.replaceFileUsers([]*UserConfig{
{Name: "dave", Group: "power", APIKey: "sk-dave"},
{Name: "alice-file", OIDCIdentity: "[email protected]", Limits: &LimitsConfig{RequestsPerMinute: 9}},
})
if err != nil {
t.Fatal(err)
}
if len(a.byDigest) != 2 {
t.Fatalf("byDigest = %d entries, want 2 (bob inline + dave file)", len(a.byDigest))
}
if ov := a.oidcOverrides["[email protected]"]; ov == nil || ov.name != "alice-file" || ov.limits.RequestsPerMinute != 9 {
t.Fatalf("file override must replace the inline one: %+v", ov)
}
if ov := a.oidcOverrides["[email protected]"]; ov == nil || ov.name != "carol" {
t.Fatalf("untouched inline override must survive: %+v", ov)
}
err = a.replaceFileUsers([]*UserConfig{
{Name: "x", OIDCIdentity: "[email protected]"},
{Name: "y", OIDCIdentity: "[email protected]"},
})
if err == nil || !strings.Contains(err.Error(), "duplicate oidcIdentity") {
t.Fatalf("err = %v", err)
}
if ov := a.oidcOverrides["[email protected]"]; ov == nil || ov.name != "alice-file" {
t.Fatal("a rejected reload must keep the previous overrides")
}
}
func TestRedactConfig_OIDCIssuerSanitized(t *testing.T) {
cfg := oidcAuthCfg()
issuer := url.URL{Scheme: "https", User: url.UserPassword("user", "hunter2"), Host: "idp.example.com", Path: "/realms/main", RawQuery: "token=s3cret"}
cfg.OIDC.Issuer = issuer.String()
redacted, err := redactConfig(cfg)
if err != nil {
t.Fatal(err)
}
got := redacted["oidc"].(map[string]any)["issuer"].(string)
if strings.Contains(got, "hunter2") || strings.Contains(got, "s3cret") {
t.Fatalf("issuer not sanitized: %q", got)
}
if !strings.Contains(got, "idp.example.com") {
t.Fatalf("issuer host lost: %q", got)
}
}
+280
View File
@@ -0,0 +1,280 @@
package traefikllmgateway
import (
"bytes"
"context"
"errors"
"fmt"
"net/http"
"strings"
"sync"
"testing"
"time"
)
func opaqueFixture(t *testing.T) *authFixture {
t.Helper()
fx := newAuthFixture(t, func(s *oidcSettings) { s.userinfo = true })
fx.idp.userinfo.Store(map[string]any{"email": "[email protected]", "email_verified": true, "groups": []any{"llm-users"}})
return fx
}
func TestAuthenticate_CanceledCallerDoesNotPoisonFetch(t *testing.T) {
fx := newAuthFixture(t, nil)
ctx, cancel := context.WithCancel(context.Background())
cancel()
if _, st, reason := fx.auth.authenticate(ctx, fx.token(t, nil), nil); st != authOK {
t.Fatalf("a caller's cancel must not fail the shared key fetch: %v %q", st, reason)
}
other := fx.token(t, func(c map[string]any) { c["email"] = "[email protected]" })
if _, st, reason := fx.run(t, other, nil); st != authOK {
t.Fatalf("next caller: %v %q", st, reason)
}
}
func TestProvider_FetchDeadlineCoversDiscoveryAndJWKS(t *testing.T) {
f := newFakeIDP(t)
p := newTestProvider(f, newFakeClock())
p.timeout = 300 * time.Millisecond
f.delay.Store(int64(200 * time.Millisecond))
if _, err := p.keysFor("rsa"); err == nil {
t.Fatal("discovery plus JWKS took 400ms against a 300ms deadline; want an error")
}
}
func TestAuthenticate_UserinfoOutageNotCached(t *testing.T) {
fx := opaqueFixture(t)
fx.idp.userinfoStatus.Store(http.StatusServiceUnavailable)
if _, st, reason := fx.run(t, "opaque-token-1", nil); st != authUnauthorized || reason != oidcReasonIDPUnavailable {
t.Fatalf("outage: %v %q", st, reason)
}
fx.idp.userinfoStatus.Store(0)
if _, st, reason := fx.run(t, "opaque-token-1", nil); st != authOK {
t.Fatalf("an IdP outage must not be cached: %v %q", st, reason)
}
}
func TestAuthenticate_UserinfoRejectionCached(t *testing.T) {
fx := opaqueFixture(t)
fx.idp.userinfo.Store(map[string]any(nil))
for i := 0; i < 2; i++ {
if _, st, reason := fx.run(t, "opaque-bad", nil); st != authUnauthorized || reason != oidcReasonUserinfo {
t.Fatalf("call %d: %v %q", i, st, reason)
}
}
if n := fx.idp.userinfoHits.Load(); n != 1 {
t.Fatalf("userinfo hits = %d, want 1: an IdP 401 is cached", n)
}
}
func TestProvider_UserinfoInFlightCap(t *testing.T) {
f := newFakeIDP(t)
p := newTestProvider(f, newFakeClock())
p.queueWait = 20 * time.Millisecond
for i := 0; i < cap(p.userinfoSlots); i++ {
p.userinfoSlots <- struct{}{}
}
if _, err := p.userinfo(context.Background(), "opaque"); !errors.Is(err, errIDPBusy) {
t.Fatalf("err = %v, want errIDPBusy", err)
}
if n := f.userinfoHits.Load(); n != 0 {
t.Fatalf("userinfo hits = %d, want 0", n)
}
}
func TestProvider_DiscoveryBackoffOnUserinfoPath(t *testing.T) {
f := newFakeIDP(t)
f.failDiscovery.Store(true)
p := newTestProvider(f, newFakeClock())
for i := 0; i < 3; i++ {
if _, err := p.userinfo(context.Background(), "opaque"); err == nil {
t.Fatal("want error")
}
}
if n := f.discoveryHits.Load(); n != 1 {
t.Fatalf("discovery hits = %d, want 1 inside the retry window", n)
}
}
func TestAuthenticate_RejectionsDoNotEvictVerdicts(t *testing.T) {
fx := newAuthFixture(t, func(s *oidcSettings) { s.maxUsers = 2; s.jwksRefresh = time.Minute })
tok := fx.token(t, nil)
if _, st, _ := fx.run(t, tok, nil); st != authOK {
t.Fatal(st)
}
for i := 0; i < 20; i++ {
bad := fx.token(t, func(c map[string]any) {
c["jti"] = fmt.Sprint(i)
c["exp"] = fx.clock.Now().Add(-time.Hour).Unix()
})
if _, st, _ := fx.run(t, bad, nil); st != authUnauthorized {
t.Fatal(st)
}
}
fx.idp.jwks.Store([]byte(`{"keys":[]}`))
fx.clock.Advance(2 * time.Minute)
if _, st, reason := fx.run(t, tok, nil); st != authOK {
t.Fatalf("a flood of rejected tokens evicted a valid verdict: %v %q", st, reason)
}
}
func TestAuthenticate_UnknownKidNotCachedOnStaleKeys(t *testing.T) {
fx := newAuthFixture(t, nil)
if _, st, _ := fx.run(t, fx.token(t, nil), nil); st != authOK {
t.Fatal(st)
}
fx.clock.Advance(61 * time.Second)
fx.idp.failJWKS.Store(true)
rotated := signTestJWT(t, "RS256", "new", oidcKeys(t), nil, func() map[string]any {
c := baseClaims(fx.clock.Now())
c["iss"] = fx.idp.srv.URL
return c
}())
if _, st, reason := fx.run(t, rotated, nil); st != authUnauthorized || reason != "unknown_kid" {
t.Fatalf("outage with stale keys: %v %q", st, reason)
}
fx.idp.jwks.Store(bytes.Replace(testJWKS(t, oidcKeys(t)), []byte(`"kid":"rsa"`), []byte(`"kid":"new"`), 1))
fx.idp.failJWKS.Store(false)
fx.clock.Advance(6 * time.Second)
if _, st, reason := fx.run(t, rotated, nil); st != authOK {
t.Fatalf("unknown_kid on stale keys must not be cached: %v %q", st, reason)
}
}
func TestAuthenticate_BadAlgSkipsKeyFetch(t *testing.T) {
fx := newAuthFixture(t, nil)
c := baseClaims(fx.clock.Now())
c["iss"] = fx.idp.srv.URL
tok := signTestJWT(t, "HS256", "rsa", oidcKeys(t), []byte("secret"), c)
if _, st, reason := fx.run(t, tok, nil); st != authUnauthorized || reason != "bad_alg" {
t.Fatalf("%v %q", st, reason)
}
if d, j := fx.idp.discoveryHits.Load(), fx.idp.jwksHits.Load(); d != 0 || j != 0 {
t.Fatalf("discovery %d jwks %d, want no IdP call for a disallowed alg", d, j)
}
}
func TestProvider_RejectsInsecureEndpoints(t *testing.T) {
f := newFakeIDP(t)
f.jwksURI.Store("http://idp.example.com/jwks")
if _, err := newTestProvider(f, newFakeClock()).keysFor("rsa"); !errors.Is(err, errInsecureIDPURL) {
t.Fatalf("jwks_uri: err = %v, want errInsecureIDPURL", err)
}
f2 := newFakeIDP(t)
f2.userinfoURI.Store("http://idp.example.com/userinfo")
if _, err := newTestProvider(f2, newFakeClock()).userinfo(context.Background(), "opaque"); !errors.Is(err, errInsecureIDPURL) {
t.Fatalf("userinfo_endpoint: err = %v, want errInsecureIDPURL", err)
}
}
func TestParseJWKS_SkipsUnusableKeys(t *testing.T) {
good := testJWKS(t, oidcKeys(t))
mixed := bytes.Replace(good, []byte(`{"keys":[`), []byte(`{"keys":[{"kty":"RSA","kid":"broken","n":"!!","e":"AQAB"},`), 1)
set, err := parseJWKS(mixed)
if err != nil {
t.Fatalf("one malformed key must not fail the set: %v", err)
}
if _, err := set.lookup("rsa"); err != nil {
t.Fatal("good key missing")
}
small := `{"keys":[{"kty":"RSA","kid":"weak","n":"` + b64(bytes.Repeat([]byte{0xff}, 128)) + `","e":"AQAB"}]}`
if _, err := parseJWKS([]byte(small)); err == nil {
t.Fatal("a JWKS whose only key is RSA-1024 must fail")
}
if _, err := parseJWKS([]byte(`{"keys":[{"kty":"RSA","kid":"x","n":"!!","e":"AQAB"}]}`)); err == nil {
t.Fatal("a JWKS with no usable key must fail")
}
}
func TestAuthenticate_CaseFoldOnlyForEmail(t *testing.T) {
fx := newAuthFixture(t, func(s *oidcSettings) { s.identityClaim = "sub"; s.requireEmailVerified = false })
e, st, reason := fx.run(t, fx.token(t, func(c map[string]any) { c["sub"] = "AbC-123" }), nil)
if st != authOK || e.user.name != "oidc:AbC-123" {
t.Fatalf("%v %q %+v", st, reason, e)
}
a, err := newAuthStore(func() *Config {
cfg := oidcAuthCfg(&UserConfig{Name: "carl", OIDCIdentity: "AbC-123"})
cfg.OIDC.IdentityClaim = "sub"
return cfg
}())
if err != nil {
t.Fatal(err)
}
if _, ok := a.oidcOverrides["AbC-123"]; !ok {
t.Fatalf("override for a case-sensitive sub must keep its case: %v", a.oidcOverrides)
}
}
func TestAuthenticate_LogsIDPFailureCause(t *testing.T) {
fx := newAuthFixture(t, nil)
var (
mu sync.Mutex
logs []string
)
fx.auth.logf = func(msg string) {
mu.Lock()
defer mu.Unlock()
logs = append(logs, msg)
}
fx.idp.issuerInDoc.Store("https://other.example.com")
tok := fx.token(t, nil)
if _, st, _ := fx.run(t, tok, nil); st != authUnauthorized {
t.Fatal(st)
}
mu.Lock()
defer mu.Unlock()
joined := strings.Join(logs, "\n")
if !strings.Contains(joined, "does not match configured issuer") {
t.Fatalf("log must name the IdP failure cause; got %q", joined)
}
if strings.Contains(joined, tok) {
t.Fatal("log must never contain the token")
}
}
func TestAuthenticate_NoGroupReasonNamesIdentity(t *testing.T) {
fx := newAuthFixture(t, nil)
_, st, reason := fx.run(t, fx.token(t, func(c map[string]any) { c["groups"] = []string{"other"} }), nil)
if st != authForbidden || !strings.HasPrefix(reason, oidcReasonNoGroup) || !strings.Contains(reason, "[email protected]") {
t.Fatalf("%v %q", st, reason)
}
}
func TestRegistry_PrunesStaleRecords(t *testing.T) {
r, client, clock := newRegistryFixture(t)
stale := clock.Now().Add(-oidcRegistryRetention - time.Hour).Unix()
if _, err := client.do("HSET", oidcRegistryKey, "oidc:[email protected]", fmt.Sprintf(`{"identity":"[email protected]","groups":["default"],"lastSeen":%d}`, stale)); err != nil {
t.Fatal(err)
}
r.touch("oidc:[email protected]", "[email protected]", []string{"default"})
if _, err := r.load(); err != nil {
t.Fatal(err)
}
reply, err := client.do("HGETALL", oidcRegistryKey)
if err != nil {
t.Fatal(err)
}
recs := decodeRegistry(reply)
if _, ok := recs["oidc:[email protected]"]; ok {
t.Fatal("a record past retention must be deleted from Redis")
}
if _, ok := recs["oidc:[email protected]"]; !ok {
t.Fatal("a current record must stay")
}
}
func TestRegistry_TouchedBoundFollowsMaxUsers(t *testing.T) {
ln := newBehavioralRedisServer(t)
client, err := buildRedisClient(&RedisConfig{Address: ln.Addr().String()})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = client.Close() })
r := newOIDCRegistry(client, newFakeClock().Now, func(f func()) { f() }, func(string, ...any) {}, 3)
for i := 0; i < 10; i++ {
r.touch(fmt.Sprintf("oidc:u%[email protected]", i), "[email protected]", []string{"default"})
if len(r.touched) > 3 {
t.Fatalf("touched holds %d names, bound is 3", len(r.touched))
}
}
}
+382
View File
@@ -0,0 +1,382 @@
package traefikllmgateway
import (
"crypto"
"crypto/ecdh"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rsa"
"crypto/sha256"
"crypto/sha512"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"math/big"
"strings"
"time"
)
var (
errTokenMalformed = errors.New("oidc: malformed token")
errTokenExpired = errors.New("oidc: token expired")
errTokenNotYetValid = errors.New("oidc: token not yet valid")
errTokenBadSignature = errors.New("oidc: bad token signature")
errTokenBadAlg = errors.New("oidc: token algorithm not allowed for this key")
errTokenIssuer = errors.New("oidc: token issuer mismatch")
errTokenAudience = errors.New("oidc: token audience not accepted")
errTokenUnknownKid = errors.New("oidc: token signed by an unknown key")
errEmailNotVerified = errors.New("oidc: email not verified")
)
// oidcClockSkew tolerates small clock drift between the IdP and the gateway.
const oidcClockSkew = 60 * time.Second
// jwk is one JSON Web Key (RFC 7517) as published in a JWKS document.
type jwk struct {
Kty string `json:"kty"`
Kid string `json:"kid"`
Use string `json:"use"`
N string `json:"n"`
E string `json:"e"`
Crv string `json:"crv"`
X string `json:"x"`
Y string `json:"y"`
}
// jwkSet holds the usable signature keys of a JWKS, by kid.
type jwkSet struct {
keys map[string]crypto.PublicKey
}
// jwsAlg describes one allowed JWS algorithm.
type jwsAlg struct {
curve elliptic.Curve // nil for RSA algorithms
hash crypto.Hash
pss bool
}
// allowedJWSAlgs is the closed set of accepted algorithms. Symmetric and
// "none" algorithms are absent on purpose: a public key must never act as an
// HMAC secret.
var allowedJWSAlgs = map[string]jwsAlg{
"RS256": {hash: crypto.SHA256},
"RS384": {hash: crypto.SHA384},
"RS512": {hash: crypto.SHA512},
"PS256": {hash: crypto.SHA256, pss: true},
"ES256": {hash: crypto.SHA256, curve: elliptic.P256()},
"ES384": {hash: crypto.SHA384, curve: elliptic.P384()},
}
// parseJWKS reads the signature keys from a JWKS document. Keys for
// encryption, key types this gateway does not verify and malformed or weak
// keys are skipped, so one bad key cannot block the others. It fails only
// when a supported key was malformed and no usable key remains.
func parseJWKS(body []byte) (*jwkSet, error) {
var doc struct {
Keys []jwk `json:"keys"`
}
if err := json.Unmarshal(body, &doc); err != nil {
return nil, fmt.Errorf("oidc: jwks: %w", err)
}
set := &jwkSet{keys: make(map[string]crypto.PublicKey, len(doc.Keys))}
var firstErr error
for _, k := range doc.Keys {
if k.Use != "" && k.Use != "sig" {
continue
}
var (
pub crypto.PublicKey
err error
)
switch k.Kty {
case "RSA":
pub, err = rsaKey(k)
case "EC":
curve := curveByName(k.Crv)
if curve == nil {
continue
}
pub, err = ecKey(k, curve)
default:
continue
}
if err != nil {
if firstErr == nil {
firstErr = fmt.Errorf("oidc: jwks key %q: %w", k.Kid, err)
}
continue
}
set.keys[k.Kid] = pub
}
if len(set.keys) == 0 && firstErr != nil {
return nil, firstErr
}
return set, nil
}
func ecdhCurve(c elliptic.Curve) ecdh.Curve {
if c == elliptic.P384() {
return ecdh.P384()
}
return ecdh.P256()
}
func curveByName(name string) elliptic.Curve {
switch name {
case "P-256":
return elliptic.P256()
case "P-384":
return elliptic.P384()
}
return nil
}
func rsaKey(k jwk) (*rsa.PublicKey, error) {
n, err := base64.RawURLEncoding.DecodeString(k.N)
if err != nil {
return nil, fmt.Errorf("modulus: %w", err)
}
e, err := base64.RawURLEncoding.DecodeString(k.E)
if err != nil {
return nil, fmt.Errorf("exponent: %w", err)
}
exp := new(big.Int).SetBytes(e)
if len(n) == 0 || !exp.IsInt64() || exp.Int64() < 3 || exp.Int64() > 1<<31-1 {
return nil, errors.New("invalid RSA parameters")
}
mod := new(big.Int).SetBytes(n)
if mod.BitLen() < oidcMinRSABits {
return nil, fmt.Errorf("RSA key of %d bits is under %d", mod.BitLen(), oidcMinRSABits)
}
return &rsa.PublicKey{N: mod, E: int(exp.Int64())}, nil
}
func ecKey(k jwk, curve elliptic.Curve) (*ecdsa.PublicKey, error) {
x, err := base64.RawURLEncoding.DecodeString(k.X)
if err != nil {
return nil, fmt.Errorf("x: %w", err)
}
y, err := base64.RawURLEncoding.DecodeString(k.Y)
if err != nil {
return nil, fmt.Errorf("y: %w", err)
}
size := (curve.Params().BitSize + 7) / 8
if len(x) != size || len(y) != size {
return nil, errors.New("coordinate length does not match the curve")
}
// crypto/ecdh's NewPublicKey rejects a point that is not on the curve.
point := append(append([]byte{4}, x...), y...)
if _, err := ecdhCurve(curve).NewPublicKey(point); err != nil {
return nil, fmt.Errorf("point: %w", err)
}
return &ecdsa.PublicKey{Curve: curve, X: new(big.Int).SetBytes(x), Y: new(big.Int).SetBytes(y)}, nil
}
// oidcMinRSABits is the smallest RSA modulus accepted for token signatures.
const oidcMinRSABits = 2048
// jwtHeader is the protected header of a compact JWS.
type jwtHeader struct {
Alg string `json:"alg"`
Kid string `json:"kid"`
}
func splitJWT(token string) ([]string, *jwtHeader, error) {
parts := strings.Split(token, ".")
if len(parts) != 3 {
return nil, nil, errTokenMalformed
}
raw, err := base64.RawURLEncoding.DecodeString(parts[0])
if err != nil {
return nil, nil, errTokenMalformed
}
var hdr jwtHeader
if err := json.Unmarshal(raw, &hdr); err != nil || hdr.Alg == "" {
return nil, nil, errTokenMalformed
}
return parts, &hdr, nil
}
// looksLikeJWT reports whether token has the compact JWS shape, so an opaque
// token is never sent through signature checks.
func looksLikeJWT(token string) bool {
_, _, err := splitJWT(token)
return err == nil
}
// jwtKid returns the kid of token's protected header. A disallowed alg is
// refused here, before any key fetch.
func jwtKid(token string) (string, error) {
_, hdr, err := splitJWT(token)
if err != nil {
return "", err
}
if _, ok := allowedJWSAlgs[hdr.Alg]; !ok {
return "", errTokenBadAlg
}
return hdr.Kid, nil
}
// verifyJWT checks token's signature against keys and its claims against s,
// and returns the claims.
func verifyJWT(token string, keys *jwkSet, s *oidcSettings, now time.Time) (map[string]any, error) {
parts, hdr, err := splitJWT(token)
if err != nil {
return nil, err
}
alg, ok := allowedJWSAlgs[hdr.Alg]
if !ok {
return nil, errTokenBadAlg
}
pub, err := keys.lookup(hdr.Kid)
if err != nil {
return nil, err
}
sig, err := base64.RawURLEncoding.DecodeString(parts[2])
if err != nil {
return nil, errTokenBadSignature
}
if err = verifySignature(alg, pub, []byte(parts[0]+"."+parts[1]), sig); err != nil {
return nil, err
}
raw, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return nil, errTokenMalformed
}
var claims map[string]any
if err := json.Unmarshal(raw, &claims); err != nil {
return nil, errTokenMalformed
}
if err := checkClaims(claims, s, now); err != nil {
return nil, err
}
return claims, nil
}
// lookup returns the key for kid. A token without a kid matches only when
// the set holds exactly one key.
func (k *jwkSet) lookup(kid string) (crypto.PublicKey, error) {
if pub, ok := k.keys[kid]; ok {
return pub, nil
}
if kid == "" && len(k.keys) == 1 {
for _, pub := range k.keys {
return pub, nil
}
}
return nil, errTokenUnknownKid
}
func verifySignature(alg jwsAlg, pub crypto.PublicKey, input, sig []byte) error {
digest := hashInput(alg.hash, input)
switch key := pub.(type) {
case *rsa.PublicKey:
if alg.curve != nil {
return errTokenBadAlg
}
var err error
if alg.pss {
err = rsa.VerifyPSS(key, alg.hash, digest, sig, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
} else {
err = rsa.VerifyPKCS1v15(key, alg.hash, digest, sig)
}
if err != nil {
return errTokenBadSignature
}
return nil
case *ecdsa.PublicKey:
if alg.curve == nil || key.Curve != alg.curve {
return errTokenBadAlg
}
size := (key.Curve.Params().BitSize + 7) / 8
if len(sig) != 2*size {
return errTokenBadSignature
}
r := new(big.Int).SetBytes(sig[:size])
sv := new(big.Int).SetBytes(sig[size:])
if !ecdsa.Verify(key, digest, r, sv) {
return errTokenBadSignature
}
return nil
}
return errTokenBadAlg
}
func hashInput(h crypto.Hash, input []byte) []byte {
switch h {
case crypto.SHA384:
d := sha512.Sum384(input)
return d[:]
case crypto.SHA512:
d := sha512.Sum512(input)
return d[:]
default:
d := sha256.Sum256(input)
return d[:]
}
}
func checkClaims(claims map[string]any, s *oidcSettings, now time.Time) error {
if iss, _ := claims["iss"].(string); iss != s.issuer {
return errTokenIssuer
}
exp, ok := numericClaim(claims, "exp")
if !ok || now.After(time.Unix(exp, 0).Add(oidcClockSkew)) {
return errTokenExpired
}
if nbf, ok := numericClaim(claims, "nbf"); ok && now.Add(oidcClockSkew).Before(time.Unix(nbf, 0)) {
return errTokenNotYetValid
}
if !audienceAccepted(claims, s.audiences, s.acceptAzp) {
return errTokenAudience
}
if s.requireEmailVerified && !emailVerified(claims) {
return errEmailNotVerified
}
return nil
}
func numericClaim(claims map[string]any, name string) (int64, bool) {
v, ok := claims[name].(float64)
if !ok {
return 0, false
}
return int64(v), true
}
// audienceAccepted matches aud (a string or an array). With acceptAzp it
// also matches azp: Keycloak and similar IdPs put the requesting client in
// azp, not aud, of access tokens. azp alone also passes a token the client
// obtained for another service, so it is opt-in.
func audienceAccepted(claims map[string]any, accepted map[string]bool, acceptAzp bool) bool {
switch aud := claims["aud"].(type) {
case string:
if accepted[aud] {
return true
}
case []any:
for _, a := range aud {
if s, ok := a.(string); ok && accepted[s] {
return true
}
}
}
if !acceptAzp {
return false
}
azp, _ := claims["azp"].(string)
return azp != "" && accepted[azp]
}
// emailVerified accepts a boolean true or the string "true", which some IdPs
// emit.
func emailVerified(claims map[string]any) bool {
switch v := claims["email_verified"].(type) {
case bool:
return v
case string:
return v == "true"
}
return false
}
+345
View File
@@ -0,0 +1,345 @@
package traefikllmgateway
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/hmac"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/sha512"
"encoding/base64"
"encoding/json"
"errors"
"math/big"
"strings"
"testing"
"time"
)
const testIssuer = "https://idp.example.com/realms/main"
// testKeys holds one signing key per supported family, generated once per
// test binary because RSA generation is slow under -race.
type testKeys struct {
rsa *rsa.PrivateKey
p256 *ecdsa.PrivateKey
p384 *ecdsa.PrivateKey
}
var sharedTestKeys *testKeys
func oidcKeys(t *testing.T) *testKeys {
t.Helper()
if sharedTestKeys != nil {
return sharedTestKeys
}
rk, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}
p256, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
p384, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
if err != nil {
t.Fatal(err)
}
sharedTestKeys = &testKeys{rsa: rk, p256: p256, p384: p384}
return sharedTestKeys
}
func b64(b []byte) string { return base64.RawURLEncoding.EncodeToString(b) }
func padded(n *big.Int, size int) []byte {
out := make([]byte, size)
n.FillBytes(out)
return out
}
// testJWKS renders the public halves of k as a JWKS document: kid "rsa",
// "p256" and "p384".
func testJWKS(t *testing.T, k *testKeys) []byte {
t.Helper()
ec := func(kid, crv string, pub *ecdsa.PublicKey, size int) map[string]string {
return map[string]string{"kty": "EC", "kid": kid, "crv": crv, "use": "sig",
"x": b64(padded(pub.X, size)), "y": b64(padded(pub.Y, size))}
}
doc := map[string]any{"keys": []any{
map[string]string{"kty": "RSA", "kid": "rsa", "use": "sig",
"n": b64(k.rsa.N.Bytes()), "e": b64(big.NewInt(int64(k.rsa.E)).Bytes())},
ec("p256", "P-256", &k.p256.PublicKey, 32),
ec("p384", "P-384", &k.p384.PublicKey, 48),
}}
out, err := json.Marshal(doc)
if err != nil {
t.Fatal(err)
}
return out
}
func digestFor(alg string, data []byte) (crypto.Hash, []byte) {
switch alg {
case "RS384", "ES384":
d := sha512.Sum384(data)
return crypto.SHA384, d[:]
case "RS512":
d := sha512.Sum512(data)
return crypto.SHA512, d[:]
default:
d := sha256.Sum256(data)
return crypto.SHA256, d[:]
}
}
// signTestJWT builds a compact JWS. alg "none" yields an empty signature;
// "HS256" signs with secret.
func signTestJWT(t *testing.T, alg, kid string, k *testKeys, secret []byte, claims map[string]any) string {
t.Helper()
hdr, err := json.Marshal(map[string]string{"alg": alg, "kid": kid, "typ": "JWT"})
if err != nil {
t.Fatal(err)
}
body, err := json.Marshal(claims)
if err != nil {
t.Fatal(err)
}
input := b64(hdr) + "." + b64(body)
var sig []byte
switch alg {
case "none":
case "HS256":
m := hmac.New(sha256.New, secret)
m.Write([]byte(input))
sig = m.Sum(nil)
case "RS256", "RS384", "RS512":
h, d := digestFor(alg, []byte(input))
sig, err = rsa.SignPKCS1v15(rand.Reader, k.rsa, h, d)
case "PS256":
h, d := digestFor(alg, []byte(input))
sig, err = rsa.SignPSS(rand.Reader, k.rsa, h, d, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
case "ES256", "ES384":
key, size := k.p256, 32
if alg == "ES384" {
key, size = k.p384, 48
}
_, d := digestFor(alg, []byte(input))
r, s, signErr := ecdsa.Sign(rand.Reader, key, d)
err = signErr
sig = append(padded(r, size), padded(s, size)...)
default:
t.Fatalf("unsupported test alg %s", alg)
}
if err != nil {
t.Fatal(err)
}
return input + "." + b64(sig)
}
func baseClaims(now time.Time) map[string]any {
return map[string]any{
"iss": testIssuer,
"aud": "openwebui",
"exp": now.Add(time.Hour).Unix(),
"iat": now.Unix(),
"email": "[email protected]",
"email_verified": true,
"groups": []string{"llm-users"},
}
}
func testSettings() *oidcSettings {
return &oidcSettings{
issuer: testIssuer,
audiences: map[string]bool{"openwebui": true},
identityClaim: "email",
requireEmailVerified: true,
groupClaim: []string{"groups"},
groupMap: map[string]string{"llm-users": "staff"},
}
}
func TestVerifyJWT(t *testing.T) {
k := oidcKeys(t)
set, err := parseJWKS(testJWKS(t, k))
if err != nil {
t.Fatal(err)
}
now := time.Unix(1_800_000_000, 0)
with := func(mut func(c map[string]any)) map[string]any {
c := baseClaims(now)
mut(c)
return c
}
tests := []struct {
claims map[string]any
tamper func(tok string) string
wantErr error
name string
alg string
kid string
secret []byte
}{
{name: "RS256", alg: "RS256", kid: "rsa"},
{name: "RS384", alg: "RS384", kid: "rsa"},
{name: "RS512", alg: "RS512", kid: "rsa"},
{name: "PS256", alg: "PS256", kid: "rsa"},
{name: "ES256", alg: "ES256", kid: "p256"},
{name: "ES384", alg: "ES384", kid: "p384"},
{name: "expired past skew", alg: "RS256", kid: "rsa", claims: with(func(c map[string]any) { c["exp"] = now.Add(-61 * time.Second).Unix() }), wantErr: errTokenExpired},
{name: "expired within skew", alg: "RS256", kid: "rsa", claims: with(func(c map[string]any) { c["exp"] = now.Add(-59 * time.Second).Unix() })},
{name: "missing exp", alg: "RS256", kid: "rsa", claims: with(func(c map[string]any) { delete(c, "exp") }), wantErr: errTokenExpired},
{name: "nbf in future", alg: "RS256", kid: "rsa", claims: with(func(c map[string]any) { c["nbf"] = now.Add(61 * time.Second).Unix() }), wantErr: errTokenNotYetValid},
{name: "nbf within skew", alg: "RS256", kid: "rsa", claims: with(func(c map[string]any) { c["nbf"] = now.Add(59 * time.Second).Unix() })},
{name: "payload tampered", alg: "RS256", kid: "rsa", tamper: func(tok string) string {
parts := strings.Split(tok, ".")
c := baseClaims(now)
c["email"] = "[email protected]"
body, _ := json.Marshal(c)
return parts[0] + "." + b64(body) + "." + parts[2]
}, wantErr: errTokenBadSignature},
{name: "alg none", alg: "none", kid: "rsa", wantErr: errTokenBadAlg},
{name: "HS256 with public key as secret", alg: "HS256", kid: "rsa", secret: k.rsa.N.Bytes(), wantErr: errTokenBadAlg},
{name: "ES256 header on RSA key", alg: "ES256", kid: "rsa", wantErr: errTokenBadAlg},
{name: "ES384 header on P-256 key", alg: "ES384", kid: "p256", wantErr: errTokenBadAlg},
{name: "wrong issuer", alg: "RS256", kid: "rsa", claims: with(func(c map[string]any) { c["iss"] = "https://evil.example.com" }), wantErr: errTokenIssuer},
{name: "aud array match", alg: "RS256", kid: "rsa", claims: with(func(c map[string]any) { c["aud"] = []string{"account", "openwebui"} })},
{name: "azp alone refused without acceptAzp", alg: "RS256", kid: "rsa", claims: with(func(c map[string]any) { c["aud"] = "account"; c["azp"] = "openwebui" }), wantErr: errTokenAudience},
{name: "aud and azp mismatch", alg: "RS256", kid: "rsa", claims: with(func(c map[string]any) { c["aud"] = "account"; c["azp"] = "other" }), wantErr: errTokenAudience},
{name: "no aud", alg: "RS256", kid: "rsa", claims: with(func(c map[string]any) { delete(c, "aud") }), wantErr: errTokenAudience},
{name: "email not verified", alg: "RS256", kid: "rsa", claims: with(func(c map[string]any) { c["email_verified"] = false }), wantErr: errEmailNotVerified},
{name: "email_verified missing", alg: "RS256", kid: "rsa", claims: with(func(c map[string]any) { delete(c, "email_verified") }), wantErr: errEmailNotVerified},
{name: "email_verified string true", alg: "RS256", kid: "rsa", claims: with(func(c map[string]any) { c["email_verified"] = "true" })},
{name: "unknown kid", alg: "RS256", kid: "rotated", wantErr: errTokenUnknownKid},
{name: "short ES256 signature", alg: "ES256", kid: "p256", tamper: func(tok string) string {
i := strings.LastIndex(tok, ".")
return tok[:i+1] + b64(make([]byte, 63))
}, wantErr: errTokenBadSignature},
{name: "signature not base64", alg: "RS256", kid: "rsa", tamper: func(tok string) string {
i := strings.LastIndex(tok, ".")
return tok[:i+1] + "!!!"
}, wantErr: errTokenBadSignature},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
claims := tc.claims
if claims == nil {
claims = baseClaims(now)
}
tok := signTestJWT(t, tc.alg, tc.kid, k, tc.secret, claims)
if tc.tamper != nil {
tok = tc.tamper(tok)
}
got, err := verifyJWT(tok, set, testSettings(), now)
if tc.wantErr != nil {
if !errors.Is(err, tc.wantErr) {
t.Fatalf("err = %v, want %v", err, tc.wantErr)
}
return
}
if err != nil {
t.Fatalf("unexpected err: %v", err)
}
if got["email"] != claims["email"] {
t.Fatalf("claims email = %v", got["email"])
}
})
}
}
func TestVerifyJWT_EmailVerifiedNotRequired(t *testing.T) {
k := oidcKeys(t)
set, err := parseJWKS(testJWKS(t, k))
if err != nil {
t.Fatal(err)
}
now := time.Unix(1_800_000_000, 0)
c := baseClaims(now)
delete(c, "email_verified")
s := testSettings()
s.requireEmailVerified = false
if _, err := verifyJWT(signTestJWT(t, "RS256", "rsa", k, nil, c), set, s, now); err != nil {
t.Fatal(err)
}
}
func TestVerifyJWT_SingleKeyWithoutKid(t *testing.T) {
k := oidcKeys(t)
doc := map[string]any{"keys": []any{map[string]string{"kty": "RSA",
"n": b64(k.rsa.N.Bytes()), "e": b64(big.NewInt(int64(k.rsa.E)).Bytes())}}}
body, err := json.Marshal(doc)
if err != nil {
t.Fatal(err)
}
set, err := parseJWKS(body)
if err != nil {
t.Fatal(err)
}
now := time.Unix(1_800_000_000, 0)
if _, err := verifyJWT(signTestJWT(t, "RS256", "", k, nil, baseClaims(now)), set, testSettings(), now); err != nil {
t.Fatalf("a kid-less token must match the only kid-less key: %v", err)
}
}
func TestParseJWKS(t *testing.T) {
k := oidcKeys(t)
set, err := parseJWKS(testJWKS(t, k))
if err != nil {
t.Fatal(err)
}
if _, ok := set.keys["rsa"].(*rsa.PublicKey); !ok {
t.Fatal("rsa key missing")
}
if pub, ok := set.keys["p256"].(*ecdsa.PublicKey); !ok || pub.Curve != elliptic.P256() {
t.Fatal("p256 key missing")
}
if pub, ok := set.keys["p384"].(*ecdsa.PublicKey); !ok || pub.Curve != elliptic.P384() {
t.Fatal("p384 key missing")
}
skipped, err := parseJWKS([]byte(`{"keys":[
{"kty":"RSA","kid":"enc","use":"enc","n":"AQAB","e":"AQAB"},
{"kty":"OKP","kid":"ed","crv":"Ed25519","x":"AAAA"},
{"kty":"EC","kid":"p521","crv":"P-521","x":"AAAA","y":"AAAA"}
]}`))
if err != nil {
t.Fatal(err)
}
if len(skipped.keys) != 0 {
t.Fatalf("enc, OKP and P-521 keys must be skipped, got %v", skipped.keys)
}
for name, body := range map[string]string{
"malformed json": `{"keys":`,
"bad rsa modulus": `{"keys":[{"kty":"RSA","kid":"x","n":"!!","e":"AQAB"}]}`,
"ec point off curve": `{"keys":[{"kty":"EC","kid":"x","crv":"P-256","x":"` + b64(make([]byte, 32)) + `","y":"` + b64(append(make([]byte, 31), 1)) + `"}]}`,
} {
t.Run(name, func(t *testing.T) {
if _, err := parseJWKS([]byte(body)); err == nil {
t.Fatal("want error")
}
})
}
}
func TestLooksLikeJWT(t *testing.T) {
k := oidcKeys(t)
real := signTestJWT(t, "RS256", "rsa", k, nil, baseClaims(time.Now()))
tests := map[string]bool{
"sk-abc": false,
"a.b.c": false,
"aaa.bbb.ccc.ddd": false,
b64([]byte(`{"alg":"RS256"}`)) + ".x.y": true,
real: true,
}
for tok, want := range tests {
if got := looksLikeJWT(tok); got != want {
t.Errorf("looksLikeJWT(%.20q) = %v, want %v", tok, got, want)
}
}
if kid, err := jwtKid(real); err != nil || kid != "rsa" {
t.Fatalf("jwtKid = %q, %v", kid, err)
}
}
+294
View File
@@ -0,0 +1,294 @@
package traefikllmgateway
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"sync"
"time"
)
const (
// oidcMaxBody caps every IdP response the gateway reads.
oidcMaxBody = 1 << 20
// oidcHTTPTimeout bounds one IdP round trip on the request path.
oidcHTTPTimeout = 5 * time.Second
// oidcKidRefetchAfter throttles JWKS refetches triggered by an unknown
// kid, so forged kids cannot turn every request into an IdP call.
oidcKidRefetchAfter = 60 * time.Second
// oidcFetchRetryAfter holds a failed discovery or JWKS fetch error, so
// an IdP outage does not turn every request into a new IdP call.
oidcFetchRetryAfter = 5 * time.Second
// oidcUserinfoMaxInFlight caps concurrent userinfo calls, so a flood of
// opaque bearers cannot become a flood of IdP requests.
oidcUserinfoMaxInFlight = 16
// oidcUserinfoQueueWait is how long a userinfo call waits for a free
// slot, so a burst shares the slots instead of failing at once.
oidcUserinfoQueueWait = 2 * time.Second
)
var (
// errIDPBusy refuses a userinfo call while oidcUserinfoMaxInFlight are
// already running.
errIDPBusy = errors.New("oidc: too many userinfo calls in flight")
// errInsecureIDPURL rejects an IdP endpoint that is not https or
// loopback http.
errInsecureIDPURL = errors.New("oidc: endpoint must be https or loopback http")
// errIDPRejected marks an IdP 401 or 403: the IdP refused the token.
errIDPRejected = errors.New("oidc: idp rejected the token")
)
// oidcDiscovery is the subset of the OpenID Provider Metadata the gateway uses.
type oidcDiscovery struct {
Issuer string `json:"issuer"`
JWKSURI string `json:"jwks_uri"`
UserinfoEndpoint string `json:"userinfo_endpoint"`
}
// oidcProvider fetches and caches the issuer's discovery document and keys.
type oidcProvider struct {
fetchedAt time.Time
failedAt time.Time
client *http.Client
now func() time.Time
// userinfoSlots is a semaphore of oidcUserinfoMaxInFlight tokens.
userinfoSlots chan struct{}
settings *oidcSettings
disc *oidcDiscovery
keys *jwkSet
failErr error
// timeout bounds one whole fetch: discovery plus JWKS, or one userinfo
// call.
timeout time.Duration
// queueWait bounds how long a userinfo call waits for a free slot.
queueWait time.Duration
stateMu sync.RWMutex
fetchMu sync.Mutex
}
func newOIDCProvider(s *oidcSettings, client *http.Client, now func() time.Time) *oidcProvider {
// A redirect would skip the https-or-loopback check on the endpoint,
// and a redirected userinfo body would become identity claims.
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
return &oidcProvider{
settings: s, client: client, now: now, timeout: oidcHTTPTimeout,
queueWait: oidcUserinfoQueueWait, userinfoSlots: make(chan struct{}, oidcUserinfoMaxInFlight),
}
}
// keysFor returns the issuer's signing keys, fetching them when none are
// cached, when they are older than jwksRefresh, or when kid is unknown and
// the last fetch is older than oidcKidRefetchAfter. A failed refresh keeps
// serving the last good keys. The fetch runs on its own deadline: one
// caller's cancel must not fail it for everyone else.
func (p *oidcProvider) keysFor(kid string) (*jwkSet, error) {
if keys, ok := p.cachedKeys(kid); ok {
return keys, nil
}
p.fetchMu.Lock()
defer p.fetchMu.Unlock()
if keys, ok := p.cachedKeys(kid); ok {
return keys, nil
}
if err := p.recentFailure(); err != nil {
p.stateMu.RLock()
keys := p.keys
p.stateMu.RUnlock()
if keys != nil {
return keys, nil
}
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), p.timeout)
defer cancel()
fresh, err := p.fetchKeys(ctx)
p.stateMu.Lock()
defer p.stateMu.Unlock()
if err != nil {
p.failedAt, p.failErr = p.now(), err
if p.keys != nil {
return p.keys, nil
}
return nil, err
}
p.keys, p.fetchedAt, p.failErr = fresh, p.now(), nil
return fresh, nil
}
// recentFailure returns the last fetch error while it is inside
// oidcFetchRetryAfter.
func (p *oidcProvider) recentFailure() error {
p.stateMu.RLock()
defer p.stateMu.RUnlock()
if p.failErr != nil && p.now().Sub(p.failedAt) < oidcFetchRetryAfter {
return p.failErr
}
return nil
}
// cachedKeys reports the cached keys when no fetch is due for kid.
func (p *oidcProvider) cachedKeys(kid string) (*jwkSet, bool) {
p.stateMu.RLock()
defer p.stateMu.RUnlock()
if p.keys == nil {
return nil, false
}
age := p.now().Sub(p.fetchedAt)
if age >= p.settings.jwksRefresh {
return nil, false
}
if _, err := p.keys.lookup(kid); err != nil && age >= oidcKidRefetchAfter {
return nil, false
}
return p.keys, true
}
func (p *oidcProvider) fetchKeys(ctx context.Context) (*jwkSet, error) {
disc, err := p.discovery(ctx)
if err != nil {
return nil, err
}
body, err := p.get(ctx, disc.JWKSURI, "")
if err != nil {
return nil, fmt.Errorf("oidc: jwks: %w", err)
}
return parseJWKS(body)
}
// discovery returns the cached discovery document, fetching it once. A
// failure is held for oidcFetchRetryAfter. The caller holds fetchMu.
func (p *oidcProvider) discovery(ctx context.Context) (*oidcDiscovery, error) {
p.stateMu.RLock()
disc := p.disc
p.stateMu.RUnlock()
if disc != nil {
return disc, nil
}
if err := p.recentFailure(); err != nil {
return nil, err
}
doc, err := p.fetchDiscovery(ctx)
p.stateMu.Lock()
defer p.stateMu.Unlock()
if err != nil {
p.failedAt, p.failErr = p.now(), err
return nil, err
}
p.disc = doc
return doc, nil
}
func (p *oidcProvider) fetchDiscovery(ctx context.Context) (*oidcDiscovery, error) {
url := strings.TrimSuffix(p.settings.issuer, "/") + "/.well-known/openid-configuration"
body, err := p.get(ctx, url, "")
if err != nil {
return nil, fmt.Errorf("oidc: discovery: %w", err)
}
var doc oidcDiscovery
if err := json.Unmarshal(body, &doc); err != nil {
return nil, fmt.Errorf("oidc: discovery: %w", err)
}
// OpenID Connect Discovery 1.0 §4.3: the document's issuer must equal
// the configured issuer exactly.
if doc.Issuer != p.settings.issuer {
return nil, fmt.Errorf("oidc: discovery issuer %q does not match configured issuer %q", doc.Issuer, p.settings.issuer)
}
if doc.JWKSURI == "" {
return nil, errors.New("oidc: discovery has no jwks_uri")
}
if !secureIDPURL(doc.JWKSURI) {
return nil, fmt.Errorf("%w: jwks_uri %q", errInsecureIDPURL, doc.JWKSURI)
}
return &doc, nil
}
// userinfo resolves an opaque token's claims at the IdP userinfo endpoint.
// At most oidcUserinfoMaxInFlight calls run at once; the rest wait up to
// queueWait for a slot, then fail with errIDPBusy. An IdP 401 or 403 wraps
// errIDPRejected.
func (p *oidcProvider) userinfo(ctx context.Context, token string) (map[string]any, error) {
wait := time.NewTimer(p.queueWait)
select {
case p.userinfoSlots <- struct{}{}:
wait.Stop()
case <-wait.C:
return nil, errIDPBusy
case <-ctx.Done():
wait.Stop()
return nil, ctx.Err()
}
defer func() { <-p.userinfoSlots }()
disc, err := p.cachedDiscovery()
if err != nil {
return nil, err
}
if disc.UserinfoEndpoint == "" {
return nil, errors.New("oidc: discovery has no userinfo_endpoint")
}
if !secureIDPURL(disc.UserinfoEndpoint) {
return nil, fmt.Errorf("%w: userinfo_endpoint %q", errInsecureIDPURL, disc.UserinfoEndpoint)
}
ctx, cancel := context.WithTimeout(ctx, p.timeout)
defer cancel()
body, err := p.get(ctx, disc.UserinfoEndpoint, token)
if err != nil {
return nil, fmt.Errorf("oidc: userinfo: %w", err)
}
var claims map[string]any
if err := json.Unmarshal(body, &claims); err != nil {
return nil, fmt.Errorf("oidc: userinfo: %w", err)
}
return claims, nil
}
// cachedDiscovery returns the discovery document, taking fetchMu only when
// it is not cached yet, so userinfo slots never wait behind a JWKS fetch.
func (p *oidcProvider) cachedDiscovery() (*oidcDiscovery, error) {
p.stateMu.RLock()
disc := p.disc
p.stateMu.RUnlock()
if disc != nil {
return disc, nil
}
p.fetchMu.Lock()
defer p.fetchMu.Unlock()
ctx, cancel := context.WithTimeout(context.Background(), p.timeout)
defer cancel()
return p.discovery(ctx)
}
func (p *oidcProvider) get(ctx context.Context, url, bearer string) ([]byte, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
if bearer != "" {
req.Header.Set("Authorization", "Bearer "+bearer)
}
resp, err := p.client.Do(req)
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }() // read-only response; a close error changes nothing
body, err := io.ReadAll(io.LimitReader(resp.Body, oidcMaxBody+1))
if err != nil {
return nil, err
}
if len(body) > oidcMaxBody {
return nil, fmt.Errorf("response too large (over %d bytes)", oidcMaxBody)
}
switch resp.StatusCode {
case http.StatusOK:
return body, nil
case http.StatusUnauthorized, http.StatusForbidden:
return nil, fmt.Errorf("%w: status %d", errIDPRejected, resp.StatusCode)
}
return nil, fmt.Errorf("status %d", resp.StatusCode)
}
+283
View File
@@ -0,0 +1,283 @@
package traefikllmgateway
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
// fakeIDP is an in-process OIDC issuer: discovery, JWKS and userinfo, with
// per-endpoint hit counters and switchable failure modes.
type fakeIDP struct {
srv *httptest.Server
jwks atomic.Value // []byte
userinfo atomic.Value // map[string]any; nil means 401
issuerInDoc atomic.Value // string; "" means srv.URL
lastAuthz atomic.Value // string
jwksURI atomic.Value // string; "" means srv.URL + "/jwks"
userinfoURI atomic.Value // string; "" means srv.URL + "/userinfo"
discoveryHits atomic.Int64
jwksHits atomic.Int64
userinfoHits atomic.Int64
delay atomic.Int64 // nanoseconds added to every reply
userinfoStatus atomic.Int32 // non-zero forces this status on /userinfo
failDiscovery atomic.Bool
failJWKS atomic.Bool
noUserinfo atomic.Bool
}
func newFakeIDP(t *testing.T) *fakeIDP {
t.Helper()
f := &fakeIDP{}
f.jwks.Store(testJWKS(t, oidcKeys(t)))
f.issuerInDoc.Store("")
f.lastAuthz.Store("")
f.jwksURI.Store("")
f.userinfoURI.Store("")
mux := http.NewServeMux()
mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) {
f.discoveryHits.Add(1)
time.Sleep(time.Duration(f.delay.Load()))
if f.failDiscovery.Load() {
http.Error(w, "down", http.StatusInternalServerError)
return
}
iss := f.issuerInDoc.Load().(string)
if iss == "" {
iss = f.srv.URL
}
jwksURI, _ := f.jwksURI.Load().(string)
if jwksURI == "" {
jwksURI = f.srv.URL + "/jwks"
}
doc := map[string]string{"issuer": iss, "jwks_uri": jwksURI}
if !f.noUserinfo.Load() {
userinfoURI, _ := f.userinfoURI.Load().(string)
if userinfoURI == "" {
userinfoURI = f.srv.URL + "/userinfo"
}
doc["userinfo_endpoint"] = userinfoURI
}
_ = json.NewEncoder(w).Encode(doc)
})
mux.HandleFunc("/redirect-jwks", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/jwks", http.StatusFound)
})
mux.HandleFunc("/jwks", func(w http.ResponseWriter, r *http.Request) {
f.jwksHits.Add(1)
time.Sleep(time.Duration(f.delay.Load()))
if f.failJWKS.Load() {
http.Error(w, "down", http.StatusServiceUnavailable)
return
}
_, _ = w.Write(f.jwks.Load().([]byte))
})
mux.HandleFunc("/userinfo", func(w http.ResponseWriter, r *http.Request) {
f.userinfoHits.Add(1)
f.lastAuthz.Store(r.Header.Get("Authorization"))
time.Sleep(time.Duration(f.delay.Load()))
if code := f.userinfoStatus.Load(); code != 0 {
http.Error(w, "forced", int(code))
return
}
claims, _ := f.userinfo.Load().(map[string]any)
if claims == nil {
http.Error(w, "invalid token", http.StatusUnauthorized)
return
}
_ = json.NewEncoder(w).Encode(claims)
})
f.srv = httptest.NewServer(mux)
t.Cleanup(f.srv.Close)
return f
}
func (f *fakeIDP) settings() *oidcSettings {
s := testSettings()
s.issuer = f.srv.URL
s.jwksRefresh = time.Hour
s.cacheTTL = 5 * time.Minute
s.maxUsers = 100
s.userinfo = true
return s
}
func newFakeClock() *fakeClock { return &fakeClock{now: time.Unix(1_800_000_000, 0)} }
func newTestProvider(f *fakeIDP, clock *fakeClock) *oidcProvider {
return newOIDCProvider(f.settings(), &http.Client{Timeout: 5 * time.Second}, clock.Now)
}
func TestProvider_LazyDiscoveryAndCache(t *testing.T) {
f := newFakeIDP(t)
p := newTestProvider(f, newFakeClock())
if f.discoveryHits.Load() != 0 {
t.Fatal("discovery must be lazy")
}
for range 2 {
set, err := p.keysFor("rsa")
if err != nil {
t.Fatal(err)
}
if _, err := set.lookup("rsa"); err != nil {
t.Fatal(err)
}
}
if d, j := f.discoveryHits.Load(), f.jwksHits.Load(); d != 1 || j != 1 {
t.Fatalf("discovery hits %d, jwks hits %d; want 1, 1", d, j)
}
}
func TestProvider_PeriodicRefresh(t *testing.T) {
f := newFakeIDP(t)
clock := newFakeClock()
p := newTestProvider(f, clock)
if _, err := p.keysFor("rsa"); err != nil {
t.Fatal(err)
}
clock.Advance(time.Hour + time.Second)
if _, err := p.keysFor("rsa"); err != nil {
t.Fatal(err)
}
if j := f.jwksHits.Load(); j != 2 {
t.Fatalf("jwks hits = %d, want 2 after jwksRefresh", j)
}
}
func TestProvider_UnknownKidRefetchThrottled(t *testing.T) {
f := newFakeIDP(t)
clock := newFakeClock()
p := newTestProvider(f, clock)
if _, err := p.keysFor("rsa"); err != nil {
t.Fatal(err)
}
steps := []struct {
advance time.Duration
wantHits int64
}{
{advance: 2 * time.Minute, wantHits: 2},
{advance: 30 * time.Second, wantHits: 2},
{advance: 31 * time.Second, wantHits: 3},
}
for i, st := range steps {
clock.Advance(st.advance)
if _, err := p.keysFor("rotated"); err != nil {
t.Fatal(err)
}
if got := f.jwksHits.Load(); got != st.wantHits {
t.Fatalf("step %d: jwks hits = %d, want %d", i, got, st.wantHits)
}
}
}
func TestProvider_IssuerMismatch(t *testing.T) {
f := newFakeIDP(t)
f.issuerInDoc.Store("https://evil.example.com")
p := newTestProvider(f, newFakeClock())
if _, err := p.keysFor("rsa"); err == nil || !strings.Contains(err.Error(), "issuer") {
t.Fatalf("err = %v, want issuer mismatch", err)
}
}
func TestProvider_BodyCap(t *testing.T) {
f := newFakeIDP(t)
f.jwks.Store([]byte(`{"keys":[],"pad":"` + strings.Repeat("a", 2<<20) + `"}`))
p := newTestProvider(f, newFakeClock())
if _, err := p.keysFor("rsa"); err == nil || !strings.Contains(err.Error(), "too large") {
t.Fatalf("err = %v, want body-too-large", err)
}
}
func TestProvider_DiscoveryFailureThenRecovery(t *testing.T) {
f := newFakeIDP(t)
clock := newFakeClock()
p := newTestProvider(f, clock)
f.failDiscovery.Store(true)
if _, err := p.keysFor("rsa"); err == nil {
t.Fatal("want error while discovery fails")
}
if _, err := p.keysFor("rsa"); err == nil {
t.Fatal("want cached error inside the retry backoff")
}
if h := f.discoveryHits.Load(); h != 1 {
t.Fatalf("discovery hits = %d, want 1 inside the retry backoff", h)
}
f.failDiscovery.Store(false)
clock.Advance(oidcFetchRetryAfter + time.Second)
if _, err := p.keysFor("rsa"); err != nil {
t.Fatalf("want recovery after backoff: %v", err)
}
}
func TestProvider_StaleKeysSurviveFailedRefresh(t *testing.T) {
f := newFakeIDP(t)
clock := newFakeClock()
p := newTestProvider(f, clock)
if _, err := p.keysFor("rsa"); err != nil {
t.Fatal(err)
}
f.jwks.Store([]byte(`not json`))
clock.Advance(time.Hour + time.Second)
set, err := p.keysFor("rsa")
if err != nil {
t.Fatalf("a failed refresh must keep serving the last good keys: %v", err)
}
if _, err := set.lookup("rsa"); err != nil {
t.Fatal(err)
}
}
func TestProvider_Userinfo(t *testing.T) {
f := newFakeIDP(t)
p := newTestProvider(f, newFakeClock())
ctx := context.Background()
f.userinfo.Store(map[string]any{"email": "[email protected]"})
claims, err := p.userinfo(ctx, "opaque-token")
if err != nil {
t.Fatal(err)
}
if claims["email"] != "[email protected]" {
t.Fatalf("claims = %v", claims)
}
if got := f.lastAuthz.Load().(string); got != "Bearer opaque-token" {
t.Fatalf("authorization = %q", got)
}
f.userinfo.Store(map[string]any(nil))
if _, err := p.userinfo(ctx, "opaque-token"); err == nil {
t.Fatal("want error on 401")
}
}
func TestProvider_UserinfoMissingEndpoint(t *testing.T) {
f := newFakeIDP(t)
f.noUserinfo.Store(true)
p := newTestProvider(f, newFakeClock())
if _, err := p.userinfo(context.Background(), "tok"); err == nil || !strings.Contains(err.Error(), "userinfo_endpoint") {
t.Fatalf("err = %v", err)
}
}
func TestProvider_ConcurrentFetchSingleFlight(t *testing.T) {
f := newFakeIDP(t)
p := newTestProvider(f, newFakeClock())
var wg sync.WaitGroup
for range 20 {
wg.Add(1)
go func() {
defer wg.Done()
if _, err := p.keysFor("rsa"); err != nil {
t.Error(err)
}
}()
}
wg.Wait()
if j := f.jwksHits.Load(); j != 1 {
t.Fatalf("jwks hits = %d, want 1", j)
}
}
+222
View File
@@ -0,0 +1,222 @@
package traefikllmgateway
import (
"encoding/json"
"fmt"
"sync"
"time"
)
const (
// oidcRegistryKey is the Redis hash of OIDC virtual users seen by any
// replica: field = accounting name, value = oidcRegistryRecord JSON.
oidcRegistryKey = "llmgw:oidc:users"
// oidcTouchEvery throttles registry writes per user.
oidcTouchEvery = time.Minute
// oidcRegistryReadTTL bounds how often snapshot reads the hash.
oidcRegistryReadTTL = 2 * time.Second
// oidcRegistryRetention hides, then deletes, users not seen for longer
// than the monthly usage window.
oidcRegistryRetention = 32 * 24 * time.Hour
)
// oidcRegistryRecord is one virtual user as stored in the registry.
type oidcRegistryRecord struct {
Identity string `json:"identity"`
Groups []string `json:"groups"`
LastSeen int64 `json:"lastSeen"`
}
// oidcRegistry records OIDC virtual users in Redis, so every replica and
// every restart lists the same users in the admin dashboard and metrics.
type oidcRegistry struct {
cachedAt time.Time
client *respClient
now func() time.Time
spawn func(func())
logf func(string, ...any)
touched map[string]time.Time
cached map[string]oidcRegistryRecord
logGate logGate
// maxTouched bounds the per-replica write throttle map.
maxTouched int
mu sync.Mutex
}
func newOIDCRegistry(client *respClient, now func() time.Time, spawn func(func()), logf func(string, ...any), maxTouched int) *oidcRegistry {
return &oidcRegistry{client: client, now: now, spawn: spawn, logf: logf, touched: map[string]time.Time{}, maxTouched: maxTouched}
}
// touch records that name was seen now, at most once per oidcTouchEvery.
// The write runs through spawn and never fails a request.
func (r *oidcRegistry) touch(name, identity string, groups []string) {
now := r.now()
r.mu.Lock()
if last, ok := r.touched[name]; ok && now.Sub(last) < oidcTouchEvery {
r.mu.Unlock()
return
}
if len(r.touched) >= r.maxTouched {
r.touched = map[string]time.Time{}
}
r.touched[name] = now
r.mu.Unlock()
rec, err := json.Marshal(oidcRegistryRecord{Identity: identity, Groups: groups, LastSeen: now.Unix()})
if err != nil {
r.logError("encode", err)
return
}
r.spawn(func() {
if _, err := r.client.do("HSET", oidcRegistryKey, name, string(rec)); err != nil {
r.logError("write", err)
}
})
}
// load returns every registry record, re-reading Redis at most once per
// oidcRegistryReadTTL. On a read error it returns the last good records.
func (r *oidcRegistry) load() (map[string]oidcRegistryRecord, error) {
now := r.now()
r.mu.Lock()
if r.cached != nil && now.Sub(r.cachedAt) < oidcRegistryReadTTL {
defer r.mu.Unlock()
return r.cached, nil
}
r.mu.Unlock()
reply, err := r.client.do("HGETALL", oidcRegistryKey)
if err == nil {
if rerr, ok := reply.(error); ok {
err = rerr
}
}
if err != nil {
r.logError("read", err)
r.mu.Lock()
defer r.mu.Unlock()
return r.cached, err
}
recs := decodeRegistry(reply)
r.prune(recs, now)
r.mu.Lock()
r.cached, r.cachedAt = recs, now
r.mu.Unlock()
return recs, nil
}
// prune drops records past oidcRegistryRetention from recs and deletes them
// from Redis, so the hash stops growing.
func (r *oidcRegistry) prune(recs map[string]oidcRegistryRecord, now time.Time) {
cutoff := now.Add(-oidcRegistryRetention).Unix()
args := []string{"HDEL", oidcRegistryKey}
for name, rec := range recs {
if rec.LastSeen < cutoff {
args = append(args, name)
delete(recs, name)
}
}
if len(args) == 2 {
return
}
r.spawn(func() {
if _, err := r.client.do(args...); err != nil {
r.logError("prune", err)
}
})
}
// decodeRegistry reads a RESP2 HGETALL reply (a flat field/value array).
// A malformed record is skipped.
func decodeRegistry(reply any) map[string]oidcRegistryRecord {
arr, _ := reply.([]any)
out := make(map[string]oidcRegistryRecord, len(arr)/2)
for i := 0; i+1 < len(arr); i += 2 {
name, ok1 := arr[i].([]byte)
val, ok2 := arr[i+1].([]byte)
if !ok1 || !ok2 {
continue
}
var rec oidcRegistryRecord
if err := json.Unmarshal(val, &rec); err != nil {
continue
}
out[string(name)] = rec
}
return out
}
func (r *oidcRegistry) logError(op string, err error) {
if log, suppressed := r.logGate.shouldLog(r.now()); log {
// Yaegi v0.16.1 crashes on a variadic func field called with more
// than one variadic argument (limiter.logf, limits.go).
r.logf("%s", fmt.Sprintf("oidc registry %s failed: %v%s", op, err, suppressedSuffix(suppressed)))
}
}
// oidcSummaries lists the OIDC virtual users for snapshot: the ones in
// memory, then registry records for users this replica has not seen.
// Registry users whose groups are all gone, or whose last request is older
// than oidcRegistryRetention, are hidden.
func (a *authStore) oidcSummaries(skip map[string]bool) []userSummary {
if a.oidcAuth == nil {
return nil
}
var out []userSummary
for _, e := range a.oidcAuth.users() {
if skip[e.user.name] {
continue
}
skip[e.user.name] = true
out = append(out, virtualSummary(e.user))
}
if a.oidcRegistry == nil {
return out
}
recs, err := a.oidcRegistry.load()
if err != nil && recs == nil {
return out
}
a.mu.RLock()
overrides := a.oidcOverrides
a.mu.RUnlock()
cutoff := a.nowFn().Add(-oidcRegistryRetention).Unix()
for name, rec := range recs {
if skip[name] || rec.LastSeen < cutoff {
continue
}
var members []*group
var names []string
for _, gn := range rec.Groups {
if g, ok := a.groups[gn]; ok {
members = append(members, g)
names = append(names, gn)
}
}
if len(members) == 0 {
continue
}
var own *LimitsConfig
if ov := overrides[rec.Identity]; ov != nil && ov.name == name {
own = ov.limits
}
limits, sources := effectiveUserLimits(own, members)
skip[name] = true
out = append(out, virtualSummary(&user{
limits: limits, limitSources: sources, name: name,
groupName: names[0], groupNames: names, oidcIdentity: rec.Identity,
}))
}
return out
}
func virtualSummary(u *user) userSummary {
return userSummary{
limits: u.limits,
limitSources: u.limitSources,
name: u.name,
groupName: u.groupName,
groups: cloneStringSlice(u.groupNames),
source: "oidc",
}
}
+181
View File
@@ -0,0 +1,181 @@
package traefikllmgateway
import (
"net/http"
"reflect"
"strconv"
"testing"
"time"
)
func findUserSummary(users []userSummary, name string) (userSummary, bool) {
for _, u := range users {
if u.name == name {
return u, true
}
}
return userSummary{}, false
}
func TestSnapshot_IncludesOIDCUsers(t *testing.T) {
fx := newOIDCGateway(t, nil)
if rec := fx.chat(t, fx.token(t, nil)); rec.Code != http.StatusOK {
t.Fatalf("status %d", rec.Code)
}
users, groups := fx.gw.auth.snapshot()
u, ok := findUserSummary(users, "oidc:[email protected]")
if !ok || u.source != "oidc" || u.groupName != "default" || u.limits.RequestsPerMinute != 50 {
t.Fatalf("virtual user summary = %+v (found %v)", u, ok)
}
for _, g := range groups {
if g.name == "default" && g.memberCount != 3 {
t.Fatalf("default memberCount = %d, want 3 (admin1, dotted, oidc user)", g.memberCount)
}
}
}
func TestScopeExists_OIDCUser(t *testing.T) {
fx := newOIDCGateway(t, nil)
if fx.gw.scopeExists("user", "oidc:[email protected]") {
t.Fatal("unseen virtual user must not exist yet")
}
if rec := fx.chat(t, fx.token(t, nil)); rec.Code != http.StatusOK {
t.Fatalf("status %d", rec.Code)
}
if !fx.gw.scopeExists("user", "oidc:[email protected]") {
t.Fatal("seen virtual user must be a known scope")
}
}
func TestPruneRejections_KeepsOIDCUsers(t *testing.T) {
fx := newOIDCGateway(t, func(cfg *Config) {
cfg.Groups["default"].MemberLimits = &LimitsConfig{RequestsPerMinute: 1}
})
tok := fx.token(t, nil)
fx.chat(t, tok)
if rec := fx.chat(t, tok); rec.Code != http.StatusTooManyRequests {
t.Fatalf("second request status %d, want 429", rec.Code)
}
has := func() bool {
for _, r := range fx.gw.limiter.rejections.snapshot() {
if r.kind == "user" && r.id == "oidc:[email protected]" {
return true
}
}
return false
}
if !has() {
t.Fatal("rejection not recorded for the virtual user")
}
fx.gw.pruneRejectionsAfterReload()
if !has() {
t.Fatal("a users-file reload must not prune a live virtual user's rejections")
}
}
func newRegistryFixture(t *testing.T) (*oidcRegistry, *respClient, *fakeClock) {
t.Helper()
ln := newBehavioralRedisServer(t)
client, err := buildRedisClient(&RedisConfig{Address: ln.Addr().String()})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = client.Close() })
clock := newFakeClock()
r := newOIDCRegistry(client, clock.Now, func(f func()) { f() }, func(string, ...any) {}, 4*oidcDefaultMaxUsers)
return r, client, clock
}
func TestRegistry_PersistAndLoad(t *testing.T) {
r, client, clock := newRegistryFixture(t)
r.touch("oidc:[email protected]", "[email protected]", []string{"default"})
recs, err := r.load()
if err != nil {
t.Fatal(err)
}
want := oidcRegistryRecord{Identity: "[email protected]", Groups: []string{"default"}, LastSeen: clock.Now().Unix()}
if got := recs["oidc:[email protected]"]; !reflect.DeepEqual(got, want) {
t.Fatalf("record = %+v, want %+v", got, want)
}
marker := `{"identity":"[email protected]","groups":["marker"],"lastSeen":` + itoa(clock.Now().Unix()) + `}`
if _, err = client.do("HSET", oidcRegistryKey, "oidc:[email protected]", marker); err != nil {
t.Fatal(err)
}
clock.Advance(30 * time.Second)
r.touch("oidc:[email protected]", "[email protected]", []string{"default"})
recs, err = r.load()
if err != nil {
t.Fatal(err)
}
if got := recs["oidc:[email protected]"]; !reflect.DeepEqual(got.Groups, []string{"marker"}) {
t.Fatalf("a touch inside 60s must not write: %+v", got)
}
clock.Advance(31 * time.Second)
r.touch("oidc:[email protected]", "[email protected]", []string{"default"})
clock.Advance(3 * time.Second)
recs, err = r.load()
if err != nil {
t.Fatal(err)
}
if got := recs["oidc:[email protected]"]; !reflect.DeepEqual(got.Groups, []string{"default"}) {
t.Fatalf("a touch after 60s must write: %+v", got)
}
}
func TestSnapshot_RegistryAcrossReplicas(t *testing.T) {
ln := newBehavioralRedisServer(t)
withRedis := func(cfg *Config) { cfg.Redis = &RedisConfig{Address: ln.Addr().String()} }
a := newOIDCGateway(t, withRedis)
b := newOIDCGateway(t, func(cfg *Config) {
withRedis(cfg)
cfg.OIDC.Issuer = a.cfg.OIDC.Issuer
})
if rec := a.chat(t, a.token(t, nil)); rec.Code != http.StatusOK {
t.Fatalf("status %d", rec.Code)
}
users, _ := b.gw.auth.snapshot()
u, ok := findUserSummary(users, "oidc:[email protected]")
if !ok || u.source != "oidc" || u.limits.RequestsPerMinute != 50 {
t.Fatalf("replica B must list the user from the registry: %+v (found %v)", u, ok)
}
}
func TestSnapshot_RegistryHidesStaleAndUnknownGroups(t *testing.T) {
ln := newBehavioralRedisServer(t)
fx := newOIDCGateway(t, func(cfg *Config) { cfg.Redis = &RedisConfig{Address: ln.Addr().String()} })
now := fx.gw.auth.nowFn().Unix()
stale := now - int64(oidcRegistryRetention/time.Second) - 1
for name, rec := range map[string]string{
"oidc:[email protected]": `{"identity":"[email protected]","groups":["default"],"lastSeen":` + itoa(stale) + `}`,
"oidc:[email protected]": `{"identity":"[email protected]","groups":["removed"],"lastSeen":` + itoa(now) + `}`,
"oidc:[email protected]": `{"identity":"[email protected]","groups":["default"],"lastSeen":` + itoa(now) + `}`,
} {
if _, err := fx.gw.redisClient.do("HSET", oidcRegistryKey, name, rec); err != nil {
t.Fatal(err)
}
}
users, _ := fx.gw.auth.snapshot()
if _, ok := findUserSummary(users, "oidc:[email protected]"); !ok {
t.Fatal("current record missing")
}
for _, hidden := range []string{"oidc:[email protected]", "oidc:[email protected]"} {
if _, ok := findUserSummary(users, hidden); ok {
t.Fatalf("%s must be hidden", hidden)
}
}
}
func TestSnapshot_NoRedis(t *testing.T) {
fx := newOIDCGateway(t, nil)
if fx.gw.auth.oidcRegistry != nil {
t.Fatal("no registry without redis")
}
fx.chat(t, fx.token(t, nil))
users, _ := fx.gw.auth.snapshot()
if _, ok := findUserSummary(users, "oidc:[email protected]"); !ok {
t.Fatal("in-memory virtual user missing")
}
}
func itoa(n int64) string { return strconv.FormatInt(n, 10) }
+1 -3
View File
@@ -106,10 +106,8 @@ const gatewayAliasKey = "__alias"
// re-marshals — registry.go owns the cache; this call site just writes
// its result).
func (g *Gateway) handleModels(w http.ResponseWriter, r *http.Request) {
u, grp, ok := g.auth.identify(r)
g.logAuthEvent(ok, authEventUserName(u), r)
_, grp, ok := g.requireAuth(w, r, false)
if !ok {
writeOAIError(w, http.StatusUnauthorized, "authentication_error", "invalid or missing API key")
return
}
+42
View File
@@ -1355,6 +1355,8 @@ func TestHandleChat_MidStreamDropAfterUsageChunk_AccountsPartialUsage(t *testing
// resp_test.go's scripted tests already pin.
type behavioralRedisServer struct {
data map[string]string
// hashes backs HSET/HGETALL for the OIDC user registry.
hashes map[string]map[string]string
// lastSetEX is the EX seconds argument from the most recent SET...EX
// command this server has handled — item B's per-group cache TTL
// override needs a way to observe the actual wire value a real
@@ -1455,6 +1457,46 @@ func (s *behavioralRedisServer) handle(args []string) []byte {
s.data[args[1]] = strconv.FormatInt(cur, 10)
s.mu.Unlock()
return []byte(fmt.Sprintf(":%d\r\n", cur))
case "HSET":
s.mu.Lock()
if s.hashes == nil {
s.hashes = map[string]map[string]string{}
}
h := s.hashes[args[1]]
if h == nil {
h = map[string]string{}
s.hashes[args[1]] = h
}
added := 0
for i := 2; i+1 < len(args); i += 2 {
if _, ok := h[args[i]]; !ok {
added++
}
h[args[i]] = args[i+1]
}
s.mu.Unlock()
return []byte(fmt.Sprintf(":%d\r\n", added))
case "HDEL":
s.mu.Lock()
removed := 0
for _, f := range args[2:] {
if _, ok := s.hashes[args[1]][f]; ok {
delete(s.hashes[args[1]], f)
removed++
}
}
s.mu.Unlock()
return []byte(fmt.Sprintf(":%d\r\n", removed))
case "HGETALL":
s.mu.Lock()
h := s.hashes[args[1]]
var b strings.Builder
fmt.Fprintf(&b, "*%d\r\n", 2*len(h))
for k, v := range h {
fmt.Fprintf(&b, "$%d\r\n%s\r\n$%d\r\n%s\r\n", len(k), k, len(v), v)
}
s.mu.Unlock()
return []byte(b.String())
default:
return []byte("-ERR unknown command\r\n")
}
+4
View File
@@ -1107,6 +1107,10 @@ func run() error {
if err := exerciseMessagesCacheUnrewritten(i, pkgName); err != nil {
return err
}
// exerciseOIDC builds its own Gateway with its own fake IdP and upstream.
if err := exerciseOIDC(i, pkgName); err != nil {
return err
}
return exerciseAdminRedesignStats(i, pkgName)
}
+193
View File
@@ -0,0 +1,193 @@
// This file probes OIDC bearer-token admission under Yaegi: discovery,
// JWKS parsing and RS256/PS256/ES256 signature checks all run in the
// interpreted plugin, against tokens this compiled harness signs.
package main
import (
"context"
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"math/big"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"time"
"github.com/traefik/yaegi/interp"
)
const oidcProbeModel = "gpt-oidc-probe"
type oidcProbeKeys struct {
rsa *rsa.PrivateKey
ec *ecdsa.PrivateKey
}
func oidcB64(b []byte) string { return base64.RawURLEncoding.EncodeToString(b) }
func oidcFixed(n *big.Int, size int) []byte {
out := make([]byte, size)
n.FillBytes(out)
return out
}
func (k *oidcProbeKeys) jwks() ([]byte, error) {
pub := k.ec.PublicKey
return json.Marshal(map[string]any{"keys": []any{
map[string]string{"kty": "RSA", "kid": "rsa", "use": "sig", "n": oidcB64(k.rsa.N.Bytes()), "e": oidcB64(big.NewInt(int64(k.rsa.E)).Bytes())},
map[string]string{"kty": "EC", "kid": "ec", "crv": "P-256", "use": "sig", "x": oidcB64(oidcFixed(pub.X, 32)), "y": oidcB64(oidcFixed(pub.Y, 32))},
}})
}
func (k *oidcProbeKeys) sign(alg string, claims map[string]any) (string, error) {
kid := "rsa"
if alg == "ES256" {
kid = "ec"
}
hdr, err := json.Marshal(map[string]string{"alg": alg, "kid": kid, "typ": "JWT"})
if err != nil {
return "", err
}
body, err := json.Marshal(claims)
if err != nil {
return "", err
}
input := oidcB64(hdr) + "." + oidcB64(body)
digest := sha256.Sum256([]byte(input))
var sig []byte
switch alg {
case "RS256":
sig, err = rsa.SignPKCS1v15(rand.Reader, k.rsa, crypto.SHA256, digest[:])
case "PS256":
sig, err = rsa.SignPSS(rand.Reader, k.rsa, crypto.SHA256, digest[:], &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
case "ES256":
r, s, signErr := ecdsa.Sign(rand.Reader, k.ec, digest[:])
err = signErr
sig = append(oidcFixed(r, 32), oidcFixed(s, 32)...)
default:
return "", fmt.Errorf("oidc probe: unsupported alg %s", alg)
}
if err != nil {
return "", err
}
return input + "." + oidcB64(sig), nil
}
func newOIDCProbeHandler(i *interp.Interpreter, pkgName, issuer, upstreamURL string) (http.Handler, error) {
cfgVal, err := i.Eval(pkgName + ".CreateConfig()")
if err != nil {
return nil, fmt.Errorf("oidc probe: CreateConfig under yaegi: %w", err)
}
cfgJSON := `{` +
`"providers":{"openai":{"type":"openai","baseUrl":"` + upstreamURL + `","apiKey":"sk-up","models":["` + oidcProbeModel + `"]}},` +
`"groups":{"oidcgroup":{}},` +
`"oidc":{"issuer":"` + issuer + `","audiences":["openwebui"],"groupClaim":"groups","groupMap":{"llm-users":"oidcgroup"}}` +
`}`
if err = json.Unmarshal([]byte(cfgJSON), cfgVal.Interface()); err != nil {
return nil, fmt.Errorf("oidc probe: decode config: %w", err)
}
newVal, err := i.Eval(pkgName + ".New")
if err != nil {
return nil, fmt.Errorf("oidc probe: resolve New: %w", err)
}
results := newVal.Call([]reflect.Value{
reflect.ValueOf(context.Background()),
reflect.ValueOf(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})),
cfgVal,
reflect.ValueOf("llmgw-check-oidc"),
})
if errVal := results[1]; !errVal.IsNil() {
return nil, fmt.Errorf("oidc probe: New returned an error: %v", errVal.Interface())
}
handler, ok := results[0].Interface().(http.Handler)
if !ok || handler == nil {
return nil, fmt.Errorf("oidc probe: New did not return an http.Handler")
}
return handler, nil
}
// exerciseOIDC admits RS256, PS256 and ES256 tokens, refuses a token with
// no mapped group (403) and one with the wrong audience (401).
func exerciseOIDC(i *interp.Interpreter, pkgName string) error {
rk, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return err
}
ek, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return err
}
keys := &oidcProbeKeys{rsa: rk, ec: ek}
jwks, err := keys.jwks()
if err != nil {
return err
}
var idp *httptest.Server
idp = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/.well-known/openid-configuration":
_ = json.NewEncoder(w).Encode(map[string]string{"issuer": idp.URL, "jwks_uri": idp.URL + "/jwks"})
case "/jwks":
_, _ = w.Write(jwks)
default:
http.NotFound(w, r)
}
}))
defer idp.Close()
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"id":"c1","object":"chat.completion","model":"` + oidcProbeModel + `","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5}}`))
}))
defer upstream.Close()
handler, err := newOIDCProbeHandler(i, pkgName, idp.URL, upstream.URL)
if err != nil {
return err
}
claims := func(mutate func(map[string]any)) map[string]any {
c := map[string]any{
"iss": idp.URL, "aud": "openwebui", "exp": time.Now().Add(time.Hour).Unix(),
"email": "[email protected]", "email_verified": true, "groups": []string{"llm-users"},
}
if mutate != nil {
mutate(c)
}
return c
}
cases := []struct {
mutate func(map[string]any)
name string
alg string
want int
}{
{name: "RS256", alg: "RS256", want: http.StatusOK},
{name: "PS256", alg: "PS256", want: http.StatusOK},
{name: "ES256", alg: "ES256", want: http.StatusOK},
{name: "no mapped group", alg: "RS256", want: http.StatusForbidden, mutate: func(c map[string]any) { c["groups"] = []string{"other"} }},
{name: "wrong audience", alg: "ES256", want: http.StatusUnauthorized, mutate: func(c map[string]any) { c["aud"] = "other" }},
}
for _, tc := range cases {
tok, err := keys.sign(tc.alg, claims(tc.mutate))
if err != nil {
return err
}
body := `{"model":"` + oidcProbeModel + `","messages":[{"role":"user","content":"hi"}]}`
req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+tok)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Code != tc.want {
return fmt.Errorf("oidc probe %s: status = %d, want %d, body=%s", tc.name, rec.Code, tc.want, rec.Body.String())
}
}
return nil
}
+13 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { formatBucketLabel, formatCompactCount, formatContextWindow, formatCostAxis, formatCostDisplay, formatElapsedAgo, formatLimits, formatLatencyMs, formatModelCostHover, formatPercentAxis, formatPercentValue, formatUntil, refreshDetailLabel, refreshLabel, ZERO_TIME } from './format'
import { formatBucketLabel, formatCompactCount, formatContextWindow, formatCostAxis, formatCostDisplay, formatElapsedAgo, formatLimits, formatLatencyMs, formatModelCostHover, formatPercentAxis, formatPercentValue, formatUntil, refreshDetailLabel, refreshLabel, userSourceLabel, ZERO_TIME } from './format'
describe('refreshLabel', () => {
it('reads "discovery off" when discovery is disabled, regardless of lastRefresh', () => {
@@ -337,3 +337,15 @@ describe('formatLimits', () => {
).toBe('req/min 9 (user), tok/min 100 (memberLimits:friends)')
})
})
describe('userSourceLabel', () => {
it('reads "OIDC" for an OIDC virtual user', () => {
expect(userSourceLabel('oidc')).toBe('OIDC')
})
it('keeps the other sources as they are', () => {
expect(userSourceLabel('inline')).toBe('inline')
expect(userSourceLabel('file')).toBe('file')
expect(userSourceLabel('anonymous')).toBe('anonymous')
})
})
+6 -1
View File
@@ -1,4 +1,4 @@
import type { HistoryWindow, LimitSources, LimitsConfig } from '@/types/api'
import type { AdminConsumerUser, HistoryWindow, LimitSources, LimitsConfig } from '@/types/api'
/** ZERO_TIME is Go's zero time.Time value in its default JSON (RFC 3339) encoding — the unset-timestamp sentinel every admin API "never happened yet" field marshals as, and every formatter/test below treats as absent. */
export const ZERO_TIME = '0001-01-01T00:00:00Z'
@@ -429,3 +429,8 @@ export function formatBucketLabel(bucket: string, window: HistoryWindow): string
}
}
}
/** The users-panel badge text for a consumer's `source`: OIDC virtual users read "OIDC". */
export function userSourceLabel(source: AdminConsumerUser['source']): string {
return source === 'oidc' ? 'OIDC' : source
}
+2 -2
View File
@@ -6,7 +6,7 @@ import LimitsForm from '@/components/forms/LimitsForm.vue'
import { useNow } from '@/composables/useNow'
import { providerAccessCell } from '@/lib/access-matrix'
import { kindLabel } from '@/lib/events-filter'
import { formatCompactCount } from '@/lib/format'
import { formatCompactCount, userSourceLabel } from '@/lib/format'
import { formatLastSeen } from '@/lib/last-seen'
import { loadState } from '@/lib/load-state'
import { effectiveLimitRows, meterModel } from '@/lib/meters'
@@ -134,7 +134,7 @@ onUnmounted(() => {
<template v-else>
<div class="flex flex-wrap items-center gap-2 pb-3 text-sm">
<Badge v-if="consumer?.admin" tone="danger" size="sm">admin</Badge>
<Badge v-if="consumer?.source" tone="neutral" variant="outline" size="sm">{{ consumer.source }}</Badge>
<Badge v-if="consumer?.source" tone="neutral" variant="outline" size="sm" data-testid="user-source">{{ userSourceLabel(consumer.source) }}</Badge>
<button
v-for="g in groups"
:key="g"
+3 -2
View File
@@ -905,7 +905,8 @@ export interface AdminCatalogResponse {
* One configured user's consumer-directory row (admin.go:
* adminConsumerUser — phase 2 redesign). `source` is 'inline' (defined
* directly in the plugin config), 'file' (loaded from users.file) or
* 'anonymous' (the keyless principal);
* 'anonymous' (the keyless principal) or 'oidc' (a virtual user admitted
* by an OIDC bearer token);
* `providers`/`models` are this user's OWN personal grant, distinct from
* anything their group(s) already allow.
*/
@@ -913,7 +914,7 @@ export interface AdminConsumerUser {
limits?: LimitsConfig
limitSources?: LimitSources
name: string
source: 'inline' | 'file' | 'anonymous'
source: 'inline' | 'file' | 'anonymous' | 'oidc'
groups: string[]
providers?: string[]
models?: string[]