mirror of
https://github.com/lukaszraczylo/traefik-llmgateway.git
synced 2026-12-06 11:03:52 +00:00
The gateway accepted an ID token when its aud named one of the configured audiences. Keycloak ID tokens carry no other marker. The gateway now refuses a token whose payload typ is ID, or whose header typ is id+jwt, in any letter case. The log reason is id_token. The header check runs before any key fetch. The payload check runs after the signature check. Access tokens still pass.
440 lines
12 KiB
Go
440 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"
|
|
oidcReasonIDToken = "id_token"
|
|
)
|
|
|
|
// 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(o.settings.groupValues(claims))
|
|
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
|
|
case errors.Is(err, errTokenIsIDToken):
|
|
return oidcReasonIDToken
|
|
}
|
|
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
|
|
}
|
|
|
|
// groupValues reads the group claim: the whole groupClaim as one top-level
|
|
// key when present, else the dotted path.
|
|
func (s *oidcSettings) groupValues(claims map[string]any) []string {
|
|
if _, ok := claims[s.groupClaimKey]; s.groupClaimKey != "" && ok {
|
|
return claimStrings(claims, []string{s.groupClaimKey})
|
|
}
|
|
return claimStrings(claims, s.groupClaim)
|
|
}
|
|
|
|
// 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
|
|
}
|