Files
traefik-llmgateway/oidc_config.go
T
lukaszraczylo b3fffdbeed fix(oidc): stop a flat claim shadowing a dotted groupClaim
The group lookup tried the raw groupClaim as one top-level key before the
dotted path. A token that carried a flat key such as "realm_access.roles"
next to the nested claim got the flat value. Only a groupClaim with "://"
is one key now. parseClaimPath already keeps such a claim as one segment,
so the separate whole-key lookup is gone. A dotted groupClaim walks the
path, as it did before this branch.
2026-12-02 02:24:52 +00:00

337 lines
12 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:"
// oidcNamespacedClaimMark marks a groupClaim that is one namespaced claim
// name, not a dotted path.
oidcNamespacedClaimMark = "://"
)
// 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"
}
// parseClaimPath splits a dotted claim path. A raw key with a URL scheme
// separator is a namespaced claim name (Auth0), so it stays one segment.
func parseClaimPath(raw string) ([]string, error) {
if raw == "" {
return nil, fmt.Errorf("llmgateway: oidc.groupClaim is required")
}
if strings.Contains(raw, oidcNamespacedClaimMark) {
if strings.TrimSpace(raw) != raw {
return nil, fmt.Errorf("llmgateway: oidc.groupClaim %q has padding", raw)
}
return []string{raw}, nil
}
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
}