Files
traefik-llmgateway/oidc_provider.go
lukaszraczylo e94225a569 fix(auth): refresh the oidc discovery document with the keys
The gateway cached the discovery document for the life of the process.
A changed jwks_uri or userinfo_endpoint stayed hidden until a restart.

The provider now fetches the document again when it is older than
jwksRefresh. A failed refresh keeps the old document. The next try waits
for the fetch retry interval.
2026-12-02 02:02:44 +00:00

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)
}