mirror of
https://github.com/lukaszraczylo/traefik-llmgateway.git
synced 2026-12-06 11:03:52 +00:00
* 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.
428 lines
12 KiB
Go
428 lines
12 KiB
Go
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
|
|
}
|