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.
270 lines
9.2 KiB
Go
270 lines
9.2 KiB
Go
package traefikllmgateway
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"net/http"
|
|
"reflect"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func oidcAuthTestGroups(t *testing.T) map[string]*group {
|
|
t.Helper()
|
|
a, err := newAuthStore(&Config{
|
|
Providers: map[string]*ProviderConfig{"openai": {Type: "openai", APIKey: "k"}},
|
|
Groups: map[string]*GroupConfig{
|
|
"staff": {MemberLimits: &LimitsConfig{RequestsPerMinute: 10, TokensPerDay: 500}},
|
|
"power": {MemberLimits: &LimitsConfig{RequestsPerMinute: 20}},
|
|
},
|
|
})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return a.groups
|
|
}
|
|
|
|
type authFixture struct {
|
|
idp *fakeIDP
|
|
clock *fakeClock
|
|
auth *oidcAuthenticator
|
|
}
|
|
|
|
func newAuthFixture(t *testing.T, mutate func(s *oidcSettings)) *authFixture {
|
|
t.Helper()
|
|
f := newFakeIDP(t)
|
|
clock := newFakeClock()
|
|
s := f.settings()
|
|
s.groupMap = map[string]string{"llm-users": "staff", "llm-power": "power"}
|
|
if mutate != nil {
|
|
mutate(s)
|
|
}
|
|
p := newOIDCProvider(s, &http.Client{Timeout: 5 * time.Second}, clock.Now)
|
|
return &authFixture{idp: f, clock: clock, auth: newOIDCAuthenticator(s, p, oidcAuthTestGroups(t), clock.Now)}
|
|
}
|
|
|
|
func (fx *authFixture) token(t *testing.T, mutate func(c map[string]any)) string {
|
|
t.Helper()
|
|
c := baseClaims(fx.clock.Now())
|
|
c["iss"] = fx.idp.srv.URL
|
|
if mutate != nil {
|
|
mutate(c)
|
|
}
|
|
return signTestJWT(t, "RS256", "rsa", oidcKeys(t), nil, c)
|
|
}
|
|
|
|
func (fx *authFixture) run(t *testing.T, tok string, overrides map[string]*oidcOverride) (*authEntry, authStatus, string) {
|
|
t.Helper()
|
|
return fx.auth.authenticate(context.Background(), tok, overrides)
|
|
}
|
|
|
|
func TestClaims_GroupShapes(t *testing.T) {
|
|
tests := []struct {
|
|
mutateClaims func(c map[string]any)
|
|
name string
|
|
groupClaim []string
|
|
}{
|
|
{name: "string", groupClaim: []string{"groups"}, mutateClaims: func(c map[string]any) { c["groups"] = "llm-users" }},
|
|
{name: "array", groupClaim: []string{"groups"}, mutateClaims: func(c map[string]any) { c["groups"] = []string{"x", "llm-users"} }},
|
|
{name: "nested path", groupClaim: []string{"realm_access", "roles"}, mutateClaims: func(c map[string]any) {
|
|
delete(c, "groups")
|
|
c["realm_access"] = map[string]any{"roles": []string{"llm-users"}}
|
|
}},
|
|
}
|
|
for _, tc := range tests {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
fx := newAuthFixture(t, func(s *oidcSettings) { s.groupClaim = tc.groupClaim })
|
|
entry, st, reason := fx.run(t, fx.token(t, tc.mutateClaims), nil)
|
|
if st != authOK {
|
|
t.Fatalf("status %v reason %q", st, reason)
|
|
}
|
|
if !reflect.DeepEqual(entry.user.groupNames, []string{"staff"}) {
|
|
t.Fatalf("groups = %v", entry.user.groupNames)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestClaimStrings_IgnoresNonStrings(t *testing.T) {
|
|
claims := map[string]any{"a": map[string]any{"b": []any{"x", 3.0, true, "y"}}, "n": 5.0}
|
|
if got := claimStrings(claims, []string{"a", "b"}); !reflect.DeepEqual(got, []string{"x", "y"}) {
|
|
t.Fatalf("claimStrings = %v", got)
|
|
}
|
|
if got := claimStrings(claims, []string{"a", "missing"}); got != nil {
|
|
t.Fatalf("missing path = %v", got)
|
|
}
|
|
if _, ok := claimString(claims, []string{"n"}); ok {
|
|
t.Fatal("a number is not an identity string")
|
|
}
|
|
}
|
|
|
|
func TestAuthenticate_NoMappedGroup(t *testing.T) {
|
|
fx := newAuthFixture(t, nil)
|
|
_, st, reason := fx.run(t, fx.token(t, func(c map[string]any) { c["groups"] = []string{"other"} }), nil)
|
|
if st != authForbidden || !strings.HasPrefix(reason, oidcReasonNoGroup) {
|
|
t.Fatalf("status %v reason %q", st, reason)
|
|
}
|
|
}
|
|
|
|
func TestAuthenticate_MultiGroup(t *testing.T) {
|
|
fx := newAuthFixture(t, nil)
|
|
entry, st, _ := fx.run(t, fx.token(t, func(c map[string]any) { c["groups"] = []string{"llm-users", "llm-power", "llm-users"} }), nil)
|
|
if st != authOK {
|
|
t.Fatal(st)
|
|
}
|
|
if !reflect.DeepEqual(entry.user.groupNames, []string{"power", "staff"}) {
|
|
t.Fatalf("groupNames = %v", entry.user.groupNames)
|
|
}
|
|
if entry.user.limits.RequestsPerMinute != 10 || entry.user.limits.TokensPerDay != 500 {
|
|
t.Fatalf("limits = %+v, want the per-field minimum", entry.user.limits)
|
|
}
|
|
}
|
|
|
|
func TestAuthenticate_VirtualName(t *testing.T) {
|
|
fx := newAuthFixture(t, nil)
|
|
tok := fx.token(t, nil)
|
|
entry, st, _ := fx.run(t, tok, nil)
|
|
if st != authOK || entry.user.name != "oidc:[email protected]" {
|
|
t.Fatalf("status %v name %q", st, entry.user.name)
|
|
}
|
|
if entry.digest != ([32]byte{}) {
|
|
t.Fatal("a virtual user must have no key digest")
|
|
}
|
|
overrides := map[string]*oidcOverride{"[email protected]": {name: "alice", limits: &LimitsConfig{RequestsPerMinute: 3}}}
|
|
entry, st, _ = fx.run(t, tok, overrides)
|
|
if st != authOK || entry.user.name != "alice" {
|
|
t.Fatalf("status %v name %q", st, entry.user.name)
|
|
}
|
|
if entry.user.limits.RequestsPerMinute != 3 || entry.user.limitSources["requestsPerMinute"] != "user" {
|
|
t.Fatalf("limits %+v sources %v", entry.user.limits, entry.user.limitSources)
|
|
}
|
|
if entry.user.limits.TokensPerDay != 500 {
|
|
t.Fatalf("unset override fields must fall back to memberLimits: %+v", entry.user.limits)
|
|
}
|
|
}
|
|
|
|
func TestAuthenticate_IdentityCaseFolded(t *testing.T) {
|
|
fx := newAuthFixture(t, nil)
|
|
overrides := map[string]*oidcOverride{"[email protected]": {name: "alice"}}
|
|
entry, st, _ := fx.run(t, fx.token(t, func(c map[string]any) { c["email"] = "[email protected]" }), overrides)
|
|
if st != authOK || entry.user.name != "alice" {
|
|
t.Fatalf("status %v name %q", st, entry.user.name)
|
|
}
|
|
}
|
|
|
|
func TestAuthenticate_MissingIdentityClaim(t *testing.T) {
|
|
fx := newAuthFixture(t, nil)
|
|
_, st, reason := fx.run(t, fx.token(t, func(c map[string]any) { delete(c, "email") }), nil)
|
|
if st != authUnauthorized || reason != "no_identity" {
|
|
t.Fatalf("status %v reason %q", st, reason)
|
|
}
|
|
}
|
|
|
|
func TestAuthenticate_InvalidTokenReasons(t *testing.T) {
|
|
fx := newAuthFixture(t, nil)
|
|
_, st, reason := fx.run(t, fx.token(t, func(c map[string]any) { c["aud"] = "other" }), nil)
|
|
if st != authUnauthorized || reason != "aud" {
|
|
t.Fatalf("status %v reason %q", st, reason)
|
|
}
|
|
_, st, reason = fx.run(t, fx.token(t, func(c map[string]any) { c["exp"] = fx.clock.Now().Add(-2 * time.Minute).Unix() }), nil)
|
|
if st != authUnauthorized || reason != "expired" {
|
|
t.Fatalf("status %v reason %q", st, reason)
|
|
}
|
|
}
|
|
|
|
func TestAuthenticate_TokenCacheHit(t *testing.T) {
|
|
fx := newAuthFixture(t, func(s *oidcSettings) { s.jwksRefresh = time.Minute })
|
|
tok := fx.token(t, nil)
|
|
if _, st, _ := fx.run(t, tok, nil); st != authOK {
|
|
t.Fatal(st)
|
|
}
|
|
// Rotate the IdP keys and let the JWKS go stale: only a cache hit can
|
|
// still admit the token without a JWKS fetch.
|
|
fx.idp.jwks.Store([]byte(`{"keys":[]}`))
|
|
fx.clock.Advance(2 * time.Minute)
|
|
if _, st, reason := fx.run(t, tok, nil); st != authOK {
|
|
t.Fatalf("cached token rejected: %v %q", st, reason)
|
|
}
|
|
if j := fx.idp.jwksHits.Load(); j != 1 {
|
|
t.Fatalf("jwks hits = %d, want 1", j)
|
|
}
|
|
}
|
|
|
|
func TestAuthenticate_CacheClampedToExp(t *testing.T) {
|
|
fx := newAuthFixture(t, nil)
|
|
tok := fx.token(t, func(c map[string]any) { c["exp"] = fx.clock.Now().Add(30 * time.Second).Unix() })
|
|
if _, st, _ := fx.run(t, tok, nil); st != authOK {
|
|
t.Fatal(st)
|
|
}
|
|
fx.clock.Advance(91 * time.Second)
|
|
if _, st, reason := fx.run(t, tok, nil); st != authUnauthorized || reason != "expired" {
|
|
t.Fatalf("status %v reason %q, want expired once past exp", st, reason)
|
|
}
|
|
}
|
|
|
|
func TestAuthenticate_NegativeCache(t *testing.T) {
|
|
fx := newAuthFixture(t, nil)
|
|
for range 2 {
|
|
if _, st, _ := fx.run(t, "opaque-garbage", nil); st != authUnauthorized {
|
|
t.Fatal(st)
|
|
}
|
|
}
|
|
if h := fx.idp.userinfoHits.Load(); h != 1 {
|
|
t.Fatalf("userinfo hits = %d, want 1 within the negative TTL", h)
|
|
}
|
|
fx.clock.Advance(31 * time.Second)
|
|
if _, st, _ := fx.run(t, "opaque-garbage", nil); st != authUnauthorized {
|
|
t.Fatal(st)
|
|
}
|
|
if h := fx.idp.userinfoHits.Load(); h != 2 {
|
|
t.Fatalf("userinfo hits = %d, want 2 after the negative TTL", h)
|
|
}
|
|
}
|
|
|
|
func TestAuthenticate_OpaqueAccepted(t *testing.T) {
|
|
fx := newAuthFixture(t, nil)
|
|
fx.idp.userinfo.Store(map[string]any{"email": "[email protected]", "email_verified": true, "groups": []string{"llm-users"}})
|
|
entry, st, reason := fx.run(t, "opaque-ok", nil)
|
|
if st != authOK || entry.user.name != "oidc:[email protected]" {
|
|
t.Fatalf("status %v reason %q", st, reason)
|
|
}
|
|
fx.idp.userinfo.Store(map[string]any{"email": "[email protected]", "email_verified": false, "groups": []string{"llm-users"}})
|
|
if _, st, reason := fx.run(t, "opaque-unverified", nil); st != authUnauthorized || reason != "email_unverified" {
|
|
t.Fatalf("status %v reason %q", st, reason)
|
|
}
|
|
}
|
|
|
|
func TestAuthenticate_OpaqueDisabled(t *testing.T) {
|
|
fx := newAuthFixture(t, func(s *oidcSettings) { s.userinfo = false })
|
|
if _, st, reason := fx.run(t, "opaque-token", nil); st != authUnauthorized || reason != "opaque_disabled" {
|
|
t.Fatalf("status %v reason %q", st, reason)
|
|
}
|
|
if d, u := fx.idp.discoveryHits.Load(), fx.idp.userinfoHits.Load(); d != 0 || u != 0 {
|
|
t.Fatalf("IdP hits discovery %d userinfo %d, want 0", d, u)
|
|
}
|
|
}
|
|
|
|
func TestAuthenticate_LRUBound(t *testing.T) {
|
|
fx := newAuthFixture(t, func(s *oidcSettings) { s.maxUsers = 3 })
|
|
for i := range 5 {
|
|
tok := fx.token(t, func(c map[string]any) { c["email"] = fmt.Sprintf("u%[email protected]", i) })
|
|
if _, st, _ := fx.run(t, tok, nil); st != authOK {
|
|
t.Fatal(st)
|
|
}
|
|
}
|
|
users := fx.auth.users()
|
|
if len(users) != 3 {
|
|
t.Fatalf("users = %d, want 3", len(users))
|
|
}
|
|
got := map[string]bool{}
|
|
for _, u := range users {
|
|
got[u.user.name] = true
|
|
}
|
|
for _, want := range []string{"oidc:[email protected]", "oidc:[email protected]", "oidc:[email protected]"} {
|
|
if !got[want] {
|
|
t.Fatalf("most recent users missing %q: %v", want, got)
|
|
}
|
|
}
|
|
}
|