Files
traefik-llmgateway/logger_test.go
lukaszraczyloandGitHub 6805253f91 feat(auth): admit oidc bearer tokens as virtual users (#27)
* 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.
2026-12-02 01:22:30 +00:00

261 lines
9.1 KiB
Go

package traefikllmgateway
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
)
// newTestGatewayForLogger builds a minimal *Gateway via the real New()
// constructor (the only supported construction path — see this package's
// other test files, none of which build a bare &Gateway{} literal) for
// logAuthEvent's own tests below.
func newTestGatewayForLogger(t *testing.T) *Gateway {
t.Helper()
cfg := CreateConfig()
cfg.Providers = map[string]*ProviderConfig{"openai": {Type: "openai", APIKey: "k"}}
h, err := New(context.Background(), http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}), cfg, "llmgw")
if err != nil {
t.Fatalf("New: %v", err)
}
gw, ok := h.(*Gateway)
if !ok {
t.Fatal("handler is not *Gateway")
}
return gw
}
// captureStderr redirects os.Stderr for the duration of fn (the same
// os.Pipe-based idiom this package's other test files already use for
// logf/errorf, e.g. TestGateway_Logf_WritesInfoPrefix, llmgateway_test.go)
// and returns everything written to it.
func captureStderr(t *testing.T, fn func()) string {
t.Helper()
origStderr := os.Stderr
r, w, err := os.Pipe()
if err != nil {
t.Fatalf("os.Pipe: %v", err)
}
os.Stderr = w
fn()
_ = w.Close()
os.Stderr = origStderr
var buf bytes.Buffer
if _, err := io.Copy(&buf, r); err != nil {
t.Fatalf("io.Copy: %v", err)
}
return buf.String()
}
// TestLogAuthEvent_Failure_RateLimited is the regression for the missing
// rate limit on logAuthEvent's failure line (security audit finding 3,
// 2026-08-22): an attacker driving many failed-auth attempts in quick
// succession must produce ONE log line per authFailureLogEvery, not one
// per attempt — otherwise the synchronous os.Stderr write itself becomes
// an amplification vector on the shared Traefik ingress.
func TestLogAuthEvent_Failure_RateLimited(t *testing.T) {
gw := newTestGatewayForLogger(t)
clock := &fakeClock{now: time.Unix(1_700_000_000, 0)}
gw.auth.nowFn = clock.Now
r := httptest.NewRequest("POST", "/v1/chat/completions", nil)
r.RemoteAddr = "203.0.113.9:1234"
out := captureStderr(t, func() {
for i := 0; i < 5; i++ {
gw.logAuthEvent(false, "", r, "")
}
})
if n := strings.Count(out, "auth failed:"); n != 1 {
t.Fatalf("auth-failed lines = %d, want exactly 1 (5 attempts within one authFailureLogEvery window), output=%q", n, out)
}
}
// TestLogAuthEvent_Failure_LogsAgainAfterIntervalElapses proves the rate
// limit is a cadence, not a one-shot silence: once authFailureLogEvery has
// actually elapsed, the next failure is logged again.
func TestLogAuthEvent_Failure_LogsAgainAfterIntervalElapses(t *testing.T) {
gw := newTestGatewayForLogger(t)
clock := &fakeClock{now: time.Unix(1_700_000_000, 0)}
gw.auth.nowFn = clock.Now
r := httptest.NewRequest("POST", "/v1/chat/completions", nil)
r.RemoteAddr = "203.0.113.9:1234"
out := captureStderr(t, func() {
gw.logAuthEvent(false, "", r, "")
clock.Advance(authFailureLogEvery + time.Second)
gw.logAuthEvent(false, "", r, "")
})
if n := strings.Count(out, "auth failed:"); n != 2 {
t.Fatalf("auth-failed lines = %d, want exactly 2 (interval elapsed between the two attempts), output=%q", n, out)
}
}
// TestLogAuthEvent_Success_NeverRateLimited proves successful-auth logging
// is deliberately left unbounded (shouldLogAuthFailure's own doc comment,
// auth.go, justifies why): it takes an already-valid key to reach, so its
// volume is bounded by legitimate traffic elsewhere, not by an
// unauthenticated caller's attempt rate.
func TestLogAuthEvent_Success_NeverRateLimited(t *testing.T) {
gw := newTestGatewayForLogger(t)
clock := &fakeClock{now: time.Unix(1_700_000_000, 0)}
gw.auth.nowFn = clock.Now
r := httptest.NewRequest("POST", "/v1/chat/completions", nil)
out := captureStderr(t, func() {
for i := 0; i < 5; i++ {
gw.logAuthEvent(true, "alice", r, "")
}
})
if n := strings.Count(out, "auth ok:"); n != 5 {
t.Fatalf("auth-ok lines = %d, want 5 (success logging must never be rate-limited), output=%q", n, out)
}
}
// TestLogAuthEvent_ThrottleEngaged_DistinctLine proves logAuthEvent emits
// a distinct "auth throttle:" line, not the routine "auth failed:" one,
// once a source IP has crossed authFailureLimit (security review round
// 2, 2026-08-22, important finding 5) — an operator seeing this line
// knows a SOURCE, not just one request, needs attention.
func TestLogAuthEvent_ThrottleEngaged_DistinctLine(t *testing.T) {
gw := newTestGatewayForLogger(t)
clock := &fakeClock{now: time.Unix(1_700_000_000, 0)}
gw.auth.nowFn = clock.Now
r := httptest.NewRequest("POST", "/v1/chat/completions", nil)
r.RemoteAddr = "203.0.113.9:1234"
for i := 0; i < authFailureLimit; i++ {
gw.auth.recordAuthFailure(clientIP(r))
}
out := captureStderr(t, func() {
gw.logAuthEvent(false, "", r, "")
})
if !strings.Contains(out, "auth throttle:") {
t.Errorf("want an 'auth throttle:' line once the IP has crossed the limit, got %q", out)
}
if strings.Contains(out, "auth failed:") {
t.Errorf("want the routine 'auth failed:' line suppressed in favor of the distinct throttle line, got %q", out)
}
}
// TestLogAuthEvent_Failure_SuppressedCountReported proves the routine
// failure line's rate-limit gate reports how many events it suppressed
// (security review round 2, 2026-08-22, important finding 6): a single
// global gate would otherwise make several rapid failures within one
// window indistinguishable from a single one — the next line actually
// written must name how many were collapsed into it.
func TestLogAuthEvent_Failure_SuppressedCountReported(t *testing.T) {
gw := newTestGatewayForLogger(t)
clock := &fakeClock{now: time.Unix(1_700_000_000, 0)}
gw.auth.nowFn = clock.Now
r := httptest.NewRequest("POST", "/v1/chat/completions", nil)
r.RemoteAddr = "203.0.113.9:1234"
captureStderr(t, func() {
gw.logAuthEvent(false, "", r, "") // logged (first call on a fresh gate)
gw.logAuthEvent(false, "", r, "") // suppressed #1
gw.logAuthEvent(false, "", r, "") // suppressed #2
})
clock.Advance(authFailureLogEvery + time.Second)
out := captureStderr(t, func() {
gw.logAuthEvent(false, "", r, "")
})
if !strings.Contains(out, "2 more suppressed since last log") {
t.Errorf("want the next line to report 2 suppressed events, got %q", out)
}
}
// TestWarnf_WritesWarnPrefix pins warnf's own severity token, so the
// level cannot drift back without a test noticing.
func TestWarnf_WritesWarnPrefix(t *testing.T) {
gw := newTestGatewayForLogger(t)
out := captureStderr(t, func() {
gw.warnf("something resolved itself: %d", 7)
})
if !strings.Contains(out, "llmgw[llmgw] WARN something resolved itself: 7") {
t.Errorf("warnf output = %q, want a WARN-prefixed line", out)
}
if strings.Contains(out, "ERROR") {
t.Errorf("warnf must not emit an ERROR line, got %q", out)
}
}
// TestWarnCollisionOnce_LogsAtWarnNotError is the regression for the
// model-id collision line's severity (2026-08-22). A model id served by
// two configured providers is resolved deterministically by the registry
// and affects no request, so it must not be an ERROR: on a cluster with
// overlapping catalogs it put 144 ERROR lines in a healthy pod's boot
// log, which is exactly the noise that hides a real failure.
func TestWarnCollisionOnce_LogsAtWarnNotError(t *testing.T) {
gw := newTestGatewayForLogger(t)
reg, err := newModelRegistry(map[string]providerAdapter{}, CreateConfig(), gw.errorf)
if err != nil {
t.Fatalf("newModelRegistry: %v", err)
}
reg.warn = gw.warnf
out := captureStderr(t, func() {
reg.warnCollisionOnce("gpt-4o", "openai", []string{"openai", "openai-audio"})
})
if !strings.Contains(out, "WARN model registry: model id \"gpt-4o\" is provided by multiple providers") {
t.Errorf("collision line = %q, want it emitted at WARN", out)
}
if strings.Contains(out, "ERROR") {
t.Errorf("collision line must not be an ERROR, got %q", out)
}
// Still logged only once per id, regardless of severity.
second := captureStderr(t, func() {
reg.warnCollisionOnce("gpt-4o", "openai", []string{"openai", "openai-audio"})
})
if second != "" {
t.Errorf("second collision for the same id logged again: %q", second)
}
}
// TestRegistryWarnf_FallsBackToLogWhenWarnNil covers the nil-warn path:
// a registry built without an injected warn (every test call site, and
// any future caller that forgets) must still emit the line through log
// rather than panicking or dropping it silently.
func TestRegistryWarnf_FallsBackToLogWhenWarnNil(t *testing.T) {
var got []string
reg, err := newModelRegistry(map[string]providerAdapter{}, CreateConfig(), func(format string, args ...any) {
got = append(got, fmt.Sprintf(format, args...))
})
if err != nil {
t.Fatalf("newModelRegistry: %v", err)
}
if reg.warn != nil {
t.Fatal("newModelRegistry must leave warn nil; it is injected by the caller")
}
reg.warnCollisionOnce("m1", "p1", []string{"p1", "p2"})
if len(got) != 1 {
t.Fatalf("log calls = %d, want 1 (the fallback path), got %v", len(got), got)
}
if !strings.Contains(got[0], `model id "m1" is provided by multiple providers`) {
t.Errorf("fallback line = %q, want the collision message", got[0])
}
}