Files
lukaszraczyloandGitHub 11fe58c70f feat(models): advertise and discover model vision capability (#28)
## Summary

This change makes the gateway advertise and discover the vision capability of each model. It also adds OIDC follow-ups and the fixes from a security audit of the change.

### Model vision capability

- `GET /v1/models` writes `architecture.input_modalities` and `info.meta.capabilities.vision` for each model with a known vision flag. Open WebUI reads `info.meta.capabilities.vision`, and other clients read `architecture.input_modalities`.
- Discovery reads the same two fields from an upstream `/v1/models` when `metadataPath` is set. A downstream gateway thus reads the flag from an upstream gateway.
- Resolution order: alias `modelMeta`, then target `modelMeta`, then discovery. An unknown flag counts as capable, as before.
- The smart router uses the resolved flag. For an alias target, it now uses the alias `modelMeta` for vision and `contextTokens`, as `/v1/models` does.

### OIDC follow-ups

- The gateway refreshes the discovery document on the `jwksRefresh` cadence. A failed refresh keeps the last good copy.
- The user list hides a registry record whose name is not the name its identity resolves to now.
- A `groupClaim` that contains `://` is one top-level claim name. A dotted `groupClaim` walks the path only, so a flat claim of the same spelling cannot shadow it.
- The gateway refuses ID tokens: header `typ` `id+jwt` (also with the `application/` prefix) and payload `typ` `ID`.
- The user registry reads Redis with `HSCAN` pages. One `HGETALL` reply failed above 512 users, and then prune stopped.

## Verification

- `go test -race ./...`: pass in both packages.
- `golangci-lint run`: 0 issues. `make yaegi-check`: OK. `govulncheck ./...`: no vulnerabilities.
- Each audit fix has a test that failed before the fix.
- A test against a local `redis-server` 7 loaded 2000 registry records and pruned the stale ones.
- A quick security audit (run-2) covered 15 units. It confirmed one low-severity availability defect, the registry read, which this change fixes.
2026-12-02 02:30:50 +00:00

334 lines
12 KiB
Go

package traefikllmgateway
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
// 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:[email protected]"); 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: "[email protected]", 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: "[email protected]", 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:[email protected]" || 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:[email protected]", 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: "[email protected]", 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)
}
}
// Slow IdP knobs: the IdP delay is far over the provider timeout, and the
// wait bound sits between the two.
const (
slowIDPProviderTimeout = 150 * time.Millisecond
slowIDPDelay = time.Second
slowIDPBound = 800 * time.Millisecond
)
func TestOIDC_SlowIdPRefusedInBoundedTimeThenRecovers(t *testing.T) {
tests := []struct {
mutate func(cfg *Config)
bearer func(t *testing.T, fx *oidcGatewayFixture) string
name string
}{
{
name: "jwks endpoint",
bearer: func(t *testing.T, fx *oidcGatewayFixture) string { return fx.token(t, nil) },
},
{
name: "userinfo endpoint",
mutate: func(cfg *Config) { cfg.OIDC.Userinfo = true },
bearer: func(*testing.T, *oidcGatewayFixture) string { return "opaque-token" },
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
fx := newOIDCGateway(t, tc.mutate)
fx.idp.userinfo.Store(map[string]any{"email": "[email protected]", "email_verified": true, "groups": []string{"llm-users"}})
prov := fx.gw.auth.oidcAuth.provider
prov.timeout = slowIDPProviderTimeout
bearer := tc.bearer(t, fx)
fx.idp.delay.Store(int64(slowIDPDelay))
start := time.Now()
rec := fx.chat(t, bearer)
if took := time.Since(start); took > slowIDPBound {
t.Fatalf("request took %s, want under %s: the gateway hung on the slow IdP", took, slowIDPBound)
}
if rec.Code != http.StatusUnauthorized {
t.Fatalf("status %d, want 401 while the IdP is slow", rec.Code)
}
fx.idp.delay.Store(0)
prov.stateMu.Lock()
prov.failedAt = time.Time{}
prov.stateMu.Unlock()
if rec := fx.chat(t, bearer); rec.Code != http.StatusOK {
t.Fatalf("status %d body %s, want 200 after the IdP recovers", rec.Code, rec.Body.String())
}
})
}
}