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.
321 lines
9.9 KiB
Go
321 lines
9.9 KiB
Go
package traefikllmgateway
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
const (
|
|
// oidcMaxBody caps every IdP response the gateway reads.
|
|
oidcMaxBody = 1 << 20
|
|
// oidcHTTPTimeout bounds one IdP round trip on the request path.
|
|
oidcHTTPTimeout = 5 * time.Second
|
|
// oidcKidRefetchAfter throttles JWKS refetches triggered by an unknown
|
|
// kid, so forged kids cannot turn every request into an IdP call.
|
|
oidcKidRefetchAfter = 60 * time.Second
|
|
// oidcFetchRetryAfter holds a failed discovery or JWKS fetch error, so
|
|
// an IdP outage does not turn every request into a new IdP call.
|
|
oidcFetchRetryAfter = 5 * time.Second
|
|
// oidcUserinfoMaxInFlight caps concurrent userinfo calls, so a flood of
|
|
// opaque bearers cannot become a flood of IdP requests.
|
|
oidcUserinfoMaxInFlight = 16
|
|
// oidcUserinfoQueueWait is how long a userinfo call waits for a free
|
|
// slot, so a burst shares the slots instead of failing at once.
|
|
oidcUserinfoQueueWait = 2 * time.Second
|
|
)
|
|
|
|
var (
|
|
// errIDPBusy refuses a userinfo call while oidcUserinfoMaxInFlight are
|
|
// already running.
|
|
errIDPBusy = errors.New("oidc: too many userinfo calls in flight")
|
|
// errInsecureIDPURL rejects an IdP endpoint that is not https or
|
|
// loopback http.
|
|
errInsecureIDPURL = errors.New("oidc: endpoint must be https or loopback http")
|
|
// errIDPRejected marks an IdP 401 or 403: the IdP refused the token.
|
|
errIDPRejected = errors.New("oidc: idp rejected the token")
|
|
)
|
|
|
|
// oidcDiscovery is the subset of the OpenID Provider Metadata the gateway uses.
|
|
type oidcDiscovery struct {
|
|
Issuer string `json:"issuer"`
|
|
JWKSURI string `json:"jwks_uri"`
|
|
UserinfoEndpoint string `json:"userinfo_endpoint"`
|
|
}
|
|
|
|
// oidcProvider fetches and caches the issuer's discovery document and keys.
|
|
type oidcProvider struct {
|
|
fetchedAt time.Time
|
|
failedAt time.Time
|
|
// discAt is when disc was fetched; discFailedAt is the last failed
|
|
// refresh of an already cached disc.
|
|
discAt time.Time
|
|
discFailedAt time.Time
|
|
client *http.Client
|
|
now func() time.Time
|
|
// userinfoSlots is a semaphore of oidcUserinfoMaxInFlight tokens.
|
|
userinfoSlots chan struct{}
|
|
settings *oidcSettings
|
|
disc *oidcDiscovery
|
|
keys *jwkSet
|
|
failErr error
|
|
// timeout bounds one whole fetch: discovery plus JWKS, or one userinfo
|
|
// call.
|
|
timeout time.Duration
|
|
// queueWait bounds how long a userinfo call waits for a free slot.
|
|
queueWait time.Duration
|
|
stateMu sync.RWMutex
|
|
fetchMu sync.Mutex
|
|
}
|
|
|
|
func newOIDCProvider(s *oidcSettings, client *http.Client, now func() time.Time) *oidcProvider {
|
|
// A redirect would skip the https-or-loopback check on the endpoint,
|
|
// and a redirected userinfo body would become identity claims.
|
|
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
|
|
return &oidcProvider{
|
|
settings: s, client: client, now: now, timeout: oidcHTTPTimeout,
|
|
queueWait: oidcUserinfoQueueWait, userinfoSlots: make(chan struct{}, oidcUserinfoMaxInFlight),
|
|
}
|
|
}
|
|
|
|
// keysFor returns the issuer's signing keys, fetching them when none are
|
|
// cached, when they are older than jwksRefresh, or when kid is unknown and
|
|
// the last fetch is older than oidcKidRefetchAfter. A failed refresh keeps
|
|
// serving the last good keys. The fetch runs on its own deadline: one
|
|
// caller's cancel must not fail it for everyone else.
|
|
func (p *oidcProvider) keysFor(kid string) (*jwkSet, error) {
|
|
if keys, ok := p.cachedKeys(kid); ok {
|
|
return keys, nil
|
|
}
|
|
p.fetchMu.Lock()
|
|
defer p.fetchMu.Unlock()
|
|
if keys, ok := p.cachedKeys(kid); ok {
|
|
return keys, nil
|
|
}
|
|
if err := p.recentFailure(); err != nil {
|
|
p.stateMu.RLock()
|
|
keys := p.keys
|
|
p.stateMu.RUnlock()
|
|
if keys != nil {
|
|
return keys, nil
|
|
}
|
|
return nil, err
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), p.timeout)
|
|
defer cancel()
|
|
fresh, err := p.fetchKeys(ctx)
|
|
p.stateMu.Lock()
|
|
defer p.stateMu.Unlock()
|
|
if err != nil {
|
|
p.failedAt, p.failErr = p.now(), err
|
|
if p.keys != nil {
|
|
return p.keys, nil
|
|
}
|
|
return nil, err
|
|
}
|
|
p.keys, p.fetchedAt, p.failErr = fresh, p.now(), nil
|
|
return fresh, nil
|
|
}
|
|
|
|
// recentFailure returns the last fetch error while it is inside
|
|
// oidcFetchRetryAfter.
|
|
func (p *oidcProvider) recentFailure() error {
|
|
p.stateMu.RLock()
|
|
defer p.stateMu.RUnlock()
|
|
if p.failErr != nil && p.now().Sub(p.failedAt) < oidcFetchRetryAfter {
|
|
return p.failErr
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// cachedKeys reports the cached keys when no fetch is due for kid.
|
|
func (p *oidcProvider) cachedKeys(kid string) (*jwkSet, bool) {
|
|
p.stateMu.RLock()
|
|
defer p.stateMu.RUnlock()
|
|
if p.keys == nil {
|
|
return nil, false
|
|
}
|
|
age := p.now().Sub(p.fetchedAt)
|
|
if age >= p.settings.jwksRefresh {
|
|
return nil, false
|
|
}
|
|
if _, err := p.keys.lookup(kid); err != nil && age >= oidcKidRefetchAfter {
|
|
return nil, false
|
|
}
|
|
return p.keys, true
|
|
}
|
|
|
|
func (p *oidcProvider) fetchKeys(ctx context.Context) (*jwkSet, error) {
|
|
disc, err := p.discovery(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
body, err := p.get(ctx, disc.JWKSURI, "")
|
|
if err != nil {
|
|
return nil, fmt.Errorf("oidc: jwks: %w", err)
|
|
}
|
|
return parseJWKS(body)
|
|
}
|
|
|
|
// discovery returns the discovery document. It re-fetches once the cached
|
|
// copy is older than jwksRefresh; a failed refresh keeps the old copy and
|
|
// retries after oidcFetchRetryAfter. A failure with no copy is held for
|
|
// oidcFetchRetryAfter. The caller holds fetchMu.
|
|
func (p *oidcProvider) discovery(ctx context.Context) (*oidcDiscovery, error) {
|
|
p.stateMu.RLock()
|
|
disc, at, failed := p.disc, p.discAt, p.discFailedAt
|
|
p.stateMu.RUnlock()
|
|
if disc != nil && !p.discoveryDue(at, failed) {
|
|
return disc, nil
|
|
}
|
|
if disc == nil {
|
|
if err := p.recentFailure(); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
doc, err := p.fetchDiscovery(ctx)
|
|
p.stateMu.Lock()
|
|
defer p.stateMu.Unlock()
|
|
if err != nil {
|
|
if disc != nil {
|
|
p.discFailedAt = p.now()
|
|
return disc, nil
|
|
}
|
|
p.failedAt, p.failErr = p.now(), err
|
|
return nil, err
|
|
}
|
|
p.disc, p.discAt, p.discFailedAt = doc, p.now(), time.Time{}
|
|
return doc, nil
|
|
}
|
|
|
|
// discoveryDue reports whether a cached document fetched at `at` needs a
|
|
// refresh, given the last failed refresh at `failed`.
|
|
func (p *oidcProvider) discoveryDue(at, failed time.Time) bool {
|
|
now := p.now()
|
|
if now.Sub(at) < p.settings.jwksRefresh {
|
|
return false
|
|
}
|
|
return failed.IsZero() || now.Sub(failed) >= oidcFetchRetryAfter
|
|
}
|
|
|
|
func (p *oidcProvider) fetchDiscovery(ctx context.Context) (*oidcDiscovery, error) {
|
|
url := strings.TrimSuffix(p.settings.issuer, "/") + "/.well-known/openid-configuration"
|
|
body, err := p.get(ctx, url, "")
|
|
if err != nil {
|
|
return nil, fmt.Errorf("oidc: discovery: %w", err)
|
|
}
|
|
var doc oidcDiscovery
|
|
if err := json.Unmarshal(body, &doc); err != nil {
|
|
return nil, fmt.Errorf("oidc: discovery: %w", err)
|
|
}
|
|
// OpenID Connect Discovery 1.0 §4.3: the document's issuer must equal
|
|
// the configured issuer exactly.
|
|
if doc.Issuer != p.settings.issuer {
|
|
return nil, fmt.Errorf("oidc: discovery issuer %q does not match configured issuer %q", doc.Issuer, p.settings.issuer)
|
|
}
|
|
if doc.JWKSURI == "" {
|
|
return nil, errors.New("oidc: discovery has no jwks_uri")
|
|
}
|
|
if !secureIDPURL(doc.JWKSURI) {
|
|
return nil, fmt.Errorf("%w: jwks_uri %q", errInsecureIDPURL, doc.JWKSURI)
|
|
}
|
|
return &doc, nil
|
|
}
|
|
|
|
// userinfo resolves an opaque token's claims at the IdP userinfo endpoint.
|
|
// At most oidcUserinfoMaxInFlight calls run at once; the rest wait up to
|
|
// queueWait for a slot, then fail with errIDPBusy. An IdP 401 or 403 wraps
|
|
// errIDPRejected.
|
|
func (p *oidcProvider) userinfo(ctx context.Context, token string) (map[string]any, error) {
|
|
wait := time.NewTimer(p.queueWait)
|
|
select {
|
|
case p.userinfoSlots <- struct{}{}:
|
|
wait.Stop()
|
|
case <-wait.C:
|
|
return nil, errIDPBusy
|
|
case <-ctx.Done():
|
|
wait.Stop()
|
|
return nil, ctx.Err()
|
|
}
|
|
defer func() { <-p.userinfoSlots }()
|
|
|
|
disc, err := p.cachedDiscovery()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if disc.UserinfoEndpoint == "" {
|
|
return nil, errors.New("oidc: discovery has no userinfo_endpoint")
|
|
}
|
|
if !secureIDPURL(disc.UserinfoEndpoint) {
|
|
return nil, fmt.Errorf("%w: userinfo_endpoint %q", errInsecureIDPURL, disc.UserinfoEndpoint)
|
|
}
|
|
ctx, cancel := context.WithTimeout(ctx, p.timeout)
|
|
defer cancel()
|
|
body, err := p.get(ctx, disc.UserinfoEndpoint, token)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("oidc: userinfo: %w", err)
|
|
}
|
|
var claims map[string]any
|
|
if err := json.Unmarshal(body, &claims); err != nil {
|
|
return nil, fmt.Errorf("oidc: userinfo: %w", err)
|
|
}
|
|
return claims, nil
|
|
}
|
|
|
|
// cachedDiscovery returns the discovery document. It takes fetchMu only to
|
|
// fetch a missing document, or to refresh a due one when the lock is free, so
|
|
// userinfo slots never wait behind a JWKS fetch.
|
|
func (p *oidcProvider) cachedDiscovery() (*oidcDiscovery, error) {
|
|
p.stateMu.RLock()
|
|
disc, at, failed := p.disc, p.discAt, p.discFailedAt
|
|
p.stateMu.RUnlock()
|
|
if disc != nil {
|
|
if !p.discoveryDue(at, failed) || !p.fetchMu.TryLock() {
|
|
return disc, nil
|
|
}
|
|
} else {
|
|
p.fetchMu.Lock()
|
|
}
|
|
defer p.fetchMu.Unlock()
|
|
ctx, cancel := context.WithTimeout(context.Background(), p.timeout)
|
|
defer cancel()
|
|
return p.discovery(ctx)
|
|
}
|
|
|
|
func (p *oidcProvider) get(ctx context.Context, url, bearer string) ([]byte, error) {
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
req.Header.Set("Accept", "application/json")
|
|
if bearer != "" {
|
|
req.Header.Set("Authorization", "Bearer "+bearer)
|
|
}
|
|
resp, err := p.client.Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer func() { _ = resp.Body.Close() }() // read-only response; a close error changes nothing
|
|
body, err := io.ReadAll(io.LimitReader(resp.Body, oidcMaxBody+1))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(body) > oidcMaxBody {
|
|
return nil, fmt.Errorf("response too large (over %d bytes)", oidcMaxBody)
|
|
}
|
|
switch resp.StatusCode {
|
|
case http.StatusOK:
|
|
return body, nil
|
|
case http.StatusUnauthorized, http.StatusForbidden:
|
|
return nil, fmt.Errorf("%w: status %d", errIDPRejected, resp.StatusCode)
|
|
}
|
|
return nil, fmt.Errorf("status %d", resp.StatusCode)
|
|
}
|