Files
traefik-llmgateway/oidc_config.go
T
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

326 lines
11 KiB
Go

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
}