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

249 lines
9.4 KiB
Go

package traefikllmgateway
import (
"net/url"
"reflect"
"strings"
"testing"
"time"
)
func validOIDCConfig() *OIDCConfig {
return &OIDCConfig{
Issuer: "https://idp.example.com/realms/main",
Audiences: []string{"openwebui"},
GroupClaim: "groups",
GroupMap: map[string]string{"llm-users": "staff"},
}
}
func oidcTestGroups() map[string]*group {
return map[string]*group{"staff": {name: "staff"}, "power": {name: "power"}}
}
func TestParseOIDCConfig(t *testing.T) {
tests := []struct {
mutate func(c *OIDCConfig)
name string
wantErr string
}{
{name: "empty issuer", mutate: func(c *OIDCConfig) { c.Issuer = "" }, wantErr: "issuer"},
{name: "plain http issuer", mutate: func(c *OIDCConfig) { c.Issuer = "http://idp.example.com" }, wantErr: "issuer"},
{name: "unparsable issuer", mutate: func(c *OIDCConfig) { c.Issuer = "https://%zz" }, wantErr: "issuer"},
{name: "empty audiences", mutate: func(c *OIDCConfig) { c.Audiences = nil }, wantErr: "audiences"},
{name: "blank audience", mutate: func(c *OIDCConfig) { c.Audiences = []string{" "} }, wantErr: "audiences"},
{name: "empty groupClaim", mutate: func(c *OIDCConfig) { c.GroupClaim = "" }, wantErr: "groupClaim"},
{name: "groupClaim empty segment", mutate: func(c *OIDCConfig) { c.GroupClaim = "a..b" }, wantErr: "groupClaim"},
{name: "empty groupMap", mutate: func(c *OIDCConfig) { c.GroupMap = nil }, wantErr: "groupMap"},
{name: "unknown group", mutate: func(c *OIDCConfig) { c.GroupMap = map[string]string{"x": "nope"} }, wantErr: `unknown group "nope"`},
{name: "negative maxUsers", mutate: func(c *OIDCConfig) { c.MaxUsers = -1 }, wantErr: "maxUsers"},
{name: "bad cacheTTL", mutate: func(c *OIDCConfig) { c.CacheTTL = "soon" }, wantErr: "cacheTTL"},
{name: "zero cacheTTL", mutate: func(c *OIDCConfig) { c.CacheTTL = "0s" }, wantErr: "cacheTTL"},
{name: "bad jwksRefresh", mutate: func(c *OIDCConfig) { c.JWKSRefresh = "-1m" }, wantErr: "jwksRefresh"},
{name: "empty identityClaim path segment", mutate: func(c *OIDCConfig) { c.IdentityClaim = " " }, wantErr: "identityClaim"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
c := validOIDCConfig()
tc.mutate(c)
_, err := parseOIDCConfig(c, oidcTestGroups())
if err == nil || !strings.Contains(err.Error(), tc.wantErr) {
t.Fatalf("err = %v, want containing %q", err, tc.wantErr)
}
})
}
}
func TestParseOIDCConfig_Defaults(t *testing.T) {
s, err := parseOIDCConfig(validOIDCConfig(), oidcTestGroups())
if err != nil {
t.Fatal(err)
}
if s.identityClaim != "email" || !s.requireEmailVerified || s.userinfo {
t.Fatalf("identity defaults: %+v", s)
}
if s.cacheTTL != 5*time.Minute || s.jwksRefresh != time.Hour || s.maxUsers != 10000 {
t.Fatalf("duration/size defaults: %+v", s)
}
if !s.audiences["openwebui"] || len(s.audiences) != 1 {
t.Fatalf("audiences = %v", s.audiences)
}
if !reflect.DeepEqual(s.groupClaim, []string{"groups"}) {
t.Fatalf("groupClaim = %v", s.groupClaim)
}
}
func TestParseOIDCConfig_Overrides(t *testing.T) {
c := validOIDCConfig()
c.Issuer = "http://127.0.0.1:8080/"
c.IdentityClaim = "sub"
c.GroupClaim = "realm_access.roles"
c.CacheTTL = "30s"
c.JWKSRefresh = "10m"
c.MaxUsers = 3
c.Userinfo = true
s, err := parseOIDCConfig(c, oidcTestGroups())
if err != nil {
t.Fatal(err)
}
if s.issuer != "http://127.0.0.1:8080/" {
t.Fatalf("issuer = %q", s.issuer)
}
if s.identityClaim != "sub" || s.requireEmailVerified {
t.Fatalf("non-email identity must not require email_verified by default: %+v", s)
}
if !reflect.DeepEqual(s.groupClaim, []string{"realm_access", "roles"}) {
t.Fatalf("groupClaim = %v", s.groupClaim)
}
if s.cacheTTL != 30*time.Second || s.jwksRefresh != 10*time.Minute || s.maxUsers != 3 || !s.userinfo {
t.Fatalf("overrides: %+v", s)
}
off := false
c.IdentityClaim = "email"
c.RequireEmailVerified = &off
s, err = parseOIDCConfig(c, oidcTestGroups())
if err != nil {
t.Fatal(err)
}
if s.requireEmailVerified {
t.Fatal("explicit requireEmailVerified=false must win")
}
}
func oidcAuthCfg(users ...*UserConfig) *Config {
return &Config{
Providers: map[string]*ProviderConfig{"openai": {Type: "openai", APIKey: "k"}},
Groups: map[string]*GroupConfig{
"staff": {MemberLimits: &LimitsConfig{RequestsPerMinute: 10}},
"power": {},
},
OIDC: validOIDCConfig(),
Users: &UsersConfig{Inline: users},
}
}
func TestNewAuthStore_OIDCOverrides(t *testing.T) {
a, err := newAuthStore(oidcAuthCfg(
&UserConfig{Name: "bob", Group: "staff", APIKey: "sk-bob"},
&UserConfig{Name: "alice", OIDCIdentity: "[email protected]", Limits: &LimitsConfig{RequestsPerMinute: 5}},
))
if err != nil {
t.Fatal(err)
}
ov, ok := a.oidcOverrides["[email protected]"]
if !ok || ov.name != "alice" || ov.limits.RequestsPerMinute != 5 {
t.Fatalf("override index = %+v", a.oidcOverrides)
}
if len(a.byDigest) != 1 {
t.Fatalf("override must not be a keyed user; byDigest has %d entries", len(a.byDigest))
}
if !a.oidcEnabled {
t.Fatal("oidcEnabled must be set when cfg.OIDC is set")
}
bad := []struct {
uc *UserConfig
name string
wantErr string
}{
{name: "apiKey", uc: &UserConfig{Name: "c", OIDCIdentity: "c@x", APIKey: "k"}, wantErr: "apiKey"},
{name: "group", uc: &UserConfig{Name: "c", OIDCIdentity: "c@x", Group: "staff"}, wantErr: "group"},
{name: "groups", uc: &UserConfig{Name: "c", OIDCIdentity: "c@x", Groups: []string{"staff"}}, wantErr: "group"},
{name: "providers", uc: &UserConfig{Name: "c", OIDCIdentity: "c@x", Providers: []string{"openai"}}, wantErr: "providers"},
{name: "models", uc: &UserConfig{Name: "c", OIDCIdentity: "c@x", Models: []string{"m"}}, wantErr: "models"},
{name: "admin", uc: &UserConfig{Name: "c", OIDCIdentity: "c@x", Admin: true}, wantErr: "admin"},
{name: "no name", uc: &UserConfig{OIDCIdentity: "c@x"}, wantErr: "name"},
{name: "bad limits", uc: &UserConfig{Name: "c", OIDCIdentity: "c@x", Limits: &LimitsConfig{RequestsPerMinute: -1}}, wantErr: `"c"`},
{name: "oidc prefix on keyed user", uc: &UserConfig{Name: "oidc:bob", Group: "staff", APIKey: "k2"}, wantErr: "oidc:"},
{name: "oidc prefix on override", uc: &UserConfig{Name: "oidc:c", OIDCIdentity: "c@x"}, wantErr: "oidc:"},
{name: "duplicate identity", uc: &UserConfig{Name: "alice2", OIDCIdentity: "[email protected]"}, wantErr: "duplicate oidcIdentity"},
{name: "name clashes with keyed user", uc: &UserConfig{Name: "bob", OIDCIdentity: "b@x"}, wantErr: "duplicate user name"},
{name: "name clashes with override", uc: &UserConfig{Name: "alice", OIDCIdentity: "other@x"}, wantErr: "duplicate user name"},
}
for _, tc := range bad {
t.Run(tc.name, func(t *testing.T) {
_, err := newAuthStore(oidcAuthCfg(
&UserConfig{Name: "bob", Group: "staff", APIKey: "sk-bob"},
&UserConfig{Name: "alice", OIDCIdentity: "[email protected]"},
tc.uc,
))
if err == nil || !strings.Contains(err.Error(), tc.wantErr) {
t.Fatalf("err = %v, want containing %q", err, tc.wantErr)
}
})
}
}
func TestNewAuthStore_OIDCIdentityNeedsOIDC(t *testing.T) {
cfg := oidcAuthCfg(&UserConfig{Name: "alice", OIDCIdentity: "[email protected]"})
cfg.OIDC = nil
_, err := newAuthStore(cfg)
if err == nil || !strings.Contains(err.Error(), "oidcIdentity needs oidc") {
t.Fatalf("err = %v", err)
}
}
func TestNewAuthStore_OIDCPrefixAllowedWithoutOIDC(t *testing.T) {
cfg := oidcAuthCfg(&UserConfig{Name: "oidc:legacy", Group: "staff", APIKey: "k"})
cfg.OIDC = nil
if _, err := newAuthStore(cfg); err != nil {
t.Fatalf("a keyed user named oidc:* must stay valid while oidc is off: %v", err)
}
}
func TestReplaceFileUsers_OIDCOverrides(t *testing.T) {
a, err := newAuthStore(oidcAuthCfg(
&UserConfig{Name: "bob", Group: "staff", APIKey: "sk-bob"},
&UserConfig{Name: "alice", OIDCIdentity: "[email protected]", Limits: &LimitsConfig{RequestsPerMinute: 5}},
&UserConfig{Name: "carol", OIDCIdentity: "[email protected]"},
))
if err != nil {
t.Fatal(err)
}
err = a.replaceFileUsers([]*UserConfig{
{Name: "dave", Group: "power", APIKey: "sk-dave"},
{Name: "alice-file", OIDCIdentity: "[email protected]", Limits: &LimitsConfig{RequestsPerMinute: 9}},
})
if err != nil {
t.Fatal(err)
}
if len(a.byDigest) != 2 {
t.Fatalf("byDigest = %d entries, want 2 (bob inline + dave file)", len(a.byDigest))
}
if ov := a.oidcOverrides["[email protected]"]; ov == nil || ov.name != "alice-file" || ov.limits.RequestsPerMinute != 9 {
t.Fatalf("file override must replace the inline one: %+v", ov)
}
if ov := a.oidcOverrides["[email protected]"]; ov == nil || ov.name != "carol" {
t.Fatalf("untouched inline override must survive: %+v", ov)
}
err = a.replaceFileUsers([]*UserConfig{
{Name: "x", OIDCIdentity: "[email protected]"},
{Name: "y", OIDCIdentity: "[email protected]"},
})
if err == nil || !strings.Contains(err.Error(), "duplicate oidcIdentity") {
t.Fatalf("err = %v", err)
}
if ov := a.oidcOverrides["[email protected]"]; ov == nil || ov.name != "alice-file" {
t.Fatal("a rejected reload must keep the previous overrides")
}
}
func TestRedactConfig_OIDCIssuerSanitized(t *testing.T) {
cfg := oidcAuthCfg()
issuer := url.URL{Scheme: "https", User: url.UserPassword("user", "hunter2"), Host: "idp.example.com", Path: "/realms/main", RawQuery: "token=s3cret"}
cfg.OIDC.Issuer = issuer.String()
redacted, err := redactConfig(cfg)
if err != nil {
t.Fatal(err)
}
got := redacted["oidc"].(map[string]any)["issuer"].(string)
if strings.Contains(got, "hunter2") || strings.Contains(got, "s3cret") {
t.Fatalf("issuer not sanitized: %q", got)
}
if !strings.Contains(got, "idp.example.com") {
t.Fatalf("issuer host lost: %q", got)
}
}