Files
traefik-llmgateway/admin_config.go
lukaszraczyloandGitHub 6805253f91 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.
2026-12-02 01:22:30 +00:00

183 lines
7.4 KiB
Go

package traefikllmgateway
import (
"encoding/json"
"net/http"
"strings"
)
// adminConfigPath is GET /admin/api/config's route (admin dashboard
// redesign, WP-B) — defined here, alongside the rest of this feature's
// own constants, mirroring adminEventsPath's own precedent (events.go).
const adminConfigPath = "/admin/api/config"
// redactedSecretPlaceholder replaces a LITERAL secret value redactConfig
// finds (below) — never an "env:"/"file:" indirection, which is kept
// verbatim (redactSecretString's own doc comment).
const redactedSecretPlaceholder = "[redacted]"
// adminConfigResponse is the full body of GET /admin/api/config: the
// live Config, redacted (redactConfig, below) so no secret — a literal
// API key, Redis password, or embedded URL credential — ever leaves the
// process, plus the SAME construction warnings GET /admin/api/overview
// already exposes (Warnings) and the SAME feature-availability flags
// (Features, admin.go's buildAdminFeatures) every other new admin
// endpoint echoes, so the Config tab's change-helper forms can gate
// their own UI on the identical flags without a second round trip.
type adminConfigResponse struct {
Config map[string]any `json:"config"`
Version string `json:"version"`
Warnings []string `json:"warnings"`
Features adminFeaturesView `json:"features"`
}
// redactedConfigKeys names every JSON object key redactConfig treats as
// carrying a secret VALUE outright (as opposed to baseURLLikeConfigKeys,
// below, whose value is a URL that may EMBED one): "apiKey" (Provider/
// UserConfig) and "password" (RedisConfig). Matched by JSON key name
// alone, not by which Go struct it came from — redactConfig walks the
// generic map[string]any json.Marshal produces, with no notion of the
// original struct type, so a future secret-shaped field is covered
// automatically the moment it reuses one of these same JSON tag names.
var redactedConfigKeys = map[string]bool{
"apiKey": true,
"password": true,
}
// hiddenConfigKeys names JSON keys whose non-empty value is replaced
// outright: RedisConfig.Address ("address"), which can embed credentials in
// a redis:// URL. UsersConfig.File stays visible on purpose, as a path
// reveals where user keys live without holding one.
var hiddenConfigKeys = map[string]bool{
"address": true,
}
// baseURLLikeConfigKeys names every JSON object key redactConfig passes
// through sanitizeBaseURL (admin.go) instead of the literal/env/file
// redaction rule above: ProviderConfig.BaseURL ("baseUrl") and
// TargetConfig/AgentConfig.URL ("url") — a URL is not itself a secret,
// but an operator can embed one in its userinfo or query string
// (sanitizeBaseURL's own doc comment), exactly the same risk GET
// /admin/api/overview's adminProviderView.BaseURL already guards
// against.
var baseURLLikeConfigKeys = map[string]bool{
"baseUrl": true,
"url": true,
"issuer": true,
}
// redactConfig returns a redacted map[string]any view of cfg, safe to
// serve over GET /admin/api/config (plan §6's security risk: "new
// endpoints expose user/model names... config redaction fuzz-tested").
// cfg is round-tripped through json.Marshal then json.Unmarshal into a
// generic map, then walked recursively (redactValue, below), so the walk
// needs no knowledge of Config's own nested struct types — a field added
// to any struct in llmgateway.go is redacted automatically the moment it
// round-trips through this walk, purely by its JSON key name matching
// redactedConfigKeys or baseURLLikeConfigKeys.
//
// The marshal/unmarshal round trip can fail only for a Config value that
// is not itself valid JSON in the first place — never reachable for a
// *Gateway's own g.cfg, which newGateway already round-tripped through
// Traefik's own YAML/JSON decoder to construct — so an error here is
// reported, never silently swallowed, but is not expected to fire on any
// real, already-running Gateway (buildAdminConfig, below, degrades
// gracefully rather than 500ing if it ever does).
func redactConfig(cfg *Config) (map[string]any, error) {
raw, err := json.Marshal(cfg)
if err != nil {
return nil, err
}
var m map[string]any
if err := json.Unmarshal(raw, &m); err != nil {
return nil, err
}
redactValue(m)
return m, nil
}
// redactValue walks v in place. json.Unmarshal decodes a JSON object
// into map[string]any and a JSON array into []any — the two cases this
// switch handles — so this walk reaches every nesting depth Config's own
// struct tree can produce (Config.Groups, Config.Users.Inline,
// Config.Providers, Config.MCPServers, Config.Agents, Config.ModelMeta,
// Config.Pricing all nest further object/array values) without needing
// its own copy of that struct tree's shape.
func redactValue(v any) {
switch t := v.(type) {
case map[string]any:
for k, val := range t {
s, isString := val.(string)
switch {
case redactedConfigKeys[k] && isString:
t[k] = redactSecretString(s)
case hiddenConfigKeys[k] && isString:
if s != "" {
t[k] = redactedSecretPlaceholder
}
case baseURLLikeConfigKeys[k] && isString:
t[k] = sanitizeBaseURL(s)
default:
redactValue(val)
}
}
case []any:
for _, item := range t {
redactValue(item)
}
}
}
// redactSecretString applies plan §1.3(ix)'s redaction rule to one
// apiKey/password value: empty stays empty (nothing configured, nothing
// to hide), an "env:NAME" or "file:/path" reference is kept verbatim
// (resolveSecret's own doc comment, secrets.go — neither form is the
// secret itself, only where to find it, and an operator reading their
// own config back needs to see which indirection a field actually uses),
// and any other value — a literal secret typed directly into config — is
// replaced with redactedSecretPlaceholder. Mirrors resolveSecret's own
// "env:"/"file:" prefix check exactly, so a value this function keeps is
// always one resolveSecret would also resolve through an indirection,
// never a literal — fuzz-tested (admin_config_test.go) so no generated
// literal secret ever survives this function.
func redactSecretString(s string) string {
switch {
case s == "":
return s
case strings.HasPrefix(s, "env:"), strings.HasPrefix(s, "file:"):
return s
default:
return redactedSecretPlaceholder
}
}
// buildAdminConfig assembles adminConfigResponse: g.cfg redacted
// (redactConfig, above), the same construction warnings
// configWarningsSnapshot already exposes on GET /admin/api/overview
// (admin.go), and this Gateway's feature-availability flags
// (buildAdminFeatures, admin.go). A redaction failure (redactConfig's
// own doc comment — not expected on any real running Gateway) degrades
// to an empty config map with a warning appended, rather than a 500:
// every other field in the response is still meaningful even if the
// config tree itself could not be built.
func (g *Gateway) buildAdminConfig() adminConfigResponse {
warnings, _ := g.configWarningsSnapshot()
redacted, err := redactConfig(g.cfg)
if err != nil {
redacted = map[string]any{}
warnings = append(warnings, "config redaction failed: "+err.Error())
}
return adminConfigResponse{
Config: redacted,
Warnings: warnings,
Features: g.buildAdminFeatures(),
Version: pluginVersion,
}
}
// serveAdminConfig writes buildAdminConfig's result as JSON.
func (g *Gateway) serveAdminConfig(w http.ResponseWriter) {
setAdminJSONHeaders(w)
_ = json.NewEncoder(w).Encode(g.buildAdminConfig())
}