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

350 lines
9.7 KiB
Go

package traefikllmgateway
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
// fakeIDP is an in-process OIDC issuer: discovery, JWKS and userinfo, with
// per-endpoint hit counters and switchable failure modes.
type fakeIDP struct {
srv *httptest.Server
jwks atomic.Value // []byte
userinfo atomic.Value // map[string]any; nil means 401
issuerInDoc atomic.Value // string; "" means srv.URL
lastAuthz atomic.Value // string
jwksURI atomic.Value // string; "" means srv.URL + "/jwks"
userinfoURI atomic.Value // string; "" means srv.URL + "/userinfo"
discoveryHits atomic.Int64
jwksHits atomic.Int64
userinfoHits atomic.Int64
delay atomic.Int64 // nanoseconds added to every reply
userinfoStatus atomic.Int32 // non-zero forces this status on /userinfo
failDiscovery atomic.Bool
failJWKS atomic.Bool
noUserinfo atomic.Bool
}
func newFakeIDP(t *testing.T) *fakeIDP {
t.Helper()
f := &fakeIDP{}
f.jwks.Store(testJWKS(t, oidcKeys(t)))
f.issuerInDoc.Store("")
f.lastAuthz.Store("")
f.jwksURI.Store("")
f.userinfoURI.Store("")
mux := http.NewServeMux()
mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) {
f.discoveryHits.Add(1)
time.Sleep(time.Duration(f.delay.Load()))
if f.failDiscovery.Load() {
http.Error(w, "down", http.StatusInternalServerError)
return
}
iss := f.issuerInDoc.Load().(string)
if iss == "" {
iss = f.srv.URL
}
jwksURI, _ := f.jwksURI.Load().(string)
if jwksURI == "" {
jwksURI = f.srv.URL + "/jwks"
}
doc := map[string]string{"issuer": iss, "jwks_uri": jwksURI}
if !f.noUserinfo.Load() {
userinfoURI, _ := f.userinfoURI.Load().(string)
if userinfoURI == "" {
userinfoURI = f.srv.URL + "/userinfo"
}
doc["userinfo_endpoint"] = userinfoURI
}
_ = json.NewEncoder(w).Encode(doc)
})
mux.HandleFunc("/redirect-jwks", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/jwks", http.StatusFound)
})
mux.HandleFunc("/jwks", func(w http.ResponseWriter, r *http.Request) {
f.jwksHits.Add(1)
time.Sleep(time.Duration(f.delay.Load()))
if f.failJWKS.Load() {
http.Error(w, "down", http.StatusServiceUnavailable)
return
}
_, _ = w.Write(f.jwks.Load().([]byte))
})
mux.HandleFunc("/userinfo", func(w http.ResponseWriter, r *http.Request) {
f.userinfoHits.Add(1)
f.lastAuthz.Store(r.Header.Get("Authorization"))
time.Sleep(time.Duration(f.delay.Load()))
if code := f.userinfoStatus.Load(); code != 0 {
http.Error(w, "forced", int(code))
return
}
claims, _ := f.userinfo.Load().(map[string]any)
if claims == nil {
http.Error(w, "invalid token", http.StatusUnauthorized)
return
}
_ = json.NewEncoder(w).Encode(claims)
})
f.srv = httptest.NewServer(mux)
t.Cleanup(f.srv.Close)
return f
}
func (f *fakeIDP) settings() *oidcSettings {
s := testSettings()
s.issuer = f.srv.URL
s.jwksRefresh = time.Hour
s.cacheTTL = 5 * time.Minute
s.maxUsers = 100
s.userinfo = true
return s
}
func newFakeClock() *fakeClock { return &fakeClock{now: time.Unix(1_800_000_000, 0)} }
func newTestProvider(f *fakeIDP, clock *fakeClock) *oidcProvider {
return newOIDCProvider(f.settings(), &http.Client{Timeout: 5 * time.Second}, clock.Now)
}
func TestProvider_LazyDiscoveryAndCache(t *testing.T) {
f := newFakeIDP(t)
p := newTestProvider(f, newFakeClock())
if f.discoveryHits.Load() != 0 {
t.Fatal("discovery must be lazy")
}
for range 2 {
set, err := p.keysFor("rsa")
if err != nil {
t.Fatal(err)
}
if _, err := set.lookup("rsa"); err != nil {
t.Fatal(err)
}
}
if d, j := f.discoveryHits.Load(), f.jwksHits.Load(); d != 1 || j != 1 {
t.Fatalf("discovery hits %d, jwks hits %d; want 1, 1", d, j)
}
}
func TestProvider_PeriodicRefresh(t *testing.T) {
f := newFakeIDP(t)
clock := newFakeClock()
p := newTestProvider(f, clock)
if _, err := p.keysFor("rsa"); err != nil {
t.Fatal(err)
}
clock.Advance(time.Hour + time.Second)
if _, err := p.keysFor("rsa"); err != nil {
t.Fatal(err)
}
if j := f.jwksHits.Load(); j != 2 {
t.Fatalf("jwks hits = %d, want 2 after jwksRefresh", j)
}
}
func TestProvider_UnknownKidRefetchThrottled(t *testing.T) {
f := newFakeIDP(t)
clock := newFakeClock()
p := newTestProvider(f, clock)
if _, err := p.keysFor("rsa"); err != nil {
t.Fatal(err)
}
steps := []struct {
advance time.Duration
wantHits int64
}{
{advance: 2 * time.Minute, wantHits: 2},
{advance: 30 * time.Second, wantHits: 2},
{advance: 31 * time.Second, wantHits: 3},
}
for i, st := range steps {
clock.Advance(st.advance)
if _, err := p.keysFor("rotated"); err != nil {
t.Fatal(err)
}
if got := f.jwksHits.Load(); got != st.wantHits {
t.Fatalf("step %d: jwks hits = %d, want %d", i, got, st.wantHits)
}
}
}
func TestProvider_IssuerMismatch(t *testing.T) {
f := newFakeIDP(t)
f.issuerInDoc.Store("https://evil.example.com")
p := newTestProvider(f, newFakeClock())
if _, err := p.keysFor("rsa"); err == nil || !strings.Contains(err.Error(), "issuer") {
t.Fatalf("err = %v, want issuer mismatch", err)
}
}
func TestProvider_BodyCap(t *testing.T) {
f := newFakeIDP(t)
f.jwks.Store([]byte(`{"keys":[],"pad":"` + strings.Repeat("a", 2<<20) + `"}`))
p := newTestProvider(f, newFakeClock())
if _, err := p.keysFor("rsa"); err == nil || !strings.Contains(err.Error(), "too large") {
t.Fatalf("err = %v, want body-too-large", err)
}
}
func TestProvider_DiscoveryFailureThenRecovery(t *testing.T) {
f := newFakeIDP(t)
clock := newFakeClock()
p := newTestProvider(f, clock)
f.failDiscovery.Store(true)
if _, err := p.keysFor("rsa"); err == nil {
t.Fatal("want error while discovery fails")
}
if _, err := p.keysFor("rsa"); err == nil {
t.Fatal("want cached error inside the retry backoff")
}
if h := f.discoveryHits.Load(); h != 1 {
t.Fatalf("discovery hits = %d, want 1 inside the retry backoff", h)
}
f.failDiscovery.Store(false)
clock.Advance(oidcFetchRetryAfter + time.Second)
if _, err := p.keysFor("rsa"); err != nil {
t.Fatalf("want recovery after backoff: %v", err)
}
}
func TestProvider_StaleKeysSurviveFailedRefresh(t *testing.T) {
f := newFakeIDP(t)
clock := newFakeClock()
p := newTestProvider(f, clock)
if _, err := p.keysFor("rsa"); err != nil {
t.Fatal(err)
}
f.jwks.Store([]byte(`not json`))
clock.Advance(time.Hour + time.Second)
set, err := p.keysFor("rsa")
if err != nil {
t.Fatalf("a failed refresh must keep serving the last good keys: %v", err)
}
if _, err := set.lookup("rsa"); err != nil {
t.Fatal(err)
}
}
func TestProvider_Userinfo(t *testing.T) {
f := newFakeIDP(t)
p := newTestProvider(f, newFakeClock())
ctx := context.Background()
f.userinfo.Store(map[string]any{"email": "[email protected]"})
claims, err := p.userinfo(ctx, "opaque-token")
if err != nil {
t.Fatal(err)
}
if claims["email"] != "[email protected]" {
t.Fatalf("claims = %v", claims)
}
if got := f.lastAuthz.Load().(string); got != "Bearer opaque-token" {
t.Fatalf("authorization = %q", got)
}
f.userinfo.Store(map[string]any(nil))
if _, err := p.userinfo(ctx, "opaque-token"); err == nil {
t.Fatal("want error on 401")
}
}
func TestProvider_UserinfoMissingEndpoint(t *testing.T) {
f := newFakeIDP(t)
f.noUserinfo.Store(true)
p := newTestProvider(f, newFakeClock())
if _, err := p.userinfo(context.Background(), "tok"); err == nil || !strings.Contains(err.Error(), "userinfo_endpoint") {
t.Fatalf("err = %v", err)
}
}
func TestProvider_ConcurrentFetchSingleFlight(t *testing.T) {
f := newFakeIDP(t)
p := newTestProvider(f, newFakeClock())
var wg sync.WaitGroup
for range 20 {
wg.Add(1)
go func() {
defer wg.Done()
if _, err := p.keysFor("rsa"); err != nil {
t.Error(err)
}
}()
}
wg.Wait()
if j := f.jwksHits.Load(); j != 1 {
t.Fatalf("jwks hits = %d, want 1", j)
}
}
func TestProvider_DiscoveryRefreshesWithKeys(t *testing.T) {
f := newFakeIDP(t)
clock := newFakeClock()
p := newTestProvider(f, clock)
if _, err := p.keysFor("rsa"); err != nil {
t.Fatal(err)
}
f.jwksURI.Store(f.srv.URL + "/jwks-moved")
clock.Advance(time.Hour + time.Second)
if _, err := p.keysFor("rsa"); err != nil {
t.Fatal(err)
}
if d := f.discoveryHits.Load(); d != 2 {
t.Fatalf("discovery hits = %d, want 2 after jwksRefresh", d)
}
p.stateMu.RLock()
got := p.disc.JWKSURI
p.stateMu.RUnlock()
if got != f.srv.URL+"/jwks-moved" {
t.Fatalf("jwks_uri = %q, want the refreshed document's value", got)
}
}
func TestProvider_StaleDiscoverySurvivesFailedRefresh(t *testing.T) {
f := newFakeIDP(t)
clock := newFakeClock()
p := newTestProvider(f, clock)
if _, err := p.keysFor("rsa"); err != nil {
t.Fatal(err)
}
f.failDiscovery.Store(true)
clock.Advance(time.Hour + time.Second)
if _, err := p.keysFor("rsa"); err != nil {
t.Fatalf("a failed discovery refresh must keep the old document: %v", err)
}
if j := f.jwksHits.Load(); j != 2 {
t.Fatalf("jwks hits = %d, want 2: keys refresh uses the stale document", j)
}
hits := f.discoveryHits.Load()
clock.Advance(oidcFetchRetryAfter - time.Second)
if _, err := p.cachedDiscovery(); err != nil {
t.Fatal(err)
}
if got := f.discoveryHits.Load(); got != hits {
t.Fatalf("discovery retried inside oidcFetchRetryAfter: %d -> %d", hits, got)
}
}
func TestProvider_UserinfoPathRefreshesDiscovery(t *testing.T) {
f := newFakeIDP(t)
clock := newFakeClock()
p := newTestProvider(f, clock)
if _, err := p.cachedDiscovery(); err != nil {
t.Fatal(err)
}
f.userinfoURI.Store(f.srv.URL + "/userinfo-moved")
clock.Advance(time.Hour + time.Second)
disc, err := p.cachedDiscovery()
if err != nil {
t.Fatal(err)
}
if disc.UserinfoEndpoint != f.srv.URL+"/userinfo-moved" {
t.Fatalf("userinfo endpoint = %q, want the refreshed value", disc.UserinfoEndpoint)
}
}