package traefikllmgateway import ( "net/http" "net/http/httptest" "strings" "testing" ) // oidcGatewayFixture is a Gateway with OIDC on, a fake IdP and a fake // OpenAI-compatible upstream that answers every chat call. type oidcGatewayFixture struct { idp *fakeIDP gw *Gateway h http.Handler cfg *Config } // jwtShapedStaticKey is a configured API key that parses as a JWT header, // to prove a static key wins before any OIDC check. var jwtShapedStaticKey = b64([]byte(`{"alg":"RS256","kid":"rsa"}`)) + ".c3RhdGlj.a2V5" func oidcGatewayConfig(issuer, upstream string) *Config { cfg := CreateConfig() cfg.Admin = &AdminConfig{Enabled: true} cfg.Providers = map[string]*ProviderConfig{ "openai": {Type: "openai", BaseURL: upstream, APIKey: "sk-up", Models: []string{"gpt-test"}}, } cfg.Groups = map[string]*GroupConfig{"default": {MemberLimits: &LimitsConfig{RequestsPerMinute: 50}}} cfg.Users = &UsersConfig{Inline: []*UserConfig{ {Name: "admin1", Group: "default", APIKey: "sk-admin1", Admin: true}, {Name: "dotted", Group: "default", APIKey: jwtShapedStaticKey}, }} cfg.OIDC = &OIDCConfig{ Issuer: issuer, Audiences: []string{"openwebui"}, GroupClaim: "groups", GroupMap: map[string]string{"llm-users": "default"}, } return cfg } func newOIDCGateway(t *testing.T, mutate func(cfg *Config)) *oidcGatewayFixture { t.Helper() idp := newFakeIDP(t) upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{"id":"c1","object":"chat.completion","model":"gpt-test","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5}}`)) })) t.Cleanup(upstream.Close) cfg := oidcGatewayConfig(idp.srv.URL, upstream.URL) if mutate != nil { mutate(cfg) } h, gw := newAdminGatewayHandle(t, cfg) return &oidcGatewayFixture{idp: idp, gw: gw, h: h, cfg: cfg} } func (fx *oidcGatewayFixture) token(t *testing.T, mutate func(c map[string]any)) string { t.Helper() c := baseClaims(fx.gw.auth.nowFn()) c["iss"] = fx.idp.srv.URL if mutate != nil { mutate(c) } return signTestJWT(t, "RS256", "rsa", oidcKeys(t), nil, c) } func (fx *oidcGatewayFixture) chat(t *testing.T, bearer string) *httptest.ResponseRecorder { t.Helper() body := map[string]any{"model": "gpt-test", "messages": []any{map[string]any{"role": "user", "content": "hi"}}} rec := httptest.NewRecorder() fx.h.ServeHTTP(rec, newUnifiedRequest(t, http.MethodPost, "/v1/chat/completions", bearer, body)) return rec } func (fx *oidcGatewayFixture) userRequests(name string) int64 { u := fx.gw.limiter.currentUsage([]limitScope{{kind: "user", id: name}}) return u[0].requestsPerDay } func TestIdentify_StaticKeyBeatsOIDC(t *testing.T) { fx := newOIDCGateway(t, nil) if !looksLikeJWT(jwtShapedStaticKey) { t.Fatal("fixture must look like a JWT") } rec := fx.chat(t, jwtShapedStaticKey) if rec.Code != http.StatusOK { t.Fatalf("status %d body %s", rec.Code, rec.Body.String()) } if fx.userRequests("dotted") != 1 { t.Fatal("request must be accounted to the keyed user") } if d, j := fx.idp.discoveryHits.Load(), fx.idp.jwksHits.Load(); d != 0 || j != 0 { t.Fatalf("IdP hits discovery %d jwks %d, want 0", d, j) } } func TestOIDC_ChatCompletionAccounted(t *testing.T) { fx := newOIDCGateway(t, nil) rec := fx.chat(t, fx.token(t, nil)) if rec.Code != http.StatusOK { t.Fatalf("status %d body %s", rec.Code, rec.Body.String()) } if got := fx.userRequests("oidc:alice@x.com"); got != 1 { t.Fatalf("user requests = %d, want 1", got) } } func TestOIDC_Models(t *testing.T) { fx := newOIDCGateway(t, nil) rec := httptest.NewRecorder() fx.h.ServeHTTP(rec, adminRequest(http.MethodGet, "/v1/models", fx.token(t, nil))) if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "gpt-test") { t.Fatalf("status %d body %s", rec.Code, rec.Body.String()) } } func TestOIDC_NoGroup403(t *testing.T) { fx := newOIDCGateway(t, nil) tok := fx.token(t, func(c map[string]any) { c["groups"] = []string{"other"} }) rec := fx.chat(t, tok) if rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), `"permission_error"`) { t.Fatalf("status %d body %s", rec.Code, rec.Body.String()) } body := map[string]any{"model": "gpt-test", "max_tokens": 5, "messages": []any{map[string]any{"role": "user", "content": "hi"}}} rec = httptest.NewRecorder() fx.h.ServeHTTP(rec, newUnifiedRequest(t, http.MethodPost, messagesPath, tok, body)) if rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), `"type":"error"`) { t.Fatalf("messages: status %d body %s", rec.Code, rec.Body.String()) } if n := fx.gw.auth.failures.get("192.0.2.1"); n != 0 { t.Fatalf("a valid identity without a group is not an auth failure; failures = %d", n) } } func TestOIDC_InvalidToken401(t *testing.T) { fx := newOIDCGateway(t, nil) tok := fx.token(t, func(c map[string]any) { c["aud"] = "someone-else" }) rec := fx.chat(t, tok) if rec.Code != http.StatusUnauthorized { t.Fatalf("status %d", rec.Code) } if n := fx.gw.auth.failures.get("192.0.2.1"); n != 1 { t.Fatalf("auth failures = %d, want 1", n) } } func TestOIDC_AdminRejected(t *testing.T) { fx := newOIDCGateway(t, nil) rec := httptest.NewRecorder() fx.h.ServeHTTP(rec, adminRequest(http.MethodGet, adminUsagePath, fx.token(t, nil))) if rec.Code != http.StatusUnauthorized { t.Fatalf("status %d, want 401", rec.Code) } } func TestOIDC_OverrideReload(t *testing.T) { fx := newOIDCGateway(t, nil) tok := fx.token(t, nil) if err := fx.gw.auth.replaceFileUsers([]*UserConfig{{Name: "alice", OIDCIdentity: "alice@x.com", Limits: &LimitsConfig{RequestsPerMinute: 5}}}); err != nil { t.Fatal(err) } u, _, st := fx.gw.auth.authenticate(adminRequest(http.MethodPost, "/v1/chat/completions", tok)) if st != authOK || u.name != "alice" || u.limits.RequestsPerMinute != 5 { t.Fatalf("status %v user %+v", st, u) } if err := fx.gw.auth.replaceFileUsers([]*UserConfig{{Name: "alice", OIDCIdentity: "alice@x.com", Limits: &LimitsConfig{RequestsPerMinute: 9}}}); err != nil { t.Fatal(err) } u, _, st = fx.gw.auth.authenticate(adminRequest(http.MethodPost, "/v1/chat/completions", tok)) if st != authOK || u.limits.RequestsPerMinute != 9 { t.Fatalf("status %v limits %+v, want the reloaded override", st, u.limits) } if err := fx.gw.auth.replaceFileUsers(nil); err != nil { t.Fatal(err) } u, _, _ = fx.gw.auth.authenticate(adminRequest(http.MethodPost, "/v1/chat/completions", tok)) if u.name != "oidc:alice@x.com" || u.limits.RequestsPerMinute != 50 { t.Fatalf("removed override must fall back: %+v", u) } } func TestIdentify_OIDCWithAnonymous(t *testing.T) { anonGroup := func(anyKey bool) func(cfg *Config) { return func(cfg *Config) { cfg.Groups["public"] = &GroupConfig{} cfg.Users.AnonymousGroup = "public" cfg.Users.AnonymousAcceptAnyKey = anyKey } } fx := newOIDCGateway(t, anonGroup(false)) cases := []struct { name string bearer string want string status authStatus }{ {name: "valid token", bearer: fx.token(t, nil), want: "oidc:alice@x.com", status: authOK}, {name: "bad token", bearer: fx.token(t, func(c map[string]any) { c["iss"] = "https://evil" }), status: authUnauthorized}, {name: "no header", want: anonymousUserName, status: authOK}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { u, _, st := fx.gw.auth.authenticate(adminRequest(http.MethodPost, "/v1/chat/completions", tc.bearer)) if st != tc.status || (st == authOK && u.name != tc.want) { t.Fatalf("status %v user %v", st, u) } }) } fx = newOIDCGateway(t, anonGroup(true)) u, _, st := fx.gw.auth.authenticate(adminRequest(http.MethodPost, "/v1/chat/completions", fx.token(t, func(c map[string]any) { c["iss"] = "https://evil" }))) if st != authOK || u.name != anonymousUserName { t.Fatalf("any-key anonymous must still take a bad token: %v %v", st, u) } u, _, st = fx.gw.auth.authenticate(adminRequest(http.MethodPost, "/v1/chat/completions", fx.token(t, func(c map[string]any) { c["groups"] = []string{"other"} }))) if st != authForbidden { t.Fatalf("a valid token without a group is 403 even with any-key anonymous: %v %v", st, u) } } func TestOIDC_Disabled(t *testing.T) { fx := newOIDCGateway(t, func(cfg *Config) { cfg.OIDC = nil }) rec := fx.chat(t, fx.token(t, nil)) if rec.Code != http.StatusUnauthorized { t.Fatalf("status %d, want 401", rec.Code) } if d := fx.idp.discoveryHits.Load(); d != 0 { t.Fatalf("discovery hits = %d, want 0", d) } } func TestOIDC_XAPIKeyNotTreatedAsToken(t *testing.T) { fx := newOIDCGateway(t, nil) req := httptest.NewRequest(http.MethodGet, "/v1/models", nil) req.Header.Set("x-api-key", fx.token(t, nil)) if _, _, st := fx.gw.auth.authenticate(req); st != authUnauthorized { t.Fatalf("status %v, want 401 for a JWT in x-api-key", st) } if d := fx.idp.discoveryHits.Load(); d != 0 { t.Fatalf("discovery hits = %d, want 0", d) } } // A reload that renames an override or changes its limits must reach a token // that is already cached, on the very next request. func TestOIDC_ReloadReachesCachedTokenNameAndLimits(t *testing.T) { fx := newOIDCGateway(t, nil) tok := fx.token(t, nil) reload := func(name string, rpm int64) { t.Helper() err := fx.gw.auth.replaceFileUsers([]*UserConfig{{Name: name, OIDCIdentity: "alice@x.com", Limits: &LimitsConfig{RequestsPerMinute: rpm}}}) if err != nil { t.Fatal(err) } } reload("alice-a", 5) if rec := fx.chat(t, tok); rec.Code != http.StatusOK { t.Fatalf("status %d", rec.Code) } if fx.userRequests("alice-a") != 1 { t.Fatal("first request must be accounted to alice-a") } reload("alice-b", 7) u, _, st := fx.gw.auth.authenticate(adminRequest(http.MethodPost, "/v1/chat/completions", tok)) if st != authOK || u.name != "alice-b" || u.limits.RequestsPerMinute != 7 { t.Fatalf("status %v user %+v, want the renamed override with its new limits", st, u) } if rec := fx.chat(t, tok); rec.Code != http.StatusOK { t.Fatalf("status %d", rec.Code) } if fx.userRequests("alice-b") != 1 { t.Fatal("request after the rename must be accounted to alice-b") } if hits := fx.idp.jwksHits.Load(); hits != 1 { t.Fatalf("jwks hits = %d: the token must stay cached across the reload", hits) } }