fix: close the run-3 security audit findings (#25)

* 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.
This commit is contained in:
2026-11-29 00:29:06 +00:00
committed by GitHub
parent f1633666ff
commit 009de03264
34 changed files with 2612 additions and 259 deletions
+51 -26
View File
@@ -242,22 +242,21 @@ that still has requests after `-reload-drain-timeout` closes anyway.
[`requestTimeout`](#request-timeout) — a progress-based watchdog, five
minutes by default — not a proxy deadline.
- **Config changes need a restart.** Traefik rebuilds the plugin
automatically on a CR change; a binary has no such hook. Roll the pods
by putting a checksum of the `ConfigMap` in the Deployment's pod
annotations, so an ArgoCD sync restarts them. There is deliberately no
SIGHUP and no file watcher: a rebuild re-runs the synchronous discovery
warm-fill, and a single-file watch never fires on a `ConfigMap` update
anyway (the kubelet swaps the whole directory's symlink).
- **Config changes reload on their own.** Traefik rebuilds the plugin
automatically on a CR change. The binary reloads when the file content
changes and on `SIGHUP`; see [Config reload in the binary](#config-reload-in-the-binary).
A checksum of the `ConfigMap` in the Deployment's pod annotations, so an
ArgoCD sync restarts the pods, is optional.
**The users file is the exception and needs none of this.** It still
hot-reloads on its own 5-second mtime poll from the request path, exactly
as in the plugin form. Do not add a watcher for it — it would race the
existing one.
- **Provider keys resolve once, at construction**, in both forms. Rotating
one means a restart even though the mounted file changed. Only
file-sourced *user* keys re-resolve on the users-file reload.
- **Provider keys resolve once per gateway build.** In the binary, `SIGHUP`
rebuilds the gateway and picks up a rotated `file:` provider key. In the
plugin form, a rebuild is the only way. Only file-sourced *user* keys
re-resolve on the users-file reload.
- **Mount the same secret volumes.** A `file:/llmgw/providers/openai`
`apiKey` reads that exact path in the binary too. Reproduce the volumes,
@@ -412,7 +411,7 @@ config accepts them as YAML, which decodes to the same JSON shape.
| `providers` | `map[string]ProviderConfig` | — | Required, at least one entry, or the plugin refuses to construct. |
| `groups` | `map[string]GroupConfig` | `{}` | Optional. A user references one or more of these groups by name (`UserConfig.group`/`groups`); an unknown reference is a construction error. |
| `pricing` | `map[string]ModelPricing` | `{}` | Per-model USD/1M-token overrides, keyed by model id (bare or `provider/model`). Merged over, not replacing, the built-in table (`pricing.go`). Every entry is validated at construction — see [Limits and accounting](#limits-and-accounting). |
| `allowUnpricedWithCostBudget` | `bool` | `false` | `false`: a request for a model with no known price — no `pricing` override, no built-in table entry, and no `modelMeta` entry marking it `free: true` — is refused with **402** whenever the caller's user or group has `costPerDayUSD`/`costPerMonthUSD` configured, since that budget could not otherwise be enforced. Applies to the unified routes and to native passthrough when the model is identifiable from the request body. `true` serves the request anyway, billing it as unpriced (cost `0`) — prefer adding the missing `pricing` entry instead. A caller with no cost budget configured is unaffected either way. |
| `allowUnpricedWithCostBudget` | `bool` | `false` | `false`: a request for a model with no known price — no `pricing` override, no built-in table entry, and no `modelMeta` entry marking it `free: true` — is refused with **402** whenever the caller's user or group has `costPerDayUSD`/`costPerMonthUSD` configured, since that budget could not otherwise be enforced. Applies to the unified routes and to native passthrough when the model is identifiable from the request body. Passthrough also refuses with **402** a JSON body whose top-level `model` is missing or repeated after the gateway has read the body up to the smaller of `maxRequestBytes` and the 32MiB passthrough cap (a body whose JSON object does not close within that bound gets **413**) because the first 64KiB did not settle it. A priced `model` placed after 64KiB is served. Two shapes are still not gated: a JSON body sent with a binary `Content-Type`, and Gemini passthrough, whose model is in the URL; both can reach an unpriced model at recorded cost `0`. `true` serves the request anyway, billing it as unpriced (cost `0`) — prefer adding the missing `pricing` entry instead. A caller with no cost budget configured is unaffected either way. |
| `mcpServers` | `map[string]TargetConfig` | `{}` | MCP server registry; see [MCP/A2A](#mcp-and-a2a). |
| `agents` | `map[string]AgentConfig` | `{}` | A2A agent registry; see [MCP/A2A](#mcp-and-a2a). |
| `users` | `UsersConfig` | — | Inline and/or file-backed API-key holders. With none configured, every request is unauthenticated and gets 401. |
@@ -420,7 +419,7 @@ config accepts them as YAML, which decodes to the same JSON shape.
| `retry` | `RetryConfig` | `{}` (disabled) | Same-provider retry for transient upstream failures — see [Retry](#retry). Omitted or `enabled: false` means no retry: every request makes exactly one upstream attempt, byte-identical to a gateway built before this field existed. |
| `failover` | `FailoverConfig` | `{}` (disabled) | Cross-provider failover for a bare model id more than one configured provider serves — see [Failover](#failover). Omitted or `enabled: false` means no failover, byte-identical to a gateway built before this field existed. `enabled: true` opts in; a deployment with no overlapping providers behaves exactly as before regardless of this setting either way. |
| `requestTimeout` | `string` (Go duration) | `5m` | Progress-based upstream request timeout, applied to every provider adapter call, native passthrough, and the MCP/A2A target proxy — see [Request timeout](#request-timeout). **Behavior change for every deployment**: before this field existed, no timeout was set at all, so a provider that accepted a connection and then went silent hung the request forever. A provider's own `requestTimeout` (`ProviderConfig`) overrides this. Empty means the default; a value that fails to parse, or parses to zero or a negative duration, is a construction error. |
| `cache` | `CacheConfig` | `{}` (disabled) | Opt-in Redis-backed response cache for unified non-streaming chat/embeddings — see [Caching](#caching). Omitted or `enabled: false` means no caching, byte-identical to a gateway built before this field existed. |
| `cache` | `CacheConfig` | `{}` (disabled) | Opt-in Redis-backed response cache for unified non-streaming chat, `/v1/messages` and embeddings — see [Caching](#caching). Omitted or `enabled: false` means no caching, byte-identical to a gateway built before this field existed. |
| `breaker` | `BreakerConfig` | `{}` (every default) | Per-provider discovery circuit breaker — see [Provider health (discovery circuit breaker)](#provider-health-discovery-circuit-breaker). Every field is individually zero-means-default; a provider whose discovery never fails is unaffected regardless of what this block contains. |
| `targetHealth` | `TargetHealthConfig` | `{}` (probes off) | Health tracking for MCP servers and A2A agents — see [MCP and A2A](#mcp-and-a2a)'s "Target health" section. Passive recording and exposure stay on regardless of this block; `enabled` gates only the active probe sweep. |
| `admin` | `*AdminConfig` | `nil` (disabled) | Read-only admin dashboard — see [Admin](#admin). `nil` or `enabled: false` means the `/admin*` routes are not registered at all. |
@@ -751,7 +750,11 @@ as the reserved user `anonymous` in that group:
```yaml
groups:
public:
providers: ["openai"]
models: ["gpt-5-mini"]
mcpServers: ["-none-"]
agents: ["-none-"]
passthroughPaths: ["-none-"]
limits: { requestsPerDay: 5000 }
memberLimits: { requestsPerMinute: 30 }
users:
@@ -780,6 +783,9 @@ to serve those requests as `anonymous` too:
- The admin API and the metrics key fallback still need a valid admin key.
Anyone who can reach the gateway can spend the providers this group allows.
An empty `mcpServers`, `agents` or `passthroughPaths` list on this group
allows every MCP server, A2A agent and native passthrough path. The example
sets each to a pattern that matches no name (`-none-`) to deny them.
Set group `limits` and `memberLimits`, and restrict who can reach the route
at the proxy.
@@ -1645,9 +1651,12 @@ model id) and per alias (`aliases[].modelMeta`) — see
`ceil(request-body-bytes / 4)` counted as prompt tokens, no completion
estimate — and marks it `estimated`. Estimated usage therefore lands
entirely in the `tokin` counter below; `tokout` never moves for an
estimated request. A **streaming** unified-route response with no usage
is logged and the request itself is still counted, but no token
estimate is applied.
estimated request. A **streaming** unified-route response that ends
cleanly with no usage is logged and the request itself is still counted,
but no token estimate is applied. A streaming response that fails or is
cancelled after output reached the client, and reports no completion
usage, records an estimated `tokout` of `ceil(forwarded-output-bytes / 4)`
(text, reasoning and tool-call argument bytes) and is marked `estimated`.
- **Tokens are tracked in two directions**: every prompt token increments
a `tokin` counter, every completion token a separate `tokout` counter —
the same split the admin usage API and usage-history API both expose
@@ -1773,7 +1782,10 @@ model id) and per alias (`aliases[].modelMeta`) — see
reports one — the request-body-size estimate (`ceil(request-bytes / 4)`
prompt tokens, `estimated`) covers it instead, so a streamed or
malformed passthrough response is never billed zero just for never
finishing cleanly.
finishing cleanly. A 2xx stream that delivered `data:` events but no
completion usage — no `include_usage`, or a client that hung up before
the final usage event — is also billed an estimated completion of one
token per `data:` event (capped at 1048576), marked `estimated`.
- **Native passthrough request bodies are capped at 32MiB**
(`maxPassthroughBytes`, `routes_passthrough.go`) — generous enough for
a multimodal payload the unified routes' own narrower caps do not need
@@ -1821,7 +1833,10 @@ released, so this never becomes a ceiling on total concurrent requests.
memory, so there is nothing here for this limit to bound (the one
exception, a bounded 64KiB peek for model-restricted groups, is
already capped independently — see [Native passthrough model
authorization](#native-passthrough-model-authorization)).
authorization](#native-passthrough-model-authorization)). Under a cost
budget, when the first 64KiB does not settle the top-level `model`,
the gate buffers the body up to the smaller of `maxRequestBytes` (4MiB
by default) and this 32MiB cap, then restores it for forwarding.)
## Retry
@@ -2109,7 +2124,7 @@ stall there is bounded at whichever of those applies, not indefinite.
## Caching
An opt-in, Redis-backed response cache for the unified, non-streaming
`POST /v1/chat/completions` and `POST /v1/embeddings` routes. Off by
`POST /v1/chat/completions`, `POST /v1/messages` and `POST /v1/embeddings` routes. Off by
default (`cache.enabled: false`); every config that predates this field
keeps calling the upstream on every request. Caching also requires
`redis` to be configured — without it, `cache.enabled: true` is silently
@@ -2117,7 +2132,8 @@ disabled with one warning logged at construction, never a per-replica
in-process fallback: divergent replicas would otherwise serve different
cached bodies for the same request.
- **What's cacheable**: a non-streaming chat request, or a non-streaming
- **What's cacheable**: a non-streaming chat or `/v1/messages` request
(endpoint value `messages`), or a non-streaming
embeddings request when `cache.cacheEmbeddings` is `true`, whose
upstream response was HTTP 200 and no larger than `cache.maxBodyBytes`.
Never cached: a streaming request, native passthrough, MCP/A2A, the
@@ -2125,9 +2141,12 @@ cached bodies for the same request.
or any non-200 upstream response.
- **Key**: `llmgw:cache:` plus a hex SHA-256 digest of the provider name,
the resolved upstream model id, the client's own exactly-as-sent
`model` string (`requestedModel`), the endpoint (`chat` or
`embeddings`), and the canonical JSON of the request body with
`stream_options` and `user` removed. `requestedModel` and the endpoint
`model` string (`requestedModel`), the endpoint (`chat`,
`messages` or `embeddings`), and the canonical JSON of the request body with
`stream_options` and `user` removed. For `/v1/messages`, the forwarded
`anthropic-beta` set (split on commas, lower-cased, sorted, de-duplicated)
is also hashed in when present; with `stripClientAnthropicBeta: true` the
header is ignored. Entries are shared across users and groups. `requestedModel` and the endpoint
are both part of the key so that two different alias forms of the same
upstream model (`claude-x` versus `anthropic/claude-x`) never collide
into one cache entry: a translating adapter (`anthropic`, `gemini`)
@@ -2409,8 +2428,12 @@ providers:
timed-out `modelBaseUrls` upstream does not
degrade the provider: its explicit `models` stay served, the other upstreams'
ids still merge, and the admin overview lists it under `upstreamErrors` (also
logged, at most once per 10 minutes). Metadata keeps the ids of the upstreams
that answered. `modelBaseUrls` ids stay declared models.
logged, at most once per 10 minutes). Metadata of an upstream that
failed keeps its last known values, and the failure is listed under
`upstreamErrors`. `modelBaseUrls` ids stay declared models.
A provider keeps at most 10000 discovered ids, each at most 256 bytes. The gateway
drops empty ids, ids with control characters, longer ids and the overflow, and logs
the count at most once per 10 minutes.
- **Admin catalog**: each `pathBaseUrls` key appears as a pseudo-model row
(`gx10/v1/decide`). It is display only and never routable as a model.
`kinds` labels a model id or a path key. The Models page then groups the
@@ -3526,7 +3549,7 @@ plugin's config.
a temporary gap in the series is the honest signal; a fabricated `0`
would read to Prometheus as a counter reset followed by a phantom spike
the instant the store recovers. This holds regardless of
`redis.failOpen`: with `failOpen: false` (or unset) the request itself
`redis.failOpen`: with `failOpen: false` the request itself
is refused during the outage, and with `failOpen: true` (the default)
requests keep flowing against the in-process fallback, but `/metrics`
still treats the affected scopes as unreadable rather than presenting
@@ -3550,7 +3573,9 @@ plugin's config.
its own query string (the only way `TargetConfig`/`AgentConfig` can pass
a credential today, since neither has a header field) keeps it — the
incoming request's own query string is merged in alongside it, neither
one overwriting the other.
one overwriting the other. A target that carries a query string and
answers with a 3xx `Location` gets a 502 instead, so the configured query
cannot reach the client through a redirect.
- Request-rate limits (`requestsPerMinute`/`requestsPerDay`) apply to
target-proxy calls the same as everywhere else; token/cost metrics do
not, since there is no usage to parse from an arbitrary MCP/A2A
+9 -5
View File
@@ -299,20 +299,24 @@ const unparseableBaseURLPlaceholder = "[unparseable url]"
//
// Still best-effort for URLs OTHER than rawBaseURL: an error naming a
// redirect target is not caught. Rejecting a credential-bearing baseUrl
// at construction (providers.go) is the only complete fix; this is the
// containment that changes no behavior.
// at construction (providers.go) would be the complete fix; instead the
// constructor only warns, so a config that loads today keeps loading.
func sanitizeProviderErr(lastErr, rawBaseURL string) string {
if lastErr == "" || rawBaseURL == "" {
return lastErr
}
out := replaceURLForm(lastErr, rawBaseURL)
u, parseErr := url.Parse(rawBaseURL)
if parseErr != nil || u.User == nil {
if parseErr != nil {
return out
}
// net/http reports url.URL.String(), which lower-cases the scheme and
// re-escapes userinfo, so it can differ from the configured text.
out = replaceURLForm(out, u.String())
if u.User == nil {
return out
}
if _, hasPassword := u.User.Password(); !hasPassword {
// No password set means net/http passed the URL through
// unmasked, so the verbatim pass above already matched it.
return out
}
// net/http's exact stripPassword output, mirrored call for call.
+46 -46
View File
File diff suppressed because one or more lines are too long
+103
View File
@@ -0,0 +1,103 @@
package traefikllmgateway
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func anonSnapshotGateway(t *testing.T, anonGroup string) (http.Handler, *Gateway) {
t.Helper()
return memberLimitsGateway(t,
map[string]*GroupConfig{"friends": {}, "public": {}},
[]*UserConfig{{Name: "a", Group: "friends", APIKey: "sk-a", Admin: true}},
func(c *Config) {
c.Users.AnonymousGroup = anonGroup
c.Metrics = &MetricsConfig{Enabled: true}
},
)
}
func TestSnapshot_IncludesAnonymousPrincipal(t *testing.T) {
a, err := newAuthStore(anonAuthCfg())
require.NoError(t, err)
users, groups := a.snapshot()
var anon []userSummary
for _, u := range users {
if u.name == anonymousUserName {
anon = append(anon, u)
}
}
require.Len(t, anon, 1)
assert.Equal(t, "anonymous", anon[0].source)
assert.False(t, anon[0].admin)
assert.Equal(t, "public", anon[0].groupName)
assert.Equal(t, []string{"public"}, anon[0].groups)
for _, g := range groups {
if g.name == "public" {
assert.Equal(t, 1, g.memberCount)
}
}
}
func TestSnapshot_NoAnonymousWhenUnset(t *testing.T) {
cfg := anonAuthCfg()
cfg.Users.AnonymousGroup = ""
a, err := newAuthStore(cfg)
require.NoError(t, err)
users, _ := a.snapshot()
for _, u := range users {
assert.NotEqual(t, anonymousUserName, u.name)
}
}
func TestAdminUsage_ListsAnonymousUser(t *testing.T) {
h, gw := anonSnapshotGateway(t, "public")
rec := memberLimitsChat(t, h, "")
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
e := findUsageEntry(t, gw.buildAdminUsage().Users, anonymousUserName)
assert.NotZero(t, e.RequestsPerDay)
}
func TestScopeExists_AnonymousUser(t *testing.T) {
h, _ := anonSnapshotGateway(t, "public")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, adminRequest(http.MethodGet, adminUsageHistoryPath+"?scope=user:anonymous&metric=req&window=hour", "sk-a"))
assert.NotEqual(t, http.StatusNotFound, rec.Code, rec.Body.String())
}
func TestPruneRejectionsAfterReload_KeepsAnonymous(t *testing.T) {
_, gw := anonSnapshotGateway(t, "public")
gw.limiter.rejections.increment("user", anonymousUserName)
gw.pruneRejectionsAfterReload()
var kept bool
for _, s := range gw.limiter.rejections.snapshot() {
if s.kind == "user" && s.id == anonymousUserName {
kept = true
}
}
assert.True(t, kept, "anonymous rejection counter must survive a users-file reload")
}
func TestUsageMetrics_ExportAnonymousUser(t *testing.T) {
h, _ := anonSnapshotGateway(t, "public")
require.Equal(t, http.StatusOK, memberLimitsChat(t, h, "").Code)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, metricsRequest(http.MethodGet, metricsPathDefault, "sk-a"))
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
_, samples := parsePrometheusText(t, rec.Body.Bytes())
var found bool
for _, s := range samples {
if s.name == "llmgateway_requests_total" && s.labels["scope_kind"] == "user" && s.labels["scope_id"] == anonymousUserName {
found = true
}
}
assert.True(t, found)
}
+13
View File
@@ -1462,6 +1462,19 @@ func (a *authStore) snapshot() ([]userSummary, []groupSummary) {
memberCounts[name]++
}
}
if anon := a.anonymous; anon != nil {
users = append(users, userSummary{
limits: anon.user.limits,
limitSources: anon.user.limitSources,
name: anon.user.name,
groupName: anon.user.groupName,
groups: cloneStringSlice(anon.user.groupNames),
source: "anonymous",
})
for _, name := range anon.user.groupNames {
memberCounts[name]++
}
}
a.mu.RUnlock()
sort.Slice(users, func(i, j int) bool { return users[i].name < users[j].name })
+37
View File
@@ -5,6 +5,8 @@ import (
"encoding/hex"
"encoding/json"
"fmt"
"sort"
"strings"
"sync"
"time"
)
@@ -455,3 +457,38 @@ func cacheKey(provider, upstreamModel, requestedModel, endpoint string, req map[
_, _ = h.Write(canonical)
return cacheKeyPrefix + hex.EncodeToString(h.Sum(nil))
}
// normalizeBetaSet canonicalises anthropic-beta header values into one
// sorted, de-duplicated, lower-case comma list; "" when no value is set.
func normalizeBetaSet(values []string) string {
var parts []string
for _, v := range values {
for _, f := range strings.Split(v, ",") {
f = strings.ToLower(strings.TrimSpace(f))
if f != "" {
parts = append(parts, f)
}
}
}
if len(parts) == 0 {
return ""
}
sort.Strings(parts)
out := parts[:1]
for _, f := range parts[1:] {
if f != out[len(out)-1] {
out = append(out, f)
}
}
return strings.Join(out, ",")
}
// cacheKeyWithVary folds a forwarded-header set into a cacheKey result so
// requests that differ in it never share an entry.
func cacheKeyWithVary(key, vary string) string {
h := sha256.New()
_, _ = h.Write([]byte(key))
_, _ = h.Write([]byte{0})
_, _ = h.Write([]byte(vary))
return cacheKeyPrefix + hex.EncodeToString(h.Sum(nil))
}
+122
View File
@@ -0,0 +1,122 @@
package traefikllmgateway
import (
"context"
"net/http"
"net/http/httptest"
"sync"
"testing"
)
const betaCacheResp = `{"id":"msg_1","type":"message","role":"assistant","content":[{"type":"text","text":"hi"}],"model":"claude-real","stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`
type betaCacheFixture struct {
gw *Gateway
betas []string
mu sync.Mutex
}
func newBetaCacheFixture(t *testing.T, strip bool) *betaCacheFixture {
t.Helper()
f := &betaCacheFixture{}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
f.betas = append(f.betas, r.Header.Get("anthropic-beta"))
f.mu.Unlock()
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(betaCacheResp))
}))
t.Cleanup(srv.Close)
redisLn := newBehavioralRedisServer(t)
cfg := CreateConfig()
cfg.Providers = map[string]*ProviderConfig{
"anthropic": {Type: providerTypeAnthropic, BaseURL: srv.URL, APIKey: "k", Models: []string{"claude-test"}},
}
cfg.Groups = map[string]*GroupConfig{"default": {}}
cfg.Users = &UsersConfig{Inline: []*UserConfig{{Name: "alice", Group: "default", APIKey: "sk-alice", Limits: &LimitsConfig{}}}}
cfg.Redis = &RedisConfig{Address: redisLn.Addr().String()}
cfg.Cache = CacheConfig{Enabled: true, TTL: "1m"}
cfg.StripClientAnthropicBeta = strip
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")
}
f.gw = gw
return f
}
// send posts the fixed messages body with the given beta header values and returns X-Llmgw-Cache.
func (f *betaCacheFixture) send(t *testing.T, betas ...string) string {
t.Helper()
body := map[string]any{"model": "claude-test", "max_tokens": 10, "messages": []any{map[string]any{"role": "user", "content": "hello"}}}
req := newMessagesRequest(t, body, "x-api-key", "sk-alice")
for _, b := range betas {
req.Header.Add("anthropic-beta", b)
}
rec := httptest.NewRecorder()
f.gw.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, body=%s", rec.Code, rec.Body.String())
}
return rec.Header().Get("X-Llmgw-Cache")
}
func (f *betaCacheFixture) upstreamCalls() int {
f.mu.Lock()
defer f.mu.Unlock()
return len(f.betas)
}
func TestMessagesCache_BetaHeaderDoesNotServeHeaderlessCaller(t *testing.T) {
f := newBetaCacheFixture(t, false)
f.send(t, "context-1m")
if got := f.send(t); got == "hit" {
t.Fatal("a caller without anthropic-beta was served the entry cached for a beta caller")
}
if f.upstreamCalls() != 2 || f.betas[1] != "" {
t.Fatalf("upstream betas = %q, want the headerless request to reach upstream with no beta", f.betas)
}
}
func TestMessagesCache_DifferentBetaValuesDoNotShare(t *testing.T) {
f := newBetaCacheFixture(t, false)
f.send(t, "a")
if got := f.send(t, "b"); got == "hit" {
t.Fatal("different beta sets shared a cache entry")
}
}
func TestMessagesCache_SameBetaSetSharesRegardlessOfOrder(t *testing.T) {
f := newBetaCacheFixture(t, false)
f.send(t, "a,b")
if got := f.send(t, "b, A"); got != "hit" {
t.Fatalf("X-Llmgw-Cache = %q, want hit for the same beta set in another order", got)
}
}
func TestMessagesCache_HeaderlessKeyUnchanged(t *testing.T) {
if got := normalizeBetaSet(nil); got != "" {
t.Fatalf("normalizeBetaSet(nil) = %q, want empty so the key stays cacheKey(...)", got)
}
if got := normalizeBetaSet([]string{" , "}); got != "" {
t.Fatalf("normalizeBetaSet(blank) = %q, want empty", got)
}
f := newBetaCacheFixture(t, false)
f.send(t)
if got := f.send(t); got != "hit" {
t.Fatalf("X-Llmgw-Cache = %q, want hit for repeated headerless requests", got)
}
}
func TestMessagesCache_StripClientBetaIgnoresHeader(t *testing.T) {
f := newBetaCacheFixture(t, true)
f.send(t, "context-1m")
if got := f.send(t); got != "hit" {
t.Fatalf("X-Llmgw-Cache = %q, want hit: with stripClientAnthropicBeta the header is not forwarded", got)
}
}
+94
View File
@@ -0,0 +1,94 @@
package traefikllmgateway
import (
"fmt"
"strings"
"sync"
"testing"
"time"
)
func newBoundsRegistry(t *testing.T, logf func(string, ...any)) (*modelRegistry, *providerState) {
t.Helper()
adapters := map[string]providerAdapter{"openai": newFakeAdapter("openai")}
cfg := &Config{Providers: map[string]*ProviderConfig{"openai": {Models: []string{"gpt-test"}}}}
reg, err := newModelRegistry(adapters, cfg, logf)
if err != nil {
t.Fatalf("newModelRegistry: %v", err)
}
return reg, reg.states["openai"]
}
func manyIDs(n int) []string {
ids := make([]string, n)
for i := range ids {
ids[i] = fmt.Sprintf("m-%d", i)
}
return ids
}
func discoveredCount(reg *modelRegistry, st *providerState) int {
st.mu.Lock()
defer st.mu.Unlock()
return len(st.discovered)
}
func TestDiscovery_DropsOverLengthAndInvalidIDs(t *testing.T) {
reg, st := newBoundsRegistry(t, func(string, ...any) {})
reg.finishRefresh(st, reg.now(), []string{strings.Repeat("a", 300), "", "bad\nid", "good-1", "good-2"}, nil)
if got := discoveredCount(reg, st); got != 2 {
t.Fatalf("discovered = %d, want 2", got)
}
if !st.discovered["good-1"] || !st.discovered["good-2"] {
t.Errorf("discovered = %v, want good-1 and good-2", st.discovered)
}
}
func TestDiscovery_AtCapAccepted(t *testing.T) {
reg, st := newBoundsRegistry(t, func(string, ...any) {})
reg.finishRefresh(st, reg.now(), manyIDs(maxDiscoveredModels), nil)
if got := discoveredCount(reg, st); got != maxDiscoveredModels {
t.Errorf("discovered = %d, want %d", got, maxDiscoveredModels)
}
}
func TestDiscovery_OverCountKeepsCapAndLogsDebounced(t *testing.T) {
var mu sync.Mutex
var lines []string
reg, st := newBoundsRegistry(t, func(f string, a ...any) {
mu.Lock()
lines = append(lines, fmt.Sprintf(f, a...))
mu.Unlock()
})
now := time.Now()
reg.finishRefresh(st, now, manyIDs(maxDiscoveredModels+5), nil)
reg.finishRefresh(st, now.Add(time.Second), manyIDs(maxDiscoveredModels+5), nil)
if got := discoveredCount(reg, st); got != maxDiscoveredModels {
t.Errorf("discovered = %d, want %d", got, maxDiscoveredModels)
}
st.mu.Lock()
over := st.discovered["m-"+fmt.Sprint(maxDiscoveredModels)]
st.mu.Unlock()
if over {
t.Error("an id past the cap was kept")
}
var n int
for _, l := range lines {
if strings.Contains(l, "dropped 5 model ids") {
n++
}
}
if n != 1 {
t.Errorf("drop log lines = %d, want 1 (debounced): %v", n, lines)
}
reg.finishRefresh(st, now.Add(upstreamErrLogEvery+time.Second), manyIDs(maxDiscoveredModels+5), nil)
n = 0
for _, l := range lines {
if strings.Contains(l, "dropped 5 model ids") {
n++
}
}
if n != 2 {
t.Errorf("drop log lines after the window = %d, want 2", n)
}
}
+10 -3
View File
@@ -446,9 +446,16 @@ func (g *Gateway) recordUpstreamEvent(scopes []limitScope, model, provider, rout
// apart in the feed (402 here, unset/0 there — a billed-0 event carries
// no HTTP status of its own, since nothing was refused).
func (g *Gateway) recordUnpricedRefusalEvent(scopes []limitScope, model, provider, route string) {
g.recordUnpricedRefusal(scopes, model, model, provider, route)
}
// recordUnpricedRefusal is recordUnpricedRefusalEvent with the counter key
// and the displayed model split: counterModel names the per-model counter
// ("" for the total scope only), shownModel goes into the event.
func (g *Gateway) recordUnpricedRefusal(scopes []limitScope, counterModel, shownModel, provider, route string) {
ev := gatewayEvent{
Model: model, Provider: provider, Route: route, Kind: eventKindUnpriced, Status: http.StatusPaymentRequired,
Message: fmt.Sprintf("model %q refused: no configured price, so the cost budget that applies to this caller cannot be enforced", model),
Model: shownModel, Provider: provider, Route: route, Kind: eventKindUnpriced, Status: http.StatusPaymentRequired,
Message: fmt.Sprintf("model %q refused: no configured price, so the cost budget that applies to this caller cannot be enforced", shownModel),
}
applyScopeAttribution(&ev, scopes)
g.recordEvent(ev)
@@ -458,7 +465,7 @@ func (g *Gateway) recordUnpricedRefusalEvent(scopes []limitScope, model, provide
// without touching either route file again. Fire-and-forget
// (recordUnpriced402's own countAsync/l.spawn); no-op when admin
// stats are off.
g.limiter.recordUnpriced402(model)
g.limiter.recordUnpriced402(counterModel)
}
// recordProxyEvent records an upstream event for a proxyUpstream result
+6 -1
View File
@@ -1273,8 +1273,13 @@ func newGateway(ctx context.Context, next http.Handler, config *Config, name str
// would otherwise reopen the same leak through g.configWarnings /
// GET /admin/api/overview's own Warnings field instead of through
// baseUrl directly.
if _, parseErr := url.Parse(pc.BaseURL); parseErr != nil {
bu, parseErr := url.Parse(pc.BaseURL)
if parseErr != nil {
g.warnf("config: provider %q baseUrl does not parse as a URL; the admin dashboard will show it redacted as %q", name, unparseableBaseURLPlaceholder)
continue
}
if bu.User != nil || bu.RawQuery != "" || bu.Fragment != "" {
g.warnf("config: provider %q baseUrl carries userinfo, a query or a fragment; error text scrubbing is best-effort, so keep credentials in apiKey instead", name)
}
}
+22 -5
View File
@@ -294,11 +294,9 @@ func mergeQueryStrings(targetQuery, requestQuery string) string {
}
merged, err := url.ParseQuery(targetQuery)
if err != nil {
// targetQuery came from an already-parsed url.URL's own RawQuery,
// so this is unreachable in practice — falls back to the
// request's own query alone rather than panicking or silently
// dropping both.
return requestQuery
// url.Parse accepts a query that ParseQuery rejects (a bare
// semicolon); the configured credential still has to go upstream.
return targetQuery + "&" + requestQuery
}
reqValues, err := url.ParseQuery(requestQuery)
if err != nil {
@@ -371,3 +369,22 @@ func validateTargetURL(raw string) error {
}
return nil
}
// queryAddedByGateway reports whether upstreamURL's query holds a pair that
// the client's own query lacks, which means the gateway added it from config.
func queryAddedByGateway(upstreamURL, clientRawQuery string) bool {
i := strings.Index(upstreamURL, "?")
if i < 0 || i == len(upstreamURL)-1 {
return false
}
have := make(map[string]bool)
for _, p := range strings.Split(clientRawQuery, "&") {
have[p] = true
}
for _, p := range strings.Split(upstreamURL[i+1:], "&") {
if p != "" && !have[p] {
return true
}
}
return false
}
+116 -25
View File
@@ -45,8 +45,18 @@ type openAIStreamChunk struct {
}
type streamToolBlock struct {
id string
block int
queued *queuedBlock
id string
block int
}
// queuedBlock is a block that arrived while a tool_use block was open. It is
// emitted at stream end so every delta targets the one open block.
type queuedBlock struct {
typ string
id string
name string
buf strings.Builder
}
// anthropicStreamWriter is the http.ResponseWriter handed to a provider
@@ -61,7 +71,10 @@ type anthropicStreamWriter struct {
sse *sseWriter
model string
finishR string
queue []*queuedBlock
raw bytes.Buffer
queueCap int
queued int
mode int
next int
openIdx int
@@ -69,10 +82,11 @@ type anthropicStreamWriter struct {
done bool
hasOpen bool
textOpen bool
toolOpen bool
}
func newAnthropicStreamWriter(rw http.ResponseWriter, model string) *anthropicStreamWriter {
return &anthropicStreamWriter{rw: rw, model: model, tools: map[int]*streamToolBlock{}}
return &anthropicStreamWriter{rw: rw, model: model, tools: map[int]*streamToolBlock{}, queueCap: maxResponseBytes}
}
// Header implements http.ResponseWriter.
@@ -185,6 +199,7 @@ func (s *anthropicStreamWriter) closeBlock() error {
}
s.hasOpen = false
s.textOpen = false
s.toolOpen = false
return s.emit("content_block_stop", map[string]any{"type": "content_block_stop", "index": s.openIdx})
}
@@ -213,31 +228,14 @@ func (s *anthropicStreamWriter) handleChunk(data []byte) error {
ch := c.Choices[0]
if ch.Delta.Content != "" {
if !s.textOpen {
if err := s.openBlock(map[string]any{"type": "text", "text": ""}); err != nil {
return err
}
s.textOpen = true
}
if err := s.delta(s.openIdx, map[string]any{"type": "text_delta", "text": ch.Delta.Content}); err != nil {
if err := s.handleText(ch.Delta.Content); err != nil {
return err
}
}
for _, tc := range ch.Delta.ToolCalls {
tb, known := s.tools[tc.Index]
if !known || (tc.ID != "" && tb.id != "" && tc.ID != tb.id) {
err := s.openBlock(map[string]any{"type": "tool_use", "id": tc.ID, "name": tc.Function.Name, "input": map[string]any{}})
if err != nil {
return err
}
tb = &streamToolBlock{block: s.openIdx, id: tc.ID}
s.tools[tc.Index] = tb
}
if tc.Function.Arguments != "" {
if err := s.delta(tb.block, map[string]any{"type": "input_json_delta", "partial_json": tc.Function.Arguments}); err != nil {
return err
}
if err := s.handleToolCall(tc.Index, tc.ID, tc.Function.Name, tc.Function.Arguments); err != nil {
return err
}
}
@@ -247,6 +245,96 @@ func (s *anthropicStreamWriter) handleChunk(data []byte) error {
return nil
}
func (s *anthropicStreamWriter) handleText(text string) error {
if s.toolOpen {
tail := len(s.queue) - 1
if tail < 0 || s.queue[tail].typ != "text" {
s.queue = append(s.queue, &queuedBlock{typ: "text"})
tail++
}
return s.appendQueued(s.queue[tail], text)
}
if !s.textOpen {
if err := s.openBlock(map[string]any{"type": "text", "text": ""}); err != nil {
return err
}
s.textOpen = true
}
return s.delta(s.openIdx, map[string]any{"type": "text_delta", "text": text})
}
func (s *anthropicStreamWriter) handleToolCall(index int, id, name, args string) error {
tb, known := s.tools[index]
if !known || (id != "" && tb.id != "" && id != tb.id) {
tb = &streamToolBlock{id: id}
if s.toolOpen {
q := &queuedBlock{typ: "tool_use", id: id, name: name}
if err := s.reserveQueue(len(id) + len(name)); err != nil {
return err
}
s.queue = append(s.queue, q)
tb.queued = q
} else {
err := s.openBlock(map[string]any{"type": "tool_use", "id": id, "name": name, "input": map[string]any{}})
if err != nil {
return err
}
s.toolOpen = true
tb.block = s.openIdx
}
s.tools[index] = tb
}
if args == "" {
return nil
}
if tb.queued != nil {
return s.appendQueued(tb.queued, args)
}
return s.delta(tb.block, map[string]any{"type": "input_json_delta", "partial_json": args})
}
func (s *anthropicStreamWriter) reserveQueue(n int) error {
s.queued += n
if s.queued > s.queueCap {
return fmt.Errorf("%w: queued content blocks exceed %d bytes", errUpstream, s.queueCap)
}
return nil
}
func (s *anthropicStreamWriter) appendQueued(q *queuedBlock, text string) error {
if err := s.reserveQueue(len(text)); err != nil {
return err
}
q.buf.WriteString(text)
return nil
}
// flushQueue emits the blocks held back behind a tool_use block, in arrival order.
func (s *anthropicStreamWriter) flushQueue() error {
queue := s.queue
s.queue = nil
for _, q := range queue {
block := map[string]any{"type": "text", "text": ""}
deltaType, field := "text_delta", "text"
if q.typ == "tool_use" {
block = map[string]any{"type": "tool_use", "id": q.id, "name": q.name, "input": map[string]any{}}
deltaType, field = "input_json_delta", "partial_json"
}
if err := s.openBlock(block); err != nil {
return err
}
if q.buf.Len() > 0 {
if err := s.delta(s.openIdx, map[string]any{"type": deltaType, field: q.buf.String()}); err != nil {
return err
}
}
if err := s.closeBlock(); err != nil {
return err
}
}
return nil
}
// finish closes the open block and writes message_delta and message_stop.
// u is the adapter's final usage. On a JSON-mode upstream it replays the
// buffered response as events. Idempotent.
@@ -269,6 +357,9 @@ func (s *anthropicStreamWriter) stop(stopReason string, input, output int64) err
if err := s.closeBlock(); err != nil {
return err
}
if err := s.flushQueue(); err != nil {
return err
}
err := s.emit("message_delta", map[string]any{
"type": "message_delta",
"delta": map[string]any{"stop_reason": stopReason, "stop_sequence": nil},
@@ -400,9 +491,9 @@ func relayAnthropicMessagesStream(w http.ResponseWriter, body io.Reader, model s
return st.usage(), nil
}
if relayed {
return st.usage(), fmt.Errorf("%w: %w", errStreamErrorRelayed, err)
return st.usageOnAbort(), fmt.Errorf("%w: %w", errStreamErrorRelayed, err)
}
return st.usage(), fmt.Errorf("%w: stream: %w", errUpstream, err)
return st.usageOnAbort(), fmt.Errorf("%w: stream: %w", errUpstream, err)
}
// writeEvent writes one frame with an "event:" line ahead of the data, the
+147
View File
@@ -0,0 +1,147 @@
package traefikllmgateway
import (
"errors"
"fmt"
"net/http/httptest"
"strings"
"testing"
)
// assertAnthropicBlockSequence checks start/delta/stop nesting: a delta must
// target the one open block, blocks never overlap, indexes run 0..n-1.
// It returns the joined delta payload per block index.
func assertAnthropicBlockSequence(t *testing.T, events []anthEvent) map[int]string {
t.Helper()
joined := map[int]string{}
open := -1
next := 0
for i, e := range events {
idx, _ := e.data["index"].(float64)
switch e.name {
case "content_block_start":
if open != -1 {
t.Fatalf("event %d: start %d while block %d open", i, int(idx), open)
}
if int(idx) != next {
t.Fatalf("event %d: start index %d, want %d", i, int(idx), next)
}
open = int(idx)
next++
case "content_block_delta":
if int(idx) != open {
t.Fatalf("event %d: delta for block %d while open block is %d", i, int(idx), open)
}
d := sub(e.data, "delta")
for _, k := range []string{"partial_json", "text"} {
if v, ok := d[k].(string); ok {
joined[open] += v
}
}
case "content_block_stop":
if int(idx) != open {
t.Fatalf("event %d: stop %d while open block is %d", i, int(idx), open)
}
open = -1
case "message_delta":
if open != -1 {
t.Fatalf("event %d: message_delta with block %d open", i, open)
}
}
}
return joined
}
func toolFrame(index int, id, name, args string) string {
return fmt.Sprintf(`{"id":"c1","choices":[{"delta":{"tool_calls":[{"index":%d,"id":%q,"function":{"name":%q,"arguments":%q}}]}}]}`, index, id, name, args)
}
func textFrame(text string) string {
return fmt.Sprintf(`{"id":"c1","choices":[{"delta":{"content":%q}}]}`, text)
}
func blockStarts(evs []anthEvent) []map[string]any {
var out []map[string]any
for _, e := range evs {
if e.name == "content_block_start" {
out = append(out, sub(e.data, "content_block"))
}
}
return out
}
func TestAnthropicStreamWriter_InterleavedToolArgumentsStayOnOpenBlock(t *testing.T) {
_, evs := runStreamWriter(t, usage{},
toolFrame(0, "call_a", "alpha", ""),
toolFrame(1, "call_b", "beta", ""),
toolFrame(0, "", "", `{"a":`),
toolFrame(1, "", "", `{"b":2}`),
toolFrame(0, "", "", `1}`),
)
joined := assertAnthropicBlockSequence(t, evs)
starts := blockStarts(evs)
if len(starts) != 2 || starts[0]["name"] != "alpha" || starts[1]["name"] != "beta" {
t.Fatalf("starts = %v", starts)
}
if joined[0] != `{"a":1}` || joined[1] != `{"b":2}` {
t.Fatalf("joined = %v", joined)
}
}
func TestAnthropicStreamWriter_TextAfterToolCallThenMoreArguments(t *testing.T) {
_, evs := runStreamWriter(t, usage{},
toolFrame(0, "call_a", "alpha", `{"a":`),
textFrame("hello "),
textFrame("world"),
toolFrame(0, "", "", `1}`),
)
joined := assertAnthropicBlockSequence(t, evs)
starts := blockStarts(evs)
if len(starts) != 2 || starts[0]["type"] != "tool_use" || starts[1]["type"] != "text" {
t.Fatalf("starts = %v", starts)
}
if joined[0] != `{"a":1}` || joined[1] != "hello world" {
t.Fatalf("joined = %v", joined)
}
}
func TestAnthropicStreamWriter_SequentialToolCallsKeepAllArguments(t *testing.T) {
_, evs := runStreamWriter(t, usage{},
toolFrame(0, "call_a", "alpha", `{"a":1}`),
toolFrame(1, "call_b", "beta", `{"b":2}`),
)
joined := assertAnthropicBlockSequence(t, evs)
starts := blockStarts(evs)
if len(starts) != 2 || starts[0]["name"] != "alpha" || starts[1]["name"] != "beta" {
t.Fatalf("starts = %v", starts)
}
if joined[0] != `{"a":1}` || joined[1] != `{"b":2}` {
t.Fatalf("joined = %v", joined)
}
}
func TestAnthropicStreamWriter_SingleToolCallStreamsLive(t *testing.T) {
rec := httptest.NewRecorder()
sw := newAnthropicStreamWriter(rec, "my-alias")
for _, f := range []string{toolFrame(0, "call_a", "alpha", ""), toolFrame(0, "", "", `{"a":1}`)} {
if _, err := sw.Write(oaiFrame(f)); err != nil {
t.Fatal(err)
}
}
if !strings.Contains(rec.Body.String(), `partial_json`) {
t.Fatalf("no delta written before finish: %s", rec.Body.String())
}
}
func TestAnthropicStreamWriter_QueuedBlocksOverCapFail(t *testing.T) {
rec := httptest.NewRecorder()
sw := newAnthropicStreamWriter(rec, "my-alias")
sw.queueCap = 8
if _, err := sw.Write(oaiFrame(toolFrame(0, "call_a", "alpha", ""))); err != nil {
t.Fatal(err)
}
_, err := sw.Write(oaiFrame(textFrame("this text is longer than the cap")))
if !errors.Is(err, errUpstream) {
t.Fatalf("err = %v, want errUpstream", err)
}
}
+163
View File
@@ -0,0 +1,163 @@
package traefikllmgateway
import (
"bufio"
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
const sseTestChunk = "data: {\"id\":\"c1\",\"model\":\"gpt-5\",\"choices\":[{\"delta\":{\"content\":\"x\"}}]}\n\n"
func newSSEEstimateGateway(t *testing.T, upstream http.HandlerFunc) *Gateway {
t.Helper()
srv := httptest.NewServer(upstream)
t.Cleanup(srv.Close)
cfg := CreateConfig()
cfg.Providers = map[string]*ProviderConfig{"openai": {Type: "openai", BaseURL: srv.URL, APIKey: "sk-up"}}
cfg.Groups = map[string]*GroupConfig{"default": {}}
cfg.Users = &UsersConfig{Inline: []*UserConfig{{Name: "alice", Group: "default", APIKey: "sk-alice", Limits: &LimitsConfig{}}}}
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")
}
gw.limiter.spawn = func(f func()) { f() }
return gw
}
func postSSE(gw *Gateway) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, "/openai/v1/native-endpoint", strings.NewReader(`{"model":"gpt-5","stream":true,"messages":[]}`))
req.Header.Set("Authorization", "Bearer sk-alice")
rec := httptest.NewRecorder()
gw.ServeHTTP(rec, req)
return rec
}
func tokOutOf(gw *Gateway) int64 {
v, _ := gw.limiter.getCounter("user", "alice", metricTokOut, windowDay, time.Now())
return v
}
func TestPassthroughSSE_NoUsageChunkBillsEstimatedCompletion(t *testing.T) {
gw := newSSEEstimateGateway(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
for i := 0; i < 30; i++ {
_, _ = io.WriteString(w, sseTestChunk)
}
})
if rec := postSSE(gw); rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", rec.Code)
}
got := tokOutOf(gw)
if got < 30 || got > 31 {
t.Errorf("tokout = %d, want 30..31 (one per data event)", got)
}
if cost, _ := gw.limiter.getCounter("user", "alice", metricCost, windowDay, time.Now()); cost <= 0 {
t.Errorf("cost = %d, want > 0", cost)
}
}
func TestPassthroughSSE_ReportedUsageWins(t *testing.T) {
gw := newSSEEstimateGateway(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
for i := 0; i < 30; i++ {
_, _ = io.WriteString(w, sseTestChunk)
}
_, _ = io.WriteString(w, "data: {\"id\":\"c1\",\"choices\":[],\"usage\":{\"prompt_tokens\":42,\"completion_tokens\":9}}\n\ndata: [DONE]\n\n")
})
postSSE(gw)
if got := tokOutOf(gw); got != 9 {
t.Errorf("tokout = %d, want 9 (reported)", got)
}
if got, _ := gw.limiter.getCounter("user", "alice", metricTokIn, windowDay, time.Now()); got != 42 {
t.Errorf("tokin = %d, want 42 (reported)", got)
}
}
func TestPassthroughSSE_HangupBeforeUsageBillsEstimate(t *testing.T) {
gw := newSSEEstimateGateway(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
for i := 0; i < 5; i++ {
_, _ = io.WriteString(w, sseTestChunk)
w.(http.Flusher).Flush()
}
<-r.Context().Done()
})
front := httptest.NewServer(gw)
defer front.Close()
req, _ := http.NewRequest(http.MethodPost, front.URL+"/openai/v1/native-endpoint", strings.NewReader(`{"model":"gpt-5","stream":true,"messages":[]}`))
req.Header.Set("Authorization", "Bearer sk-alice")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
rd := bufio.NewReader(resp.Body)
for i := 0; i < 5; i++ {
for {
line, rerr := rd.ReadString('\n')
if rerr != nil {
t.Fatalf("read: %v", rerr)
}
if line == "\n" {
break
}
}
}
_ = resp.Body.Close()
deadline := time.Now().Add(3 * time.Second)
for tokOutOf(gw) == 0 && time.Now().Before(deadline) {
time.Sleep(10 * time.Millisecond)
}
if got := tokOutOf(gw); got < 1 || got > 6 {
t.Errorf("tokout = %d, want 1..6 after a client hang-up", got)
}
}
func TestPassthroughJSON_NoUsageStaysNoOp(t *testing.T) {
gw := newSSEEstimateGateway(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"id":"file-1","object":"file"}`)
})
if rec := postSSE(gw); rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", rec.Code)
}
if got := tokOutOf(gw); got != 0 {
t.Errorf("tokout = %d, want 0", got)
}
if got, _ := gw.limiter.getCounter("user", "alice", metricTokIn, windowDay, time.Now()); got != 0 {
t.Errorf("tokin = %d, want 0", got)
}
}
func TestSSEAccountingBuffer_CountsDataEvents(t *testing.T) {
var b sseAccountingBuffer
_, _ = b.Write([]byte(sseTestChunk + sseTestChunk))
_, _ = b.Write([]byte(": keepalive\n\n"))
_, _ = b.Write([]byte("data: [DONE]\n\n"))
if b.events != 3 {
t.Errorf("events = %d, want 3", b.events)
}
}
func TestPassthroughSSE_ReportedPromptWithoutCompletionKeptWithoutRequestBody(t *testing.T) {
gw := newSSEEstimateGateway(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = io.WriteString(w, "data: {\"model\":\"gpt-5\",\"choices\":[],\"usage\":{\"prompt_tokens\":7,\"completion_tokens\":0}}\n\n")
})
req := httptest.NewRequest(http.MethodPost, "/openai/v1/native-endpoint", nil)
req.Header.Set("Authorization", "Bearer sk-alice")
gw.ServeHTTP(httptest.NewRecorder(), req)
if got, _ := gw.limiter.getCounter("user", "alice", metricTokIn, windowDay, time.Now()); got != 7 {
t.Errorf("tokin = %d, want 7 (reported prompt usage must not be dropped)", got)
}
}
+316
View File
@@ -0,0 +1,316 @@
package traefikllmgateway
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
)
const gateUpstreamReply = `{"model":"gpt-5","usage":{"prompt_tokens":10,"completion_tokens":5,"total_tokens":15}}`
// gateEnv is a gateway with a cost-budgeted user "alice" in front of an
// upstream that records how many requests reached it and how many body
// bytes it received.
type gateEnv struct {
gw *Gateway
h http.Handler
calls *int32
lastBody *atomic.Value
}
func newGateEnv(t *testing.T, mutate func(*Config)) *gateEnv {
t.Helper()
var calls int32
var lastBody atomic.Value
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
atomic.AddInt32(&calls, 1)
b, _ := io.ReadAll(r.Body)
lastBody.Store(string(b))
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, gateUpstreamReply)
}))
t.Cleanup(srv.Close)
cfg := CreateConfig()
cfg.Admin = &AdminConfig{Enabled: true}
cfg.Providers = map[string]*ProviderConfig{
"openai": {Type: "openai", BaseURL: srv.URL, APIKey: "sk-up", Models: []string{"cat-unpriced"}},
}
cfg.Groups = map[string]*GroupConfig{"default": {}, "public": {Limits: &LimitsConfig{CostPerDayUSD: 5}}}
cfg.Users = &UsersConfig{
AnonymousGroup: "public",
Inline: []*UserConfig{
{Name: "alice", Group: "default", APIKey: "sk-alice", Limits: &LimitsConfig{CostPerDayUSD: 5}},
{Name: "admin1", Group: "default", APIKey: "sk-admin1", Admin: true},
},
}
if mutate != nil {
mutate(cfg)
}
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")
}
gw.limiter.spawn = func(f func()) { f() }
return &gateEnv{gw: gw, h: h, calls: &calls, lastBody: &lastBody}
}
func (e *gateEnv) post(body, key string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, "/openai/v1/native-endpoint", strings.NewReader(body))
if key != "" {
req.Header.Set("Authorization", "Bearer "+key)
}
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
e.h.ServeHTTP(rec, req)
return rec
}
func (e *gateEnv) upstreamCalls() int { return int(atomic.LoadInt32(e.calls)) }
func (e *gateEnv) aliceTokOut() int64 {
v, _ := e.gw.limiter.getCounter("user", "alice", metricTokOut, windowDay, time.Now())
return v
}
// padThenModel puts the model after more than maxModelPeekBytes of prompt.
func padThenModel(model string) string {
return `{"messages":[{"role":"user","content":"` + strings.Repeat("a", maxModelPeekBytes+1024) + `"}],"model":"` + model + `"}`
}
func TestPassthroughCostGate_UnpricedModelBeyondPeekWindowRefused(t *testing.T) {
e := newGateEnv(t, nil)
rec := e.post(padThenModel("cat-unpriced"), "sk-alice")
if rec.Code != http.StatusPaymentRequired {
t.Fatalf("status = %d, want 402, body=%.200s", rec.Code, rec.Body.String())
}
if e.upstreamCalls() != 0 {
t.Errorf("upstream calls = %d, want 0", e.upstreamCalls())
}
if got := e.aliceTokOut(); got != 0 {
t.Errorf("tokout = %d, want 0", got)
}
}
func TestPassthroughCostGate_PricedModelBeyondPeekWindowServedWithFullBody(t *testing.T) {
e := newGateEnv(t, nil)
body := padThenModel("gpt-5")
rec := e.post(body, "sk-alice")
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200, body=%.200s", rec.Code, rec.Body.String())
}
if got, _ := e.lastBody.Load().(string); got != body {
t.Errorf("upstream body differs from the request body (got %d bytes, want %d)", len(got), len(body))
}
if got := e.aliceTokOut(); got != 5 {
t.Errorf("tokout = %d, want 5", got)
}
}
func TestPassthroughCostGate_LargeBodyWithoutModelRefused(t *testing.T) {
e := newGateEnv(t, nil)
body := `{"messages":[{"role":"user","content":"` + strings.Repeat("a", maxModelPeekBytes+1024) + `"}]}`
rec := e.post(body, "sk-alice")
if rec.Code != http.StatusPaymentRequired {
t.Fatalf("status = %d, want 402, body=%.200s", rec.Code, rec.Body.String())
}
if e.upstreamCalls() != 0 {
t.Errorf("upstream calls = %d, want 0", e.upstreamCalls())
}
}
func TestPassthroughCostGate_DuplicateModelKeyRefused(t *testing.T) {
e := newGateEnv(t, nil)
rec := e.post(`{"model":"gpt-5","model":"cat-unpriced"}`, "sk-alice")
if rec.Code != http.StatusPaymentRequired {
t.Fatalf("status = %d, want 402, body=%.200s", rec.Code, rec.Body.String())
}
if e.upstreamCalls() != 0 {
t.Errorf("upstream calls = %d, want 0", e.upstreamCalls())
}
}
func TestPassthroughCostGate_DuplicateModelBeyondPeekWindowRefused(t *testing.T) {
e := newGateEnv(t, nil)
body := `{"model":"gpt-5","pad":"` + strings.Repeat("a", maxModelPeekBytes+1024) + `","model":"cat-unpriced"}`
rec := e.post(body, "sk-alice")
if rec.Code != http.StatusPaymentRequired {
t.Fatalf("status = %d, want 402, body=%.200s", rec.Code, rec.Body.String())
}
if e.upstreamCalls() != 0 {
t.Errorf("upstream calls = %d, want 0", e.upstreamCalls())
}
}
func TestPassthroughCostGate_BodylessGetStillServed(t *testing.T) {
e := newGateEnv(t, nil)
req := httptest.NewRequest(http.MethodGet, "/openai/v1/models", nil)
req.Header.Set("Authorization", "Bearer sk-alice")
rec := httptest.NewRecorder()
e.h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200, body=%.200s", rec.Code, rec.Body.String())
}
}
func TestPassthroughCostGate_ModelFirstPricedStillServed(t *testing.T) {
e := newGateEnv(t, nil)
body := `{"model":"gpt-5","messages":[{"role":"user","content":"` + strings.Repeat("a", maxModelPeekBytes+1024) + `"}]}`
rec := e.post(body, "sk-alice")
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200, body=%.200s", rec.Code, rec.Body.String())
}
if got := e.aliceTokOut(); got != 5 {
t.Errorf("tokout = %d, want 5", got)
}
}
func TestPassthroughCostGate_AllowUnpricedOptInServesAllShapes(t *testing.T) {
e := newGateEnv(t, func(c *Config) { c.AllowUnpricedWithCostBudget = true })
for name, body := range map[string]string{
"padded": padThenModel("cat-unpriced"),
"duplicate": `{"model":"gpt-5","model":"cat-unpriced"}`,
} {
if rec := e.post(body, "sk-alice"); rec.Code != http.StatusOK {
t.Errorf("%s: status = %d, want 200, body=%.200s", name, rec.Code, rec.Body.String())
}
}
}
func TestPassthroughCostGate_NoCostBudgetUnchanged(t *testing.T) {
e := newGateEnv(t, func(c *Config) {
c.Users.Inline[0].Limits = &LimitsConfig{}
})
for name, body := range map[string]string{
"padded": padThenModel("cat-unpriced"),
"duplicate": `{"model":"gpt-5","model":"cat-unpriced"}`,
} {
if rec := e.post(body, "sk-alice"); rec.Code != http.StatusOK {
t.Errorf("%s: status = %d, want 200, body=%.200s", name, rec.Code, rec.Body.String())
}
}
}
func TestPassthroughCostGate_OverCapBodyIs413(t *testing.T) {
e := newGateEnv(t, nil)
req := httptest.NewRequest(http.MethodPost, "/openai/v1/native-endpoint", strings.NewReader(padThenModel("gpt-5")))
req.ContentLength = maxPassthroughBytes + 1
req.Header.Set("Authorization", "Bearer sk-alice")
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
e.h.ServeHTTP(rec, req)
if rec.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("status = %d, want 413", rec.Code)
}
}
func TestPassthroughCostGate_ObjectUnclosedWithinBoundIs413(t *testing.T) {
e := newGateEnv(t, func(c *Config) { c.MaxRequestBytes = 1 << 20 })
body := `{"model":"gpt-5"` + strings.Repeat(" ", 1<<20) + `,"model":"cat-unpriced"}`
rec := e.post(body, "sk-alice")
if rec.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("status = %d, want 413, body=%.200s", rec.Code, rec.Body.String())
}
if !strings.Contains(rec.Body.String(), "maxRequestBytes") {
t.Errorf("body does not name maxRequestBytes: %.200s", rec.Body.String())
}
if e.upstreamCalls() != 0 {
t.Errorf("upstream calls = %d, want 0", e.upstreamCalls())
}
}
func TestPassthroughCostGate_ChunkedOverCapBodyIs413(t *testing.T) {
e := newGateEnv(t, func(c *Config) { c.MaxRequestBytes = maxExplicitUnifiedRequestBytes })
body := `{"pad":"` + strings.Repeat("a", maxPassthroughBytes) + `"}`
req := httptest.NewRequest(http.MethodPost, "/openai/v1/native-endpoint", strings.NewReader(body))
req.ContentLength = -1
req.Header.Set("Authorization", "Bearer sk-alice")
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
e.h.ServeHTTP(rec, req)
if rec.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("status = %d, want 413", rec.Code)
}
if e.upstreamCalls() != 0 {
t.Errorf("upstream calls = %d, want 0", e.upstreamCalls())
}
}
func TestPassthroughCostGate_HugeNonStringModelValueRefused(t *testing.T) {
e := newGateEnv(t, nil)
body := `{"model":[` + strings.Repeat("1,", 100_000) + `1],"x":1}`
body = strings.Replace(body, `"x":1`, `"pad":"`+strings.Repeat("a", maxModelPeekBytes)+`"`, 1)
rec := e.post(body, "sk-alice")
if rec.Code != http.StatusPaymentRequired {
t.Fatalf("status = %d, want 402, body=%.200s", rec.Code, rec.Body.String())
}
}
func TestPassthroughCostGate_ModelBeyondMaxRequestBytesIs413(t *testing.T) {
e := newGateEnv(t, func(c *Config) { c.MaxRequestBytes = 1 << 20 })
body := `{"pad":"` + strings.Repeat("a", 2<<20) + `","model":"gpt-5"}`
rec := e.post(body, "sk-alice")
if rec.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("status = %d, want 413", rec.Code)
}
if e.upstreamCalls() != 0 {
t.Errorf("upstream calls = %d, want 0", e.upstreamCalls())
}
}
func TestPassthroughCostGate_UnparseableObjectRefused(t *testing.T) {
for name, body := range map[string]string{
"nan between duplicates": `{"model":"gpt-5","a":NaN,"model":"cat-unpriced"}`,
"truncated mid-object": `{"model":"gpt-5","messages":[{"role":"user"`,
} {
e := newGateEnv(t, nil)
rec := e.post(body, "sk-alice")
if rec.Code != http.StatusPaymentRequired {
t.Errorf("%s: status = %d, want 402, body=%.200s", name, rec.Code, rec.Body.String())
}
if e.upstreamCalls() != 0 {
t.Errorf("%s: upstream calls = %d, want 0", name, e.upstreamCalls())
}
}
}
type clientResetReader struct{}
func (clientResetReader) Read([]byte) (int, error) { return 0, errors.New("client reset") }
func TestPassthroughCostGate_WidenedReadErrorIs400(t *testing.T) {
e := newGateEnv(t, nil)
body := io.MultiReader(strings.NewReader(`{"pad":"`+strings.Repeat("a", maxModelPeekBytes+1024)), clientResetReader{})
req := httptest.NewRequest(http.MethodPost, "/openai/v1/native-endpoint", body)
req.ContentLength = -1
req.Header.Set("Authorization", "Bearer sk-alice")
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
e.h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400, body=%.200s", rec.Code, rec.Body.String())
}
if e.upstreamCalls() != 0 {
t.Errorf("upstream calls = %d, want 0", e.upstreamCalls())
}
}
func BenchmarkScanTopLevelModelLargeBody(b *testing.B) {
body := []byte(`{"messages":[` + strings.Repeat(`{"role":"user","content":"hello"},`, 1<<17) + `{}],"model":"gpt-5"}`)
b.SetBytes(int64(len(body)))
for i := 0; i < b.N; i++ {
if m, ok, _, _ := scanTopLevelModel(body); !ok || m != "gpt-5" {
b.Fatal("model not found")
}
}
}
+119
View File
@@ -0,0 +1,119 @@
package traefikllmgateway
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
const refusalBoundBytes = 512
func (e *gateEnv) modelKeys() []string {
st := e.gw.limiter.fallback
st.mu.Lock()
defer st.mu.Unlock()
var keys []string
for k := range st.data {
if strings.HasPrefix(k, "llmgw:"+kindModel+":") {
keys = append(keys, k)
}
}
return keys
}
func (e *gateEnv) totalR402() int64 {
v, _ := e.gw.limiter.getCounter(totalScopeKind, totalScopeID, metricR402, windowDay, time.Now())
return v
}
func longModelBody(i int) string {
return `{"model":"` + strings.Repeat("m", 60_000) + fmt.Sprint(i) + `"}`
}
func testRefusalNoModelKeys(t *testing.T, key string) {
t.Helper()
e := newGateEnv(t, nil)
const n = 8
for i := 0; i < n; i++ {
rec := e.post(longModelBody(i), key)
if rec.Code != http.StatusPaymentRequired {
t.Fatalf("request %d: status = %d, want 402, body=%.200s", i, rec.Code, rec.Body.String())
}
}
if e.upstreamCalls() != 0 {
t.Errorf("upstream calls = %d, want 0", e.upstreamCalls())
}
if keys := e.modelKeys(); len(keys) != 0 {
t.Errorf("caller-named model counter keys minted: %d (first key length %d)", len(keys), len(keys[0]))
}
if got := e.totalR402(); got != n {
t.Errorf("total r402 = %d, want %d", got, n)
}
}
func TestPassthroughUnpricedRefusal_NoModelKeysForUncataloguedNames(t *testing.T) {
testRefusalNoModelKeys(t, "sk-alice")
}
func TestPassthroughUnpricedRefusal_AnonymousCaller(t *testing.T) {
testRefusalNoModelKeys(t, "")
}
func TestPassthroughUnpricedRefusal_EventLogAndBodyAreBounded(t *testing.T) {
e := newGateEnv(t, nil)
cap := captureStderrStart()
rec := e.post(longModelBody(0), "sk-alice")
logged := captureStderrStop(cap)
if rec.Code != http.StatusPaymentRequired {
t.Fatalf("status = %d, want 402", rec.Code)
}
if rec.Body.Len() > refusalBoundBytes {
t.Errorf("402 body = %d bytes, want <= %d", rec.Body.Len(), refusalBoundBytes)
}
if len(logged) > refusalBoundBytes {
t.Errorf("log output = %d bytes, want <= %d", len(logged), refusalBoundBytes)
}
events := e.gw.events.ring.snapshot(eventRingCap)
if len(events) == 0 {
t.Fatal("no refusal event recorded")
}
ev := events[0]
if ev.Kind != eventKindUnpriced || ev.Status != http.StatusPaymentRequired {
t.Fatalf("event = kind %q status %d, want unpriced/402", ev.Kind, ev.Status)
}
if len(ev.Model) > refusalBoundBytes || len(ev.Message) > refusalBoundBytes {
t.Errorf("event Model = %d bytes, Message = %d bytes, want each <= %d", len(ev.Model), len(ev.Message), refusalBoundBytes)
}
}
func TestPassthroughUnpricedRefusal_CataloguedModelKeepsModelCounter(t *testing.T) {
e := newGateEnv(t, nil)
rec := e.post(`{"model":"cat-unpriced"}`, "sk-alice")
if rec.Code != http.StatusPaymentRequired {
t.Fatalf("status = %d, want 402, body=%.200s", rec.Code, rec.Body.String())
}
if got, _ := e.gw.limiter.getCounter(kindModel, "openai/cat-unpriced", metricR402, windowDay, time.Now()); got != 1 {
t.Errorf("model r402 counter = %d, want 1", got)
}
}
func TestUnifiedUnpricedRefusal_Unchanged(t *testing.T) {
e := newGateEnv(t, nil)
req := newUnifiedRequest(t, http.MethodPost, "/v1/chat/completions", "sk-alice",
map[string]any{"model": "cat-unpriced", "messages": []any{map[string]any{"role": "user", "content": "hi"}}})
rec := httptest.NewRecorder()
e.h.ServeHTTP(rec, req)
if rec.Code != http.StatusPaymentRequired {
t.Fatalf("status = %d, want 402, body=%.200s", rec.Code, rec.Body.String())
}
events := e.gw.events.ring.snapshot(eventRingCap)
if len(events) == 0 || events[0].Model != "openai/cat-unpriced" {
t.Fatalf("event model = %+v, want openai/cat-unpriced", events)
}
if got, _ := e.gw.limiter.getCounter(kindModel, "openai/cat-unpriced", metricR402, windowDay, time.Now()); got != 1 {
t.Errorf("model r402 counter = %d, want 1", got)
}
}
+129
View File
@@ -0,0 +1,129 @@
package traefikllmgateway
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
const (
responsesJSONBody = `{"id":"resp_1","model":"gpt-5","usage":{"input_tokens":1000,"output_tokens":50000,"input_tokens_details":{"cached_tokens":200}}}`
geminiArrayBody = `[{"candidates":[{"content":{"parts":[{"text":"a"}]}}]},{"candidates":[],"usageMetadata":{"promptTokenCount":1000,"candidatesTokenCount":50000,"cachedContentTokenCount":200},"modelVersion":"gemini-2.5"}]`
responsesSSEBody = "event: response.created\ndata: {\"type\":\"response.created\",\"response\":{\"model\":\"gpt-5\",\"usage\":null}}\n\n" +
"event: response.completed\ndata: {\"type\":\"response.completed\",\"response\":{\"model\":\"gpt-5\",\"usage\":{\"input_tokens\":1000,\"output_tokens\":50000,\"input_tokens_details\":{\"cached_tokens\":200}}}}\n\n"
geminiSSEBody = "data: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"a\"}]}}],\"usageMetadata\":{\"promptTokenCount\":1000,\"candidatesTokenCount\":10}}\n\n" +
"data: {\"candidates\":[],\"usageMetadata\":{\"promptTokenCount\":1000,\"candidatesTokenCount\":50000,\"cachedContentTokenCount\":200},\"modelVersion\":\"gemini-2.5\"}\n\n"
chatSSEBody = "data: {\"id\":\"c1\",\"choices\":[{\"delta\":{\"content\":\"Hi\"}}]}\n\n" +
"data: {\"id\":\"c1\",\"choices\":[],\"usage\":{\"prompt_tokens\":1000,\"completion_tokens\":50000}}\n\n" +
"data: [DONE]\n\n"
)
func TestExtractPassthroughUsage_OpenAIResponsesShape(t *testing.T) {
u, model, err := extractPassthroughUsage(providerTypeOpenAI, "p", []byte(responsesJSONBody))
if err != nil {
t.Fatalf("err = %v", err)
}
if u.prompt != 1000 || u.completion != 50000 || u.cached != 200 || model != "gpt-5" {
t.Errorf("got %+v model %q, want 1000/50000 cached 200 gpt-5", u, model)
}
}
func TestExtractPassthroughUsage_GeminiJSONArray(t *testing.T) {
u, model, err := extractPassthroughUsage(providerTypeGemini, "p", []byte(geminiArrayBody))
if err != nil {
t.Fatalf("err = %v", err)
}
if u.prompt != 1000 || u.completion != 50000 || u.cached != 200 || model != "gemini-2.5" {
t.Errorf("got %+v model %q, want 1000/50000 cached 200 gemini-2.5", u, model)
}
}
func TestExtractPassthroughUsage_GeminiJSONArray_Truncated(t *testing.T) {
u, model, _ := extractPassthroughUsage(providerTypeGemini, "p", []byte(geminiArrayBody[:len(geminiArrayBody)-30]))
if u.total() != 0 || model != "unknown/p" {
t.Errorf("got %+v model %q, want zero usage and fallback model", u, model)
}
}
func TestExtractPassthroughUsage_ChatShapeUnchanged(t *testing.T) {
u, model, err := extractPassthroughUsage(providerTypeOpenAI, "p", []byte(`{"model":"m","usage":{"prompt_tokens":7,"completion_tokens":3,"input_tokens":99,"output_tokens":99}}`))
if err != nil || u.prompt != 7 || u.completion != 3 || model != "m" {
t.Errorf("got %+v model %q err %v, want 7/3 m", u, model, err)
}
}
func TestExtractPassthroughUsage_AnthropicShapeUnchanged(t *testing.T) {
u, _, err := extractPassthroughUsage(providerTypeAnthropic, "p", []byte(`{"model":"m","usage":{"input_tokens":10,"output_tokens":4,"cache_read_input_tokens":5,"cache_creation_input_tokens":2}}`))
if err != nil || u.prompt != 17 || u.completion != 4 || u.cached != 5 || u.cacheWrite != 2 {
t.Errorf("got %+v err %v, want prompt 17 completion 4 cached 5 write 2", u, err)
}
}
func TestParseSSEUsageChunk_OpenAIResponsesCompleted(t *testing.T) {
u, model := parseSSEUsageChunk(providerTypeOpenAI, []byte(responsesSSEBody))
if u.prompt != 1000 || u.completion != 50000 || u.cached != 200 || model != "gpt-5" {
t.Errorf("got %+v model %q, want 1000/50000 cached 200 gpt-5", u, model)
}
}
func TestParseSSEUsageChunk_GeminiUsageMetadata(t *testing.T) {
u, model := parseSSEUsageChunk(providerTypeGemini, []byte(geminiSSEBody))
if u.prompt != 1000 || u.completion != 50000 || u.cached != 200 || model != "gemini-2.5" {
t.Errorf("got %+v model %q, want last chunk 1000/50000 cached 200 gemini-2.5", u, model)
}
}
func TestPassthroughUsageShapes_BillReportedTokens(t *testing.T) {
tests := []struct {
name, provType, path, ctype, body string
}{
{"responses json", "openai", "/openai/v1/responses", "application/json", responsesJSONBody},
{"responses sse", "openai", "/openai/v1/responses", "text/event-stream", responsesSSEBody},
{"chat sse", "openai", "/openai/v1/chat/completions", "text/event-stream", chatSSEBody},
{"gemini json array", "gemini", "/gemini/v1beta/models/gemini-2.5:streamGenerateContent", "application/json", geminiArrayBody},
{"gemini sse", "gemini", "/gemini/v1beta/models/gemini-2.5:streamGenerateContent?alt=sse", "text/event-stream", geminiSSEBody},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", tt.ctype)
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(tt.body))
}))
defer srv.Close()
cfg := CreateConfig()
cfg.Providers = map[string]*ProviderConfig{tt.provType: {Type: tt.provType, BaseURL: srv.URL, APIKey: "sk-up"}}
cfg.Groups = map[string]*GroupConfig{"default": {}}
cfg.Users = &UsersConfig{Inline: []*UserConfig{{Name: "alice", Group: "default", APIKey: "sk-alice", Limits: &LimitsConfig{}}}}
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")
}
gw.limiter.spawn = func(f func()) { f() }
req := httptest.NewRequest(http.MethodPost, tt.path, strings.NewReader(`{"model":"m","input":"hi"}`))
req.Header.Set("Authorization", "Bearer sk-alice")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, body=%s", rec.Code, rec.Body.String())
}
if rec.Body.String() != tt.body {
t.Errorf("client body altered")
}
tokIn, _ := gw.limiter.getCounter("user", "alice", metricTokIn, windowDay, time.Now())
tokOut, _ := gw.limiter.getCounter("user", "alice", metricTokOut, windowDay, time.Now())
if tokIn != 1000 || tokOut != 50000 {
t.Errorf("tokin/tokout = %d/%d, want 1000/50000", tokIn, tokOut)
}
})
}
}
+2 -2
View File
@@ -224,11 +224,11 @@ func (a *anthropicAdapter) forwardStream(w http.ResponseWriter, body io.Reader,
return terr
})
if err != nil {
return st.usage(), fmt.Errorf("%w: stream: %w", errUpstream, err)
return st.usageOnAbort(), fmt.Errorf("%w: stream: %w", errUpstream, err)
}
if clientAskedUsage {
if werr := sw.writeData(st.usageChunk()); werr != nil {
return st.usage(), fmt.Errorf("%w: stream: %w", errUpstream, werr)
return st.usageOnAbort(), fmt.Errorf("%w: stream: %w", errUpstream, werr)
}
}
sw.writeDone()
+77 -7
View File
@@ -39,6 +39,9 @@ type openaiAdapter struct {
metadataPath string
// upstreamErrs is the modelBaseUrls failures of the latest listModels call; guarded by upstreamMu.
upstreamErrs []upstreamFailure
// metaLast is the last good metadata per upstream base; metaErrs the metadata failures of the latest fetchModelMetadata. Guarded by upstreamMu.
metaLast map[string]map[string]int
metaErrs []upstreamFailure
// timeout is this adapter's resolved per-request timeout
// (resolveProviderTimeout, timeout.go) — UNLIKE retry above, it is NOT
// left at its zero value by a bare newOpenAIAdapter call: a
@@ -130,8 +133,53 @@ type promptTokenDetails struct {
// chatCompletion's streaming path needs: whether it carries content
// (Choices non-empty) and, on the final chunk, its usage totals.
type chatStreamChunk struct {
Usage *chatStreamUsage `json:"usage"`
Choices []json.RawMessage `json:"choices"`
Usage *chatStreamUsage `json:"usage"`
Choices []chatStreamChoice `json:"choices"`
}
// chatStreamChoice carries only the delta fields forwardStream sizes for an
// abort-time completion estimate.
type chatStreamChoice struct {
Delta chatStreamDelta `json:"delta"`
}
// chatStreamDelta holds raw JSON so a non-string value cannot fail the
// decode and drop the chunk's usage.
type chatStreamDelta struct {
Content json.RawMessage `json:"content"`
ReasoningContent json.RawMessage `json:"reasoning_content"`
Reasoning json.RawMessage `json:"reasoning"`
ToolCalls []chatStreamToolDelta `json:"tool_calls"`
}
type chatStreamToolDelta struct {
Function chatStreamToolFunction `json:"function"`
}
type chatStreamToolFunction struct {
Arguments json.RawMessage `json:"arguments"`
}
// rawTextLen is the byte length of a raw JSON string value without its quotes; 0 for null or absent.
func rawTextLen(raw json.RawMessage) int64 {
n := int64(len(raw))
if n < 3 || raw[0] != '"' {
return 0
}
return n - 2
}
// chunkOutputBytes sums the forwarded output text of every choice in c.
func chunkOutputBytes(c *chatStreamChunk) int64 {
var n int64
for i := range c.Choices {
d := &c.Choices[i].Delta
n += rawTextLen(d.Content) + rawTextLen(d.ReasoningContent) + rawTextLen(d.Reasoning)
for j := range d.ToolCalls {
n += rawTextLen(d.ToolCalls[j].Function.Arguments)
}
}
return n
}
// chatCompletion implements providerAdapter.
@@ -284,6 +332,7 @@ func (a *openaiAdapter) forwardStream(w http.ResponseWriter, body io.Reader, cli
var u usage
finish := ""
hasOutput := false
var outBytes int64
sawDone := false
@@ -302,6 +351,7 @@ func (a *openaiAdapter) forwardStream(w http.ResponseWriter, body io.Reader, cli
var chunk chatStreamChunk
hasUsage := json.Unmarshal(ev.data, &chunk) == nil && chunk.Usage != nil
outBytes += chunkOutputBytes(&chunk)
if hasUsage {
u.prompt = chunk.Usage.PromptTokens
u.completion = chunk.Usage.CompletionTokens
@@ -321,6 +371,10 @@ func (a *openaiAdapter) forwardStream(w http.ResponseWriter, body io.Reader, cli
// u carries whatever usage was already captured before the stream
// broke — a usage chunk that arrived, then a dropped connection,
// must not report as zero and get treated as an unbilled request.
if u.completion == 0 && outBytes > 0 {
u.completion = estimateCompletionTokens(outBytes)
u.estimated = true
}
return u, fmt.Errorf("%w: stream: %w", errUpstream, err)
}
return withAnswerFlags(u, finish, hasOutput), nil
@@ -457,11 +511,14 @@ type upstreamErrorReporter interface {
upstreamErrors() []upstreamFailure
}
// upstreamErrors returns the modelBaseUrls failures of the latest listModels call.
// upstreamErrors returns the modelBaseUrls failures of the latest listModels
// call, followed by those of the latest metadata fetch.
func (a *openaiAdapter) upstreamErrors() []upstreamFailure {
a.upstreamMu.Lock()
defer a.upstreamMu.Unlock()
return append([]upstreamFailure(nil), a.upstreamErrs...)
out := make([]upstreamFailure, 0, len(a.upstreamErrs)+len(a.metaErrs))
out = append(out, a.upstreamErrs...)
return append(out, a.metaErrs...)
}
func (a *openaiAdapter) setUpstreamErrors(errs []upstreamFailure) {
@@ -645,21 +702,34 @@ func (a *openaiAdapter) fetchModelMetadata(ctx context.Context) (map[string]int,
})
out := make(map[string]int)
var firstErr error
var failures []upstreamFailure
ok := false
a.upstreamMu.Lock()
if a.metaLast == nil {
a.metaLast = make(map[string]map[string]int)
}
for i, base := range bases {
src := got[i]
if errs[i] != nil {
if firstErr == nil {
firstErr = errs[i]
}
continue
failures = append(failures, upstreamFailure{Upstream: base, Err: "metadata: " + errs[i].Error()})
src = a.metaLast[base]
} else {
ok = true
a.metaLast[base] = got[i]
}
ok = true
for id, n := range got[i] {
for id, n := range src {
if a.baseForModel(id) == base {
out[id] = n
}
}
}
if ok && ctx.Err() == nil {
a.metaErrs = failures
}
a.upstreamMu.Unlock()
if !ok {
return nil, firstErr
}
+164
View File
@@ -0,0 +1,164 @@
package traefikllmgateway
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// flakyMetaServer serves ids with the given max_model_len on /v1/models,
// or a 500 while down is set.
func flakyMetaServer(t *testing.T, id string, n *atomic.Int32, down *atomic.Bool) *httptest.Server {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
if down.Load() {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = fmt.Fprintf(w, `{"data":[{"id":%q,"max_model_len":%d}]}`, id, n.Load())
}))
t.Cleanup(srv.Close)
return srv
}
type metaFixture struct {
ad *openaiAdapter
mainN, otherN *atomic.Int32
mainDown, otherDown *atomic.Bool
otherURL string
}
func newMetaFixture(t *testing.T) *metaFixture {
t.Helper()
f := &metaFixture{
mainN: new(atomic.Int32), otherN: new(atomic.Int32),
mainDown: new(atomic.Bool), otherDown: new(atomic.Bool),
}
f.mainN.Store(1000)
f.otherN.Store(2000)
mainSrv := flakyMetaServer(t, "main-model", f.mainN, f.mainDown)
otherSrv := flakyMetaServer(t, "glm", f.otherN, f.otherDown)
f.otherURL = otherSrv.URL
f.ad = newOpenAIAdapter("d1", mainSrv.URL, "")
f.ad.modelBases = map[string]string{"glm": otherSrv.URL}
f.ad.metadataPath = "/v1/models"
return f
}
func TestFetchModelMetadata_PartialFailureKeepsLastKnown(t *testing.T) {
f := newMetaFixture(t)
got, err := f.ad.fetchModelMetadata(context.Background())
require.NoError(t, err)
assert.Equal(t, map[string]int{"main-model": 1000, "glm": 2000}, got)
f.mainN.Store(1500)
f.otherDown.Store(true)
got, err = f.ad.fetchModelMetadata(context.Background())
require.NoError(t, err)
assert.Equal(t, map[string]int{"main-model": 1500, "glm": 2000}, got)
}
func TestFetchModelMetadata_PartialFailureReportedInUpstreamErrors(t *testing.T) {
f := newMetaFixture(t)
_, err := f.ad.fetchModelMetadata(context.Background())
require.NoError(t, err)
assert.Empty(t, f.ad.upstreamErrors())
f.otherDown.Store(true)
_, err = f.ad.fetchModelMetadata(context.Background())
require.NoError(t, err)
errs := f.ad.upstreamErrors()
require.Len(t, errs, 1)
assert.Equal(t, f.otherURL, errs[0].Upstream)
assert.Contains(t, errs[0].Err, "metadata")
}
func TestFetchModelMetadata_RecoveryClearsMetadataError(t *testing.T) {
f := newMetaFixture(t)
_, _ = f.ad.fetchModelMetadata(context.Background())
f.otherDown.Store(true)
_, _ = f.ad.fetchModelMetadata(context.Background())
require.NotEmpty(t, f.ad.upstreamErrors())
f.otherDown.Store(false)
f.otherN.Store(3000)
got, err := f.ad.fetchModelMetadata(context.Background())
require.NoError(t, err)
assert.Empty(t, f.ad.upstreamErrors())
assert.Equal(t, 3000, got["glm"])
}
func TestFetchModelMetadata_AllFailReturnsError(t *testing.T) {
f := newMetaFixture(t)
_, _ = f.ad.fetchModelMetadata(context.Background())
f.mainDown.Store(true)
f.otherDown.Store(true)
got, err := f.ad.fetchModelMetadata(context.Background())
assert.Error(t, err)
assert.Nil(t, got)
}
func TestRegistry_PartialMetadataFailureKeepsContextFor(t *testing.T) {
f := newMetaFixture(t)
cfg := &Config{Providers: map[string]*ProviderConfig{"d1": {Discovery: true, MetadataPath: "/v1/models"}}}
reg, err := newModelRegistry(map[string]providerAdapter{"d1": f.ad}, cfg, func(string, ...any) {})
require.NoError(t, err)
st := reg.states["d1"]
reg.captureModelMetadata(context.Background(), "d1", f.ad, st)
f.otherDown.Store(true)
reg.captureModelMetadata(context.Background(), "d1", f.ad, st)
n, ok := st.contextFor("glm")
assert.True(t, ok, "context of the failed upstream's model must survive")
assert.Equal(t, 2000, n)
}
func TestAdminOverview_UpstreamErrorsCarryMetadataFailure(t *testing.T) {
mainSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = fmt.Fprint(w, `{"data":[{"id":"main-model","max_model_len":1000}]}`)
}))
t.Cleanup(mainSrv.Close)
otherSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/meta" {
w.WriteHeader(http.StatusBadGateway)
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = fmt.Fprint(w, `{"data":[{"id":"glm"}]}`)
}))
t.Cleanup(otherSrv.Close)
cfg := newAdminTestConfig()
cfg.Providers = map[string]*ProviderConfig{
"uni": {
Type: "openai", BaseURL: mainSrv.URL, APIKey: "sk", Discovery: true,
MetadataPath: "/meta",
Models: []string{"glm"},
ModelBaseURLs: map[string]string{"glm": otherSrv.URL},
},
}
h, _ := newAdminGatewayHandle(t, cfg)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, adminRequest(http.MethodGet, adminOverviewPath, "sk-admin1"))
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
var got adminOverviewResponse
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got))
require.Len(t, got.Providers, 1)
require.Len(t, got.Providers[0].UpstreamErrors, 1)
e := got.Providers[0].UpstreamErrors[0]
assert.Contains(t, e.Error, "metadata")
assert.Contains(t, e.Error, "502")
assert.True(t, strings.HasPrefix(e.Upstream, "http://"), e.Upstream)
}
+40
View File
@@ -0,0 +1,40 @@
package traefikllmgateway
import (
"net/http"
"net/http/httptest"
"testing"
)
// The values mirror the README "Anonymous access" example.
func TestReadmeAnonymousExample_DeniesTargets(t *testing.T) {
cfg := &Config{
Providers: map[string]*ProviderConfig{"openai": {Type: "openai", APIKey: "k"}},
Groups: map[string]*GroupConfig{
"public": {
Providers: []string{"openai"},
Models: []string{"gpt-5-mini"},
MCPServers: []string{"-none-"},
Agents: []string{"-none-"},
PassthroughPaths: []string{"-none-"},
Limits: &LimitsConfig{RequestsPerDay: 5000},
MemberLimits: &LimitsConfig{RequestsPerMinute: 30},
},
},
Users: &UsersConfig{AnonymousGroup: "public"},
}
a, err := newAuthStore(cfg)
if err != nil {
t.Fatal(err)
}
_, grp, ok := a.identify(httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil))
if !ok {
t.Fatal("anonymous request not identified")
}
if grp.allowsMCP("docs") || grp.allowsAgent("planner") || grp.allowsPassthroughPath("v1/files") {
t.Fatal("README anonymous example allows an MCP server, agent or passthrough path")
}
if !grp.allowsProvider("openai") {
t.Fatal("README anonymous example denies its own provider")
}
}
+56
View File
@@ -385,6 +385,12 @@ func (st *providerState) tryBeginWarmFillRetry(sinceWarmFill time.Time) bool {
// upstreamErrLogEvery bounds how often a provider's tolerated upstream failures are logged.
const upstreamErrLogEvery = 10 * time.Minute
// Bounds on one provider's discovered model ids.
const (
maxDiscoveredModels = 10000
maxDiscoveredModelIDBytes = 256
)
// finishRefresh records the outcome of a refresh attempt started by
// tryBeginRefresh (or, for the synchronous warm fill, run unconditionally).
// lastRefresh always advances to now, on success or failure alike — that is
@@ -726,6 +732,8 @@ type modelRegistry struct {
warned map[string]bool
// upstreamErrLogAt is each provider's last upstream-failure log time; guarded by warnedMu.
upstreamErrLogAt map[string]time.Time
// discoveryDropLogAt is each provider's last discovery-drop log time; guarded by warnedMu.
discoveryDropLogAt map[string]time.Time
// routerShadowClean maps a router name to modelsGen+1 of its last collision-free scan; guarded by warnedMu.
routerShadowClean map[string]int64
// modelsCache holds one encoded GET /v1/models response body per
@@ -870,6 +878,7 @@ func newModelRegistry(adapters map[string]providerAdapter, cfg *Config, log func
warmFillTimeout: warmFillTimeout,
warned: make(map[string]bool),
upstreamErrLogAt: make(map[string]time.Time),
discoveryDropLogAt: make(map[string]time.Time),
routerShadowClean: make(map[string]int64),
providerNames: make([]string, 0, len(adapters)),
modelsCache: make(map[string]modelsCacheEntry),
@@ -1099,6 +1108,13 @@ func (m *modelRegistry) discoveryHealthy(name string) bool {
// succeeded, and a metadata-only change must invalidate the cache just as
// much as a discovered-set change would.
func (m *modelRegistry) finishRefresh(st *providerState, now time.Time, ids []string, err error) {
if err == nil {
var dropped int
ids, dropped = boundDiscoveredIDs(ids)
if dropped > 0 {
m.logDiscoveryDrop(st.name, now, dropped)
}
}
st.finishRefresh(now, ids, err)
atomic.AddInt64(&m.modelsGen, 1)
if err == nil {
@@ -1106,6 +1122,46 @@ func (m *modelRegistry) finishRefresh(st *providerState, now time.Time, ids []st
}
}
// boundDiscoveredIDs drops ids that are invalid or longer than
// maxDiscoveredModelIDBytes, then keeps the first maxDiscoveredModels. It
// returns the kept ids and how many it dropped.
func boundDiscoveredIDs(ids []string) ([]string, int) {
kept := ids
copied := false
n := 0
for i := 0; i < len(ids); i++ {
id := ids[i]
ok := len(id) <= maxDiscoveredModelIDBytes && n < maxDiscoveredModels && isValidModelID(id)
if ok {
if copied {
kept = append(kept, id)
}
n++
continue
}
if !copied {
kept = make([]string, 0, len(ids))
kept = append(kept, ids[:i]...)
copied = true
}
}
return kept, len(ids) - len(kept)
}
// logDiscoveryDrop logs, at most once per upstreamErrLogEvery per provider, how many discovered ids were dropped. Never logs id text.
func (m *modelRegistry) logDiscoveryDrop(name string, now time.Time, dropped int) {
m.warnedMu.Lock()
due := now.Sub(m.discoveryDropLogAt[name]) >= upstreamErrLogEvery
if due {
m.discoveryDropLogAt[name] = now
}
m.warnedMu.Unlock()
if due {
m.log("%s", fmt.Sprintf("model registry: provider %q discovery dropped %d model ids (empty, control characters, over %d bytes, or past the %d id cap)",
name, dropped, maxDiscoveredModelIDBytes, maxDiscoveredModels))
}
}
// logUpstreamErrors logs name's tolerated modelBaseUrls failures, at most once per upstreamErrLogEvery per provider.
func (m *modelRegistry) logUpstreamErrors(name string, now time.Time) {
adapter := m.adapters[name]
+271 -124
View File
@@ -50,6 +50,8 @@ const (
sseAccountingTailBytes = 64 << 10
)
var sseDataMarker = []byte("data:")
// maxModelPeekBytes caps how much of a passthrough request body
// peekPassthroughModel reads to find a top-level "model" field: 64KiB
// (security review fix, 2026-08-22, round 2). This is deliberately far
@@ -75,6 +77,23 @@ const (
// URL-independent "model" field those routes already require.
const maxModelPeekBytes = 64 << 10
// maxRefusedModelChars bounds caller-supplied model text in a refusal's
// log line, event and 402 body.
const maxRefusedModelChars = 128
// undeterminedModelLabel stands in for the model of a refusal whose body
// did not yield one.
const undeterminedModelLabel = "(undetermined)"
// shortenRefusedText cuts caller-supplied text to maxRefusedModelChars
// bytes on a rune boundary, marking the cut.
func shortenRefusedText(s string) string {
if len(s) <= maxRefusedModelChars {
return s
}
return strings.ToValidUTF8(s[:maxRefusedModelChars], "") + "..."
}
// passthroughBinaryContentTypePrefixes lists Content-Type prefixes
// peekPassthroughModel treats as genuinely binary and never reads at all
// (security review fix, 2026-08-22, round 2): multipart uploads
@@ -512,6 +531,10 @@ func (c *cappedAccountingBuffer) Write(p []byte) (int, error) {
type sseAccountingBuffer struct {
tail []byte
head bytes.Buffer
// events counts "data:" markers across all writes, for a completion
// estimate when no usage arrives. A marker split across two writes is
// missed; that is acceptable for an estimate.
events int64
}
// Write implements io.Writer. head fills once, like
@@ -524,6 +547,7 @@ type sseAccountingBuffer struct {
// Chosen over a circular-index ring buffer for simplicity.
func (b *sseAccountingBuffer) Write(p []byte) (int, error) {
n := len(p)
b.events += int64(bytes.Count(p, sseDataMarker))
if remaining := sseAccountingHeadBytes - b.head.Len(); remaining > 0 {
head := p
if len(head) > remaining {
@@ -565,8 +589,15 @@ func (b *sseAccountingBuffer) tailBytes() []byte {
// carry (Gemini's native response carries neither "model" nor any of the
// URL-supplied model id).
type passthroughUsagePayload struct {
Model string `json:"model"`
Usage struct {
// Response carries the Responses API's nested object on streaming
// events such as response.completed.
Response *struct {
Model string `json:"model"`
Usage responsesUsagePayload `json:"usage"`
} `json:"response"`
Model string `json:"model"`
ModelVersion string `json:"modelVersion"`
Usage struct {
PromptTokens int64 `json:"prompt_tokens"`
CompletionTokens int64 `json:"completion_tokens"`
InputTokens int64 `json:"input_tokens"`
@@ -585,6 +616,7 @@ type passthroughUsagePayload struct {
// PromptDetails carries the OpenAI-shaped cached_tokens count.
PromptDetails promptTokenDetails `json:"prompt_tokens_details"`
PromptCacheHitTokens int64 `json:"prompt_cache_hit_tokens"`
InputDetails promptTokenDetails `json:"input_tokens_details"`
} `json:"usage"`
UsageMetadata struct {
PromptTokenCount int64 `json:"promptTokenCount"`
@@ -593,6 +625,42 @@ type passthroughUsagePayload struct {
} `json:"usageMetadata"`
}
// responsesUsagePayload is the OpenAI Responses API usage object.
type responsesUsagePayload struct {
InputTokens int64 `json:"input_tokens"`
OutputTokens int64 `json:"output_tokens"`
InputDetails promptTokenDetails `json:"input_tokens_details"`
}
// openAIUsageOf reads chat-completions figures, falling back to the
// Responses API names when both chat counters are zero.
func openAIUsageOf(p *passthroughUsagePayload) usage {
if p.Usage.PromptTokens == 0 && p.Usage.CompletionTokens == 0 {
return usage{prompt: p.Usage.InputTokens, completion: p.Usage.OutputTokens, cached: p.Usage.InputDetails.CachedTokens}
}
return usage{prompt: p.Usage.PromptTokens, completion: p.Usage.CompletionTokens, cached: cachedPromptTokens(p.Usage.PromptDetails.CachedTokens, p.Usage.PromptCacheHitTokens)}
}
func geminiUsageOf(p *passthroughUsagePayload) usage {
return usage{prompt: p.UsageMetadata.PromptTokenCount, completion: p.UsageMetadata.CandidatesTokenCount, cached: p.UsageMetadata.CachedContentTokenCount}
}
// decodeGeminiArrayUsage handles streamGenerateContent without alt=sse,
// which replies with a JSON array of chunks; the last chunk reporting
// usageMetadata wins.
func decodeGeminiArrayUsage(body []byte) (passthroughUsagePayload, error) {
var chunks []passthroughUsagePayload
if err := json.Unmarshal(body, &chunks); err != nil {
return passthroughUsagePayload{}, err
}
for i := len(chunks) - 1; i >= 0; i-- {
if geminiUsageOf(&chunks[i]).total() > 0 {
return chunks[i], nil
}
}
return passthroughUsagePayload{}, nil
}
// extractPassthroughUsage best-effort parses body as one of the three
// provider types' native non-streaming JSON response shapes, returning
// its reported token usage and model id, keyed by typeName (one of
@@ -608,20 +676,32 @@ type passthroughUsagePayload struct {
// response.
func extractPassthroughUsage(typeName, providerName string, body []byte) (usage, string, error) {
var payload passthroughUsagePayload
err := json.Unmarshal(body, &payload)
var err error
first := 0
for first < len(body) && (body[first] == ' ' || body[first] == '\n' || body[first] == '\r' || body[first] == '\t') {
first++
}
if typeName == providerTypeGemini && first < len(body) && body[first] == '[' {
payload, err = decodeGeminiArrayUsage(body)
} else {
err = json.Unmarshal(body, &payload)
}
model := payload.Model
if model == "" {
model = payload.ModelVersion
}
if model == "" {
model = "unknown/" + providerName
}
switch typeName {
case providerTypeOpenAI:
return usage{prompt: payload.Usage.PromptTokens, completion: payload.Usage.CompletionTokens, cached: cachedPromptTokens(payload.Usage.PromptDetails.CachedTokens, payload.Usage.PromptCacheHitTokens)}, model, err
return openAIUsageOf(&payload), model, err
case providerTypeAnthropic:
return usage{prompt: payload.Usage.InputTokens + payload.Usage.CacheCreationInputTokens + payload.Usage.CacheReadInputTokens, completion: payload.Usage.OutputTokens, cached: payload.Usage.CacheReadInputTokens, cacheWrite: payload.Usage.CacheCreationInputTokens}, model, err
case providerTypeGemini:
return usage{prompt: payload.UsageMetadata.PromptTokenCount, completion: payload.UsageMetadata.CandidatesTokenCount, cached: payload.UsageMetadata.CachedContentTokenCount}, model, err
return geminiUsageOf(&payload), model, err
default:
return usage{}, model, err
}
@@ -643,11 +723,10 @@ func extractPassthroughUsage(typeName, providerName string, body []byte) (usage,
// message_start.message.usage for the prompt side (folding in its own
// prompt-cache counters, matching extractPassthroughUsage's
// providerTypeAnthropic case) and the LAST message_delta.usage.
// output_tokens for the completion side. Gemini's own SSE convention is
// not documented here and is deliberately left unhandled — the returned
// usage simply stays zero for it, exactly like any other unrecognized or
// empty stream, and the caller's own request-body-size estimate covers
// the rest. model falls back to "unknown/"+providerName when neither
// output_tokens for the completion side. Gemini's usageMetadata is read from every
// data event (last wins), and the Responses API's response.completed
// event carries usage under "response". Any other unrecognized or empty
// stream stays zero and the caller's own estimate covers the rest. model falls back to "unknown/"+providerName when neither
// window named one, matching extractPassthroughUsage's own convention.
//
// head and tail are parsed independently (parseSSEUsageChunk, below),
@@ -714,12 +793,34 @@ func parseSSEUsageChunk(typeName string, raw []byte) (usage, string) {
if json.Unmarshal(ev.data, &chunk) != nil {
return nil
}
if chunk.Usage.PromptTokens > 0 || chunk.Usage.CompletionTokens > 0 {
u = usage{prompt: chunk.Usage.PromptTokens, completion: chunk.Usage.CompletionTokens, cached: cachedPromptTokens(chunk.Usage.PromptDetails.CachedTokens, chunk.Usage.PromptCacheHitTokens)}
if cu := openAIUsageOf(&chunk); cu.prompt > 0 || cu.completion > 0 {
u = cu
}
if chunk.Model != "" {
model = chunk.Model
}
if r := chunk.Response; r != nil {
if r.Usage.InputTokens > 0 || r.Usage.OutputTokens > 0 {
u = usage{prompt: r.Usage.InputTokens, completion: r.Usage.OutputTokens, cached: r.Usage.InputDetails.CachedTokens}
}
if r.Model != "" {
model = r.Model
}
}
return nil
})
case providerTypeGemini:
_ = readSSE(bytes.NewReader(raw), func(ev sseEvent) error {
var chunk passthroughUsagePayload
if json.Unmarshal(ev.data, &chunk) != nil {
return nil
}
if gu := geminiUsageOf(&chunk); gu.total() > 0 {
u = gu
}
if chunk.ModelVersion != "" {
model = chunk.ModelVersion
}
return nil
})
case providerTypeAnthropic:
@@ -822,35 +923,35 @@ func parseSSEUsageChunk(typeName string, raw []byte) (usage, string) {
// deadline) distinct from merely reaching the end of a body shorter than
// the peek window — the caller maps err to the same 400 runUnified's own
// body-read failure uses (routes_unified.go).
func peekPassthroughModel(r *http.Request) (model string, hasModel, truncated bool, err error) {
func peekPassthroughModel(r *http.Request) (string, bool, bool, error) {
model, hasModel, truncated, _, _, err := peekPassthroughModelUpTo(r, maxModelPeekBytes)
return model, hasModel, truncated, err
}
// peekPassthroughModelUpTo is peekPassthroughModel with an explicit read
// limit. It also reports a duplicate top-level "model" key, and
// unparseable: the body opens a JSON object that the scan could not follow
// to its closing brace (malformed, or cut off by the limit). A later
// duplicate key could hide behind such a point, so the cost gate treats it
// as undeterminable.
func peekPassthroughModelUpTo(r *http.Request, limit int64) (string, bool, bool, bool, bool, error) {
if r.Body == nil || isPassthroughBinaryContentType(r.Header.Get("Content-Type")) {
return "", false, false, nil
return "", false, false, false, false, nil
}
head := make([]byte, maxModelPeekBytes)
n, readErr := io.ReadFull(r.Body, head)
capped := false
switch readErr { //nolint:errorlint // io.ReadFull returns these sentinels bare, never wrapped — see its own doc comment
case nil:
// Read exactly maxModelPeekBytes: the body has at least that much
// left unread on r.Body, restored below via io.MultiReader — a
// LATER "model" key beyond this window cannot be ruled out unless
// scanTopLevelModel confirms the object closed within it.
capped = true
case io.EOF, io.ErrUnexpectedEOF:
// Body was shorter than the peek window (io.EOF: empty; io.
// ErrUnexpectedEOF: 0 < n < len(head)) — head[:n] IS the whole
// body; r.Body is now exhausted, so appending it below is a
// harmless immediate EOF. No bytes exist beyond what was scanned,
// so "truncated" (in the hidden-duplicate sense) cannot apply.
default:
return "", false, false, readErr
head, readErr := io.ReadAll(io.LimitReader(r.Body, limit))
if readErr != nil {
return "", false, false, false, false, readErr
}
head = head[:n]
// A full read means the body has at least that much; a LATER "model"
// key beyond the window cannot be ruled out unless the scan confirms
// the object closed within it. A shorter read is the whole body.
capped := int64(len(head)) >= limit
r.Body = io.NopCloser(io.MultiReader(bytes.NewReader(head), r.Body))
model, hasModel, closed := scanTopLevelModel(head)
return model, hasModel, capped && !closed, nil
model, hasModel, closed, duplicate := scanTopLevelModel(head)
unparseable := !closed && bytes.HasPrefix(bytes.TrimLeft(head, " \t\r\n"), []byte("{"))
return model, hasModel, capped && !closed, duplicate, unparseable, nil
}
// scanTopLevelModel walks head — a bounded, possibly-truncated PREFIX of
@@ -882,59 +983,67 @@ func peekPassthroughModel(r *http.Request) (model string, hasModel, truncated bo
// alone. peekPassthroughModel combines closed with its own knowledge of
// whether the read actually hit the byte cap (there is more of r.Body
// left unread) to decide whether a "found" model can be trusted.
func scanTopLevelModel(head []byte) (model string, found, closed bool) {
//
// duplicate is true only when a second top-level "model" key was seen: the
// model is then ambiguous, which is different from absent.
func scanTopLevelModel(head []byte) (string, bool, bool, bool) {
var model string
var found bool
seenModel := false
dec := json.NewDecoder(bytes.NewReader(head))
tok, err := dec.Token()
if err != nil {
return "", false, false
return "", false, false, false
}
if d, ok := tok.(json.Delim); !ok || d != '{' {
return "", false, false
return "", false, false, false
}
for dec.More() {
keyTok, keyErr := dec.Token()
if keyErr != nil {
return model, found, false
return model, found, false, false
}
key, ok := keyTok.(string)
if !ok {
return model, found, false // malformed: expected an object key
return model, found, false, false // malformed: expected an object key
}
valTok, valErr := dec.Token()
if valErr != nil {
return model, found, false
}
if key == "model" {
// A DUPLICATE top-level "model" fails closed, matching
// extractMultipartModel's errDuplicateModelField rule
// (routes_media.go). Returning on the FIRST occurrence would be
// an authorization bypass: RFC 8259 permits duplicate names and
// every mainstream parser an upstream might use (Go's
// encoding/json, Python json.loads, Node JSON.parse, Ruby, PHP,
// Newtonsoft) resolves them LAST-wins, while this body is
// forwarded byte-for-byte unmodified — so a client could get
// {"model":"allowed","model":"expensive"} authorized against the
// first and executed as the second. Ambiguity is not
// resolvable here without rewriting the client's bytes, so the
// only safe answer is to refuse to answer.
if seenModel {
return "", false, false
}
seenModel = true
if s, isStr := valTok.(string); isStr && s != "" {
model = s
found = true
if key != "model" {
// Decode into RawMessage skips a whole value in one native call;
// stepping its tokens through the interpreter costs ~15x more CPU
// on a multi-MiB body.
var skipped json.RawMessage
if skipErr := dec.Decode(&skipped); skipErr != nil {
return model, found, false, false
}
continue
}
if d, ok := valTok.(json.Delim); ok && (d == '{' || d == '[') {
if skipErr := skipJSONValue(dec); skipErr != nil {
return model, found, false
var rawModel json.RawMessage
if valErr := dec.Decode(&rawModel); valErr != nil {
return model, found, false, false
}
// A DUPLICATE top-level "model" fails closed, matching
// extractMultipartModel's errDuplicateModelField rule
// (routes_media.go). Returning on the FIRST occurrence would be
// an authorization bypass: RFC 8259 permits duplicate names and
// every mainstream parser an upstream might use (Go's
// encoding/json, Python json.loads, Node JSON.parse, Ruby, PHP,
// Newtonsoft) resolves them LAST-wins, while this body is
// forwarded byte-for-byte unmodified — so a client could get
// {"model":"allowed","model":"expensive"} authorized against the
// first and executed as the second. Ambiguity is not
// resolvable here without rewriting the client's bytes, so the
// only safe answer is to refuse to answer.
if seenModel {
return "", false, false, true
}
seenModel = true
if len(rawModel) > 0 && rawModel[0] == '"' {
var s string
if json.Unmarshal(rawModel, &s) == nil && s != "" {
model = s
found = true
}
}
// Otherwise valTok was a scalar (string/float64/bool/nil) other
// than "model" — nothing further to do; loop to the next key.
}
// dec.More() returned false above: either the object legitimately
// closed, or the decoder simply ran out of bytes searching for the
@@ -944,37 +1053,12 @@ func scanTopLevelModel(head []byte) (model string, found, closed bool) {
// within head.
closeTok, err := dec.Token()
if err != nil {
return model, found, false
return model, found, false, false
}
if d, ok := closeTok.(json.Delim); !ok || d != '}' {
return model, found, false
return model, found, false, false
}
return model, found, true
}
// skipJSONValue consumes the remainder of a nested JSON array/object
// value whose opening delimiter dec has already emitted, so
// scanTopLevelModel's own dec.More() call — which reports position in
// whatever object/array dec is CURRENTLY inside — correctly reports the
// outer top-level object's state again once this returns, rather than
// still appearing "inside" the value just skipped.
func skipJSONValue(dec *json.Decoder) error {
depth := 1
for depth > 0 {
tok, err := dec.Token()
if err != nil {
return err
}
if d, ok := tok.(json.Delim); ok {
switch d {
case '{', '[':
depth++
case '}', ']':
depth--
}
}
}
return nil
return model, found, true, false
}
// allowsPassthroughModel reports whether grp's Models glob authorizes
@@ -1275,34 +1359,74 @@ func (g *Gateway) handlePassthrough(w http.ResponseWriter, r *http.Request, u *u
// Finding 6 fix (review-routes.md): the same unpriced-model-under-a-
// cost-budget refusal runMeteredCall applies to /v1/chat/completions
// (routes_unified.go's own F-1 gate) must also cover native
// passthrough, or a tenant whose cost budget is exhausted on the
// unified routes can keep spending without limit simply by calling
// the identical model through "/{provider}/...". Passthrough has no
// resolved canonical/upstream model id the way the unified route
// does — only whatever "model" the CLIENT's OWN request body names,
// peeked the same bounded way model authorization above already does
// — so this only ever fires when that model is actually determinable
// from the body; a request this gateway cannot price at all (Gemini
// passthrough, whose model id lives in the URL, never the body; a
// binary content type; or a body whose "model" sits beyond the peek
// window) is let through unpriced, exactly as before this fix,
// rather than fail-closed on a value it never had. peekPassthroughModel
// is called again here even when the model-restriction branches above
// already called it (a second bounded, cheap 64KiB re-peek — r.Body
// was already restored via io.MultiReader after that first call) so
// this check runs independently of whether the group restricts
// models at all.
// must cover native passthrough, or a tenant whose cost budget is
// exhausted on the unified routes can keep spending through
// "/{provider}/...". Only the model the client's own body names is
// known here. A first 64KiB peek settles it when the object closes
// there; otherwise the body is read up to min(maxRequestBytes, the
// passthrough cap) and the request is refused (402 missing or repeated
// model, 413 object not closed) rather than served unpriced. Still
// ungated: Gemini passthrough (model in the URL) and a binary content
// type, whose body is never read.
var gatedModel string
if !g.cfg.AllowUnpricedWithCostBudget && scopesHaveCostBudget(scopes) {
if model, hasModel, _, peekErr := peekPassthroughModel(r); peekErr == nil && hasModel {
model, hasModel, truncated, duplicate, unparseable, peekErr := peekPassthroughModelUpTo(r, maxModelPeekBytes)
widened := peekErr == nil && truncated
if widened {
// The first window cannot settle the model (a later key may add or
// repeat it): look at the rest of the body, up to the smaller of
// maxRequestBytes and the route cap. The body is restored for
// forwarding.
if r.ContentLength > maxPassthroughBytes {
writeOAIError(w, http.StatusRequestEntityTooLarge, "invalid_request_error", "request body exceeds the maximum allowed size")
return
}
bound := g.unifiedRequestBytes
if bound <= 0 || bound > maxPassthroughBytes {
bound = maxPassthroughBytes
}
// The scan allocates a few times the body, so it runs inside a
// body-admission slot like the unified routes' decode.
release, admitted := g.acquireBodyAdmission(&statusTrackingWriter{ResponseWriter: w}, writeOAIError)
if !admitted {
return
}
// One byte past the bound tells an over-cap body from one that ends at it.
model, hasModel, truncated, duplicate, unparseable, peekErr = peekPassthroughModelUpTo(r, bound+1)
release()
if peekErr != nil {
writeOAIError(w, http.StatusBadRequest, "invalid_request_error", "cannot read request body")
return
}
// An object that does not close within the bound may repeat the
// model past it, so the model cannot be settled.
if truncated {
writeOAIError(w, http.StatusRequestEntityTooLarge, "invalid_request_error",
"request body exceeds maxRequestBytes before its top-level JSON object ends, so the model cannot be determined for the cost budget; send a smaller body or raise maxRequestBytes")
return
}
}
if peekErr == nil && (duplicate || unparseable || (!hasModel && widened)) {
g.logf("passthrough: refusing a request whose top-level model cannot be determined: a cost budget applies to this caller that cannot be enforced without it")
g.recordUnpricedRefusal(scopes, "", undeterminedModelLabel, providerName, routePassthrough)
writeOAIError(w, http.StatusPaymentRequired, "invalid_request_error",
"the model cannot be determined from the request body (missing or repeated top-level \"model\", or a malformed or unterminated JSON object), so the cost budget that applies to this request cannot be enforced; send the model once, or set allowUnpricedWithCostBudget to serve it unbounded")
return
}
if peekErr == nil && hasModel {
canonical := providerName + "/" + model
gatedModel = model
if !priceKnown(canonical, model, g.cfg.Pricing, g.cfg.ModelMeta) {
g.logf("passthrough: refusing model %q: it has no configured price, and a cost budget applies to this caller that cannot be enforced without one", model)
g.recordUnpricedRefusalEvent(scopes, canonical, providerName, routePassthrough) // F3 hook 5 (item 5, this round)
shown := shortenRefusedText(model)
// Only ids the provider is known to serve may name a counter key.
counterModel := ""
if g.registry.providerHasModel(providerName, model) {
counterModel = canonical
}
g.logf("passthrough: refusing model %q: it has no configured price, and a cost budget applies to this caller that cannot be enforced without one", shown)
g.recordUnpricedRefusal(scopes, counterModel, shortenRefusedText(canonical), providerName, routePassthrough) // F3 hook 5 (item 5, this round)
writeOAIError(w, http.StatusPaymentRequired, "invalid_request_error",
fmt.Sprintf("model %q has no configured price, so the cost budget that applies to this request cannot be enforced; add a \"pricing\" entry for it, or set allowUnpricedWithCostBudget to serve it unbounded", model))
fmt.Sprintf("model %q has no configured price, so the cost budget that applies to this request cannot be enforced; add a \"pricing\" entry for it, or set allowUnpricedWithCostBudget to serve it unbounded", shown))
return
}
}
@@ -1400,7 +1524,12 @@ func (g *Gateway) handlePassthrough(w http.ResponseWriter, r *http.Request, u *u
respUsage, respModel = extractPassthroughSSEUsage(adapter.typeName(), providerName, result.sseTee.head.Bytes(), result.sseTee.tailBytes())
}
if respUsage.total() == 0 {
is2xx := result.status >= 200 && result.status < 300
// An SSE reply that delivered events but no completion usage (no
// include_usage, or a hang-up before the final usage event) must not
// record zero output tokens: one token per data event is the floor.
sseNoCompletion := is2xx && result.isSSE && respUsage.completion == 0 && result.sseTee.events > 0
if respUsage.total() == 0 || sseNoCompletion {
// Verify-core fix (round 4): the estimate below is only a valid
// stand-in for real usage when the upstream actually accepted
// the request (2xx) AND either the response is SSE (whose usage
@@ -1416,17 +1545,25 @@ func (g *Gateway) handlePassthrough(w http.ResponseWriter, r *http.Request, u *u
// A 4xx/5xx JSON error body must never be estimated either: the
// upstream billed nothing for a rejected request, so neither
// should this gateway.
is2xx := result.status >= 200 && result.status < 300
copyAborted := !complete
canEstimate := is2xx && (result.isSSE || (result.isJSON && (result.tee.truncated || copyAborted)))
if !canEstimate || result.requestBytes <= 0 {
if !canEstimate || (respUsage.prompt == 0 && result.requestBytes <= 0) {
return
}
respUsage = usage{prompt: estimatePromptTokens(int64(result.requestBytes)), estimated: true}
if respUsage.prompt == 0 {
respUsage.prompt = estimatePromptTokens(int64(result.requestBytes))
}
if sseNoCompletion {
respUsage.completion = result.sseTee.events
if respUsage.completion > maxEstimatedPromptTokens {
respUsage.completion = maxEstimatedPromptTokens
}
}
respUsage.estimated = true
if respModel == "" {
respModel = "unknown/" + providerName
}
g.logf("passthrough: usage for provider %q logged as estimated (%d prompt tokens derived from request body size, not the provider's reported usage)", providerName, respUsage.prompt)
g.logf("passthrough: usage for provider %q logged as estimated (%d prompt, %d completion tokens derived from request size and stream events, not the provider's reported usage)", providerName, respUsage.prompt, respUsage.completion)
}
canonical := providerName + "/" + respModel
@@ -1782,6 +1919,16 @@ func (g *Gateway) proxyUpstream(w http.ResponseWriter, r *http.Request, upstream
writeOAIError(w, http.StatusBadGateway, "server_error", "upstream connection error")
return proxyResult{}, false
}
// A redirect Location commonly echoes the request query, so one that
// answers a request carrying a gateway-added query would hand the
// configured credential to the client.
if resp.StatusCode >= 300 && resp.StatusCode < 400 && resp.Header.Get("Location") != "" && queryAddedByGateway(upstreamURL, r.URL.RawQuery) {
_ = resp.Body.Close()
cancel()
g.errorf("%s: upstream answered %d with a redirect; not relaying it because the upstream URL carries a configured query", logPrefix, resp.StatusCode)
writeOAIError(w, http.StatusBadGateway, "server_error", "upstream answered with a redirect, which the gateway does not relay")
return proxyResult{}, false
}
// logPrefix, not a hardcoded "provider %q": handleTargetProxy's own
// calls here (mcp_a2a.go) pass "mcp target (name ...)"/"a2a target
// (name ...)" — an MCP/A2A target is not a provider, and the watchdog
+3 -3
View File
@@ -198,7 +198,7 @@ func TestScanTopLevelModel(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotModel, gotFound, _ := scanTopLevelModel([]byte(tt.head))
gotModel, gotFound, _, _ := scanTopLevelModel([]byte(tt.head))
if gotFound != tt.wantFound {
t.Errorf("found = %v, want %v", gotFound, tt.wantFound)
}
@@ -3077,7 +3077,7 @@ func TestScanTopLevelModel_DuplicateModelKeyFailsClosed(t *testing.T) {
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
gotModel, gotFound, gotClosed := scanTopLevelModel([]byte(tc.body))
gotModel, gotFound, gotClosed, _ := scanTopLevelModel([]byte(tc.body))
if gotModel != tc.wantModel || gotFound != tc.wantFound || gotClosed != tc.wantClosed {
t.Fatalf("scanTopLevelModel(%s) = (%q, %v, %v), want (%q, %v, %v)",
tc.body, gotModel, gotFound, gotClosed, tc.wantModel, tc.wantFound, tc.wantClosed)
@@ -3105,7 +3105,7 @@ func TestScanTopLevelModel_ClosedTracksWindowTruncation(t *testing.T) {
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
_, _, gotClosed := scanTopLevelModel([]byte(tc.body))
_, _, gotClosed, _ := scanTopLevelModel([]byte(tc.body))
if gotClosed != tc.wantClosed {
t.Errorf("scanTopLevelModel(%s) closed = %v, want %v", tc.body, gotClosed, tc.wantClosed)
}
+19
View File
@@ -330,6 +330,11 @@ func (g *Gateway) runMeteredCall(sw *statusTrackingWriter, r *http.Request, scop
cacheable := !streaming && g.cache != nil && groupCacheEnabled(grp) &&
(endpoint != cacheEndpointEmbeddings || g.cache.embeddings)
vary := ""
if cacheable && endpoint == cacheEndpointMessages && !g.cfg.StripClientAnthropicBeta {
vary = normalizeBetaSet(r.Header.Values("anthropic-beta"))
}
// pristineReq is the client's own decoded request, snapshotted ONCE,
// BEFORE any candidate's adapter ever touches it ("model" is rewritten
// per attempt below). Every attempt below
@@ -474,6 +479,9 @@ func (g *Gateway) runMeteredCall(sw *statusTrackingWriter, r *http.Request, scop
var cacheKeyStr string
if cacheable {
cacheKeyStr = cacheKey(cand.providerName, cand.upstreamModel, requestedModel, endpoint, attemptReq)
if vary != "" {
cacheKeyStr = cacheKeyWithVary(cacheKeyStr, vary)
}
}
g.applyPromptCacheKey(attemptReq, endpoint, cand.providerName, pck)
if endpoint == cacheEndpointChat {
@@ -715,6 +723,11 @@ func (g *Gateway) runMeteredCall(sw *statusTrackingWriter, r *http.Request, scop
// only when it is genuinely zero (a non-streaming failure), never
// skipped, so a later successful candidate's real usage is never
// silently doubled with a phantom first entry either.
if streaming && callErr != nil && sw.wroteHeader && result.prompt == 0 && result.total() != 0 {
// An estimated completion must not suppress the prompt estimate.
result.prompt = estimatePromptTokens(int64(len(body)))
result.estimated = true
}
if result.total() == 0 {
switch {
case streaming && callErr != nil && sw.wroteHeader:
@@ -1576,6 +1589,12 @@ func reserveTokensFor(bodyBytes int64) int64 {
// window would legitimately hold.
const maxEstimatedPromptTokens = 1 << 20
// estimateCompletionTokens estimates completion tokens from forwarded output
// bytes, with the same rule and cap as estimatePromptTokens.
func estimateCompletionTokens(outBytes int64) int64 {
return estimatePromptTokens(outBytes)
}
// estimatePromptTokens estimates prompt tokens as one per four body bytes,
// rounded up and capped at maxEstimatedPromptTokens.
func estimatePromptTokens(bodyBytes int64) int64 {
@@ -0,0 +1,79 @@
package traefikllmgateway
import (
"context"
"net"
"net/http"
"strings"
"testing"
)
func closedLoopbackAddr(t *testing.T) string {
t.Helper()
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
addr := l.Addr().String()
_ = l.Close()
return addr
}
func TestSanitizeProviderErr_ReserialisedForms(t *testing.T) {
const tok = "DUMMYTOKEN123"
addr := closedLoopbackAddr(t)
cases := []struct {
name string
base string
}{
{"upper-case scheme with userinfo", "HTTP://" + tok + "@" + addr + "/v1"},
{"escaped userinfo, no password", "http://us%40" + tok + "@" + addr + "/v1"},
{"upper-case scheme with query credential", "HTTP://" + addr + "/v1?key=" + tok},
{"lower-case userinfo", "http://" + tok + "@" + addr + "/v1"},
{"user and password", "http://user:" + tok + "@" + addr + "/v1"},
{"lower-case query", "http://" + addr + "/v1?key=" + tok},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
resp, err := http.Get(tc.base) //nolint:gosec,noctx // loopback closed port, error text is the subject
if err == nil {
_ = resp.Body.Close()
t.Fatal("expected a dial error")
}
if !strings.Contains(err.Error(), tok) && !strings.Contains(err.Error(), "***") {
t.Fatalf("precondition: error text does not carry the credential: %v", err)
}
got := sanitizeProviderErr(err.Error(), tc.base)
if strings.Contains(got, tok) {
t.Fatalf("credential leaked: %q", got)
}
})
}
}
func TestNew_WarnsOnceForCredentialBearingBaseURL(t *testing.T) {
const tok = "DUMMYTOKEN123"
cfg := CreateConfig()
cfg.Providers = map[string]*ProviderConfig{
"bad": {Type: "openai", APIKey: "k", BaseURL: "https://" + tok + "@example.invalid/v1"},
"good": {Type: "openai", APIKey: "k", BaseURL: "https://example.invalid/v1"},
}
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
h, err := New(context.Background(), next, cfg, "llmgw")
if err != nil {
t.Fatalf("New must keep accepting the config: %v", err)
}
warnings, _ := h.(*Gateway).configWarningsSnapshot()
var n int
for _, w := range warnings {
if strings.Contains(w, "userinfo") {
n++
if strings.Contains(w, tok) || !strings.Contains(w, `"bad"`) {
t.Errorf("warning must name the provider and never the credential: %q", w)
}
}
}
if n != 1 {
t.Errorf("userinfo warnings = %d, want 1 (%v)", n, warnings)
}
}
+190
View File
@@ -0,0 +1,190 @@
package traefikllmgateway
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
// hangupServer writes frames, flushes, then closes the connection without a terminator.
func hangupServer(t *testing.T, contentType string, frames []string) *httptest.Server {
t.Helper()
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", contentType)
w.WriteHeader(http.StatusOK)
fl, ok := w.(http.Flusher)
if !ok {
t.Error("upstream writer cannot flush")
return
}
for _, f := range frames {
_, _ = w.Write([]byte(f))
fl.Flush()
}
hj, ok := w.(http.Hijacker)
if !ok {
t.Error("upstream writer cannot hijack")
return
}
if conn, _, err := hj.Hijack(); err == nil {
_ = conn.Close()
}
}))
}
func newStreamBillingGateway(t *testing.T, providerType, baseURL, model string) *Gateway {
t.Helper()
cfg := CreateConfig()
cfg.Providers = map[string]*ProviderConfig{
"up": {Type: providerType, BaseURL: baseURL, APIKey: "k", Models: []string{model}},
}
cfg.Groups = map[string]*GroupConfig{"default": {}}
cfg.Users = &UsersConfig{Inline: []*UserConfig{{Name: "alice", Group: "default", APIKey: "sk-alice", Limits: &LimitsConfig{}}}}
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
}
func aliceTokens(gw *Gateway) (int64, int64) {
in, _ := gw.limiter.getCounter("user", "alice", metricTokIn, windowDay, time.Now())
out, _ := gw.limiter.getCounter("user", "alice", metricTokOut, windowDay, time.Now())
return in, out
}
func openAIContentFrames(n int) []string {
frames := make([]string, 0, n)
for i := 0; i < n; i++ {
frames = append(frames, `data: {"id":"c1","object":"chat.completion.chunk","choices":[{"delta":{"content":"hello world, this is a chunk of text "}}]}`+"\n\n")
}
return frames
}
func anthropicFrames(deltas int, withMessageDelta bool) []string {
frames := []string{
"event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_1\",\"usage\":{\"input_tokens\":100}}}\n\n",
"event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n",
}
for i := 0; i < deltas; i++ {
frames = append(frames, "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"hello world, this is a chunk of text \"}}\n\n")
}
if withMessageDelta {
frames = append(frames,
"event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":5000}}\n\n",
"event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n")
}
return frames
}
func TestOpenAIStreamHangup_BillsEstimatedCompletion(t *testing.T) {
srv := hangupServer(t, "text/event-stream", openAIContentFrames(12))
defer srv.Close()
gw := newStreamBillingGateway(t, providerTypeOpenAI, srv.URL, "gpt-test")
body := map[string]any{"model": "gpt-test", "stream": true, "messages": []any{map[string]any{"role": "user", "content": "hi"}}}
gw.ServeHTTP(newRecordingWriter(), newUnifiedRequest(t, http.MethodPost, "/v1/chat/completions", "sk-alice", body))
in, out := aliceTokens(gw)
if in <= 0 || out <= 0 {
t.Fatalf("tokin/tokout = %d/%d, want both > 0 after a hang-up that followed forwarded output", in, out)
}
}
func TestOpenAIStreamFullRead_BillsReportedUsage(t *testing.T) {
frames := append(openAIContentFrames(3),
`data: {"id":"c1","object":"chat.completion.chunk","choices":[],"usage":{"prompt_tokens":9,"completion_tokens":3000}}`+"\n\n",
"data: [DONE]\n\n")
srv := hangupServer(t, "text/event-stream", frames)
defer srv.Close()
gw := newStreamBillingGateway(t, providerTypeOpenAI, srv.URL, "gpt-test")
body := map[string]any{"model": "gpt-test", "stream": true, "messages": []any{map[string]any{"role": "user", "content": "hi"}}}
gw.ServeHTTP(newRecordingWriter(), newUnifiedRequest(t, http.MethodPost, "/v1/chat/completions", "sk-alice", body))
if in, out := aliceTokens(gw); in != 9 || out != 3000 {
t.Fatalf("tokin/tokout = %d/%d, want 9/3000", in, out)
}
}
func TestAnthropicChatStreamHangup_BillsEstimatedCompletion(t *testing.T) {
srv := hangupServer(t, "text/event-stream", anthropicFrames(20, false))
defer srv.Close()
gw := newStreamBillingGateway(t, providerTypeAnthropic, srv.URL, "claude-test")
body := map[string]any{"model": "claude-test", "stream": true, "max_tokens": 100, "messages": []any{map[string]any{"role": "user", "content": "hi"}}}
gw.ServeHTTP(newRecordingWriter(), newUnifiedRequest(t, http.MethodPost, "/v1/chat/completions", "sk-alice", body))
in, out := aliceTokens(gw)
if in != 100 || out <= 0 {
t.Fatalf("tokin/tokout = %d/%d, want 100 / >0", in, out)
}
}
func TestAnthropicMessagesRelayHangup_BillsEstimatedCompletion(t *testing.T) {
srv := hangupServer(t, "text/event-stream", anthropicFrames(20, false))
defer srv.Close()
gw := newStreamBillingGateway(t, providerTypeAnthropic, srv.URL, "claude-test")
body := map[string]any{"model": "claude-test", "stream": true, "max_tokens": 100, "messages": []any{map[string]any{"role": "user", "content": "hi"}}}
gw.ServeHTTP(httptest.NewRecorder(), newMessagesRequest(t, body, "x-api-key", "sk-alice"))
in, out := aliceTokens(gw)
if in != 100 || out <= 0 {
t.Fatalf("tokin/tokout = %d/%d, want 100 / >0", in, out)
}
}
func TestAnthropicStreamFullRead_BillsReportedUsage(t *testing.T) {
srv := hangupServer(t, "text/event-stream", anthropicFrames(3, true))
defer srv.Close()
gw := newStreamBillingGateway(t, providerTypeAnthropic, srv.URL, "claude-test")
body := map[string]any{"model": "claude-test", "stream": true, "max_tokens": 100, "messages": []any{map[string]any{"role": "user", "content": "hi"}}}
gw.ServeHTTP(newRecordingWriter(), newUnifiedRequest(t, http.MethodPost, "/v1/chat/completions", "sk-alice", body))
if in, out := aliceTokens(gw); in != 100 || out != 5000 {
t.Fatalf("tokin/tokout = %d/%d, want 100/5000", in, out)
}
}
func TestAnthropicStreamState_UsageOnAbortKeepsReportedCompletion(t *testing.T) {
st := newAnthropicStreamState("m", 1)
for _, ev := range []sseEvent{
{event: "message_start", data: []byte(`{"message":{"id":"x","usage":{"input_tokens":10}}}`)},
{event: "content_block_delta", data: []byte(`{"index":0,"delta":{"type":"text_delta","text":"abcdefgh"}}`)},
} {
if _, err := st.translate(ev); err != nil {
t.Fatal(err)
}
}
if u := st.usageOnAbort(); u.completion != 2 || !u.estimated {
t.Fatalf("before message_delta: completion=%d estimated=%v, want 2/true", u.completion, u.estimated)
}
if _, err := st.translate(sseEvent{event: "message_delta", data: []byte(`{"delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":77}}`)}); err != nil {
t.Fatal(err)
}
if u := st.usageOnAbort(); u.completion != 77 || u.estimated {
t.Fatalf("after message_delta: completion=%d estimated=%v, want 77/false", u.completion, u.estimated)
}
}
type failingReader struct{}
func (failingReader) Read([]byte) (int, error) { return 0, errors.New("hang-up") }
// Pin only: Gemini reports usageMetadata on every chunk, so an abort keeps the last one.
func TestGeminiStreamHangup_PinsLastUsageMetadata(t *testing.T) {
a, err := newGeminiAdapter("p1", "http://unused", "k")
if err != nil {
t.Fatal(err)
}
frame := fmt.Sprintf("data: %s\n\n", `{"candidates":[{"content":{"role":"model","parts":[{"text":"hello there"}]}}],"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":4}}`)
u, err := a.forwardStream(httptest.NewRecorder(), io.MultiReader(strings.NewReader(frame), failingReader{}), "g", false)
if err == nil {
t.Fatal("want a stream error")
}
if u.prompt != 10 || u.completion != 4 {
t.Fatalf("usage = %d/%d, want 10/4 (report to integrator if completion is 0)", u.prompt, u.completion)
}
}
+43
View File
@@ -0,0 +1,43 @@
package traefikllmgateway
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestMergeQueryStrings_UnparseableTargetQueryIsKept(t *testing.T) {
if got, want := mergeQueryStrings("token=s;v=1", "a=1"), "token=s;v=1&a=1"; got != want {
t.Errorf("got %q, want %q", got, want)
}
}
func TestMergeQueryStrings_ParseableUnchanged(t *testing.T) {
cases := []struct{ target, req, want string }{
{"token=s", "", "token=s"},
{"", "a=1", "a=1"},
{"token=s", "a=1", "a=1&token=s"},
{"a=1", "a=2", "a=1&a=2"},
{"token=s", "a=1;b=2", "token=s"},
}
for _, c := range cases {
if got := mergeQueryStrings(c.target, c.req); got != c.want {
t.Errorf("merge(%q, %q) = %q, want %q", c.target, c.req, got, c.want)
}
}
}
func TestBuildUpstreamTargetURL_SemicolonTargetQueryReachesUpstream(t *testing.T) {
var gotRaw string
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotRaw = r.URL.RawQuery
}))
defer up.Close()
h := newTargetRedirectGateway(t, up.URL+"/mcp?token=s;v=1", up.URL+"/a2a")
if rec := doTarget(h, "/mcp/alpha?a=1"); rec.Code != http.StatusOK {
t.Fatalf("status = %d", rec.Code)
}
if gotRaw != "token=s;v=1&a=1" {
t.Errorf("upstream raw query = %q, want %q", gotRaw, "token=s;v=1&a=1")
}
}
+92
View File
@@ -0,0 +1,92 @@
package traefikllmgateway
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
const redirectSecret = "SECRETQUERYTOKEN"
func newTargetRedirectGateway(t *testing.T, mcpURL, agentURL string) http.Handler {
t.Helper()
cfg := CreateConfig()
cfg.Providers = map[string]*ProviderConfig{"openai": {Type: "openai", APIKey: "k"}}
cfg.MCPServers = map[string]*TargetConfig{"alpha": {URL: mcpURL}}
cfg.Agents = map[string]*AgentConfig{"ag": {URL: agentURL}}
cfg.Groups = map[string]*GroupConfig{"default": {}}
cfg.Users = &UsersConfig{Inline: []*UserConfig{{Name: "alice", Group: "default", APIKey: "sk-alice"}}}
h, err := New(context.Background(), http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}), cfg, "llmgw")
if err != nil {
t.Fatalf("New: %v", err)
}
return h
}
func redirectingUpstream() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/tools") {
_, _ = w.Write([]byte("ok"))
return
}
http.Redirect(w, r, "http://elsewhere.invalid/x?"+r.URL.RawQuery, http.StatusTemporaryRedirect) //nolint:gosec // test upstream echoing the query
}))
}
func doTarget(h http.Handler, path string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodGet, path, nil)
req.Header.Set("Authorization", "Bearer sk-alice")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
func TestTargetProxy_RedirectWithTargetQueryNotRelayed(t *testing.T) {
up := redirectingUpstream()
defer up.Close()
h := newTargetRedirectGateway(t, up.URL+"/mcp?token="+redirectSecret, up.URL+"/a2a?token="+redirectSecret)
for _, path := range []string{"/mcp/alpha", "/a2a/ag"} {
rec := doTarget(h, path)
if rec.Code != http.StatusBadGateway {
t.Errorf("%s: status = %d, want 502", path, rec.Code)
}
if loc := rec.Header().Get("Location"); loc != "" {
t.Errorf("%s: Location relayed: %q", path, loc)
}
if strings.Contains(rec.Body.String(), redirectSecret) || strings.Contains(rec.Header().Get("Location"), redirectSecret) {
t.Errorf("%s: secret reached the client", path)
}
}
}
func TestTargetProxy_RedirectWithoutTargetQueryStillRelayed(t *testing.T) {
up := redirectingUpstream()
defer up.Close()
h := newTargetRedirectGateway(t, up.URL+"/mcp", up.URL+"/a2a")
rec := doTarget(h, "/mcp/alpha")
if rec.Code != http.StatusTemporaryRedirect || rec.Header().Get("Location") == "" {
t.Errorf("status = %d, Location = %q, want 307 relayed", rec.Code, rec.Header().Get("Location"))
}
}
func TestTargetProxy_ClientOnlyQueryRedirectStillRelayed(t *testing.T) {
up := redirectingUpstream()
defer up.Close()
h := newTargetRedirectGateway(t, up.URL+"/mcp", up.URL+"/a2a")
rec := doTarget(h, "/mcp/alpha?x=1")
if rec.Code != http.StatusTemporaryRedirect || rec.Header().Get("Location") == "" {
t.Errorf("status = %d, Location = %q, want 307 relayed", rec.Code, rec.Header().Get("Location"))
}
}
func TestTargetProxy_NonRedirectUnchanged(t *testing.T) {
up := redirectingUpstream()
defer up.Close()
h := newTargetRedirectGateway(t, up.URL+"/mcp?token="+redirectSecret, up.URL+"/a2a")
rec := doTarget(h, "/mcp/alpha/tools")
if rec.Code != http.StatusOK || rec.Body.String() != "ok" {
t.Errorf("status = %d body = %q, want 200 ok", rec.Code, rec.Body.String())
}
}
+19
View File
@@ -745,6 +745,8 @@ type anthropicStreamState struct {
created int64
nextToolOrdinal int
hasOutput bool
// outBytes counts forwarded delta text, for the estimate when the stream aborts before message_delta.
outBytes int64
}
// newAnthropicStreamState returns an anthropicStreamState for one
@@ -763,6 +765,17 @@ func (st *anthropicStreamState) usage() usage {
return withAnswerFlags(st.u, st.finish, st.hasOutput)
}
// usageOnAbort is usage() for a stream that ended in an error: with no
// reported completion it estimates one from the output already forwarded.
func (st *anthropicStreamState) usageOnAbort() usage {
u := st.usage()
if u.completion == 0 && st.outBytes > 0 {
u.completion = estimateCompletionTokens(st.outBytes)
u.estimated = true
}
return u
}
// chunk builds one OpenAI-shaped "chat.completion.chunk" payload carrying
// delta, and finishReason as its choices[0].finish_reason — nil for the
// JSON null every non-terminal chunk carries.
@@ -940,6 +953,7 @@ type anthropicContentBlockDeltaPayload struct {
Type string `json:"type"`
Text string `json:"text"`
PartialJSON string `json:"partial_json"`
Thinking string `json:"thinking"`
} `json:"delta"`
Index int `json:"index"`
}
@@ -1033,11 +1047,16 @@ func (st *anthropicStreamState) translate(ev sseEvent) ([][]byte, error) {
}
switch p.Delta.Type {
case "text_delta":
st.outBytes += int64(len(p.Delta.Text))
if p.Delta.Text != "" {
st.hasOutput = true
}
return [][]byte{st.content.build(p.Delta.Text)}, nil
case "thinking_delta":
st.outBytes += int64(len(p.Delta.Thinking))
return nil, nil
case "input_json_delta":
st.outBytes += int64(len(p.Delta.PartialJSON))
ordinal, ok := st.toolOrdinals[p.Index]
if !ok {
// Defensive: an input_json_delta for a content-block index
+24
View File
@@ -221,6 +221,30 @@ describe('breakerRows', () => {
it('returns nothing without an overview', () => {
expect(breakerRows(null)).toEqual([])
})
it('breakerRows marks a closed provider with upstreamErrors as degraded', () => {
const rows = breakerRows({ providers: [{ ...p('a', 'closed'), upstreamErrors: [{ upstream: 'http://x', error: 'boom' }] }] })
expect(rows[0]!.degraded).toBe(true)
})
it('breakerRows shows the first upstream error when lastErr is empty', () => {
const errs = [
{ upstream: 'http://x', error: 'boom' },
{ upstream: 'http://y', error: 'bang' },
]
const [one] = breakerRows({ providers: [{ ...p('a', 'closed'), upstreamErrors: errs.slice(0, 1) }] })
expect(one!.lastErr).toBe('http://x: boom')
const [two] = breakerRows({ providers: [{ ...p('a', 'closed'), upstreamErrors: errs }] })
expect(two!.lastErr).toBe('http://x: boom (+1 more)')
const [own] = breakerRows({ providers: [{ ...p('a', 'closed', { lastErr: 'real' }), upstreamErrors: errs }] })
expect(own!.lastErr).toBe('real')
})
it('breakerRows keeps a closed provider with neither healthy', () => {
const [row] = breakerRows({ providers: [{ ...p('a', 'closed'), upstreamErrors: [] }] })
expect(row!.degraded).toBe(false)
expect(row!.lastErr).toBe('')
})
})
describe('ratePercentSeries', () => {
+21 -9
View File
@@ -180,11 +180,11 @@ export interface BreakerRow {
state: ProviderHealthState
openUntil: string
lastErr: string
/** Closed breaker that still reports a last error. */
/** Closed breaker that still reports a last error or a failing upstream. */
degraded: boolean
}
type BreakerSource = Pick<AdminProviderView, 'name' | 'healthState' | 'openUntil' | 'lastErr'>
type BreakerSource = Pick<AdminProviderView, 'name' | 'healthState' | 'openUntil' | 'lastErr' | 'upstreamErrors'>
const BREAKER_STATE_ORDER: Record<ProviderHealthState, number> = { open: 0, 'half-open': 1, closed: 2 }
@@ -193,15 +193,27 @@ function breakerTier(r: BreakerRow): number {
return r.state === 'closed' && !r.degraded ? 3 : BREAKER_STATE_ORDER[r.state]
}
/** The last error, or the first upstream error (with a count of the rest) when there is none. */
function breakerErrText(p: BreakerSource): string {
if (p.lastErr) return p.lastErr
const ups = p.upstreamErrors ?? []
if (ups.length === 0) return ''
const first = `${ups[0]!.upstream}: ${ups[0]!.error}`
return ups.length > 1 ? `${first} (+${ups.length - 1} more)` : first
}
/** One row per provider, ordered open, half-open, degraded, healthy; ties by name. */
export function breakerRows(overview: { providers: ReadonlyArray<BreakerSource> } | null): BreakerRow[] {
const rows = (overview?.providers ?? []).map((p) => ({
provider: p.name,
state: p.healthState,
openUntil: p.openUntil,
lastErr: p.lastErr ?? '',
degraded: p.healthState === 'closed' && !!p.lastErr,
}))
const rows = (overview?.providers ?? []).map((p) => {
const lastErr = breakerErrText(p)
return {
provider: p.name,
state: p.healthState,
openUntil: p.openUntil,
lastErr,
degraded: p.healthState === 'closed' && lastErr !== '',
}
})
return rows.sort((a, b) => breakerTier(a) - breakerTier(b) || a.provider.localeCompare(b.provider))
}
+4 -1
View File
@@ -78,7 +78,10 @@ function showAll(): void {
<PanelSection title="Last error">
<p v-if="provider.lastErr" class="text-destructive m-0 text-sm break-words whitespace-pre-wrap" data-testid="provider-last-err">{{ provider.lastErr }}</p>
<p v-else class="text-muted-foreground m-0 text-sm">No error recorded.</p>
<ul v-if="provider.upstreamErrors?.length" class="m-0 flex list-none flex-col gap-1 p-0" :class="{ 'mt-2': provider.lastErr }" aria-label="Upstream errors" data-testid="provider-upstream-errors">
<li v-for="(e, i) in provider.upstreamErrors" :key="i" class="text-destructive text-sm break-words whitespace-pre-wrap">{{ e.upstream }}: {{ e.error }}</li>
</ul>
<p v-if="!provider.lastErr && !provider.upstreamErrors?.length" class="text-muted-foreground m-0 text-sm">No error recorded.</p>
</PanelSection>
<PanelSection title="Latency (time to first byte)">
+5 -2
View File
@@ -103,6 +103,8 @@ export interface AdminProviderView {
baseUrl: string
lastRefresh: string
lastErr?: string
/** modelBaseUrls upstreams whose discovery failed while the provider stayed healthy (admin.go: adminProviderView.UpstreamErrors). */
upstreamErrors?: Array<{ upstream: string; error: string }>
/** Sorted explicit∪discovered model ids (admin.go: adminProviderView.Models) — always an array, never omitted, even when empty. */
models: string[]
/** Display labels from the provider's `kinds` config, keyed by model id or endpoint path (admin.go: adminProviderView.Kinds). */
@@ -902,7 +904,8 @@ export interface AdminCatalogResponse {
/**
* One configured user's consumer-directory row (admin.go:
* adminConsumerUser — phase 2 redesign). `source` is 'inline' (defined
* directly in the plugin config) or 'file' (loaded from users.file);
* directly in the plugin config), 'file' (loaded from users.file) or
* 'anonymous' (the keyless principal);
* `providers`/`models` are this user's OWN personal grant, distinct from
* anything their group(s) already allow.
*/
@@ -910,7 +913,7 @@ export interface AdminConsumerUser {
limits?: LimitsConfig
limitSources?: LimitSources
name: string
source: 'inline' | 'file'
source: 'inline' | 'file' | 'anonymous'
groups: string[]
providers?: string[]
models?: string[]