Files
traefik-llmgateway/oidc_jwt.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

383 lines
10 KiB
Go

package traefikllmgateway
import (
"crypto"
"crypto/ecdh"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rsa"
"crypto/sha256"
"crypto/sha512"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"math/big"
"strings"
"time"
)
var (
errTokenMalformed = errors.New("oidc: malformed token")
errTokenExpired = errors.New("oidc: token expired")
errTokenNotYetValid = errors.New("oidc: token not yet valid")
errTokenBadSignature = errors.New("oidc: bad token signature")
errTokenBadAlg = errors.New("oidc: token algorithm not allowed for this key")
errTokenIssuer = errors.New("oidc: token issuer mismatch")
errTokenAudience = errors.New("oidc: token audience not accepted")
errTokenUnknownKid = errors.New("oidc: token signed by an unknown key")
errEmailNotVerified = errors.New("oidc: email not verified")
)
// oidcClockSkew tolerates small clock drift between the IdP and the gateway.
const oidcClockSkew = 60 * time.Second
// jwk is one JSON Web Key (RFC 7517) as published in a JWKS document.
type jwk struct {
Kty string `json:"kty"`
Kid string `json:"kid"`
Use string `json:"use"`
N string `json:"n"`
E string `json:"e"`
Crv string `json:"crv"`
X string `json:"x"`
Y string `json:"y"`
}
// jwkSet holds the usable signature keys of a JWKS, by kid.
type jwkSet struct {
keys map[string]crypto.PublicKey
}
// jwsAlg describes one allowed JWS algorithm.
type jwsAlg struct {
curve elliptic.Curve // nil for RSA algorithms
hash crypto.Hash
pss bool
}
// allowedJWSAlgs is the closed set of accepted algorithms. Symmetric and
// "none" algorithms are absent on purpose: a public key must never act as an
// HMAC secret.
var allowedJWSAlgs = map[string]jwsAlg{
"RS256": {hash: crypto.SHA256},
"RS384": {hash: crypto.SHA384},
"RS512": {hash: crypto.SHA512},
"PS256": {hash: crypto.SHA256, pss: true},
"ES256": {hash: crypto.SHA256, curve: elliptic.P256()},
"ES384": {hash: crypto.SHA384, curve: elliptic.P384()},
}
// parseJWKS reads the signature keys from a JWKS document. Keys for
// encryption, key types this gateway does not verify and malformed or weak
// keys are skipped, so one bad key cannot block the others. It fails only
// when a supported key was malformed and no usable key remains.
func parseJWKS(body []byte) (*jwkSet, error) {
var doc struct {
Keys []jwk `json:"keys"`
}
if err := json.Unmarshal(body, &doc); err != nil {
return nil, fmt.Errorf("oidc: jwks: %w", err)
}
set := &jwkSet{keys: make(map[string]crypto.PublicKey, len(doc.Keys))}
var firstErr error
for _, k := range doc.Keys {
if k.Use != "" && k.Use != "sig" {
continue
}
var (
pub crypto.PublicKey
err error
)
switch k.Kty {
case "RSA":
pub, err = rsaKey(k)
case "EC":
curve := curveByName(k.Crv)
if curve == nil {
continue
}
pub, err = ecKey(k, curve)
default:
continue
}
if err != nil {
if firstErr == nil {
firstErr = fmt.Errorf("oidc: jwks key %q: %w", k.Kid, err)
}
continue
}
set.keys[k.Kid] = pub
}
if len(set.keys) == 0 && firstErr != nil {
return nil, firstErr
}
return set, nil
}
func ecdhCurve(c elliptic.Curve) ecdh.Curve {
if c == elliptic.P384() {
return ecdh.P384()
}
return ecdh.P256()
}
func curveByName(name string) elliptic.Curve {
switch name {
case "P-256":
return elliptic.P256()
case "P-384":
return elliptic.P384()
}
return nil
}
func rsaKey(k jwk) (*rsa.PublicKey, error) {
n, err := base64.RawURLEncoding.DecodeString(k.N)
if err != nil {
return nil, fmt.Errorf("modulus: %w", err)
}
e, err := base64.RawURLEncoding.DecodeString(k.E)
if err != nil {
return nil, fmt.Errorf("exponent: %w", err)
}
exp := new(big.Int).SetBytes(e)
if len(n) == 0 || !exp.IsInt64() || exp.Int64() < 3 || exp.Int64() > 1<<31-1 {
return nil, errors.New("invalid RSA parameters")
}
mod := new(big.Int).SetBytes(n)
if mod.BitLen() < oidcMinRSABits {
return nil, fmt.Errorf("RSA key of %d bits is under %d", mod.BitLen(), oidcMinRSABits)
}
return &rsa.PublicKey{N: mod, E: int(exp.Int64())}, nil
}
func ecKey(k jwk, curve elliptic.Curve) (*ecdsa.PublicKey, error) {
x, err := base64.RawURLEncoding.DecodeString(k.X)
if err != nil {
return nil, fmt.Errorf("x: %w", err)
}
y, err := base64.RawURLEncoding.DecodeString(k.Y)
if err != nil {
return nil, fmt.Errorf("y: %w", err)
}
size := (curve.Params().BitSize + 7) / 8
if len(x) != size || len(y) != size {
return nil, errors.New("coordinate length does not match the curve")
}
// crypto/ecdh's NewPublicKey rejects a point that is not on the curve.
point := append(append([]byte{4}, x...), y...)
if _, err := ecdhCurve(curve).NewPublicKey(point); err != nil {
return nil, fmt.Errorf("point: %w", err)
}
return &ecdsa.PublicKey{Curve: curve, X: new(big.Int).SetBytes(x), Y: new(big.Int).SetBytes(y)}, nil
}
// oidcMinRSABits is the smallest RSA modulus accepted for token signatures.
const oidcMinRSABits = 2048
// jwtHeader is the protected header of a compact JWS.
type jwtHeader struct {
Alg string `json:"alg"`
Kid string `json:"kid"`
}
func splitJWT(token string) ([]string, *jwtHeader, error) {
parts := strings.Split(token, ".")
if len(parts) != 3 {
return nil, nil, errTokenMalformed
}
raw, err := base64.RawURLEncoding.DecodeString(parts[0])
if err != nil {
return nil, nil, errTokenMalformed
}
var hdr jwtHeader
if err := json.Unmarshal(raw, &hdr); err != nil || hdr.Alg == "" {
return nil, nil, errTokenMalformed
}
return parts, &hdr, nil
}
// looksLikeJWT reports whether token has the compact JWS shape, so an opaque
// token is never sent through signature checks.
func looksLikeJWT(token string) bool {
_, _, err := splitJWT(token)
return err == nil
}
// jwtKid returns the kid of token's protected header. A disallowed alg is
// refused here, before any key fetch.
func jwtKid(token string) (string, error) {
_, hdr, err := splitJWT(token)
if err != nil {
return "", err
}
if _, ok := allowedJWSAlgs[hdr.Alg]; !ok {
return "", errTokenBadAlg
}
return hdr.Kid, nil
}
// verifyJWT checks token's signature against keys and its claims against s,
// and returns the claims.
func verifyJWT(token string, keys *jwkSet, s *oidcSettings, now time.Time) (map[string]any, error) {
parts, hdr, err := splitJWT(token)
if err != nil {
return nil, err
}
alg, ok := allowedJWSAlgs[hdr.Alg]
if !ok {
return nil, errTokenBadAlg
}
pub, err := keys.lookup(hdr.Kid)
if err != nil {
return nil, err
}
sig, err := base64.RawURLEncoding.DecodeString(parts[2])
if err != nil {
return nil, errTokenBadSignature
}
if err = verifySignature(alg, pub, []byte(parts[0]+"."+parts[1]), sig); err != nil {
return nil, err
}
raw, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return nil, errTokenMalformed
}
var claims map[string]any
if err := json.Unmarshal(raw, &claims); err != nil {
return nil, errTokenMalformed
}
if err := checkClaims(claims, s, now); err != nil {
return nil, err
}
return claims, nil
}
// lookup returns the key for kid. A token without a kid matches only when
// the set holds exactly one key.
func (k *jwkSet) lookup(kid string) (crypto.PublicKey, error) {
if pub, ok := k.keys[kid]; ok {
return pub, nil
}
if kid == "" && len(k.keys) == 1 {
for _, pub := range k.keys {
return pub, nil
}
}
return nil, errTokenUnknownKid
}
func verifySignature(alg jwsAlg, pub crypto.PublicKey, input, sig []byte) error {
digest := hashInput(alg.hash, input)
switch key := pub.(type) {
case *rsa.PublicKey:
if alg.curve != nil {
return errTokenBadAlg
}
var err error
if alg.pss {
err = rsa.VerifyPSS(key, alg.hash, digest, sig, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
} else {
err = rsa.VerifyPKCS1v15(key, alg.hash, digest, sig)
}
if err != nil {
return errTokenBadSignature
}
return nil
case *ecdsa.PublicKey:
if alg.curve == nil || key.Curve != alg.curve {
return errTokenBadAlg
}
size := (key.Curve.Params().BitSize + 7) / 8
if len(sig) != 2*size {
return errTokenBadSignature
}
r := new(big.Int).SetBytes(sig[:size])
sv := new(big.Int).SetBytes(sig[size:])
if !ecdsa.Verify(key, digest, r, sv) {
return errTokenBadSignature
}
return nil
}
return errTokenBadAlg
}
func hashInput(h crypto.Hash, input []byte) []byte {
switch h {
case crypto.SHA384:
d := sha512.Sum384(input)
return d[:]
case crypto.SHA512:
d := sha512.Sum512(input)
return d[:]
default:
d := sha256.Sum256(input)
return d[:]
}
}
func checkClaims(claims map[string]any, s *oidcSettings, now time.Time) error {
if iss, _ := claims["iss"].(string); iss != s.issuer {
return errTokenIssuer
}
exp, ok := numericClaim(claims, "exp")
if !ok || now.After(time.Unix(exp, 0).Add(oidcClockSkew)) {
return errTokenExpired
}
if nbf, ok := numericClaim(claims, "nbf"); ok && now.Add(oidcClockSkew).Before(time.Unix(nbf, 0)) {
return errTokenNotYetValid
}
if !audienceAccepted(claims, s.audiences, s.acceptAzp) {
return errTokenAudience
}
if s.requireEmailVerified && !emailVerified(claims) {
return errEmailNotVerified
}
return nil
}
func numericClaim(claims map[string]any, name string) (int64, bool) {
v, ok := claims[name].(float64)
if !ok {
return 0, false
}
return int64(v), true
}
// audienceAccepted matches aud (a string or an array). With acceptAzp it
// also matches azp: Keycloak and similar IdPs put the requesting client in
// azp, not aud, of access tokens. azp alone also passes a token the client
// obtained for another service, so it is opt-in.
func audienceAccepted(claims map[string]any, accepted map[string]bool, acceptAzp bool) bool {
switch aud := claims["aud"].(type) {
case string:
if accepted[aud] {
return true
}
case []any:
for _, a := range aud {
if s, ok := a.(string); ok && accepted[s] {
return true
}
}
}
if !acceptAzp {
return false
}
azp, _ := claims["azp"].(string)
return azp != "" && accepted[azp]
}
// emailVerified accepts a boolean true or the string "true", which some IdPs
// emit.
func emailVerified(claims map[string]any) bool {
switch v := claims["email_verified"].(type) {
case bool:
return v
case string:
return v == "true"
}
return false
}