Files
traefik-llmgateway/oidc_auth_test.go
T
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

391 lines
14 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)
}
}
}
func TestClaims_NamespacedKeyAndDottedPath(t *testing.T) {
const ns = "https://example.com/groups"
tests := []struct {
mutate func(c map[string]any)
name string
key string
}{
{name: "namespaced top-level key", key: ns, mutate: func(c map[string]any) {
delete(c, "groups")
c[ns] = []string{"llm-users"}
}},
{name: "flat key does not shadow the nested path", key: "realm_access.roles", mutate: func(c map[string]any) {
delete(c, "groups")
c["realm_access.roles"] = []string{"unmapped"}
c["realm_access"] = map[string]any{"roles": []string{"llm-users"}}
}},
{name: "absent key walks the dotted path", key: "realm_access.roles", mutate: 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) {
path, err := parseClaimPath(tc.key)
if err != nil {
t.Fatal(err)
}
s.groupClaim = path
})
entry, st, reason := fx.run(t, fx.token(t, tc.mutate), 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 TestAuthenticate_IDTokenRejectedByTyp(t *testing.T) {
tests := []struct {
payload any
name string
headerTyp string
wantOK bool
}{
{name: "payload typ ID", headerTyp: "JWT", payload: "ID"},
{name: "payload typ id lowercase", headerTyp: "JWT", payload: "id"},
{name: "header typ id+jwt", headerTyp: "id+jwt"},
{name: "header typ ID+JWT", headerTyp: "ID+JWT"},
{name: "header typ application/id+jwt", headerTyp: "application/id+jwt"},
{name: "header typ Application/ID+JWT", headerTyp: "Application/ID+JWT"},
{name: "header application/at+jwt", headerTyp: "application/at+jwt", wantOK: true},
{name: "prefix only at the start", headerTyp: "x-application/id+jwt", wantOK: true},
{name: "bare media-type prefix", headerTyp: "application/", wantOK: true},
{name: "payload Bearer", headerTyp: "JWT", payload: "Bearer", wantOK: true},
{name: "header at+jwt", headerTyp: "at+jwt", wantOK: true},
{name: "no typ anywhere", headerTyp: "", wantOK: true},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
fx := newAuthFixture(t, nil)
c := baseClaims(fx.clock.Now())
c["iss"] = fx.idp.srv.URL
if tc.payload != nil {
c["typ"] = tc.payload
}
tok := signTestJWTTyp(t, tc.headerTyp, "RS256", "rsa", oidcKeys(t), nil, c)
_, st, reason := fx.run(t, tok, nil)
if tc.wantOK {
if st != authOK {
t.Fatalf("status %v reason %q, want accepted", st, reason)
}
return
}
if st != authUnauthorized || reason != oidcReasonIDToken {
t.Fatalf("status %v reason %q, want 401 %q", st, reason, oidcReasonIDToken)
}
})
}
}
// A token of the maximum size with a disallowed alg is refused from its
// header alone: no IdP call, and the oversized payload is never decoded.
func TestAuthenticate_MaxSizeBadAlgTokenCostsNoIdPCall(t *testing.T) {
for _, alg := range []string{"none", "HS256", "bogus"} {
t.Run(alg, func(t *testing.T) {
fx := newAuthFixture(t, nil)
hdr := b64([]byte(`{"alg":"` + alg + `","kid":"rsa"}`))
// "!" is not base64url: a payload decode would fail as malformed.
filler := strings.Repeat("!", oidcMaxTokenBytes-len(hdr)-len(".."))
tok := hdr + "." + filler + "."
if len(tok) != oidcMaxTokenBytes {
t.Fatalf("token is %d bytes, want %d", len(tok), oidcMaxTokenBytes)
}
_, st, reason := fx.run(t, tok, nil)
if st != authUnauthorized || reason != "bad_alg" {
t.Fatalf("status %v reason %q, want 401 bad_alg", st, reason)
}
d, j, u := fx.idp.discoveryHits.Load(), fx.idp.jwksHits.Load(), fx.idp.userinfoHits.Load()
if d+j+u != 0 {
t.Fatalf("IdP hits discovery %d jwks %d userinfo %d, want 0", d, j, u)
}
})
}
}
// A signature that fails is refused before the payload is decoded: the
// payload here is invalid base64, yet the reason is bad_sig, not malformed.
func TestVerifyJWT_SignatureBeforePayloadDecode(t *testing.T) {
fx := newAuthFixture(t, nil)
hdr := b64([]byte(`{"alg":"RS256","kid":"rsa"}`))
tok := hdr + ".!!!!." + b64([]byte("not a signature"))
_, st, reason := fx.run(t, tok, nil)
if st != authUnauthorized || reason != "bad_sig" {
t.Fatalf("status %v reason %q, want 401 bad_sig", st, reason)
}
}