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.
281 lines
9.4 KiB
Go
281 lines
9.4 KiB
Go
package traefikllmgateway
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func opaqueFixture(t *testing.T) *authFixture {
|
|
t.Helper()
|
|
fx := newAuthFixture(t, func(s *oidcSettings) { s.userinfo = true })
|
|
fx.idp.userinfo.Store(map[string]any{"email": "[email protected]", "email_verified": true, "groups": []any{"llm-users"}})
|
|
return fx
|
|
}
|
|
|
|
func TestAuthenticate_CanceledCallerDoesNotPoisonFetch(t *testing.T) {
|
|
fx := newAuthFixture(t, nil)
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
cancel()
|
|
if _, st, reason := fx.auth.authenticate(ctx, fx.token(t, nil), nil); st != authOK {
|
|
t.Fatalf("a caller's cancel must not fail the shared key fetch: %v %q", st, reason)
|
|
}
|
|
other := fx.token(t, func(c map[string]any) { c["email"] = "[email protected]" })
|
|
if _, st, reason := fx.run(t, other, nil); st != authOK {
|
|
t.Fatalf("next caller: %v %q", st, reason)
|
|
}
|
|
}
|
|
|
|
func TestProvider_FetchDeadlineCoversDiscoveryAndJWKS(t *testing.T) {
|
|
f := newFakeIDP(t)
|
|
p := newTestProvider(f, newFakeClock())
|
|
p.timeout = 300 * time.Millisecond
|
|
f.delay.Store(int64(200 * time.Millisecond))
|
|
if _, err := p.keysFor("rsa"); err == nil {
|
|
t.Fatal("discovery plus JWKS took 400ms against a 300ms deadline; want an error")
|
|
}
|
|
}
|
|
|
|
func TestAuthenticate_UserinfoOutageNotCached(t *testing.T) {
|
|
fx := opaqueFixture(t)
|
|
fx.idp.userinfoStatus.Store(http.StatusServiceUnavailable)
|
|
if _, st, reason := fx.run(t, "opaque-token-1", nil); st != authUnauthorized || reason != oidcReasonIDPUnavailable {
|
|
t.Fatalf("outage: %v %q", st, reason)
|
|
}
|
|
fx.idp.userinfoStatus.Store(0)
|
|
if _, st, reason := fx.run(t, "opaque-token-1", nil); st != authOK {
|
|
t.Fatalf("an IdP outage must not be cached: %v %q", st, reason)
|
|
}
|
|
}
|
|
|
|
func TestAuthenticate_UserinfoRejectionCached(t *testing.T) {
|
|
fx := opaqueFixture(t)
|
|
fx.idp.userinfo.Store(map[string]any(nil))
|
|
for i := 0; i < 2; i++ {
|
|
if _, st, reason := fx.run(t, "opaque-bad", nil); st != authUnauthorized || reason != oidcReasonUserinfo {
|
|
t.Fatalf("call %d: %v %q", i, st, reason)
|
|
}
|
|
}
|
|
if n := fx.idp.userinfoHits.Load(); n != 1 {
|
|
t.Fatalf("userinfo hits = %d, want 1: an IdP 401 is cached", n)
|
|
}
|
|
}
|
|
|
|
func TestProvider_UserinfoInFlightCap(t *testing.T) {
|
|
f := newFakeIDP(t)
|
|
p := newTestProvider(f, newFakeClock())
|
|
p.queueWait = 20 * time.Millisecond
|
|
for i := 0; i < cap(p.userinfoSlots); i++ {
|
|
p.userinfoSlots <- struct{}{}
|
|
}
|
|
if _, err := p.userinfo(context.Background(), "opaque"); !errors.Is(err, errIDPBusy) {
|
|
t.Fatalf("err = %v, want errIDPBusy", err)
|
|
}
|
|
if n := f.userinfoHits.Load(); n != 0 {
|
|
t.Fatalf("userinfo hits = %d, want 0", n)
|
|
}
|
|
}
|
|
|
|
func TestProvider_DiscoveryBackoffOnUserinfoPath(t *testing.T) {
|
|
f := newFakeIDP(t)
|
|
f.failDiscovery.Store(true)
|
|
p := newTestProvider(f, newFakeClock())
|
|
for i := 0; i < 3; i++ {
|
|
if _, err := p.userinfo(context.Background(), "opaque"); err == nil {
|
|
t.Fatal("want error")
|
|
}
|
|
}
|
|
if n := f.discoveryHits.Load(); n != 1 {
|
|
t.Fatalf("discovery hits = %d, want 1 inside the retry window", n)
|
|
}
|
|
}
|
|
|
|
func TestAuthenticate_RejectionsDoNotEvictVerdicts(t *testing.T) {
|
|
fx := newAuthFixture(t, func(s *oidcSettings) { s.maxUsers = 2; s.jwksRefresh = time.Minute })
|
|
tok := fx.token(t, nil)
|
|
if _, st, _ := fx.run(t, tok, nil); st != authOK {
|
|
t.Fatal(st)
|
|
}
|
|
for i := 0; i < 20; i++ {
|
|
bad := fx.token(t, func(c map[string]any) {
|
|
c["jti"] = fmt.Sprint(i)
|
|
c["exp"] = fx.clock.Now().Add(-time.Hour).Unix()
|
|
})
|
|
if _, st, _ := fx.run(t, bad, nil); st != authUnauthorized {
|
|
t.Fatal(st)
|
|
}
|
|
}
|
|
fx.idp.jwks.Store([]byte(`{"keys":[]}`))
|
|
fx.clock.Advance(2 * time.Minute)
|
|
if _, st, reason := fx.run(t, tok, nil); st != authOK {
|
|
t.Fatalf("a flood of rejected tokens evicted a valid verdict: %v %q", st, reason)
|
|
}
|
|
}
|
|
|
|
func TestAuthenticate_UnknownKidNotCachedOnStaleKeys(t *testing.T) {
|
|
fx := newAuthFixture(t, nil)
|
|
if _, st, _ := fx.run(t, fx.token(t, nil), nil); st != authOK {
|
|
t.Fatal(st)
|
|
}
|
|
fx.clock.Advance(61 * time.Second)
|
|
fx.idp.failJWKS.Store(true)
|
|
rotated := signTestJWT(t, "RS256", "new", oidcKeys(t), nil, func() map[string]any {
|
|
c := baseClaims(fx.clock.Now())
|
|
c["iss"] = fx.idp.srv.URL
|
|
return c
|
|
}())
|
|
if _, st, reason := fx.run(t, rotated, nil); st != authUnauthorized || reason != "unknown_kid" {
|
|
t.Fatalf("outage with stale keys: %v %q", st, reason)
|
|
}
|
|
fx.idp.jwks.Store(bytes.Replace(testJWKS(t, oidcKeys(t)), []byte(`"kid":"rsa"`), []byte(`"kid":"new"`), 1))
|
|
fx.idp.failJWKS.Store(false)
|
|
fx.clock.Advance(6 * time.Second)
|
|
if _, st, reason := fx.run(t, rotated, nil); st != authOK {
|
|
t.Fatalf("unknown_kid on stale keys must not be cached: %v %q", st, reason)
|
|
}
|
|
}
|
|
|
|
func TestAuthenticate_BadAlgSkipsKeyFetch(t *testing.T) {
|
|
fx := newAuthFixture(t, nil)
|
|
c := baseClaims(fx.clock.Now())
|
|
c["iss"] = fx.idp.srv.URL
|
|
tok := signTestJWT(t, "HS256", "rsa", oidcKeys(t), []byte("secret"), c)
|
|
if _, st, reason := fx.run(t, tok, nil); st != authUnauthorized || reason != "bad_alg" {
|
|
t.Fatalf("%v %q", st, reason)
|
|
}
|
|
if d, j := fx.idp.discoveryHits.Load(), fx.idp.jwksHits.Load(); d != 0 || j != 0 {
|
|
t.Fatalf("discovery %d jwks %d, want no IdP call for a disallowed alg", d, j)
|
|
}
|
|
}
|
|
|
|
func TestProvider_RejectsInsecureEndpoints(t *testing.T) {
|
|
f := newFakeIDP(t)
|
|
f.jwksURI.Store("http://idp.example.com/jwks")
|
|
if _, err := newTestProvider(f, newFakeClock()).keysFor("rsa"); !errors.Is(err, errInsecureIDPURL) {
|
|
t.Fatalf("jwks_uri: err = %v, want errInsecureIDPURL", err)
|
|
}
|
|
f2 := newFakeIDP(t)
|
|
f2.userinfoURI.Store("http://idp.example.com/userinfo")
|
|
if _, err := newTestProvider(f2, newFakeClock()).userinfo(context.Background(), "opaque"); !errors.Is(err, errInsecureIDPURL) {
|
|
t.Fatalf("userinfo_endpoint: err = %v, want errInsecureIDPURL", err)
|
|
}
|
|
}
|
|
|
|
func TestParseJWKS_SkipsUnusableKeys(t *testing.T) {
|
|
good := testJWKS(t, oidcKeys(t))
|
|
mixed := bytes.Replace(good, []byte(`{"keys":[`), []byte(`{"keys":[{"kty":"RSA","kid":"broken","n":"!!","e":"AQAB"},`), 1)
|
|
set, err := parseJWKS(mixed)
|
|
if err != nil {
|
|
t.Fatalf("one malformed key must not fail the set: %v", err)
|
|
}
|
|
if _, err := set.lookup("rsa"); err != nil {
|
|
t.Fatal("good key missing")
|
|
}
|
|
small := `{"keys":[{"kty":"RSA","kid":"weak","n":"` + b64(bytes.Repeat([]byte{0xff}, 128)) + `","e":"AQAB"}]}`
|
|
if _, err := parseJWKS([]byte(small)); err == nil {
|
|
t.Fatal("a JWKS whose only key is RSA-1024 must fail")
|
|
}
|
|
if _, err := parseJWKS([]byte(`{"keys":[{"kty":"RSA","kid":"x","n":"!!","e":"AQAB"}]}`)); err == nil {
|
|
t.Fatal("a JWKS with no usable key must fail")
|
|
}
|
|
}
|
|
|
|
func TestAuthenticate_CaseFoldOnlyForEmail(t *testing.T) {
|
|
fx := newAuthFixture(t, func(s *oidcSettings) { s.identityClaim = "sub"; s.requireEmailVerified = false })
|
|
e, st, reason := fx.run(t, fx.token(t, func(c map[string]any) { c["sub"] = "AbC-123" }), nil)
|
|
if st != authOK || e.user.name != "oidc:AbC-123" {
|
|
t.Fatalf("%v %q %+v", st, reason, e)
|
|
}
|
|
a, err := newAuthStore(func() *Config {
|
|
cfg := oidcAuthCfg(&UserConfig{Name: "carl", OIDCIdentity: "AbC-123"})
|
|
cfg.OIDC.IdentityClaim = "sub"
|
|
return cfg
|
|
}())
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, ok := a.oidcOverrides["AbC-123"]; !ok {
|
|
t.Fatalf("override for a case-sensitive sub must keep its case: %v", a.oidcOverrides)
|
|
}
|
|
}
|
|
|
|
func TestAuthenticate_LogsIDPFailureCause(t *testing.T) {
|
|
fx := newAuthFixture(t, nil)
|
|
var (
|
|
mu sync.Mutex
|
|
logs []string
|
|
)
|
|
fx.auth.logf = func(msg string) {
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
logs = append(logs, msg)
|
|
}
|
|
fx.idp.issuerInDoc.Store("https://other.example.com")
|
|
tok := fx.token(t, nil)
|
|
if _, st, _ := fx.run(t, tok, nil); st != authUnauthorized {
|
|
t.Fatal(st)
|
|
}
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
joined := strings.Join(logs, "\n")
|
|
if !strings.Contains(joined, "does not match configured issuer") {
|
|
t.Fatalf("log must name the IdP failure cause; got %q", joined)
|
|
}
|
|
if strings.Contains(joined, tok) {
|
|
t.Fatal("log must never contain the token")
|
|
}
|
|
}
|
|
|
|
func TestAuthenticate_NoGroupReasonNamesIdentity(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) || !strings.Contains(reason, "[email protected]") {
|
|
t.Fatalf("%v %q", st, reason)
|
|
}
|
|
}
|
|
|
|
func TestRegistry_PrunesStaleRecords(t *testing.T) {
|
|
r, client, clock := newRegistryFixture(t)
|
|
stale := clock.Now().Add(-oidcRegistryRetention - time.Hour).Unix()
|
|
if _, err := client.do("HSET", oidcRegistryKey, "oidc:[email protected]", fmt.Sprintf(`{"identity":"[email protected]","groups":["default"],"lastSeen":%d}`, stale)); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
r.touch("oidc:[email protected]", "[email protected]", []string{"default"})
|
|
if _, err := r.load(); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
reply, err := client.do("HGETALL", oidcRegistryKey)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
recs := decodeRegistry(reply)
|
|
if _, ok := recs["oidc:[email protected]"]; ok {
|
|
t.Fatal("a record past retention must be deleted from Redis")
|
|
}
|
|
if _, ok := recs["oidc:[email protected]"]; !ok {
|
|
t.Fatal("a current record must stay")
|
|
}
|
|
}
|
|
|
|
func TestRegistry_TouchedBoundFollowsMaxUsers(t *testing.T) {
|
|
ln := newBehavioralRedisServer(t)
|
|
client, err := buildRedisClient(&RedisConfig{Address: ln.Addr().String()})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { _ = client.Close() })
|
|
r := newOIDCRegistry(client, newFakeClock().Now, func(f func()) { f() }, func(string, ...any) {}, 3)
|
|
for i := 0; i < 10; i++ {
|
|
r.touch(fmt.Sprintf("oidc:u%[email protected]", i), "[email protected]", []string{"default"})
|
|
if len(r.touched) > 3 {
|
|
t.Fatalf("touched holds %d names, bound is 3", len(r.touched))
|
|
}
|
|
}
|
|
}
|