mirror of
https://github.com/lukaszraczylo/traefik-llmgateway.git
synced 2026-12-06 11:03:52 +00:00
## 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.
356 lines
12 KiB
Go
356 lines
12 KiB
Go
package traefikllmgateway
|
|
|
|
import (
|
|
"crypto"
|
|
"crypto/ecdsa"
|
|
"crypto/elliptic"
|
|
"crypto/hmac"
|
|
"crypto/rand"
|
|
"crypto/rsa"
|
|
"crypto/sha256"
|
|
"crypto/sha512"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"math/big"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
const testIssuer = "https://idp.example.com/realms/main"
|
|
|
|
// testKeys holds one signing key per supported family, generated once per
|
|
// test binary because RSA generation is slow under -race.
|
|
type testKeys struct {
|
|
rsa *rsa.PrivateKey
|
|
p256 *ecdsa.PrivateKey
|
|
p384 *ecdsa.PrivateKey
|
|
}
|
|
|
|
var sharedTestKeys *testKeys
|
|
|
|
func oidcKeys(t *testing.T) *testKeys {
|
|
t.Helper()
|
|
if sharedTestKeys != nil {
|
|
return sharedTestKeys
|
|
}
|
|
rk, err := rsa.GenerateKey(rand.Reader, 2048)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
p256, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
p384, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
sharedTestKeys = &testKeys{rsa: rk, p256: p256, p384: p384}
|
|
return sharedTestKeys
|
|
}
|
|
|
|
func b64(b []byte) string { return base64.RawURLEncoding.EncodeToString(b) }
|
|
|
|
func padded(n *big.Int, size int) []byte {
|
|
out := make([]byte, size)
|
|
n.FillBytes(out)
|
|
return out
|
|
}
|
|
|
|
// testJWKS renders the public halves of k as a JWKS document: kid "rsa",
|
|
// "p256" and "p384".
|
|
func testJWKS(t *testing.T, k *testKeys) []byte {
|
|
t.Helper()
|
|
ec := func(kid, crv string, pub *ecdsa.PublicKey, size int) map[string]string {
|
|
return map[string]string{"kty": "EC", "kid": kid, "crv": crv, "use": "sig",
|
|
"x": b64(padded(pub.X, size)), "y": b64(padded(pub.Y, size))}
|
|
}
|
|
doc := map[string]any{"keys": []any{
|
|
map[string]string{"kty": "RSA", "kid": "rsa", "use": "sig",
|
|
"n": b64(k.rsa.N.Bytes()), "e": b64(big.NewInt(int64(k.rsa.E)).Bytes())},
|
|
ec("p256", "P-256", &k.p256.PublicKey, 32),
|
|
ec("p384", "P-384", &k.p384.PublicKey, 48),
|
|
}}
|
|
out, err := json.Marshal(doc)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return out
|
|
}
|
|
|
|
func digestFor(alg string, data []byte) (crypto.Hash, []byte) {
|
|
switch alg {
|
|
case "RS384", "ES384":
|
|
d := sha512.Sum384(data)
|
|
return crypto.SHA384, d[:]
|
|
case "RS512":
|
|
d := sha512.Sum512(data)
|
|
return crypto.SHA512, d[:]
|
|
default:
|
|
d := sha256.Sum256(data)
|
|
return crypto.SHA256, d[:]
|
|
}
|
|
}
|
|
|
|
// signTestJWT builds a compact JWS. alg "none" yields an empty signature;
|
|
// "HS256" signs with secret.
|
|
func signTestJWT(t *testing.T, alg, kid string, k *testKeys, secret []byte, claims map[string]any) string {
|
|
t.Helper()
|
|
return signTestJWTTyp(t, "JWT", alg, kid, k, secret, claims)
|
|
}
|
|
|
|
// signTestJWTTyp is signTestJWT with a chosen header typ ("" omits it).
|
|
func signTestJWTTyp(t *testing.T, typ, alg, kid string, k *testKeys, secret []byte, claims map[string]any) string {
|
|
t.Helper()
|
|
h := map[string]string{"alg": alg, "kid": kid}
|
|
if typ != "" {
|
|
h["typ"] = typ
|
|
}
|
|
hdr, err := json.Marshal(h)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
body, err := json.Marshal(claims)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
input := b64(hdr) + "." + b64(body)
|
|
var sig []byte
|
|
switch alg {
|
|
case "none":
|
|
case "HS256":
|
|
m := hmac.New(sha256.New, secret)
|
|
m.Write([]byte(input))
|
|
sig = m.Sum(nil)
|
|
case "RS256", "RS384", "RS512":
|
|
h, d := digestFor(alg, []byte(input))
|
|
sig, err = rsa.SignPKCS1v15(rand.Reader, k.rsa, h, d)
|
|
case "PS256":
|
|
h, d := digestFor(alg, []byte(input))
|
|
sig, err = rsa.SignPSS(rand.Reader, k.rsa, h, d, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
|
|
case "ES256", "ES384":
|
|
key, size := k.p256, 32
|
|
if alg == "ES384" {
|
|
key, size = k.p384, 48
|
|
}
|
|
_, d := digestFor(alg, []byte(input))
|
|
r, s, signErr := ecdsa.Sign(rand.Reader, key, d)
|
|
err = signErr
|
|
sig = append(padded(r, size), padded(s, size)...)
|
|
default:
|
|
t.Fatalf("unsupported test alg %s", alg)
|
|
}
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return input + "." + b64(sig)
|
|
}
|
|
|
|
func baseClaims(now time.Time) map[string]any {
|
|
return map[string]any{
|
|
"iss": testIssuer,
|
|
"aud": "openwebui",
|
|
"exp": now.Add(time.Hour).Unix(),
|
|
"iat": now.Unix(),
|
|
"email": "[email protected]",
|
|
"email_verified": true,
|
|
"groups": []string{"llm-users"},
|
|
}
|
|
}
|
|
|
|
func testSettings() *oidcSettings {
|
|
return &oidcSettings{
|
|
issuer: testIssuer,
|
|
audiences: map[string]bool{"openwebui": true},
|
|
identityClaim: "email",
|
|
requireEmailVerified: true,
|
|
groupClaim: []string{"groups"},
|
|
groupMap: map[string]string{"llm-users": "staff"},
|
|
}
|
|
}
|
|
|
|
func TestVerifyJWT(t *testing.T) {
|
|
k := oidcKeys(t)
|
|
set, err := parseJWKS(testJWKS(t, k))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
now := time.Unix(1_800_000_000, 0)
|
|
with := func(mut func(c map[string]any)) map[string]any {
|
|
c := baseClaims(now)
|
|
mut(c)
|
|
return c
|
|
}
|
|
tests := []struct {
|
|
claims map[string]any
|
|
tamper func(tok string) string
|
|
wantErr error
|
|
name string
|
|
alg string
|
|
kid string
|
|
secret []byte
|
|
}{
|
|
{name: "RS256", alg: "RS256", kid: "rsa"},
|
|
{name: "RS384", alg: "RS384", kid: "rsa"},
|
|
{name: "RS512", alg: "RS512", kid: "rsa"},
|
|
{name: "PS256", alg: "PS256", kid: "rsa"},
|
|
{name: "ES256", alg: "ES256", kid: "p256"},
|
|
{name: "ES384", alg: "ES384", kid: "p384"},
|
|
{name: "expired past skew", alg: "RS256", kid: "rsa", claims: with(func(c map[string]any) { c["exp"] = now.Add(-61 * time.Second).Unix() }), wantErr: errTokenExpired},
|
|
{name: "expired within skew", alg: "RS256", kid: "rsa", claims: with(func(c map[string]any) { c["exp"] = now.Add(-59 * time.Second).Unix() })},
|
|
{name: "missing exp", alg: "RS256", kid: "rsa", claims: with(func(c map[string]any) { delete(c, "exp") }), wantErr: errTokenExpired},
|
|
{name: "nbf in future", alg: "RS256", kid: "rsa", claims: with(func(c map[string]any) { c["nbf"] = now.Add(61 * time.Second).Unix() }), wantErr: errTokenNotYetValid},
|
|
{name: "nbf within skew", alg: "RS256", kid: "rsa", claims: with(func(c map[string]any) { c["nbf"] = now.Add(59 * time.Second).Unix() })},
|
|
{name: "payload tampered", alg: "RS256", kid: "rsa", tamper: func(tok string) string {
|
|
parts := strings.Split(tok, ".")
|
|
c := baseClaims(now)
|
|
c["email"] = "[email protected]"
|
|
body, _ := json.Marshal(c)
|
|
return parts[0] + "." + b64(body) + "." + parts[2]
|
|
}, wantErr: errTokenBadSignature},
|
|
{name: "alg none", alg: "none", kid: "rsa", wantErr: errTokenBadAlg},
|
|
{name: "HS256 with public key as secret", alg: "HS256", kid: "rsa", secret: k.rsa.N.Bytes(), wantErr: errTokenBadAlg},
|
|
{name: "ES256 header on RSA key", alg: "ES256", kid: "rsa", wantErr: errTokenBadAlg},
|
|
{name: "ES384 header on P-256 key", alg: "ES384", kid: "p256", wantErr: errTokenBadAlg},
|
|
{name: "wrong issuer", alg: "RS256", kid: "rsa", claims: with(func(c map[string]any) { c["iss"] = "https://evil.example.com" }), wantErr: errTokenIssuer},
|
|
{name: "aud array match", alg: "RS256", kid: "rsa", claims: with(func(c map[string]any) { c["aud"] = []string{"account", "openwebui"} })},
|
|
{name: "azp alone refused without acceptAzp", alg: "RS256", kid: "rsa", claims: with(func(c map[string]any) { c["aud"] = "account"; c["azp"] = "openwebui" }), wantErr: errTokenAudience},
|
|
{name: "aud and azp mismatch", alg: "RS256", kid: "rsa", claims: with(func(c map[string]any) { c["aud"] = "account"; c["azp"] = "other" }), wantErr: errTokenAudience},
|
|
{name: "no aud", alg: "RS256", kid: "rsa", claims: with(func(c map[string]any) { delete(c, "aud") }), wantErr: errTokenAudience},
|
|
{name: "email not verified", alg: "RS256", kid: "rsa", claims: with(func(c map[string]any) { c["email_verified"] = false }), wantErr: errEmailNotVerified},
|
|
{name: "email_verified missing", alg: "RS256", kid: "rsa", claims: with(func(c map[string]any) { delete(c, "email_verified") }), wantErr: errEmailNotVerified},
|
|
{name: "email_verified string true", alg: "RS256", kid: "rsa", claims: with(func(c map[string]any) { c["email_verified"] = "true" })},
|
|
{name: "unknown kid", alg: "RS256", kid: "rotated", wantErr: errTokenUnknownKid},
|
|
{name: "short ES256 signature", alg: "ES256", kid: "p256", tamper: func(tok string) string {
|
|
i := strings.LastIndex(tok, ".")
|
|
return tok[:i+1] + b64(make([]byte, 63))
|
|
}, wantErr: errTokenBadSignature},
|
|
{name: "signature not base64", alg: "RS256", kid: "rsa", tamper: func(tok string) string {
|
|
i := strings.LastIndex(tok, ".")
|
|
return tok[:i+1] + "!!!"
|
|
}, wantErr: errTokenBadSignature},
|
|
}
|
|
for _, tc := range tests {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
claims := tc.claims
|
|
if claims == nil {
|
|
claims = baseClaims(now)
|
|
}
|
|
tok := signTestJWT(t, tc.alg, tc.kid, k, tc.secret, claims)
|
|
if tc.tamper != nil {
|
|
tok = tc.tamper(tok)
|
|
}
|
|
got, err := verifyJWT(tok, set, testSettings(), now)
|
|
if tc.wantErr != nil {
|
|
if !errors.Is(err, tc.wantErr) {
|
|
t.Fatalf("err = %v, want %v", err, tc.wantErr)
|
|
}
|
|
return
|
|
}
|
|
if err != nil {
|
|
t.Fatalf("unexpected err: %v", err)
|
|
}
|
|
if got["email"] != claims["email"] {
|
|
t.Fatalf("claims email = %v", got["email"])
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestVerifyJWT_EmailVerifiedNotRequired(t *testing.T) {
|
|
k := oidcKeys(t)
|
|
set, err := parseJWKS(testJWKS(t, k))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
now := time.Unix(1_800_000_000, 0)
|
|
c := baseClaims(now)
|
|
delete(c, "email_verified")
|
|
s := testSettings()
|
|
s.requireEmailVerified = false
|
|
if _, err := verifyJWT(signTestJWT(t, "RS256", "rsa", k, nil, c), set, s, now); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
|
|
func TestVerifyJWT_SingleKeyWithoutKid(t *testing.T) {
|
|
k := oidcKeys(t)
|
|
doc := map[string]any{"keys": []any{map[string]string{"kty": "RSA",
|
|
"n": b64(k.rsa.N.Bytes()), "e": b64(big.NewInt(int64(k.rsa.E)).Bytes())}}}
|
|
body, err := json.Marshal(doc)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
set, err := parseJWKS(body)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
now := time.Unix(1_800_000_000, 0)
|
|
if _, err := verifyJWT(signTestJWT(t, "RS256", "", k, nil, baseClaims(now)), set, testSettings(), now); err != nil {
|
|
t.Fatalf("a kid-less token must match the only kid-less key: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestParseJWKS(t *testing.T) {
|
|
k := oidcKeys(t)
|
|
set, err := parseJWKS(testJWKS(t, k))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, ok := set.keys["rsa"].(*rsa.PublicKey); !ok {
|
|
t.Fatal("rsa key missing")
|
|
}
|
|
if pub, ok := set.keys["p256"].(*ecdsa.PublicKey); !ok || pub.Curve != elliptic.P256() {
|
|
t.Fatal("p256 key missing")
|
|
}
|
|
if pub, ok := set.keys["p384"].(*ecdsa.PublicKey); !ok || pub.Curve != elliptic.P384() {
|
|
t.Fatal("p384 key missing")
|
|
}
|
|
|
|
skipped, err := parseJWKS([]byte(`{"keys":[
|
|
{"kty":"RSA","kid":"enc","use":"enc","n":"AQAB","e":"AQAB"},
|
|
{"kty":"OKP","kid":"ed","crv":"Ed25519","x":"AAAA"},
|
|
{"kty":"EC","kid":"p521","crv":"P-521","x":"AAAA","y":"AAAA"}
|
|
]}`))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(skipped.keys) != 0 {
|
|
t.Fatalf("enc, OKP and P-521 keys must be skipped, got %v", skipped.keys)
|
|
}
|
|
|
|
for name, body := range map[string]string{
|
|
"malformed json": `{"keys":`,
|
|
"bad rsa modulus": `{"keys":[{"kty":"RSA","kid":"x","n":"!!","e":"AQAB"}]}`,
|
|
"ec point off curve": `{"keys":[{"kty":"EC","kid":"x","crv":"P-256","x":"` + b64(make([]byte, 32)) + `","y":"` + b64(append(make([]byte, 31), 1)) + `"}]}`,
|
|
} {
|
|
t.Run(name, func(t *testing.T) {
|
|
if _, err := parseJWKS([]byte(body)); err == nil {
|
|
t.Fatal("want error")
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestLooksLikeJWT(t *testing.T) {
|
|
k := oidcKeys(t)
|
|
real := signTestJWT(t, "RS256", "rsa", k, nil, baseClaims(time.Now()))
|
|
tests := map[string]bool{
|
|
"sk-abc": false,
|
|
"a.b.c": false,
|
|
"aaa.bbb.ccc.ddd": false,
|
|
b64([]byte(`{"alg":"RS256"}`)) + ".x.y": true,
|
|
real: true,
|
|
}
|
|
for tok, want := range tests {
|
|
if got := looksLikeJWT(tok); got != want {
|
|
t.Errorf("looksLikeJWT(%.20q) = %v, want %v", tok, got, want)
|
|
}
|
|
}
|
|
if kid, err := jwtKid(real); err != nil || kid != "rsa" {
|
|
t.Fatalf("jwtKid = %q, %v", kid, err)
|
|
}
|
|
}
|