The gateway accepted an ID token when its aud named one of the
configured audiences. Keycloak ID tokens carry no other marker.
The gateway now refuses a token whose payload typ is ID, or whose header
typ is id+jwt, in any letter case. The log reason is id_token. The header
check runs before any key fetch. The payload check runs after the
signature check. Access tokens still pass.
The gateway split groupClaim on dots. An Auth0 claim such as
https://example.com/groups could not be addressed.
The gateway now tries the whole groupClaim as one top-level key first.
It walks the dotted path only when that key is absent. A groupClaim with
a URL scheme separator is accepted as one claim name.
A renamed users file override left its old name in the Redis registry.
The admin list showed that name for up to 32 days.
The list now shows a registry record only under the name its identity
resolves to now. This is the override name, or the default oidc name when
no override exists. Usage counters stay untouched.
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.
GET /v1/models now carries a known vision flag in two forms:
architecture.input_modalities for OpenRouter-style clients and other
gateways, and info.meta.capabilities.vision for Open WebUI. An unknown
flag adds no field.
Discovery through metadataPath reads the same two forms from the
upstream. Thus a flag set in modelMeta on one gateway reaches the next
gateway and Open WebUI. A field in another shape is ignored and does not
fail the fetch.
The flag resolves from the alias modelMeta entry, then the target
modelMeta entry, then discovery. The smart router uses the resolved
flag. An unknown flag still counts as capable.
* 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.
* fix(admin): list the anonymous user in snapshot views
The auth snapshot built users from the key digest map only. The keyless
principal never appeared in usage, catalog, metrics or fleet views, and
its rejection counter was pruned on a users-file reload. The snapshot now
adds the anonymous principal once, with source anonymous.
* fix(discovery): keep context lengths when one upstream fails metadata
A failing modelBaseUrls upstream dropped its models from the metadata map.
The registry replaced the discovered contexts, so those models lost their
context length. The failure was also not visible. The adapter now keeps the
last good metadata per upstream and reports metadata failures through
upstreamErrors.
* fix(webui): show provider upstream errors
The dashboard ignored upstreamErrors from the admin overview. A provider
with a failing modelBaseUrls upstream looked healthy. The provider panel
now lists each upstream error, and the breaker rows mark such a provider
as degraded.
* fix(passthrough): gate and bill passthrough requests by cost budget
Refusal text stays under 128 bytes, and only models the provider serves get a per-model counter. When the first 64 KiB does not settle the model, the gate reads the body up to the smaller of maxRequestBytes and the passthrough cap, inside a body-admission slot. It refuses with 402 if the model is missing, repeated, or in a malformed or unterminated object, with 413 if the object does not close within the bound, and with 400 if the body read fails. A priced model after 64 KiB passes and the body reaches the upstream unchanged. A 2xx event stream with no completion usage bills one estimated token per data event.
* fix(billing): estimate completion when a stream ends before its usage
A streaming unified request that failed after output reached the client
recorded zero completion tokens. The gateway now estimates them from the
forwarded output bytes and marks the usage as estimated. Streams that
report usage, and streams that end cleanly, are unchanged.
* fix(cache): key /v1/messages entries on the forwarded anthropic-beta set
Two callers that sent different anthropic-beta values shared one cache
entry, although the gateway forwards that header upstream. The key now
includes the normalised beta set when the header is present. Requests
without the header keep their existing key.
* docs: state that /v1/messages responses are cached
The Caching section named chat and embeddings only. It now names
/v1/messages, the beta set in the key, and that entries are shared
across users and groups.
* fix(passthrough): bill Responses API and Gemini streaming usage shapes
Read input_tokens/output_tokens and input_tokens_details.cached_tokens
for OpenAI Responses JSON, and response.usage from response.completed
SSE events. Decode the Gemini streamGenerateContent JSON array and read
usageMetadata from Gemini SSE data events, last one wins.
Field names follow the OpenAI Responses API and Gemini
GenerateContentResponse references. A truncated array yields no usage.
* fix(admin): scrub the re-serialised base URL from provider errors
sanitizeProviderErr now also replaces the URL as net/url writes it.
A provider baseUrl with userinfo, a query or a fragment logs one
construction warning. The config still loads.
* fix(proxy): do not relay a redirect that carries a configured target query
proxyUpstream answers 502 when an upstream replies with a 3xx Location
and the upstream URL holds a query the client did not send. Targets
without a configured query still relay redirects.
* test(passthrough): rename the client reset reader helper
Two packages each declared failingReader in the same test package. The passthrough gate test now uses clientResetReader.
* fix(discovery): bound the number and length of discovered model ids
A provider keeps at most 10000 discovered ids of at most 256 bytes.
The registry drops empty ids, ids with control characters, longer ids
and the overflow, and logs the count once per 10 minutes.
* fix(mcp): keep the target query when it does not parse
mergeQueryStrings now forwards a configured query that ParseQuery
rejects, next to the client query, instead of dropping it.
* fix(messages): keep tool argument deltas on the open block
Blocks that follow an open tool_use block are queued and emitted at
stream end, so every delta targets the one open block.
* docs: correct failOpen, reload and anonymous access text
* chore(webui): regenerate admin assets
Rebuilt with make admin-ui for the dashboard changes in this branch.
Discovery and metadata polled the upstreams one after another on one
shared context. A hanging modelBaseUrls upstream used up the deadline,
and the whole provider failed again.
Query all upstreams concurrently. Give each modelBaseUrls upstream its
own context with 3/4 of the remaining time, or 30s without a deadline.
A child timeout is recorded in upstreamErrors and skipped. Only a
baseUrl failure, or a cancelled or expired parent context, fails the
listing. The result order stays baseUrl first, then the sorted upstreams.
* fix(admin): attach model aliases to the model their target resolves to
The catalog grouped aliases by the raw target string and looked them up by
canonical provider/model id. A bare target never matched, so no model card
listed its aliases. Each alias now keys on the canonical id that the
registry resolves its target to. The alias view gains an additive
resolvedTarget field.
Model-id cells in the overview, usage and panels now show an alias badge
with the target, using the catalog alias list.
* fix(webui): omit the provider filter select until providers load
* fix(discovery): tolerate failing modelBaseUrls upstreams
A modelBaseUrls upstream that fails /v1/models must not fail the provider.
Discovery now fails only when baseUrl fails. The explicit models of the
failing upstream stay listed, and the other upstreams still merge.
The admin overview reports each failed upstream in the additive
upstreamErrors field. The registry logs it at most once per 10 minutes
per provider. The README states the new semantics.
* chore(webui): regenerate admin assets
Rebuilt with make admin-ui for the alias badge and the provider filter changes.
* style(auth): order authStore fields for fieldalignment
golangci-lint's fieldalignment check reported 240 leading pointer bytes on authStore where 232 is optimal. The bool anonymousAnyKey moves next to the mutexes. No behaviour change.
GET /v1/models now emits max_context_length next to the other context
fields, so a downstream gateway can read it through metadataPath. The
field is omitted when the context window is unknown.
Discovery and metadataPath now query baseUrl and each distinct
modelBaseUrls upstream. The gateway keeps an id only from the upstream
that serves it. Discovery fails when any upstream fails and keeps the
last-known set. Metadata keeps the ids of the upstreams that answered.
A thinking model spends a small max_tokens on reasoning and returns empty
content with finish_reason length. TensorFold on the d1 DeepSeek server
warns about this and suggests chat_template_kwargs enable_thinking false.
providers.<name>.thinking.offBelowMaxTokens (openai type, default off)
adds chat_template_kwargs: {"enable_thinking": false} to the upstream
body when a chat request caps its output under the value. It also does
this when /v1/messages translates a request for that provider. A request
with no cap, a cap at or above the value, or its own thinking choice
(reasoning_effort, reasoning, thinking, enable_thinking, or
chat_template_kwargs.enable_thinking or .thinking) is not changed. Other
client chat_template_kwargs keys are kept, and the client's map is not
modified. The response cache still keys on the client body.
An OpenAI-compatible stream that ended with neither a finish_reason nor
[DONE] counted as a finished answer. When the d1 model server died
mid-reply, the gateway sent the client an empty stream with no
finish_reason, and the smart router did not try its next tier.
forwardStream now returns errStreamTruncated for such a stream, wrapped
in errUpstream. Before any output reaches the client, the request fails
over or escalates to the next tier. After output, the client gets an
error event and no [DONE]. A stream with [DONE] but no finish_reason
keeps its old behaviour.
The passthrough proxy wrote the status line but flushed only on the first
body write. An MCP server-to-client stream (GET with text/event-stream)
can stay silent for a long time, so the client did not get the response
headers. Traefik in front of the standalone gateway waited for its 20m
responseHeaderTimeout and then returned 504.
The proxy now flushes the headers at once when the upstream answers with
text/event-stream.
The OpenAI SDKs refuse to start without an API key, so keyless callers
set a placeholder key. With users.anonymousGroup alone, that placeholder
gets 401.
Set users.anonymousAcceptAnyKey to true to serve a key that matches no
user as "anonymous". A configured user's key still resolves to that
user. A placeholder key does not count toward the auth-failure
throttle. The admin API and the metrics key fallback still use
identifyKeyed, so they still need a valid key. The option is false by
default, and it needs users.anonymousGroup.
TestPacing_ConcurrentPacedRequestsCappedPerUser counted every paced
request, but the gate caps only the requests that wait at the same time.
The delays were 4 to 44 ms, so with one CPU early requests finished and
freed their slots, and a fifth request was paced correctly. The test now
gives each request a delay of at least 3 s, waits until the gate holds
maxConcurrentPaced requests, and checks that two more requests return at
once without the paced header.
TestCacheHit_BodyParseSkippedWhenStatsAdminOff compared the CPU time of
a cache hit with admin on and off. The parse is a small part of a hit,
so the ratio fell below the 1.33 threshold on every run without -race.
A nil-by-default Gateway field now lets the test count the parses: a hit
with admin on parses the body, and a hit with admin off does not.
A request with "stream": true on POST /v1/messages now gets the
Anthropic Messages event stream instead of a 400. Claude Code streams
every call, so the route must stream before it can front an
OpenAI-compatible cluster.
For openai and gemini providers, the gateway asks the upstream for a
stream with include_usage and translates each chunk as it arrives. It
emits message_start, one content block group per text or tool_use
block, then message_delta and message_stop. Tool call arguments arrive
as input_json_delta. The stop reason uses the non-streaming mapping.
For anthropic providers, the gateway relays each upstream event and
rewrites only message.model in message_start. An upstream error event
reaches the client once, as sent.
Billing uses the stream usage. An error before the stream starts gets
the normal JSON error. An error after the start ends the stream with an
error event. Streams are never cached. yaegi-check now drives a
streamed request under the interpreter.
Set users.anonymousGroup to a configured group to serve requests that
carry no credential as the reserved user "anonymous" in that group. The
group grant applies, and the group memberLimits are the per-user limits
that all keyless callers share.
A request that sends an Authorization or x-api-key header must carry a
valid key, so a wrong or malformed credential still gets 401. The admin
API and the metrics key fallback use identifyKeyed and never admit the
anonymous user. The name "anonymous" is reserved while the option is
set. The option is empty by default, and then every route needs a key as
before.
The .traefik.yml testData now enables anonymous access, and yaegi-check
exercises it under the interpreter.
MCP GET event streams (the server-to-client channel) now run without the progress watchdog and are ended by the client, the upstream or Gateway.DrainIdleStreams.
The standalone binary drains them on shutdown and when a config reload retires a gateway, so they do not hold either open.
examples/standalone is a kustomization for the compiled gateway with restart draining, a configMapGenerator config, placeholder Secrets and an optional Traefik route.
TestHandleChat_RequestLimitExceeded_BodyNeverRead now pins the limiter clock and uses an unreachable local upstream, so it no longer flakes at a minute boundary or calls api.openai.com.
The standalone binary reloads its config file on change and on SIGHUP, and keeps the old gateway for running requests.
GoReleaser publishes the standalone binaries and a signed multi-arch image to ghcr.io/lukaszraczylo/traefik-llmgateway.
The plugin form does not change.
This change adds the redesigned admin panel and the smart router decision model assist.
It adds opt-in prompt-prefix caching per provider and cached-token pricing and metrics.
With Redis, the metrics route reports fleet-wide values. The redis.sharedState switch shares six coordination states across replicas.
PR CI grants actions read, which the shared go-pr workflow needs.
The pull request description has the full list and the verification.
Add smart routers: virtual models that score each request and route it to admin-defined model tiers. A retryable failure moves the request to a higher tier. The classifier v2 extracts prose, finds the original ask in long tool loops, adds an uncertainty margin and reads tool-output failures. Sessions, outcome signals, bounded calibration, adaptive selection within a tier, gated saturation downgrade, a first-byte timeout and an opt-in timeout fallback are included. Every new feature is off by default.
Add per-member group limits, a tokensPerMinute window that counts uncached input and output, rate-limit headers in three dialects, soft pacing before the hard limit, and a limitExemptKinds list so embedding and reranking traffic never counts toward or hits a limit.
Fix yaegi named-result state that made smartContentSize grow between calls.
The provider accordion reads the overview response, not the catalog, so
the earlier change never reached it. Add kinds and endpoints to the
overview provider view and group the accordion rows by kind. Endpoint ids
now read gx10/v1/decide, without a doubled slash.
Add a display-only kinds map to the provider config. Each pathBaseUrls key
now appears in the admin catalog as an endpoint row. The Models page splits
a provider into one sub-section per kind.
The error-rate axis rounded half-percent ticks up, so labels repeated (4%, 4%, 3%, 3%). Ticks now show one decimal where needed. The CSS layer test imported node:fs, which broke npm run build under vue-tsc, so it is removed.
The per-user detail cache grew without limit and now keeps the 20 most recently fetched users. Spend refresh built the breakdown from a stale ranking after the ranking failed or was superseded, and now skips that step. The FontAwesome stylesheet overrode Tailwind hidden and showed two accordion chevrons, so it now loads in a low cascade layer.
A new API key kept the previous key's data on screen until each store refreshed. All data stores now reset when the key changes. The Spend breakdown chart showed a column of identical zero ticks for an empty range, so it now shows an empty message. A stray quote in the Reliability page markup is removed.
CSV export prefixed negative numbers with an apostrophe, which corrupted the data. YAML emitted NaN and Infinity as plain strings. Context windows such as 1500 read as 2k. Numbers now skip the CSV formula guard, non-finite values use YAML float forms, and counts below 10k keep one decimal.
The burn-down chart drew the budget line even when it was more than ten times the spend, which flattened the spend curve. The line now hides with a note. Limits, pricing, model metadata and grant forms mark invalid inputs with aria-invalid and aria-describedby.
The table had 11 columns and scrolled at 1280px, hiding p50, p95 and error rate. It now shows compact price, one token column and a short error header. Context window stays in the model chip hover, and the :free flag moves into the price cell.
FontAwesome injected a style element at runtime. The admin CSP blocks that and logged a console error on every load. The UI now imports the stylesheet and disables auto injection.
Label configured model aliases with an alias badge wherever a model id shows.
List only providers with traffic in the window in provider chart legends.
Page long tables, show a scroll shadow on wide ones and drop the duplicate model link.
Show costs with thousands separators and magnitude-scaled decimals on cards and chart axes.
Use whole-number ticks for count charts and replace all-zero charts with a message.
Back off polling after failures.
Keep the CSV status region from widening the page on phones.
Regenerate admin_assets_gen.go.
Fetch the consumers list on the user detail page so admin and grant data show on a deep link.
Gate Recent errors, the Spend total and the forecast card on load state instead of showing zeros.
Show a stale notice on top lists when a refresh fails.
Clear the target name when the target kind changes.
Ignore out-of-order config responses.
Wrap long group names and event messages, and announce projected budget overruns to screen readers.
Regenerate admin_assets_gen.go.
Show a persistent notice when a refresh fails while old data is on screen.
Add retry to the Targets and Access Matrix error states.
Give tables names, skeletons a status role and CSV export a live region.
Abort admin requests after 15 seconds and share concurrent identical GETs.
Show a reload prompt when a lazy page chunk fails to load.
Ignore prototype keys in the location hash.
Stop formatContextWindow emitting 1000k, round latency before the 1s cutoff,
and treat NaN as not enough data in the month projection.
Regenerate admin_assets_gen.go.
The README claimed an at-most-one-request overshoot. Requests in flight
together all pass the pre-check, so the bound is concurrency times the
largest request cost.
time.After keeps its timer alive until it fires on go 1.22 semantics,
so each cancelled retry wait pinned a timer for up to 2s. A stoppable
timer releases it at once.
A secret field added under a new JSON key would pass through the config
endpoint unredacted because the redactor matches keys by name. The test
fails until each string key is redacted or declared non-secret.
Go leaves a float to int64 conversion implementation-defined when the value is out of range, so a huge max_tokens could become a negative number on some architectures. The conversion now saturates to the int64 range and refuses NaN.
The parser allocated the full declared bulk length before any payload arrived, so a stalled peer could pin 64 MiB per connection. The buffer now starts at 64 KiB and doubles only after the previous capacity has fully arrived. A test measures the allocation.
The loader read the whole users file into memory on the request path, whatever its size. The loader now reads at most the cap plus one byte and refuses a larger file. The last good user set stays active.
A panic inside the response copy skipped the caller's release, so the tee kept its reserved bytes in the shared budget for good. The proxy now releases the tee and keeps unwinding. A test reproduces the leak.
A successful but empty discovery answer replaced the known model set with nothing, so a flapping upstream made every discovered model return 404 until the next refresh. The registry now treats that answer as a failure. It keeps the previous set and counts the failure toward the discovery breaker.
The reserve step added first and checked after. Concurrent reservations saw a transient overshoot and were denied while room remained. The step now claims bytes only when they fit, so used never exceeds the limit.
An upstream could send millions of empty data lines in one event. The cap counted one byte per line, but each line kept a 16-byte string header in memory. The cap now counts the header too, so retained memory stays within the cap.
A zero or negative backoff passed validation and made retries fire with no pause. The config loader now rejects it. The wait ladder compares the backoff to the cap before it multiplies, so a very large backoff cannot overflow.