fix(security): audit run-4 fixes and run-3 leftovers (#26)

Corrects passthrough metering, the cost gate, credential redaction, reload drain, response headers and the discovery cap.
This commit is contained in:
2026-11-29 10:50:36 +00:00
committed by GitHub
parent 009de03264
commit f1b198bce4
48 changed files with 3598 additions and 211 deletions
+65 -22
View File
@@ -178,9 +178,12 @@ can be lifted into a `ConfigMap` unchanged. `.json` is accepted directly.
The binary reads the config file every `-reload-interval` and on `SIGHUP`.
When the content changes, it builds a new gateway from the file. If that
succeeds, new requests go to the new gateway at once. Requests already
running finish on the old gateway, which then closes. A replaced gateway
that still has requests after `-reload-drain-timeout` closes anyway.
`-reload-drain-timeout` must be positive.
running finish on the old gateway, which then closes. The old gateway
stays open, with its Redis client, until its last request ends, however
long that takes. No request is cancelled. A replaced gateway that still has
requests after `-reload-drain-timeout` logs a warning with the running
count, and repeats it every `-reload-drain-timeout`. `-reload-drain-timeout`
must be positive.
- **A bad file changes nothing.** A file that does not parse, has an
unknown key or fails validation is logged at error level. The old
@@ -300,8 +303,9 @@ Unchanged, and no new flag: `oss-telemetry` reads `DO_NOT_TRACK`,
`OSS_TELEMETRY_DISABLED` and `TRAEFIK_LLMGATEWAY_DISABLE_TELEMETRY` from
the process environment, so setting one on the Deployment works exactly as
it does on the Traefik pod (see [Anonymous usage
reporting](#anonymous-usage-reporting)). The binary logs which opt-out is
set at startup. A locally built binary carries the `0.0.0-dev` sentinel
reporting](#anonymous-usage-reporting)). The binary logs an opt-out at
startup only for a value the client honours (`1`, `true`, `yes`, `on`) and
warns about any other non-empty value. A locally built binary carries the `0.0.0-dev` sentinel
and never pings regardless.
```yaml
@@ -411,7 +415,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. 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. |
| `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 object body whose top-level `model` is repeated, or is missing at any size (Gemini is exempt, since its model is in the URL). For a body over 64KiB the gateway first reads 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. A top-level key that equals `model` only without regard to case (`Model`, `MODEL`) is refused, alone or beside `model`, like a repeated `model`. A leading UTF-8 BOM is skipped. Three shapes are still not gated: a JSON body sent with a binary `Content-Type`, Gemini passthrough, whose model is in the URL, and a body under 64KiB that is not a UTF-8 JSON object (an array, a scalar, UTF-16 or UTF-32 JSON); all can reach an unpriced model at recorded cost `0`. A native endpoint whose JSON object has no `model`, such as batches, threads or vector stores, gets **402** for a caller with a cost budget. `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. |
@@ -1649,14 +1653,18 @@ model id) and per alias (`aliases[].modelMeta`) — see
`usageMetadata`. When a **non-streaming** unified-route response reports
no usage at all, the gateway falls back to a rough estimate —
`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 that ends
estimate — and marks it `estimated`. For this non-streaming
fallback the estimate lands entirely in the `tokin` counter below. 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`.
on openai-type and anthropic-type providers (a gemini-type stream has no estimate)
(openai-type: every string value in the delta except `role`, `id`, `type`, `name` and
audio `data`, counting escaped text at its decoded length and mirrored
reasoning text once; when none is counted, one token per forwarded output chunk;
anthropic-type: text, thinking and partial tool JSON only)
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
@@ -1786,6 +1794,24 @@ model id) and per alias (`aliases[].modelMeta`) — see
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`.
This applies to every configuration, not only cost-budgeted ones: the
estimate counts toward `tokout` and any token budget, so a passthrough
stream without usage can no longer record zero output tokens.
- **Native passthrough meters three usage shapes only.** A non-streaming
JSON reply over 4MiB is billed the usage it reports when the usage
object lies in the first 4MiB or the last 64KiB of the body (the last
top-level `usage` object wins; `usageMetadata` for Gemini, where an array
reply uses its last element with usage). Otherwise it is billed a
request-size prompt estimate and no completion, because a size-based
completion estimate would charge a large image reply about a million
phantom tokens. A JSON reply that the client cuts short before its
usage arrives is billed the same prompt estimate. Gemini thinking tokens (`thoughtsTokenCount`) count as
completion. The gateway reads OpenAI, Anthropic and Gemini usage in
JSON or SSE only. Other shapes are not metered: other usage field
names, Ollama-native replies, NDJSON streams, other content types, and
asynchronous APIs such as batches. A binary `Content-Type` request
body and a Gemini request whose model is in the URL are not gated by
the model checks either. Keep such endpoints out of `passthroughPaths`.
- **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
@@ -1817,6 +1843,11 @@ cache, and the upstream call itself (which can run for seconds to
minutes on a real completion) all happen with the slot already
released, so this never becomes a ceiling on total concurrent requests.
- A client that stalls its request body holds its slot until the
connection ends. The standalone binary sets no inbound body timeout, so
put a proxy with a request read timeout in front of it (Traefik or Cilium
Envoy) and do not expose port 8080 directly. The gateway has no cap on
slots held by one client.
- On exhaustion (every slot in use at that instant), the request gets an
immediate **503** with a `Retry-After` header — never queued, never
blocked.
@@ -2144,8 +2175,8 @@ cached bodies for the same request.
`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
`anthropic-beta` set (split on commas, case preserved, sorted, de-duplicated)
is also hashed in when present (a header made only of commas and spaces counts as absent and is not forwarded); 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
@@ -2379,7 +2410,9 @@ only once it has something to authorize:
multipart, `audio/*`, `image/*`, `video/*`, `application/octet-stream`
— is never read at all, since it cannot carry one). The field, when
found, is checked against `models` in both its bare and
`provider/model` forms. **A `model` field not found within that 64KiB
`provider/model` forms. A key that equals `model` only without regard
to case is refused (403, model could not be determined), alone or beside
`model`, and a leading UTF-8 BOM is skipped. **A `model` field not found within that 64KiB
window is DENIED (403)** — fail closed, not fail open. This includes a
**Gemini** passthrough request: Gemini's model id lives in the URL
path, never the JSON body, so a group with a restricted `models` list
@@ -2481,7 +2514,7 @@ Behavior depends entirely on the resolved provider's configured `type`:
A few translation specifics worth knowing:
- **`anthropic-beta` is forwarded** to an `anthropic`-type upstream (an
- **`anthropic-beta` is forwarded** to an `anthropic`-type upstream (a header of only commas and spaces is dropped; an
explicit allowlist — `Authorization`, `x-api-key`, `Cookie`, and every
hop-by-hop header are never forwarded, and the gateway's own credential
injection always overrides whatever the allowlist copied), so Claude
@@ -3570,12 +3603,15 @@ plugin's config.
the way out: an MCP server or A2A agent is treated as an in-cluster
target that trusts the gateway's network position, not a per-provider
key the gateway holds on the caller's behalf. A target `url` carrying
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. A target that carries a query string and
its own query string keeps it — the incoming request's own query string
is merged in alongside it, neither one overwriting the other. The query
string is not the only channel: userinfo in the `url` is accepted and
sent as Basic auth. Neither `TargetConfig` nor `AgentConfig` has a
header field. 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.
cannot reach the client through a redirect. The gateway removes the
configured credential from its logs and error text on a best-effort
basis, so treat the gateway log as sensitive.
- 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
@@ -3769,7 +3805,12 @@ plugin's config.
along with `Set-Cookie`, `Strict-Transport-Security`,
`Content-Security-Policy` and every `Access-Control-*` header
(`routes_passthrough.go`'s `dangerousResponseHeaders`), so a tenant
never learns which upstream account serves it.
never learns which upstream account serves it. Every response outside
`/admin` carries `X-Content-Type-Options: nosniff` and
`Content-Security-Policy: sandbox`, so a browser does not run a
relayed body as a page under the gateway origin. An upstream
`X-Content-Type-Options` value replaces the default; an upstream
`Content-Security-Policy` is always stripped.
- Neither kind of key is ever written to a log line — the logging helpers
(`logger.go`) carry an explicit "never log key material" contract.
`providerHTTPError`'s `Error()` string (`providers.go`) separately omits
@@ -3804,7 +3845,8 @@ versions are in use.
{ "project": "traefik-llmgateway", "version": "1.0.3", "ts": 1747782200 }
```
**What is never sent:** no identifiers, no hostname or IP, no machine
**What is never sent:** no identifiers, no hostname or IP in the payload
(the receiving server sees the connection's source address), no machine
information, no configuration, no provider names or base URLs, no API
keys, no user or group names, no model names, and nothing derived from a
request. The gateway sends the three fields above and nothing else.
@@ -3819,7 +3861,8 @@ request. The gateway sends the three fields above and nothing else.
- Only once per process, however many routes use the plugin.
**How to turn it off** in a release build — set any one of these in
Traefik's environment:
Traefik's environment to `1`, `true`, `yes` or `on` (case-insensitive;
any other value is ignored and reporting stays enabled):
```bash
DO_NOT_TRACK=1 # honours the do-not-track.dev convention
+129 -12
View File
@@ -308,29 +308,146 @@ func sanitizeProviderErr(lastErr, rawBaseURL string) string {
out := replaceURLForm(lastErr, rawBaseURL)
u, parseErr := url.Parse(rawBaseURL)
if parseErr != nil {
// The parse error quotes part of the URL (invalid port ":TOKEN").
if ue, ok := parseErr.(*url.Error); ok {
for _, r := range textRenderings(ue.Err.Error()) {
out = strings.ReplaceAll(out, r, errInvalidURLText)
}
}
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 u.User != nil {
if _, hasPassword := u.User.Password(); hasPassword {
// net/http's exact stripPassword output, mirrored call for call.
masked := strings.Replace(u.String(), u.User.String()+"@", u.User.Username()+":***@", 1)
out = replaceURLForm(out, masked)
}
}
if _, hasPassword := u.User.Password(); !hasPassword {
return out
}
// net/http's exact stripPassword output, mirrored call for call.
masked := strings.Replace(u.String(), u.User.String()+"@", u.User.Username()+":***@", 1)
return replaceURLForm(out, masked)
return scrubSecretComponents(out, u)
}
// replaceURLForm replaces every occurrence of one rendering of a URL in
// msg with sanitizeBaseURL's cleaned form of that same rendering.
// errInvalidURLText replaces a configured URL's parse error, which quotes
// part of the URL.
const errInvalidURLText = "invalid url"
// secretMinBytes and commonURLWords keep the component scrub from blanking
// short or ordinary text that a credential happens to equal.
const secretMinBytes = 4
var commonURLWords = map[string]bool{"http": true, "https": true, "true": true, "false": true, "null": true}
// secretRedaction replaces a credential component of the configured URL.
const secretRedaction = "***"
// replaceURLForm replaces every rendering of form in msg with
// sanitizeBaseURL's cleaned form of form itself.
func replaceURLForm(msg, form string) string {
if form == "" || !strings.Contains(msg, form) {
if form == "" {
return msg
}
return strings.ReplaceAll(msg, form, sanitizeBaseURL(form))
clean := sanitizeBaseURL(form)
for _, r := range textRenderings(form) {
if strings.Contains(msg, r) {
msg = strings.ReplaceAll(msg, r, clean)
}
}
return msg
}
// scrubSecretComponents redacts every rendering of u's userinfo and query
// parts. u must be the configured URL: a requested URL carries client
// text, which is neither secret nor cheap to scan.
func scrubSecretComponents(msg string, u *url.URL) string {
var secrets []string
if u.User != nil {
secrets = append(secrets, u.User.Username(), url.User(u.User.Username()).String())
if pw, ok := u.User.Password(); ok {
secrets = append(secrets, pw, url.UserPassword("", pw).String()[1:])
}
}
// Query() drops ";"-separated pairs and valueless keys, so split by hand.
for _, part := range strings.FieldsFunc(u.RawQuery, func(r rune) bool { return r == '&' || r == ';' }) {
// A name is a secret only when valueless (?TOKEN); otherwise it is a label such as timeout.
piece := part
if eq := strings.IndexByte(part, '='); eq >= 0 {
piece = part[eq+1:]
}
secrets = append(secrets, piece)
if dec, err := url.QueryUnescape(piece); err == nil {
secrets = append(secrets, dec)
}
}
var forms []string
for _, secret := range secrets {
if len(secret) < secretMinBytes || commonURLWords[strings.ToLower(secret)] {
continue
}
forms = append(forms, textRenderings(secret)...)
}
sort.Slice(forms, func(a, b int) bool {
if len(forms[a]) != len(forms[b]) {
return len(forms[a]) > len(forms[b])
}
return forms[a] < forms[b]
})
for _, f := range forms {
msg = strings.ReplaceAll(msg, f, secretRedaction)
}
return msg
}
// lowerPercentHex rewrites %XX escapes with lower-case hex digits.
func lowerPercentHex(s string) string {
b := []byte(s)
for i := 0; i+2 < len(b); i++ {
if b[i] == '%' {
b[i+1] = lowerASCII(b[i+1])
b[i+2] = lowerASCII(b[i+2])
}
}
return string(b)
}
func lowerASCII(c byte) byte {
if c >= 'A' && c <= 'F' {
return c + ('a' - 'A')
}
return c
}
// textRenderings lists s as Go's error paths print it: verbatim, as the
// body of a %q verb (*url.Error), and query- or path-escaped. Longest
// first, so a rendering that contains another is replaced whole.
func textRenderings(s string) []string {
quoted := strconv.Quote(s)
qe, pe := url.QueryEscape(s), url.PathEscape(s)
cands := []string{s, quoted[1 : len(quoted)-1], qe, pe, lowerPercentHex(qe), lowerPercentHex(pe)}
out := make([]string, 0, len(cands))
for _, c := range cands {
if c == "" {
continue
}
dup := false
for _, o := range out {
if o == c {
dup = true
break
}
}
if dup {
continue
}
pos := len(out)
out = append(out, c)
for pos > 0 && len(out[pos-1]) < len(c) {
out[pos], out[pos-1] = out[pos-1], out[pos]
pos--
}
}
return out
}
// adminProviderView is one provider's read-only view in GET
+3 -2
View File
@@ -181,6 +181,7 @@ func effectiveTTL(c *responseCache, grp *group) time.Duration {
// Body automatically (it is a []byte field), matching spec §2's "value:
// JSON {status, contentType, body(base64)}".
type cachedResponse struct {
// ContentType is upstream-chosen and replayed verbatim on a hit.
ContentType string `json:"contentType"`
Body []byte `json:"body"`
Status int `json:"status"`
@@ -459,12 +460,12 @@ func cacheKey(provider, upstreamModel, requestedModel, endpoint string, req map[
}
// normalizeBetaSet canonicalises anthropic-beta header values into one
// sorted, de-duplicated, lower-case comma list; "" when no value is set.
// sorted, de-duplicated comma list; names keep their case, as Anthropic documents the exact name as the value; "" 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))
f = strings.TrimSpace(f)
if f != "" {
parts = append(parts, f)
}
+9 -1
View File
@@ -94,7 +94,7 @@ func TestMessagesCache_DifferentBetaValuesDoNotShare(t *testing.T) {
func TestMessagesCache_SameBetaSetSharesRegardlessOfOrder(t *testing.T) {
f := newBetaCacheFixture(t, false)
f.send(t, "a,b")
if got := f.send(t, "b, A"); got != "hit" {
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)
}
}
@@ -120,3 +120,11 @@ func TestMessagesCache_StripClientBetaIgnoresHeader(t *testing.T) {
t.Fatalf("X-Llmgw-Cache = %q, want hit: with stripClientAnthropicBeta the header is not forwarded", got)
}
}
func TestMessagesCache_BetaCaseVariantsDoNotShare(t *testing.T) {
f := newBetaCacheFixture(t, false)
f.send(t, "context-1m")
if got := f.send(t, "Context-1M"); got == "hit" {
t.Fatal("beta names differing only in case shared a cache entry")
}
}
+24 -10
View File
@@ -142,7 +142,7 @@ func parseOptions(args []string, stderr *os.File) (*options, error) {
fs.DurationVar(&o.reloadEvery, "reload-interval", envDurationOr("LLMGW_RELOAD_INTERVAL", defaultReloadEvery),
"how often to check the config file for changes; 0 turns polling off (SIGHUP still reloads) [LLMGW_RELOAD_INTERVAL]")
fs.DurationVar(&o.reloadDrain, "reload-drain-timeout", envDurationOr("LLMGW_RELOAD_DRAIN_TIMEOUT", defaultReloadDrain),
"how long a replaced gateway keeps running for its in-flight requests before it is closed [LLMGW_RELOAD_DRAIN_TIMEOUT]")
"how long to wait before warning that a replaced gateway still has in-flight requests; it closes only when the last one ends [LLMGW_RELOAD_DRAIN_TIMEOUT]")
fs.BoolVar(&o.showVersion, "version", false, "print this binary's version and exit")
if err := fs.Parse(args); err != nil {
return nil, err
@@ -260,7 +260,7 @@ func run() error {
}
sw := &swapHandler{}
sw.cur.Store(newGeneration(handler, func() { closeGateway(handler, log) }))
sw.cur.Store(loggedGeneration(handler, log, opts.reloadDrain))
var ready atomic.Bool
srv := &http.Server{
@@ -367,7 +367,8 @@ func run() error {
// The reloader exits on ctx; waiting for it means no swap lands after the close below.
<-reloadDone
// STRICTLY after Shutdown returns. Close releases the pooled Redis
// STRICTLY after Shutdown returns; when it timed out, requests still
// running are abandoned and lose their last Redis writes. Close releases the pooled Redis
// connections shared by the limiter's store and the response cache;
// closing them while requests are still draining would pull Redis out
// from under in-flight handlers, and under the common redis.failOpen
@@ -579,23 +580,36 @@ func yamlToJSON(raw []byte) ([]byte, error) {
return j, nil
}
// logTelemetryOptOut reports which anonymous-telemetry opt-out variable is
// set, if any, so a deployment that believes it opted out can confirm it
// from the startup log. It deliberately does not claim whether a ping
// will actually be sent: that also depends on the build being
// version-stamped, and the root package's decision function is
// unexported.
// logTelemetryOptOut confirms an opt-out only when the client will act on it,
// so a deployment that believes it opted out can trust the startup log. A
// non-empty value the client ignores gets a warning instead. It does not
// claim a ping will be sent: that also depends on the build being
// version-stamped, and the root package's decision function is unexported.
func logTelemetryOptOut(log *logger) {
for _, k := range telemetryOptOutVars {
if v := os.Getenv(k); v != "" {
if v := os.Getenv(k); telemetryTruthy(v) {
log.info("anonymous usage reporting opted out via %s=%s", k, v)
return
}
}
for _, k := range telemetryOptOutVars {
if v := os.Getenv(k); v != "" {
log.warn("%s=%s is not a recognised opt-out value (1, true, yes, on); reporting stays enabled", k, v)
}
}
log.info("anonymous usage reporting not opted out (set DO_NOT_TRACK=1 to disable); " +
"only version-stamped release builds ever send a ping")
}
// telemetryTruthy mirrors the opt-out values oss-telemetry accepts (its telemetry.go, truthy).
func telemetryTruthy(s string) bool {
switch strings.ToLower(strings.TrimSpace(s)) {
case "1", "true", "yes", "on":
return true
}
return false
}
// logger is this binary's own leveled logger. It governs ONLY the
// lifecycle lines written here — the gateway's own output goes straight
// to stderr from the root package's unexported helpers and cannot be
+44 -7
View File
@@ -19,8 +19,10 @@ const genRetired int64 = 1 << 62
// generation is one constructed gateway and the requests running on it.
type generation struct {
h http.Handler
closeFn func()
h http.Handler
closeFn func()
// overdue reports a generation that outlived its drain timeout, with the requests still running on it.
overdue func(running int64)
timer atomic.Pointer[time.Timer]
state atomic.Int64
once sync.Once
@@ -31,6 +33,17 @@ func newGeneration(h http.Handler, closeFn func()) *generation {
return &generation{h: h, closeFn: closeFn}
}
const overdueFormat = "reload: a replaced gateway still has %d running requests after %s; it stays open until they end"
// loggedGeneration wraps h in a generation that closes the gateway and warns when it outlives drain once retired.
func loggedGeneration(h http.Handler, log *logger, drain time.Duration) *generation {
g := newGeneration(h, func() { closeGateway(h, log) })
g.overdue = func(running int64) {
log.warn(overdueFormat, running, drain)
}
return g
}
// enter counts a request in. It returns false when the generation is retired; the caller must not serve on it.
func (g *generation) enter() bool {
if g.state.Add(1)&genRetired != 0 {
@@ -46,7 +59,9 @@ func (g *generation) leave() {
}
}
// retire stops new requests. The gateway closes when the last running request leaves, or after maxWait.
// retire stops new requests. The gateway closes when the last running request leaves, however long that takes.
// A request is never cancelled: closing the gateway under it would drop its Redis-backed accounting.
// Each maxWait after the retire, a generation that still has requests reports them through overdue.
func (g *generation) retire(maxWait time.Duration) {
if !g.markRetired() {
return
@@ -54,7 +69,20 @@ func (g *generation) retire(maxWait time.Duration) {
// Idle MCP event streams have no end of their own; ending them lets their
// clients reconnect to the new generation and this one close.
drainIdleStreams(g.h)
g.timer.Store(time.AfterFunc(maxWait, g.shut))
g.armOverdue(maxWait)
}
// armOverdue schedules the next overdue report in d.
func (g *generation) armOverdue(d time.Duration) {
g.timer.Store(time.AfterFunc(d, func() {
if g.shutDone.Load() {
return
}
if g.overdue != nil {
g.overdue(g.state.Load() &^ genRetired)
}
g.armOverdue(d)
}))
// A shut that ran before the Store could not stop the timer, so stop it here.
if g.shutDone.Load() {
g.stopTimer()
@@ -79,7 +107,7 @@ func (g *generation) markRetired() bool {
}
}
// shut closes the gateway once and stops the drain timer, so a closed generation is not held until it fires.
// shut closes the gateway once and stops the overdue timer, so a closed generation is not held until it fires.
func (g *generation) shut() {
g.once.Do(func() {
g.closeFn()
@@ -102,12 +130,17 @@ type swapHandler struct {
func (s *swapHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
for {
g := s.cur.Load()
// A false enter means a swap already installed a newer generation, so the next load finds it.
if g.enter() {
defer g.leave()
g.h.ServeHTTP(w, r)
return
}
// A swap installs the newer generation before it retires the old one, so an unchanged
// pointer means closeCurrent ran and no other generation will come.
if s.cur.Load() == g {
http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)
return
}
}
}
@@ -195,7 +228,11 @@ func (r *reloader) check(force bool) {
}
r.buildErr = ""
r.last = sum
r.swap.swap(newGeneration(h, func() { closeGateway(h, r.log) }), r.drain)
g := newGeneration(h, func() { closeGateway(h, r.log) })
g.overdue = func(running int64) {
r.log.warn(overdueFormat, running, r.drain)
}
r.swap.swap(g, r.drain)
r.log.info("reload: config %s applied", r.path)
}
+140
View File
@@ -0,0 +1,140 @@
package main
import (
"net/http"
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
// fakeRedis stands in for the shared Redis client: closing it makes later use fail, as in a real closed pool.
type fakeRedis struct {
closed atomic.Bool
writes atomic.Int32
failed atomic.Int32
}
func (f *fakeRedis) incr() {
if f.closed.Load() {
f.failed.Add(1)
return
}
f.writes.Add(1)
}
func waitFor(t *testing.T, what string, cond func() bool) {
t.Helper()
deadline := time.Now().Add(3 * time.Second)
for !cond() {
if time.Now().After(deadline) {
t.Fatalf("timed out waiting for %s", what)
}
time.Sleep(2 * time.Millisecond)
}
}
// TestGenerationOutlivingDrainTimeoutStaysOpen: a request that runs past the drain timeout still reaches its
// Redis-backed state, and the generation closes only after that request leaves.
func TestGenerationOutlivingDrainTimeoutStaysOpen(t *testing.T) {
redis := &fakeRedis{}
var closes atomic.Int32
release := make(chan struct{})
started := make(chan struct{})
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
close(started)
<-release
redis.incr()
w.WriteHeader(http.StatusNoContent)
})
oldGen := newGeneration(h, func() { closes.Add(1); redis.closed.Store(true) })
var warned atomic.Int32
oldGen.overdue = func(int64) { warned.Add(1) }
sw := &swapHandler{}
sw.cur.Store(oldGen)
done := make(chan struct{})
rec := httptest.NewRecorder()
go func() {
sw.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
close(done)
}()
<-started
sw.swap(newGeneration(okHandler(), func() {}), 15*time.Millisecond)
waitFor(t, "the overdue warning", func() bool { return warned.Load() >= 1 })
if closes.Load() != 0 {
t.Fatalf("generation closed %d times under a running request", closes.Load())
}
close(release)
<-done
if redis.writes.Load() != 1 || redis.failed.Load() != 0 {
t.Errorf("request after the timeout: writes=%d failed=%d, want 1 and 0", redis.writes.Load(), redis.failed.Load())
}
if closes.Load() != 1 {
t.Errorf("closes = %d after the last request left, want 1", closes.Load())
}
}
func TestGenerationWarnsRepeatedlyWithRunningCount(t *testing.T) {
var closes atomic.Int32
g := countingGen(okHandler(), &closes)
var mu sync.Mutex
var counts []int64
g.overdue = func(n int64) {
mu.Lock()
counts = append(counts, n)
mu.Unlock()
}
g.enter()
g.enter()
g.retire(10 * time.Millisecond)
waitFor(t, "two warnings", func() bool { mu.Lock(); defer mu.Unlock(); return len(counts) >= 2 })
g.leave()
g.leave()
if closes.Load() != 1 {
t.Fatalf("closes = %d, want 1", closes.Load())
}
mu.Lock()
n := len(counts)
first := counts[0]
mu.Unlock()
if first != 2 {
t.Errorf("first warning counted %d running requests, want 2", first)
}
time.Sleep(50 * time.Millisecond)
mu.Lock()
defer mu.Unlock()
if len(counts) != n {
t.Errorf("warnings continued after the generation closed: %d then %d", n, len(counts))
}
}
func TestGenerationNoWarningWhenDrainedInTime(t *testing.T) {
var closes atomic.Int32
g := countingGen(okHandler(), &closes)
var warned atomic.Int32
g.overdue = func(int64) { warned.Add(1) }
g.enter()
g.retire(20 * time.Millisecond)
g.leave()
time.Sleep(60 * time.Millisecond)
if warned.Load() != 0 || closes.Load() != 1 {
t.Errorf("warned=%d closes=%d, want 0 and 1", warned.Load(), closes.Load())
}
}
// TestLoggedGenerationWarnsWhenOverdue covers the generation that main installs first: its first replacement must warn too.
func TestLoggedGenerationWarnsWhenOverdue(t *testing.T) {
g := loggedGeneration(okHandler(), newLogger("info"), 10*time.Millisecond)
g.enter()
out := captureTelemetryStderr(t, func() {
// Called directly: a timer callback could still log while captureTelemetryStderr restores os.Stderr.
g.overdue(1)
})
if !strings.Contains(out, "still has 1 running requests") {
t.Errorf("no overdue warning from the initial generation: %q", out)
}
}
+69
View File
@@ -0,0 +1,69 @@
package main
import (
"bytes"
"context"
"io"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
const reloadTargetMarker = "DUMMY-RELOAD-TARGET-0006"
func captureStderr(t *testing.T, fn func()) string {
t.Helper()
orig := os.Stderr
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
os.Stderr = w
defer func() { os.Stderr = orig }()
fn()
_ = w.Close()
var buf bytes.Buffer
if _, err := io.Copy(&buf, r); err != nil {
t.Fatal(err)
}
return buf.String()
}
func TestReloadRejectionLog_OmitsTargetCredential(t *testing.T) {
const tmpl = `providers:
openai:
type: openai
apiKey: test-key
models:
- model-a
mcpServers:
alpha:
url: "%s"
`
for name, raw := range map[string]string{
"mistyped scheme": "htps://mcp.invalid/mcp?api-key=" + reloadTargetMarker,
"unparseable": "https://u:" + reloadTargetMarker + "@mcp.invalid:99x/mcp",
} {
t.Run(name, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "config.yaml")
if err := os.WriteFile(path, []byte(strings.Replace(tmpl, "%s", raw, 1)), 0o600); err != nil {
t.Fatal(err)
}
log := newLogger("error")
build := gatewayBuilder(context.Background(), path, "test", log)
sw := &swapHandler{}
sw.cur.Store(newGeneration(okHandler(), func() {}))
r := newReloader(path, []byte("previous"), build, sw, time.Hour, log)
t.Cleanup(sw.closeCurrent)
out := captureStderr(t, func() { r.check(false) })
if !strings.Contains(out, "rejected") {
t.Fatalf("precondition: no rejection logged: %q", out)
}
if strings.Contains(out, reloadTargetMarker) {
t.Errorf("rejection log carries the target credential: %q", out)
}
})
}
}
+24 -5
View File
@@ -66,21 +66,26 @@ func TestGenerationLifecycle(t *testing.T) {
}
}
func TestGenerationDrainTimeoutForcesClose(t *testing.T) {
func TestGenerationDrainTimeoutKeepsGatewayOpen(t *testing.T) {
var closes atomic.Int32
g := countingGen(okHandler(), &closes)
var warned atomic.Int32
g.overdue = func(int64) { warned.Add(1) }
g.enter()
g.retire(20 * time.Millisecond)
deadline := time.Now().Add(2 * time.Second)
for closes.Load() == 0 && time.Now().Before(deadline) {
for warned.Load() == 0 && time.Now().Before(deadline) {
time.Sleep(5 * time.Millisecond)
}
if closes.Load() != 1 {
t.Fatalf("closes = %d after the drain timeout, want 1", closes.Load())
if warned.Load() == 0 {
t.Fatal("no warning after the drain timeout")
}
if closes.Load() != 0 {
t.Fatalf("closes = %d after the drain timeout, want 0", closes.Load())
}
g.leave()
if closes.Load() != 1 {
t.Errorf("a leave after the forced close closed again: %d", closes.Load())
t.Errorf("closes = %d after the last leave, want 1", closes.Load())
}
}
@@ -186,6 +191,20 @@ func TestCloseCurrentTurnsAwayLaterRequests(t *testing.T) {
if g.enter() {
t.Error("enter after closeCurrent must return false")
}
rec := httptest.NewRecorder()
served := make(chan struct{})
go func() {
defer close(served)
sw.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
}()
select {
case <-served:
case <-time.After(2 * time.Second):
t.Fatal("ServeHTTP did not return after closeCurrent")
}
if rec.Code != http.StatusServiceUnavailable {
t.Errorf("status = %d, want 503", rec.Code)
}
}
func TestShutStopsDrainTimer(t *testing.T) {
+121
View File
@@ -0,0 +1,121 @@
package main
import (
"io"
"net/http"
"os"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/lukaszraczylo/oss-telemetry"
)
// captureTelemetryStderr returns what fn writes to os.Stderr.
func captureTelemetryStderr(t *testing.T, fn func()) string {
t.Helper()
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
old := os.Stderr
os.Stderr = w
fn()
os.Stderr = old
_ = w.Close()
b, err := io.ReadAll(r)
if err != nil {
t.Fatal(err)
}
return string(b)
}
// setOptOutEnv clears every opt-out variable, then applies set.
func setOptOutEnv(t *testing.T, set map[string]string) {
t.Helper()
for _, k := range telemetryOptOutVars {
t.Setenv(k, "")
}
for k, v := range set {
t.Setenv(k, v)
}
}
func TestLogTelemetryOptOut_NonTruthyValuesAreNotReportedAsOptedOut(t *testing.T) {
for _, v := range []string{"y", "enabled", "0", "false", "disabled", "t"} {
t.Run(v, func(t *testing.T) {
setOptOutEnv(t, map[string]string{"DO_NOT_TRACK": v})
out := captureTelemetryStderr(t, func() { logTelemetryOptOut(newLogger("info")) })
if strings.Contains(out, "opted out via") {
t.Errorf("value %q reported as an opt-out: %s", v, out)
}
if !strings.Contains(out, "not a recognised opt-out value") {
t.Errorf("value %q got no warning: %s", v, out)
}
if !strings.Contains(out, "not opted out") {
t.Errorf("value %q: missing the not-opted-out line: %s", v, out)
}
})
}
}
func TestLogTelemetryOptOut_SkipsNonTruthyVariableToFindTruthyOne(t *testing.T) {
setOptOutEnv(t, map[string]string{"DO_NOT_TRACK": "0", "OSS_TELEMETRY_DISABLED": "1"})
out := captureTelemetryStderr(t, func() { logTelemetryOptOut(newLogger("info")) })
if !strings.Contains(out, "opted out via OSS_TELEMETRY_DISABLED=1") {
t.Errorf("the truthy variable was not reported: %s", out)
}
if strings.Contains(out, "DO_NOT_TRACK=0") {
t.Errorf("a non-truthy variable was reported: %s", out)
}
}
func TestLogTelemetryOptOut_TruthyValues(t *testing.T) {
for _, v := range []string{"1", "true", "yes", "on", " TRUE ", "On"} {
t.Run(v, func(t *testing.T) {
setOptOutEnv(t, map[string]string{"TRAEFIK_LLMGATEWAY_DISABLE_TELEMETRY": v})
out := captureTelemetryStderr(t, func() { logTelemetryOptOut(newLogger("info")) })
if !strings.Contains(out, "opted out via TRAEFIK_LLMGATEWAY_DISABLE_TELEMETRY=") {
t.Errorf("value %q not reported as an opt-out: %s", v, out)
}
})
}
}
func TestLogTelemetryOptOut_UnsetIsSilentAboutValues(t *testing.T) {
setOptOutEnv(t, nil)
out := captureTelemetryStderr(t, func() { logTelemetryOptOut(newLogger("info")) })
if strings.Contains(out, "WARN") || strings.Contains(out, "opted out via") {
t.Errorf("unset environment produced an opt-out or a warning: %s", out)
}
}
type recordingTransport struct{ n atomic.Int32 }
func (r *recordingTransport) RoundTrip(*http.Request) (*http.Response, error) {
r.n.Add(1)
return &http.Response{StatusCode: http.StatusNoContent, Body: http.NoBody}, nil
}
// TestTelemetryPredicateMatchesVendoredClient drives the real client over a recording transport, so no ping leaves
// the machine, and checks that the log's opt-out decision equals whether the client sent nothing.
func TestTelemetryPredicateMatchesVendoredClient(t *testing.T) {
rt := &recordingTransport{}
old := http.DefaultTransport
http.DefaultTransport = rt
t.Cleanup(func() { http.DefaultTransport = old })
for _, v := range []string{"1", "true", "yes", "on", " Yes ", "TRUE", "0", "false", "y", "t", "enabled", "disabled", "off", "2"} {
for _, k := range telemetryOptOutVars {
setOptOutEnv(t, map[string]string{k: v})
before := rt.n.Load()
telemetry.Send("traefik-llmgateway", "1.0.0")
telemetry.Wait(2 * time.Second)
sent := rt.n.Load() != before
if got := !telemetryTruthy(v); sent != got {
t.Errorf("%s=%q: client sent=%v, predicate says it sends=%v", k, v, sent, got)
}
}
}
}
+81 -1
View File
@@ -52,6 +52,44 @@ func TestDiscovery_AtCapAccepted(t *testing.T) {
}
}
func TestBoundDiscoveredIDs_RepeatedIDsCountOnce(t *testing.T) {
cases := map[string]struct {
explicit map[string]bool
ids []string
wantKept int
wantDropped int
}{
"copies of an explicit id cannot pass the cap": {
ids: append(repeatID("m-x", maxDiscoveredModels*2), "other"), explicit: map[string]bool{"m-x": true}, wantKept: 2,
},
"copies do not evict distinct ids": {
ids: append(repeatID("a", maxDiscoveredModels), manyIDs(10)...), wantKept: 11,
},
"copies are not reported as dropped": {
ids: append(repeatID("a", 3), "", "bad\nid"), wantKept: 1, wantDropped: 2,
},
"distinct ids past the cap are still dropped": {
ids: append(manyIDs(maxDiscoveredModels+5), manyIDs(7)...), wantKept: maxDiscoveredModels, wantDropped: 5,
},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
kept, dropped := boundDiscoveredIDs(c.ids, c.explicit)
if len(kept) != c.wantKept || dropped != c.wantDropped {
t.Errorf("kept %d dropped %d, want %d and %d", len(kept), dropped, c.wantKept, c.wantDropped)
}
})
}
}
func repeatID(id string, n int) []string {
ids := make([]string, n)
for i := range ids {
ids[i] = id
}
return ids
}
func TestDiscovery_OverCountKeepsCapAndLogsDebounced(t *testing.T) {
var mu sync.Mutex
var lines []string
@@ -67,7 +105,7 @@ func TestDiscovery_OverCountKeepsCapAndLogsDebounced(t *testing.T) {
t.Errorf("discovered = %d, want %d", got, maxDiscoveredModels)
}
st.mu.Lock()
over := st.discovered["m-"+fmt.Sprint(maxDiscoveredModels)]
over := st.discovered["m-9999"] // lexicographically last, so the first surplus id dropped
st.mu.Unlock()
if over {
t.Error("an id past the cap was kept")
@@ -92,3 +130,45 @@ func TestDiscovery_OverCountKeepsCapAndLogsDebounced(t *testing.T) {
t.Errorf("drop log lines after the window = %d, want 2", n)
}
}
func TestDiscovery_OverCountKeepsExplicitIDsAndIsDeterministic(t *testing.T) {
adapters := map[string]providerAdapter{"openai": newFakeAdapter("openai")}
cfg := &Config{Providers: map[string]*ProviderConfig{"openai": {
Models: []string{"zz-model"},
ModelBaseURLs: map[string]string{"zz-routed": "http://other.invalid"},
}}}
run := func(ids []string) map[string]bool {
reg, err := newModelRegistry(adapters, cfg, func(string, ...any) {})
if err != nil {
t.Fatalf("newModelRegistry: %v", err)
}
st := reg.states["openai"]
reg.finishRefresh(st, reg.now(), ids, nil)
st.mu.Lock()
defer st.mu.Unlock()
got := make(map[string]bool, len(st.discovered))
for id := range st.discovered {
got[id] = true
}
return got
}
ids := append(manyIDs(maxDiscoveredModels+50), "zz-model", "zz-routed")
rev := make([]string, len(ids))
for i, id := range ids {
rev[len(ids)-1-i] = id
}
a, b := run(ids), run(rev)
for _, id := range []string{"zz-model", "zz-routed"} {
if !a[id] || !b[id] {
t.Errorf("explicit id %q dropped by the cap", id)
}
}
if len(a) != maxDiscoveredModels {
t.Errorf("kept %d ids, want %d", len(a), maxDiscoveredModels)
}
for id := range a {
if !b[id] {
t.Fatalf("kept set depends on listing order: %q only in the forward run", id)
}
}
}
+4
View File
@@ -570,6 +570,10 @@ type usage struct {
// upstream cut it at the output cap, or returned neither text nor a tool
// call. Smart router outcome counters read them; billing ignores them.
finishLength, emptyOutput bool
// noStore keeps a reply the route could not fully re-encode (a valid
// but non-object JSON body relayed unrewritten) out of the response
// cache, so it can never be served in place of a live upstream reply.
noStore bool
// cached is the part of prompt the provider served from its prompt
// cache (Anthropic cache reads, OpenAI cached_tokens). The minute token
// window excludes it; the day and month windows keep the full prompt.
+11 -1
View File
@@ -943,7 +943,8 @@ var telemetryStartupOnce sync.Once
// never phone home. Operators of a RELEASE build opt out with any of
// DO_NOT_TRACK=1, OSS_TELEMETRY_DISABLED=1, or
// TRAEFIK_LLMGATEWAY_DISABLE_TELEMETRY=1 (oss-telemetry reads all three;
// the last is this project's name uppercased with dashes replaced). This
// the last is this project's name uppercased with dashes replaced). Only
// 1, true, yes and on count (case-insensitive); other values are ignored. This
// is documented in README.md — a plugin that phones home without saying
// so in its own README would be indefensible.
func sendStartupTelemetry() {
@@ -1487,6 +1488,13 @@ func (g *Gateway) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if g.cfg.MaxConcurrency > 0 {
sw.Header().Set(rateLimitPolicyHeader, concurrencyPolicyValue(g.cfg.MaxConcurrency))
}
var outerHardening http.Header
if g.cfg.PassthroughUnknown {
outerHardening = saveRelayHardeningHeaders(sw.Header())
}
if !isAdminPath(r.URL.Path) {
setRelayHardeningHeaders(sw.Header())
}
// pruneRejectionsAfterReload only runs when maybeReload just performed
// a REAL reload (users_file.go's own doc comment explains why it must
// never run on every request) — a deleted file-sourced user must not
@@ -1659,6 +1667,8 @@ func (g *Gateway) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
if g.cfg.PassthroughUnknown {
// The downstream app owns its own response headers.
restoreRelayHardeningHeaders(sw.Header(), outerHardening)
g.next.ServeHTTP(sw, r)
return
}
+35 -8
View File
@@ -1,7 +1,9 @@
package traefikllmgateway
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
@@ -161,7 +163,8 @@ func (g *Gateway) resolveTarget(kind, name string, grp *group) (targetURL string
// credential is injected (proxyUpstream's injectAuth argument is nil):
// MCP servers and A2A agents are in-cluster targets that trust the
// gateway's network position, not a per-provider API key the gateway
// holds on the caller's behalf. Accounting is likewise passthrough-only —
// holds on the caller's behalf. The configured target url can still carry
// a credential in its query or userinfo. Accounting is likewise passthrough-only —
// a target request is counted by checkAndCount below (the caller's own
// user/group/total scopes) and, additionally, attributed to name's own
// per-target scope (limiter.countTargetRequest, Feature B v0.21) — but its
@@ -243,7 +246,7 @@ func (g *Gateway) handleTargetProxy(w http.ResponseWriter, r *http.Request, u *u
// recordTargetProxyHealth's own doc comment for the exact
// success/failure rule.
start := time.Now()
result, ok := g.proxyUpstream(w, r, upstreamURL, g.targetClient, nil, nil, false, kind+" target (name "+name+")", g.targetTimeout, kind == targetKindMCP)
result, ok := g.proxyUpstream(w, withConfiguredURL(r, targetURL), upstreamURL, g.targetClient, nil, nil, false, kind+" target (name "+name+")", g.targetTimeout, kind == targetKindMCP)
g.recordTargetProxyHealth(kind, name, targetURL, result, ok, time.Since(start))
g.recordProxyEvent(scopes, name, kind, result) // F3 hook 3 (v0.3 dashboard task)
}
@@ -256,8 +259,9 @@ func (g *Gateway) handleTargetProxy(w http.ResponseWriter, r *http.Request, u *u
// round 3, 2026-09): the prior "+ \"/\" + rest" produced a doubled slash
// whenever targetURL's own path already ended in "/" (e.g. configured as
// "http://x/mcp/"), and, worse, a targetURL carrying its own query string
// — the only way TargetConfig/AgentConfig can pass a credential to an
// upstream today, since neither carries a header field — got that query
// — one of two ways TargetConfig/AgentConfig can pass a credential to an
// upstream today (the other is userinfo, sent as Basic auth), since neither
// carries a header field — got that query
// glued onto the wrong side of "?" + the request's own RawQuery,
// producing something like "...?token=abc/foo" or two "?" characters and
// corrupting the token federation was relying on. The target's own query
@@ -267,7 +271,7 @@ func (g *Gateway) handleTargetProxy(w http.ResponseWriter, r *http.Request, u *u
func buildUpstreamTargetURL(targetURL, rest, requestRawQuery string) (string, error) {
base, err := url.Parse(targetURL)
if err != nil {
return "", err
return "", errTargetURLUnparseable
}
joined := base
if rest != "" {
@@ -358,18 +362,24 @@ func validateTargetURLs(cfg *Config) error {
}
// validateTargetURL reports an error unless raw parses as a URL with an
// http or https scheme.
// http or https scheme. The errors are fixed text: raw, its scheme and the
// parse error all echo a configured credential.
func validateTargetURL(raw string) error {
u, err := url.Parse(raw)
if err != nil {
return fmt.Errorf("invalid url %q: %w", raw, err)
return errTargetURLUnparseable
}
if u.Scheme != "http" && u.Scheme != "https" {
return fmt.Errorf("url %q must use http or https scheme, got %q", raw, u.Scheme)
return errTargetURLScheme
}
return nil
}
var (
errTargetURLUnparseable = errors.New(errInvalidURLText)
errTargetURLScheme = errors.New("url must use the http or https scheme")
)
// 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 {
@@ -388,3 +398,20 @@ func queryAddedByGateway(upstreamURL, clientRawQuery string) bool {
}
return false
}
// configuredURLKey must differ in size from every other context key: Yaegi
// matches zero-size struct keys across types (see latencyRecorderCtxKey).
type configuredURLKey struct{ _ [3]byte }
// withConfiguredURL records the operator-configured URL behind a proxied
// request, so error scrubbing never derives secrets from client text.
func withConfiguredURL(r *http.Request, raw string) *http.Request {
return r.WithContext(context.WithValue(r.Context(), configuredURLKey{}, raw))
}
// configuredURLOf returns the URL withConfiguredURL recorded, or "" (no
// components to scrub) when a caller recorded none.
func configuredURLOf(r *http.Request) string {
v, _ := r.Context().Value(configuredURLKey{}).(string)
return v
}
+52
View File
@@ -0,0 +1,52 @@
package traefikllmgateway
import (
"net/http"
"net/http/httptest"
"sync"
"testing"
)
func upstreamBetaHeaders(t *testing.T, sent ...string) [][]string {
t.Helper()
var mu sync.Mutex
var seen [][]string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
seen = append(seen, append([]string(nil), r.Header.Values("anthropic-beta")...))
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(betaCacheResp))
}))
t.Cleanup(srv.Close)
gw := newMessagesTestGateway(t, srv.URL, "")
body := map[string]any{"model": "claude-test", "max_tokens": 10, "messages": []any{map[string]any{"role": "user", "content": "hi"}}}
req := newMessagesRequest(t, body, "x-api-key", "sk-alice")
for _, v := range sent {
req.Header.Add("anthropic-beta", v)
}
rec := httptest.NewRecorder()
gw.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, body=%s", rec.Code, rec.Body.String())
}
mu.Lock()
defer mu.Unlock()
return seen
}
func TestMessages_EmptyTokenBetaHeaderNotForwarded(t *testing.T) {
for _, v := range []string{",", " , ,"} {
seen := upstreamBetaHeaders(t, v)
if len(seen) != 1 || len(seen[0]) != 0 {
t.Errorf("sent %q: upstream saw %q, want no anthropic-beta header", v, seen)
}
}
}
func TestMessages_BetaHeaderForwardedVerbatim(t *testing.T) {
seen := upstreamBetaHeaders(t, "b-two, b-one", "b-three")
if len(seen) != 1 || len(seen[0]) != 2 || seen[0][0] != "b-two, b-one" || seen[0][1] != "b-three" {
t.Fatalf("upstream saw %q, want both values verbatim", seen)
}
}
+88
View File
@@ -0,0 +1,88 @@
package traefikllmgateway
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
)
type rawCacheFixture struct {
gw *Gateway
calls atomic.Int32
}
func newRawCacheFixture(t *testing.T, body string) *rawCacheFixture {
t.Helper()
f := &rawCacheFixture{}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
f.calls.Add(1)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(body))
}))
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"}
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
}
func (f *rawCacheFixture) send(t *testing.T) *httptest.ResponseRecorder {
t.Helper()
body := map[string]any{"model": "claude-test", "max_tokens": 10, "messages": []any{map[string]any{"role": "user", "content": "hello"}}}
rec := httptest.NewRecorder()
f.gw.ServeHTTP(rec, newMessagesRequest(t, body, "x-api-key", "sk-alice"))
return rec
}
func TestMessagesPassthrough_UnrewrittenBodyHandling(t *testing.T) {
overCap := "[" + strings.Repeat("0,", maxResponseBytes/2+10) + "0]"
cases := []struct {
name string
body string
wantCode int
}{
{"truncated over cap", overCap, http.StatusBadGateway},
{"malformed", `{"id":`, http.StatusBadGateway},
{"empty", ``, http.StatusBadGateway},
{"html", `<html>oops</html>`, http.StatusBadGateway},
{"valid array", `[1,2,3]`, http.StatusOK},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
f := newRawCacheFixture(t, tc.body)
for i := 0; i < 2; i++ {
rec := f.send(t)
if rec.Code != tc.wantCode {
t.Fatalf("send %d: status = %d, want %d", i, rec.Code, tc.wantCode)
}
if tc.wantCode == http.StatusOK && rec.Body.String() != tc.body {
t.Fatalf("body = %q, want verbatim", rec.Body.String())
}
if rec.Header().Get("X-Llmgw-Cache") == "hit" {
t.Fatalf("send %d: an unrewritten reply was served from the cache", i)
}
}
if got := f.calls.Load(); got != 2 {
t.Fatalf("upstream calls = %d, want 2 (nothing cached)", got)
}
})
}
}
+43
View File
@@ -0,0 +1,43 @@
package traefikllmgateway
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
const nonObjectUpstreamBody = `[1,2,3]`
func serveNonObjectMessages(t *testing.T) (*Gateway, *httptest.ResponseRecorder) {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(nonObjectUpstreamBody))
}))
t.Cleanup(srv.Close)
gw := newMessagesTestGateway(t, srv.URL, "")
body := map[string]any{"model": "claude-test", "max_tokens": 10, "messages": []any{map[string]any{"role": "user", "content": strings.Repeat("hello ", 400)}}}
rec := httptest.NewRecorder()
gw.ServeHTTP(rec, newMessagesRequest(t, body, "x-api-key", "sk-alice"))
return gw, rec
}
func TestMessagesPassthrough_NonObjectBodyDeliveredVerbatim(t *testing.T) {
_, rec := serveNonObjectMessages(t)
if rec.Code != http.StatusOK || rec.Body.String() != nonObjectUpstreamBody {
t.Fatalf("status=%d body=%q, want 200 and the upstream body verbatim", rec.Code, rec.Body.String())
}
if ct := rec.Header().Get("Content-Type"); ct != "application/json" {
t.Errorf("Content-Type = %q, want application/json", ct)
}
}
func TestMessagesPassthrough_NonObjectBodyStillBilledEstimate(t *testing.T) {
gw, _ := serveNonObjectMessages(t)
tokIn, ok := gw.limiter.getCounter("user", "alice", metricTokIn, windowDay, time.Now())
if !ok || tokIn <= 0 {
t.Fatalf("tokin/day = %d (ok=%v), want a positive request-size estimate", tokIn, ok)
}
}
+16 -1
View File
@@ -16,6 +16,13 @@ const sseEventPrefix = "event: "
// anthropicStreamErrorType is the error.type of an in-stream Anthropic error event.
const anthropicStreamErrorType = "api_error"
const (
// maxStreamToolBlocks bounds the tool index map; real parallel tool use stays far below it.
maxStreamToolBlocks = 1024
// queuedBlockOverhead is charged per queued block so zero-length blocks still consume queue budget.
queuedBlockOverhead = 64
)
const (
streamModeUnset = iota
streamModeSSE
@@ -75,6 +82,7 @@ type anthropicStreamWriter struct {
raw bytes.Buffer
queueCap int
queued int
blocks int
mode int
next int
openIdx int
@@ -249,6 +257,9 @@ func (s *anthropicStreamWriter) handleText(text string) error {
if s.toolOpen {
tail := len(s.queue) - 1
if tail < 0 || s.queue[tail].typ != "text" {
if err := s.reserveQueue(queuedBlockOverhead); err != nil {
return err
}
s.queue = append(s.queue, &queuedBlock{typ: "text"})
tail++
}
@@ -266,10 +277,14 @@ func (s *anthropicStreamWriter) handleText(text string) error {
func (s *anthropicStreamWriter) handleToolCall(index int, id, name, args string) error {
tb, known := s.tools[index]
if !known || (id != "" && tb.id != "" && id != tb.id) {
if s.blocks >= maxStreamToolBlocks {
return fmt.Errorf("%w: more than %d tool blocks in one stream", errUpstream, maxStreamToolBlocks)
}
s.blocks++
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 {
if err := s.reserveQueue(queuedBlockOverhead + len(id) + len(name)); err != nil {
return err
}
s.queue = append(s.queue, q)
+81
View File
@@ -0,0 +1,81 @@
package traefikllmgateway
import (
"errors"
"fmt"
"net/http/httptest"
"testing"
)
const flood = 200000
func TestAnthropicStreamWriter_EmptyToolBlocksCannotGrowQueueUnbounded(t *testing.T) {
sw := newAnthropicStreamWriter(httptest.NewRecorder(), "m")
if _, err := sw.Write(oaiFrame(toolFrame(0, "call_a", "alpha", ""))); err != nil {
t.Fatal(err)
}
var err error
for i := 1; i <= flood && err == nil; i++ {
_, err = sw.Write(oaiFrame(toolFrame(i, "", "", "")))
}
if !errors.Is(err, errUpstream) {
t.Fatalf("err = %v, want errUpstream before the flood ended", err)
}
if len(sw.queue) > maxStreamToolBlocks {
t.Fatalf("queue holds %d blocks", len(sw.queue))
}
}
func TestAnthropicStreamWriter_ToolIndexCountBounded(t *testing.T) {
sw := newAnthropicStreamWriter(httptest.NewRecorder(), "m")
var err error
for i := 0; i < flood && err == nil; i++ {
_, err = sw.Write(oaiFrame(toolFrame(i, "", "", "")))
}
if !errors.Is(err, errUpstream) {
t.Fatalf("err = %v, want errUpstream before the flood ended", err)
}
if len(sw.tools) > maxStreamToolBlocks {
t.Fatalf("tools map holds %d entries", len(sw.tools))
}
}
func TestAnthropicStreamWriter_QueuedBlockChargedFixedOverhead(t *testing.T) {
sw := newAnthropicStreamWriter(httptest.NewRecorder(), "m")
sw.queueCap = 10 * queuedBlockOverhead
if _, err := sw.Write(oaiFrame(toolFrame(0, "call_a", "alpha", ""))); err != nil {
t.Fatal(err)
}
var err error
for i := 1; i <= 20 && err == nil; i++ {
_, err = sw.Write(oaiFrame(toolFrame(i, "", "", "")))
}
if !errors.Is(err, errUpstream) {
t.Fatalf("err = %v, want errUpstream once empty blocks exhaust the queue cap", err)
}
}
func TestAnthropicStreamWriter_ToolBlocksUnderBoundStillWork(t *testing.T) {
_, evs := runStreamWriter(t, usage{},
toolFrame(0, "call_a", "alpha", `{"a":1}`),
toolFrame(1, "call_b", "beta", `{"b":2}`),
toolFrame(2, "call_c", "gamma", `{"c":3}`),
)
if starts := blockStarts(evs); len(starts) != 3 {
t.Fatalf("starts = %v, want 3 blocks", starts)
}
}
func TestAnthropicStreamWriter_IDChurnOnOneIndexBounded(t *testing.T) {
sw := newAnthropicStreamWriter(httptest.NewRecorder(), "m")
var err error
for i := 0; i < flood && err == nil; i++ {
_, err = sw.Write(oaiFrame(toolFrame(0, fmt.Sprintf("call_%d", i), "n", "")))
}
if !errors.Is(err, errUpstream) {
t.Fatalf("err = %v, want errUpstream before the flood ended", err)
}
if len(sw.queue) > maxStreamToolBlocks {
t.Fatalf("queue holds %d blocks", len(sw.queue))
}
}
+43
View File
@@ -0,0 +1,43 @@
package traefikllmgateway
import (
"io"
"net/http"
"strings"
"testing"
)
func estimateLogOf(t *testing.T, usageChunk string) string {
t.Helper()
gw := newResidualGateway(t, providerTypeOpenAI, "gpt-5", func(w http.ResponseWriter, r *http.Request) {
_, _ = io.Copy(io.Discard, r.Body)
w.Header().Set("Content-Type", "text/event-stream")
for i := 0; i < 5; i++ {
_, _ = io.WriteString(w, sseTestChunk)
}
if usageChunk != "" {
_, _ = io.WriteString(w, usageChunk)
}
})
return captureStderr(t, func() {
residualPost(gw, "/up/v1/native-endpoint", `{"model":"gpt-5","stream":true,"messages":[]}`)
})
}
func TestPassthroughSSE_EstimateLogNamesOnlyEstimatedParts(t *testing.T) {
t.Run("completion only", func(t *testing.T) {
out := estimateLogOf(t, "data: {\"choices\":[],\"usage\":{\"prompt_tokens\":42,\"completion_tokens\":0}}\n\n")
if !strings.Contains(out, "logged as estimated (completion tokens estimated from the stream event count)") {
t.Errorf("log = %q, want a completion-only estimate", out)
}
if strings.Contains(out, "prompt tokens estimated") {
t.Errorf("log claims the prompt was estimated: %q", out)
}
})
t.Run("prompt and completion", func(t *testing.T) {
out := estimateLogOf(t, "")
if !strings.Contains(out, "prompt tokens estimated from the request size") || !strings.Contains(out, "completion tokens estimated from the stream event count") {
t.Errorf("log = %q, want both parts named", out)
}
})
}
+33
View File
@@ -0,0 +1,33 @@
package traefikllmgateway
import (
"io"
"net/http"
"testing"
)
func geminiThoughtsBody() string {
return `{"candidates":[{"content":{"parts":[{"text":"hi"}]}}],"usageMetadata":{"promptTokenCount":700,"candidatesTokenCount":60,"thoughtsTokenCount":29940},"modelVersion":"gemini-x"}`
}
func TestPassthroughGemini_ThoughtsTokensBilledAsCompletion(t *testing.T) {
gw := newResidualGateway(t, providerTypeGemini, "gemini-x", jsonUpstream(geminiThoughtsBody))
residualPost(gw, "/up/v1beta/models/gemini-x:generateContent", `{"contents":[]}`)
in, out := residualCounters(gw)
if in != residualPrompt || out != residualCompletion {
t.Fatalf("tokens in/out = %d/%d, want %d/%d", in, out, residualPrompt, residualCompletion)
}
}
func TestPassthroughGeminiSSE_ThoughtsTokensBilledAsCompletion(t *testing.T) {
gw := newResidualGateway(t, providerTypeGemini, "gemini-x", func(w http.ResponseWriter, r *http.Request) {
_, _ = io.Copy(io.Discard, r.Body)
w.Header().Set("Content-Type", "text/event-stream")
_, _ = io.WriteString(w, "data: "+geminiThoughtsBody()+"\n\n")
})
residualPost(gw, "/up/v1beta/models/gemini-x:streamGenerateContent?alt=sse", `{"contents":[]}`)
in, out := residualCounters(gw)
if in != residualPrompt || out != residualCompletion {
t.Fatalf("tokens in/out = %d/%d, want %d/%d", in, out, residualPrompt, residualCompletion)
}
}
+163
View File
@@ -0,0 +1,163 @@
package traefikllmgateway
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
)
// modelKeyEnv fronts an upstream that decodes the body into a Go struct,
// the way a case-folding, last-wins upstream does, and records the model
// it would have run.
type modelKeyEnv struct {
h http.Handler
models []string
mu sync.Mutex
}
func (e *modelKeyEnv) seen() []string {
e.mu.Lock()
defer e.mu.Unlock()
return append([]string(nil), e.models...)
}
func newModelKeyEnv(t *testing.T, mutate func(*Config)) *modelKeyEnv {
t.Helper()
e := &modelKeyEnv{}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
var s struct {
Model string `json:"model"`
}
_ = json.Unmarshal(b, &s)
e.mu.Lock()
e.models = append(e.models, s.Model)
e.mu.Unlock()
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"model":"gpt-5","usage":{"prompt_tokens":1,"completion_tokens":1}}`)
}))
t.Cleanup(srv.Close)
cfg := CreateConfig()
cfg.Providers = map[string]*ProviderConfig{"openai": {Type: "openai", BaseURL: srv.URL, APIKey: "sk-up", Models: []string{"cat-unpriced"}}}
cfg.Groups = map[string]*GroupConfig{"default": {}}
cfg.Users = &UsersConfig{Inline: []*UserConfig{{Name: "alice", Group: "default", APIKey: "sk-alice", Limits: &LimitsConfig{CostPerDayUSD: 5}}}}
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)
}
e.h = h
return e
}
func (e *modelKeyEnv) post(body, contentType string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, "/openai/v1/native-endpoint", strings.NewReader(body))
req.Header.Set("Authorization", "Bearer sk-alice")
req.Header.Set("Content-Type", contentType)
rec := httptest.NewRecorder()
e.h.ServeHTTP(rec, req)
return rec
}
func restrictToAllowed(c *Config) {
c.Groups = map[string]*GroupConfig{"default": {Models: []string{"gpt-allowed"}}}
c.Users.Inline[0].Limits = &LimitsConfig{}
}
func TestPassthroughCostGate_BOMPrefixedUnpricedModelRefused(t *testing.T) {
e := newModelKeyEnv(t, nil)
rec := e.post("\xef\xbb\xbf"+`{"model":"cat-unpriced"}`, "application/json")
if rec.Code != http.StatusPaymentRequired || len(e.seen()) != 0 {
t.Fatalf("status = %d, upstream saw %v, want 402 and no upstream call", rec.Code, e.seen())
}
}
func TestPassthroughCostGate_CaseVariantSecondModelKeyRefused(t *testing.T) {
e := newModelKeyEnv(t, nil)
rec := e.post(`{"model":"gpt-5","MODEL":"cat-unpriced"}`, "application/json")
if rec.Code != http.StatusPaymentRequired || len(e.seen()) != 0 {
t.Fatalf("status = %d, upstream saw %v, want 402 and no upstream call", rec.Code, e.seen())
}
}
func TestPassthroughModelRestriction_CaseVariantSecondModelKeyRefused(t *testing.T) {
e := newModelKeyEnv(t, restrictToAllowed)
rec := e.post(`{"model":"gpt-allowed","Model":"gpt-forbidden"}`, "application/json")
if rec.Code != http.StatusForbidden || len(e.seen()) != 0 {
t.Fatalf("status = %d, upstream saw %v, want 403 and no upstream call", rec.Code, e.seen())
}
}
func TestPassthroughModelRestriction_LoneCaseVariantAllowedModelRefused(t *testing.T) {
e := newModelKeyEnv(t, restrictToAllowed)
for _, body := range []string{`{"Model":"gpt-allowed"}`, `{"model":"gpt-allowed","MODEL":"gpt-allowed"}`, `{"Model":"gpt-allowed","model":"gpt-allowed"}`} {
if rec := e.post(body, "application/json"); rec.Code != http.StatusForbidden {
t.Errorf("%s: status = %d, want 403", body, rec.Code)
}
}
if len(e.seen()) != 0 {
t.Errorf("upstream saw %v, want no call", e.seen())
}
}
func TestPassthroughCostGate_LoneCaseVariantPricedModelRefused(t *testing.T) {
e := newModelKeyEnv(t, nil)
rec := e.post(`{"Model":"gpt-5"}`, "application/json")
if rec.Code != http.StatusPaymentRequired || len(e.seen()) != 0 {
t.Fatalf("status = %d, upstream saw %v, want 402 and no upstream call", rec.Code, e.seen())
}
}
func TestPassthroughModelRestriction_LoneCaseVariantForbiddenModelDenied(t *testing.T) {
e := newModelKeyEnv(t, restrictToAllowed)
for _, body := range []string{`{"Model":"gpt-forbidden"}`, `{"MODEL":"gpt-forbidden"}`} {
if rec := e.post(body, "application/json"); rec.Code != http.StatusForbidden {
t.Errorf("%s: status = %d, want 403", body, rec.Code)
}
}
if len(e.seen()) != 0 {
t.Errorf("upstream saw %v, want no call", e.seen())
}
}
func TestPassthroughCostGate_BinaryContentTypeStillUngated(t *testing.T) {
e := newModelKeyEnv(t, nil)
rec := e.post(`{"model":"cat-unpriced"}`, "application/octet-stream")
if rec.Code != http.StatusOK || len(e.seen()) != 1 {
t.Fatalf("status = %d, upstream calls = %d, want 200 and 1 (documented ungated shape)", rec.Code, len(e.seen()))
}
}
func TestScanTopLevelModel_FoldsKeyCase(t *testing.T) {
cases := []struct {
name string
body string
model string
found bool
duplicate bool
}{
{"exact", `{"model":"a"}`, "a", true, false},
{"Model", `{"Model":"a"}`, "", false, true},
{"MODEL", `{"MODEL":"a"}`, "", false, true},
{"mOdEl", `{"mOdEl":"a"}`, "", false, true},
{"escaped key", `{"model":"a"}`, "a", true, false},
{"variant then exact", `{"Model":"a","model":"a"}`, "", false, true},
{"exact then variant", `{"model":"a","MODEL":"b"}`, "", false, true},
{"unrelated key", `{"models":"a","modelx":"b"}`, "", false, false},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
model, found, closed, dup := scanTopLevelModel([]byte(c.body))
if model != c.model || found != c.found || dup != c.duplicate || (!dup && !closed) {
t.Errorf("got (%q, found=%v, closed=%v, dup=%v), want (%q, %v, dup=%v)", model, found, closed, dup, c.model, c.found, c.duplicate)
}
})
}
}
+44
View File
@@ -314,3 +314,47 @@ func BenchmarkScanTopLevelModelLargeBody(b *testing.B) {
}
}
}
func TestPassthroughCostGate_SmallBodyWithoutModelRefusedLikeLarge(t *testing.T) {
e := newGateEnv(t, nil)
rec := e.post(`{"messages":[{"role":"user","content":"hi"}]}`, "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_SmallBodyWithoutModelServedWithOptIn(t *testing.T) {
e := newGateEnv(t, func(c *Config) { c.AllowUnpricedWithCostBudget = true })
if rec := e.post(`{"messages":[]}`, "sk-alice"); rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200, body=%.200s", rec.Code, rec.Body.String())
}
}
func TestPassthroughCostGate_SmallGeminiBodyWithoutModelServed(t *testing.T) {
var calls int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
atomic.AddInt32(&calls, 1)
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{}`)
}))
defer srv.Close()
cfg := CreateConfig()
cfg.Providers = map[string]*ProviderConfig{"gem": {Type: providerTypeGemini, BaseURL: srv.URL, APIKey: "k", Models: []string{"gemini-x"}}}
cfg.Groups = map[string]*GroupConfig{"default": {}}
cfg.Users = &UsersConfig{Inline: []*UserConfig{{Name: "alice", Group: "default", APIKey: "sk-alice", Limits: &LimitsConfig{CostPerDayUSD: 5}}}}
h, err := New(context.Background(), http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}), cfg, "llmgw")
if err != nil {
t.Fatalf("New: %v", err)
}
req := httptest.NewRequest(http.MethodPost, "/gem/v1beta/models/gemini-x:generateContent", strings.NewReader(`{"contents":[]}`))
req.Header.Set("Authorization", "Bearer sk-alice")
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code == http.StatusPaymentRequired || atomic.LoadInt32(&calls) != 1 {
t.Fatalf("status = %d, upstream calls = %d, want the Gemini request served", rec.Code, calls)
}
}
+189
View File
@@ -0,0 +1,189 @@
package traefikllmgateway
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"time"
)
const (
residualPrompt = 700
residualCompletion = 30000
residualDailyLimit = 20000
)
func newResidualGateway(t *testing.T, providerType, model string, upstream http.HandlerFunc) *Gateway {
t.Helper()
srv := httptest.NewServer(upstream)
t.Cleanup(srv.Close)
cfg := CreateConfig()
cfg.Providers = map[string]*ProviderConfig{"up": {Type: providerType, BaseURL: srv.URL, APIKey: "sk-up", Models: []string{model}}}
cfg.Groups = map[string]*GroupConfig{"default": {}}
cfg.Users = &UsersConfig{Inline: []*UserConfig{{Name: "alice", Group: "default", APIKey: "sk-alice", Limits: &LimitsConfig{TokensPerDay: residualDailyLimit}}}}
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 residualPost(gw *Gateway, path, body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
req.Header.Set("Authorization", "Bearer sk-alice")
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
gw.ServeHTTP(rec, req)
return rec
}
func residualCounters(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 jsonUpstream(body func() string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
_, _ = io.Copy(io.Discard, r.Body)
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, body())
}
}
func overCapFiller() string { return strings.Repeat("a", maxAccountingTeeBytes+200<<10) }
func TestPassthroughJSON_OverTeeCapBillsReportedUsageFromTail(t *testing.T) {
gw := newResidualGateway(t, providerTypeOpenAI, "gpt-5", jsonUpstream(func() string {
return `{"id":"c1","model":"gpt-5","choices":[{"message":{"content":"` + overCapFiller() + `"}}],"usage":{"prompt_tokens":700,"completion_tokens":30000}}`
}))
if rec := residualPost(gw, "/up/v1/native-endpoint", `{"model":"gpt-5","messages":[]}`); rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", rec.Code)
}
in, out := residualCounters(gw)
if in != residualPrompt || out != residualCompletion {
t.Fatalf("tokens in/out = %d/%d, want %d/%d", in, out, residualPrompt, residualCompletion)
}
if rec := residualPost(gw, "/up/v1/native-endpoint", `{"model":"gpt-5","messages":[]}`); rec.Code != http.StatusTooManyRequests {
t.Errorf("second request status = %d, want 429", rec.Code)
}
}
func TestPassthroughJSON_OverTeeCapGeminiUsageMetadataFromTail(t *testing.T) {
gw := newResidualGateway(t, providerTypeGemini, "gemini-x", jsonUpstream(func() string {
return `{"candidates":[{"content":{"parts":[{"text":"` + overCapFiller() + `"}]}}],"usageMetadata":{"promptTokenCount":700,"candidatesTokenCount":30000},"modelVersion":"gemini-x"}`
}))
if rec := residualPost(gw, "/up/v1beta/models/gemini-x:generateContent", `{"contents":[]}`); rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", rec.Code)
}
in, out := residualCounters(gw)
if in != residualPrompt || out != residualCompletion {
t.Fatalf("tokens in/out = %d/%d, want %d/%d", in, out, residualPrompt, residualCompletion)
}
}
func TestPassthroughJSON_UsageTextInsideStringNotParsed(t *testing.T) {
gw := newResidualGateway(t, providerTypeOpenAI, "gpt-5", jsonUpstream(func() string {
fake := `{\"usage\":{\"prompt_tokens\":1,\"completion_tokens\":1}}`
return `{"model":"gpt-5","choices":[{"message":{"content":"` + overCapFiller() + `"}}],"usage":{"prompt_tokens":700,"completion_tokens":30000},"note":"` + fake + `"}`
}))
residualPost(gw, "/up/v1/native-endpoint", `{"model":"gpt-5","messages":[]}`)
in, out := residualCounters(gw)
if in != residualPrompt || out != residualCompletion {
t.Fatalf("tokens in/out = %d/%d, want %d/%d", in, out, residualPrompt, residualCompletion)
}
}
func TestPassthroughJSON_OverTeeCapWithoutUsageKeepsPromptEstimate(t *testing.T) {
gw := newResidualGateway(t, providerTypeOpenAI, "gpt-5", jsonUpstream(func() string {
return `{"model":"gpt-5","data":[{"b64_json":"` + overCapFiller() + `"}]}`
}))
body := `{"model":"gpt-5","prompt":"` + strings.Repeat("p", 400) + `"}`
residualPost(gw, "/up/v1/native-endpoint", body)
in, out := residualCounters(gw)
if want := estimatePromptTokens(int64(len(body))); in != want {
t.Errorf("tokin = %d, want request-size estimate %d", in, want)
}
if out != 0 {
t.Errorf("tokout = %d, want 0", out)
}
}
func TestPassthroughJSON_UsageStraddlingTeeCapBilled(t *testing.T) {
gw := newResidualGateway(t, providerTypeOpenAI, "gpt-5", jsonUpstream(func() string {
pre := `{"model":"gpt-5","c":"` + strings.Repeat("a", maxAccountingTeeBytes-20-len(`{"model":"gpt-5","c":"`)) + `"`
return pre + `,"usage":{"prompt_tokens":700,"completion_tokens":30000}}`
}))
residualPost(gw, "/up/v1/native-endpoint", `{"model":"gpt-5","messages":[]}`)
in, out := residualCounters(gw)
if in != residualPrompt || out != residualCompletion {
t.Fatalf("tokens in/out = %d/%d, want %d/%d", in, out, residualPrompt, residualCompletion)
}
}
func TestPassthroughJSON_EchoedUsageAfterRealOneIgnored(t *testing.T) {
gw := newResidualGateway(t, providerTypeOpenAI, "gpt-5", jsonUpstream(func() string {
return `{"model":"gpt-5","c":"` + overCapFiller() + `","usage":{"prompt_tokens":700,"completion_tokens":30000},"metadata":{"usage":"x"}}`
}))
residualPost(gw, "/up/v1/native-endpoint", `{"model":"gpt-5","messages":[]}`)
in, out := residualCounters(gw)
if in != residualPrompt || out != residualCompletion {
t.Fatalf("tokens in/out = %d/%d, want %d/%d", in, out, residualPrompt, residualCompletion)
}
}
func TestPassthroughJSON_EchoedObjectAfterRealUsageIgnored(t *testing.T) {
gw := newResidualGateway(t, providerTypeOpenAI, "gpt-5", jsonUpstream(func() string {
return `{"model":"gpt-5","c":"` + overCapFiller() + `","usage":{"prompt_tokens":700,"completion_tokens":30000},"tool":{"usage":{"prompt_tokens":1,"completion_tokens":9000000}}}`
}))
residualPost(gw, "/up/v1/native-endpoint", `{"model":"gpt-5","messages":[]}`)
in, out := residualCounters(gw)
if in != residualPrompt || out != residualCompletion {
t.Fatalf("tokens in/out = %d/%d, want %d/%d", in, out, residualPrompt, residualCompletion)
}
}
func TestPassthroughJSON_UsageInHeadBilled(t *testing.T) {
gw := newResidualGateway(t, providerTypeOpenAI, "gpt-5", jsonUpstream(func() string {
return `{"model":"gpt-5","usage":{"prompt_tokens":700,"completion_tokens":30000},"c":"` + overCapFiller() + `"}`
}))
residualPost(gw, "/up/v1/native-endpoint", `{"model":"gpt-5","messages":[]}`)
in, out := residualCounters(gw)
if in != residualPrompt || out != residualCompletion {
t.Fatalf("tokens in/out = %d/%d, want %d/%d", in, out, residualPrompt, residualCompletion)
}
}
func TestPassthroughJSON_HangupAfterEchoedObjectKeepsHeadUsage(t *testing.T) {
gw := newResidualGateway(t, providerTypeOpenAI, "gpt-5", func(w http.ResponseWriter, r *http.Request) {
body := `{"model":"gpt-5","usage":{"prompt_tokens":6,"completion_tokens":10000},"c":"` + overCapFiller() + `","echo":{"usage":{"prompt_tokens":1,"completion_tokens":0}}`
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Length", strconv.Itoa(len(body)+1000))
_, _ = io.WriteString(w, body)
})
residualPost(gw, "/up/v1/native-endpoint", `{"model":"gpt-5","messages":[]}`)
in, out := residualCounters(gw)
if in != 6 || out != 10000 {
t.Fatalf("tokens in/out = %d/%d, want 6/10000", in, out)
}
}
func TestPassthroughJSON_OverTeeCapGeminiArrayReplyBilled(t *testing.T) {
gw := newResidualGateway(t, providerTypeGemini, "gemini-x", jsonUpstream(func() string {
return `[{"candidates":[{"content":{"parts":[{"text":"` + overCapFiller() + `"}]}}],"usageMetadata":{"promptTokenCount":700,"candidatesTokenCount":30000},"modelVersion":"gemini-x"}]`
}))
residualPost(gw, "/up/v1beta/models/gemini-x:streamGenerateContent", `{"contents":[]}`)
in, out := residualCounters(gw)
if in != residualPrompt || out != residualCompletion {
t.Fatalf("tokens in/out = %d/%d, want %d/%d", in, out, residualPrompt, residualCompletion)
}
}
+191
View File
@@ -0,0 +1,191 @@
package traefikllmgateway
import (
"bytes"
"testing"
"time"
)
func TestCappedAccountingBuffer_KeepsBoundedRollingTailAfterCap(t *testing.T) {
c := &cappedAccountingBuffer{}
chunk := bytes.Repeat([]byte("x"), 32<<10)
total := 0
for total <= maxAccountingTeeBytes+3*sseAccountingTailBytes {
if n, err := c.Write(chunk); n != len(chunk) || err != nil {
t.Fatalf("Write = %d, %v", n, err)
}
total += len(chunk)
}
end := []byte("END-MARKER")
_, _ = c.Write(end)
if c.buf.Len() != maxAccountingTeeBytes || !c.truncated {
t.Fatalf("head len = %d truncated = %v, want cap and truncated", c.buf.Len(), c.truncated)
}
tail := c.tailBytes()
if len(tail) == 0 || len(tail) > sseAccountingTailBytes {
t.Fatalf("tail len = %d, want 1..%d", len(tail), sseAccountingTailBytes)
}
if !bytes.HasSuffix(tail, end) {
t.Errorf("tail does not end with the last bytes written")
}
}
func TestExtractTruncatedJSONUsage_PicksLastUsageKeyOutsideStrings(t *testing.T) {
head := []byte(`{"model":"gpt-5","choices":[{"message":{"content":"text \"usage\": {\"prompt_tokens\": 9}"}}],"usage" : {"prompt_tokens":5,"completion_tokens":6}`)
u, model := extractTruncatedJSONUsage(providerTypeOpenAI, "up", head, nil, true)
if u.prompt != 5 || u.completion != 6 || model != "gpt-5" {
t.Fatalf("usage = %+v model = %q, want 5/6 gpt-5", u, model)
}
if u, _ := extractTruncatedJSONUsage(providerTypeOpenAI, "up", []byte(`{"a":"b"`), nil, true); u.total() != 0 {
t.Errorf("usage without a usage key = %+v, want zero", u)
}
}
func TestPassthroughSSE_TailBufferUnchanged(t *testing.T) {
b := &sseAccountingBuffer{}
chunk := bytes.Repeat([]byte("y"), 10<<10)
for i := 0; i < 40; i++ {
_, _ = b.Write(chunk)
}
_, _ = b.Write([]byte("LAST"))
tail := b.tailBytes()
if len(tail) != sseAccountingTailBytes || !bytes.HasSuffix(tail, []byte("LAST")) {
t.Fatalf("tail len = %d suffix ok = %v, want %d bytes ending LAST", len(tail), bytes.HasSuffix(tail, []byte("LAST")), sseAccountingTailBytes)
}
if b.head.Len() != sseAccountingHeadBytes {
t.Errorf("head len = %d, want %d", b.head.Len(), sseAccountingHeadBytes)
}
big := &sseAccountingBuffer{}
_, _ = big.Write(bytes.Repeat([]byte("z"), 3*sseAccountingTailBytes))
if len(big.tailBytes()) != sseAccountingTailBytes {
t.Errorf("single oversized write tail len = %d, want %d", len(big.tailBytes()), sseAccountingTailBytes)
}
}
func TestExtractTruncatedJSONUsage_SkipsEchoedAndEmptyUsage(t *testing.T) {
tail := []byte(`x"},"usage":{"prompt_tokens":700,"completion_tokens":30000},"metadata":{"usage":"x"},"schema":{"usage":{"type":"object"}},"z":{"usage":{}}}`)
u, _ := extractTruncatedJSONUsage(providerTypeOpenAI, "up", nil, tail, true)
if u.prompt != 700 || u.completion != 30000 {
t.Fatalf("usage = %+v, want 700/30000", u)
}
}
func TestExtractTruncatedJSONUsage_NestedCandidatesAreBounded(t *testing.T) {
head := bytes.Repeat([]byte(`"usage":{`), maxAccountingTeeBytes/len(`"usage":{`))
start := time.Now()
u, _ := extractTruncatedJSONUsage(providerTypeOpenAI, "up", head, head[:sseAccountingTailBytes], true)
if u.total() != 0 {
t.Errorf("usage = %+v, want zero", u)
}
if d := time.Since(start); d > time.Second {
t.Errorf("scan took %v, want under 1s", d)
}
}
func TestCappedAccountingBuffer_ScanTailJoinsHeadWhenContiguous(t *testing.T) {
c := &cappedAccountingBuffer{}
_, _ = c.Write(bytes.Repeat([]byte("h"), maxAccountingTeeBytes-3))
_, _ = c.Write([]byte("ABCDEF"))
if got := c.scanTail(); !bytes.HasSuffix(got, []byte("ABCDEF")) || !bytes.Contains(got, []byte("hhhABC")) {
t.Errorf("scanTail does not join head and tail")
}
_, _ = c.Write(bytes.Repeat([]byte("t"), 3*sseAccountingTailBytes))
if got := c.scanTail(); bytes.Contains(got, []byte("h")) {
t.Errorf("scanTail joined head across a gap")
}
}
func TestExtractTruncatedJSONUsage_NestedObjectsNeverWinTail(t *testing.T) {
cases := []struct {
name, typ string
tail string
prompt int64
out int64
}{
{"schema object after real usage", providerTypeOpenAI, `x"},"usage":{"prompt_tokens":700,"completion_tokens":30000},"tool":{"usage":{"prompt_tokens":1,"completion_tokens":9000000}}}`, 700, 30000},
{"usage inside usage", providerTypeOpenAI, `x"},"usage":{"prompt_tokens":700,"completion_tokens":30000,"usage":{"prompt_tokens":1,"completion_tokens":0}}}`, 700, 30000},
{"anthropic tool_use input", providerTypeAnthropic, `x"},"usage":{"input_tokens":700,"output_tokens":30000},"z":{"type":"tool_use","input":{"usage":{"input_tokens":1,"output_tokens":0}}}}`, 700, 30000},
{"echo as last key, real one before", providerTypeOpenAI, `x"},"usage":{"prompt_tokens":700,"completion_tokens":30000},"echo":{"usage":{"prompt_tokens":1}}}`, 700, 30000},
{"cut short after echo", providerTypeOpenAI, `x"},"usage":{"prompt_tokens":700,"completion_tokens":30000},"echo":{"usage":{"prompt_tokens":1,"completion_tokens":0}`, 0, 0},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
u, _ := extractTruncatedJSONUsage(c.typ, "up", nil, []byte(c.tail), true)
if u.prompt != c.prompt || u.completion != c.out {
t.Errorf("usage = %d/%d, want %d/%d", u.prompt, u.completion, c.prompt, c.out)
}
})
}
}
func TestExtractTruncatedJSONUsage_HeadTopLevelUsageOnly(t *testing.T) {
head := []byte(`{"model":"gpt-5","usage":{"prompt_tokens":6,"completion_tokens":10000},"c":"` + string(bytes.Repeat([]byte("a"), 1<<10)) + `","echo":{"usage":{"prompt_tokens":1}`)
u, model := extractTruncatedJSONUsage(providerTypeOpenAI, "up", head, nil, true)
if u.prompt != 6 || u.completion != 10000 || model != "gpt-5" {
t.Fatalf("usage = %+v model = %q, want 6/10000 gpt-5", u, model)
}
nested := []byte(`{"model":"gpt-5","echo":{"usage":{"prompt_tokens":1,"completion_tokens":2}},"c":"x`)
if u, _ := extractTruncatedJSONUsage(providerTypeOpenAI, "up", nested, nil, true); u.total() != 0 {
t.Errorf("nested head usage = %+v, want zero", u)
}
}
func TestExtractTruncatedJSONUsage_AbortedCopyIgnoresClosedLookingTail(t *testing.T) {
head := []byte(`{"model":"gpt-5","usage":{"prompt_tokens":6,"completion_tokens":10000},"c":"x`)
tail := []byte(`x"},"echo":{"usage":{"prompt_tokens":1,"completion_tokens":0}}`)
if u, _ := extractTruncatedJSONUsage(providerTypeOpenAI, "up", head, tail, false); u.prompt != 6 || u.completion != 10000 {
t.Errorf("aborted usage = %+v, want 6/10000 from the head", u)
}
}
func TestExtractTruncatedJSONUsage_GeminiShapes(t *testing.T) {
arrayHead := []byte(`[{"candidates":[{"content":{"parts":[{"text":"x`)
objectHead := []byte(`{"candidates":[{"content":{"parts":[{"text":"x`)
real := `"usageMetadata":{"promptTokenCount":700,"candidatesTokenCount":30000},"modelVersion":"gemini-x"`
forged := `{"functionCall":{"args":{"usageMetadata":{"promptTokenCount":1,"candidatesTokenCount":0}}}}`
cases := []struct {
name string
tail string
head []byte
}{
{"array", `x"}]}}],` + real + `}]`, arrayHead},
{"array, forged args after real", `x"}]}}],` + real + `},{"candidates":[{"content":{"parts":[` + forged + `]}}]}]`, arrayHead},
{"array, real in an earlier element", `x"}]}}],` + real + `},{"candidates":[]}]`, arrayHead},
{"object, forged args after real", `x"}]}}],` + real + `,"extra":` + forged + `}`, objectHead},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
u, model := extractTruncatedJSONUsage(providerTypeGemini, "up", c.head, []byte(c.tail), true)
if u.prompt != 700 || u.completion != 30000 || model != "gemini-x" {
t.Errorf("usage = %d/%d model = %q, want 700/30000 gemini-x", u.prompt, u.completion, model)
}
})
}
}
func TestExtractTruncatedJSONUsage_GeminiArrayUsageInHead(t *testing.T) {
head := []byte(`[{"usageMetadata":{"promptTokenCount":700,"candidatesTokenCount":30000},"modelVersion":"gemini-x"},{"candidates":[{"content":{"parts":[{"text":"x`)
u, model := extractTruncatedJSONUsage(providerTypeGemini, "up", head, nil, false)
if u.prompt != 700 || u.completion != 30000 || model != "gemini-x" {
t.Errorf("usage = %d/%d model = %q, want 700/30000 gemini-x", u.prompt, u.completion, model)
}
}
func TestExtractTruncatedJSONUsage_UnrelatedTypeMismatchKeepsFigures(t *testing.T) {
tail := []byte(`x"},"usage":{"prompt_tokens":700,"completion_tokens":30000},"response":"text"}`)
u, _ := extractTruncatedJSONUsage(providerTypeOpenAI, "up", nil, tail, true)
if u.prompt != 700 || u.completion != 30000 {
t.Errorf("usage = %d/%d, want 700/30000", u.prompt, u.completion)
}
}
func TestExtractTruncatedJSONUsage_GeminiModelVersionOnlyFromTopLevel(t *testing.T) {
head := []byte(`{"usageMetadata":{"promptTokenCount":6,"candidatesTokenCount":9},"modelVersion":"gemini-real","c":{"args":{"modelVersion":"forged"}},"d":"x`)
if _, model := extractTruncatedJSONUsage(providerTypeGemini, "up", head, nil, false); model != "gemini-real" {
t.Errorf("aborted model = %q, want gemini-real", model)
}
tail := []byte(`x"},"usageMetadata":{"promptTokenCount":6,"candidatesTokenCount":9},"modelVersion":"gemini-real","c":{"args":{"modelVersion":"forged"}}}`)
if _, model := extractTruncatedJSONUsage(providerTypeGemini, "up", []byte(`{"a":"x`), tail, true); model != "gemini-real" {
t.Errorf("complete model = %q, want gemini-real", model)
}
}
+107 -44
View File
@@ -133,55 +133,106 @@ 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 []chatStreamChoice `json:"choices"`
Usage *chatStreamUsage `json:"usage"`
Choices json.RawMessage `json:"choices"`
}
// chatStreamChoice carries only the delta fields forwardStream sizes for an
// abort-time completion estimate.
type chatStreamChoice struct {
Delta chatStreamDelta `json:"delta"`
// decodeChatStreamChunk decodes usage independently of choices, so a
// malformed choices value cannot lose the chunk's usage. choices holds each
// choice's raw JSON; hasChoices is false only for an absent, null or empty
// array, and true when choices is present but not an array.
func decodeChatStreamChunk(data []byte) (*chatStreamUsage, []json.RawMessage, bool) {
var c chatStreamChunk
if json.Unmarshal(data, &c) != nil && c.Usage == nil {
var u struct {
Usage *chatStreamUsage `json:"usage"`
}
if json.Unmarshal(data, &u) == nil {
c.Usage = u.Usage
}
}
if len(c.Choices) == 0 || string(c.Choices) == "null" {
return c.Usage, nil, false
}
var choices []json.RawMessage
if json.Unmarshal(c.Choices, &choices) != nil {
return c.Usage, nil, true
}
return c.Usage, choices, len(choices) > 0
}
// 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"`
}
// deltaMetaKeys are delta keys whose string values are identifiers or binary
// payloads, not output text.
var deltaMetaKeys = map[string]bool{"role": true, "id": true, "type": true, "name": true, "data": true}
type chatStreamToolDelta struct {
Function chatStreamToolFunction `json:"function"`
}
// maxDeltaDepth bounds the walk so a hostile upstream cannot drive deep
// interpreted recursion.
const maxDeltaDepth = 8
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] != '"' {
// deltaTextBytes sums the byte length of every string leaf under v except
// those under deltaMetaKeys.
func deltaTextBytes(v any, depth int) int64 {
if depth > maxDeltaDepth {
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)
switch t := v.(type) {
case string:
n = int64(len(t))
case []any:
for i := range t {
n += deltaTextBytes(t[i], depth+1)
}
case map[string]any:
for k, e := range t {
if deltaMetaKeys[k] {
continue
}
n += deltaTextBytes(e, depth+1)
}
}
return n
}
// dropMirroredReasoning removes the copies of reasoning text that some
// upstreams repeat under reasoning_details or a second reasoning key, so
// each distinct text counts once.
func dropMirroredReasoning(delta map[string]any) {
rc, _ := delta["reasoning_content"].(string)
r, _ := delta["reasoning"].(string)
if rc != "" && rc == r {
delete(delta, "reasoning")
r = ""
}
if rc != "" || r != "" {
delete(delta, "reasoning_details")
}
}
// chunkOutputBytes sums the forwarded output text of every choice and
// reports whether any delta carried a non-null key other than role; a choice
// that does not decode contributes nothing.
func chunkOutputBytes(choices []json.RawMessage) (int64, bool) {
var n int64
has := false
for i := range choices {
var ch struct {
Delta map[string]any `json:"delta"`
}
if json.Unmarshal(choices[i], &ch) != nil {
continue
}
for k, v := range ch.Delta {
if k != "role" && v != nil {
has = true
}
}
dropMirroredReasoning(ch.Delta)
n += deltaTextBytes(ch.Delta, 0)
}
return n, has
}
// chatCompletion implements providerAdapter.
//
// When req["stream"] is true, chatCompletion always forces
@@ -283,7 +334,8 @@ type chatChoice struct {
}
// forwardJSON reads resp's full body (capped at maxResponseBytes),
// extracts its usage for accounting, and writes resp's Content-Type,
// extracts its usage for accounting, and writes resp's Content-Type (chosen
// by the upstream, stored and replayed by the response cache),
// status code, and body verbatim to w — the non-streaming passthrough both
// chatCompletion and embeddings use. A body that fails to decode as JSON
// still passes through unchanged; forwardJSON only fails on a read error,
@@ -332,7 +384,7 @@ func (a *openaiAdapter) forwardStream(w http.ResponseWriter, body io.Reader, cli
var u usage
finish := ""
hasOutput := false
var outBytes int64
var outBytes, outChunks int64
sawDone := false
@@ -349,16 +401,20 @@ func (a *openaiAdapter) forwardStream(w http.ResponseWriter, body io.Reader, cli
hasOutput = chunkHasOutput(ev.data)
}
var chunk chatStreamChunk
hasUsage := json.Unmarshal(ev.data, &chunk) == nil && chunk.Usage != nil
outBytes += chunkOutputBytes(&chunk)
chunkUsage, choices, hasChoices := decodeChatStreamChunk(ev.data)
hasUsage := chunkUsage != nil
chunkBytes, chunkOut := chunkOutputBytes(choices)
outBytes += chunkBytes
if chunkOut {
outChunks++
}
if hasUsage {
u.prompt = chunk.Usage.PromptTokens
u.completion = chunk.Usage.CompletionTokens
u.cached = cachedPromptTokens(chunk.Usage.PromptDetails.CachedTokens, chunk.Usage.PromptCacheHitTokens)
u.prompt = chunkUsage.PromptTokens
u.completion = chunkUsage.CompletionTokens
u.cached = cachedPromptTokens(chunkUsage.PromptDetails.CachedTokens, chunkUsage.PromptCacheHitTokens)
}
isUsageOnlyChunk := hasUsage && len(chunk.Choices) == 0
isUsageOnlyChunk := hasUsage && !hasChoices
if isUsageOnlyChunk && !clientAskedUsage {
return nil
}
@@ -374,6 +430,13 @@ func (a *openaiAdapter) forwardStream(w http.ResponseWriter, body io.Reader, cli
if u.completion == 0 && outBytes > 0 {
u.completion = estimateCompletionTokens(outBytes)
u.estimated = true
} else if u.completion == 0 && outChunks > 0 {
// Non-text deltas still cost output: floor at one token per chunk.
u.completion = outChunks
if u.completion > maxEstimatedPromptTokens {
u.completion = maxEstimatedPromptTokens
}
u.estimated = true
}
return u, fmt.Errorf("%w: stream: %w", errUpstream, err)
}
+33
View File
@@ -0,0 +1,33 @@
package traefikllmgateway
import (
"net/http/httptest"
"strings"
"testing"
)
func TestOpenAIForwardStream_MalformedChoicesKeepUsage(t *testing.T) {
tests := []struct {
name string
body string
}{
{"tool_calls object", `data: {"choices":[{"delta":{"tool_calls":{"function":{"arguments":"x"}}}}],"usage":{"prompt_tokens":7,"completion_tokens":9}}` + "\n\n"},
{"choices object", `data: {"choices":{"delta":{}},"usage":{"prompt_tokens":7,"completion_tokens":9}}` + "\n\n"},
{"choice not object", `data: {"choices":["x"],"usage":{"prompt_tokens":7,"completion_tokens":9}}` + "\n\n"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
rec := httptest.NewRecorder()
u, err := (&openaiAdapter{}).forwardStream(rec, strings.NewReader(tt.body+"data: [DONE]\n\n"), false)
if err != nil {
t.Fatalf("forwardStream: %v", err)
}
if u.prompt != 7 || u.completion != 9 {
t.Fatalf("usage = %d/%d, want 7/9", u.prompt, u.completion)
}
if !strings.Contains(rec.Body.String(), `"choices"`) {
t.Errorf("chunk with choices was suppressed: %q", rec.Body.String())
}
})
}
}
+40 -18
View File
@@ -938,6 +938,7 @@ func newModelRegistry(adapters map[string]providerAdapter, cfg *Config, log func
}
m.states[name] = &providerState{
name: name,
explicit: explicit,
discovered: make(map[string]bool),
discoveryEnabled: pc.Discovery,
@@ -1110,7 +1111,7 @@ func (m *modelRegistry) discoveryHealthy(name string) bool {
func (m *modelRegistry) finishRefresh(st *providerState, now time.Time, ids []string, err error) {
if err == nil {
var dropped int
ids, dropped = boundDiscoveredIDs(ids)
ids, dropped = boundDiscoveredIDs(ids, st.explicit)
if dropped > 0 {
m.logDiscoveryDrop(st.name, now, dropped)
}
@@ -1123,29 +1124,50 @@ 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
// maxDiscoveredModelIDBytes, then caps the rest at maxDiscoveredModels.
// Ids in explicit are always kept; only the other ids are dropped past the
// cap, in lexicographic order of the survivors so the result does not depend
// on the upstream's listing order. A repeated id counts once: otherwise
// copies of an explicit id would pass the cap. It returns the kept ids and
// how many distinct or invalid ids it dropped.
func boundDiscoveredIDs(ids []string, explicit map[string]bool) ([]string, int) {
var valid []string
seen := map[string]bool{}
repeats := 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++
if len(id) > maxDiscoveredModelIDBytes || !isValidModelID(id) {
continue
}
if !copied {
kept = make([]string, 0, len(ids))
kept = append(kept, ids[:i]...)
copied = true
if seen[id] {
repeats++
continue
}
seen[id] = true
valid = append(valid, id)
}
if len(valid) <= maxDiscoveredModels {
return valid, len(ids) - repeats - len(valid)
}
kept := make([]string, 0, maxDiscoveredModels)
surplus := make([]string, 0, len(valid))
for _, id := range valid {
if explicit[id] {
kept = append(kept, id)
} else {
surplus = append(surplus, id)
}
}
return kept, len(ids) - len(kept)
sort.Strings(surplus)
room := maxDiscoveredModels - len(kept)
if room < 0 {
room = 0
}
if len(surplus) > room {
surplus = surplus[:room]
}
kept = append(kept, surplus...)
return kept, len(ids) - repeats - len(kept)
}
// logDiscoveryDrop logs, at most once per upstreamErrLogEvery per provider, how many discovered ids were dropped. Never logs id text.
+78
View File
@@ -0,0 +1,78 @@
package traefikllmgateway
import (
"fmt"
"strings"
"sync"
"testing"
"time"
)
type capturedLog struct {
lines []string
mu sync.Mutex
}
func (c *capturedLog) logf(f string, a ...any) {
c.mu.Lock()
c.lines = append(c.lines, fmt.Sprintf(f, a...))
c.mu.Unlock()
}
func (c *capturedLog) count(sub string) int {
c.mu.Lock()
defer c.mu.Unlock()
n := 0
for _, l := range c.lines {
if strings.Contains(l, sub) {
n++
}
}
return n
}
func newTwoProviderRegistry(t *testing.T, logf func(string, ...any)) *modelRegistry {
t.Helper()
adapters := map[string]providerAdapter{"alpha": newFakeAdapter("alpha"), "beta": newFakeAdapter("beta")}
cfg := &Config{Providers: map[string]*ProviderConfig{"alpha": {Models: []string{"a"}}, "beta": {Models: []string{"b"}}}}
reg, err := newModelRegistry(adapters, cfg, logf)
if err != nil {
t.Fatalf("newModelRegistry: %v", err)
}
return reg
}
func TestRegistry_DiscoveryDropLogNamesProvider(t *testing.T) {
var cl capturedLog
reg := newTwoProviderRegistry(t, cl.logf)
reg.finishRefresh(reg.states["alpha"], time.Now(), []string{""}, nil)
if cl.count(`provider "alpha" discovery dropped 1`) != 1 {
t.Fatalf("log does not name the provider: %v", cl.lines)
}
}
func TestRegistry_DiscoveryDropLogDebouncedPerProvider(t *testing.T) {
var cl capturedLog
reg := newTwoProviderRegistry(t, cl.logf)
now := time.Now()
reg.finishRefresh(reg.states["alpha"], now, []string{""}, nil)
reg.finishRefresh(reg.states["beta"], now.Add(time.Second), []string{""}, nil)
if cl.count(`provider "beta" discovery dropped`) != 1 || cl.count(`provider "alpha" discovery dropped`) != 1 {
t.Fatalf("each provider must log its own drop once: %v", cl.lines)
}
}
func TestRegistry_UpstreamErrorsLoggedWithoutSharedState(t *testing.T) {
var cl capturedLog
ad := newOpenAIAdapter("d1", "http://127.0.0.1:1", "")
ad.setUpstreamErrors([]upstreamFailure{{Upstream: "http://127.0.0.1:2", Err: "boom"}})
cfg := &Config{Providers: map[string]*ProviderConfig{"d1": {Models: []string{"m"}}}}
reg, err := newModelRegistry(map[string]providerAdapter{"d1": ad}, cfg, cl.logf)
if err != nil {
t.Fatalf("newModelRegistry: %v", err)
}
reg.finishRefresh(reg.states["d1"], time.Now(), []string{"m"}, nil)
if cl.count(`provider "d1" upstream`) != 1 {
t.Fatalf("tolerated upstream failure not logged: %v", cl.lines)
}
}
+104
View File
@@ -0,0 +1,104 @@
package traefikllmgateway
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func relayHeaderGateway(t *testing.T, upstream http.HandlerFunc) *Gateway {
t.Helper()
gw := newResidualGateway(t, providerTypeOpenAI, "gpt-5", upstream)
gw.cfg.Admin = &AdminConfig{Enabled: true}
return gw
}
func TestRelayHardeningHeaders_PresentOnRelayedResponses(t *testing.T) {
gw := relayHeaderGateway(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
w.Header().Set("Content-Security-Policy", "default-src *")
_, _ = w.Write([]byte(`{"model":"gpt-5"}`))
})
rec := residualPost(gw, "/up/v1/native-endpoint", `{"model":"gpt-5"}`)
if got := rec.Header().Get("X-Content-Type-Options"); got != "nosniff" {
t.Errorf("X-Content-Type-Options = %q, want nosniff", got)
}
if got := rec.Header().Get("Content-Security-Policy"); got != "sandbox" {
t.Errorf("Content-Security-Policy = %q, want sandbox (the upstream value is stripped)", got)
}
}
func TestRelayHardeningHeaders_UpstreamNosniffValueKept(t *testing.T) {
gw := relayHeaderGateway(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Content-Type-Options", "upstream-value")
_, _ = w.Write([]byte(`{}`))
})
rec := residualPost(gw, "/up/v1/native-endpoint", `{"model":"gpt-5"}`)
if got := rec.Header().Get("X-Content-Type-Options"); got != "upstream-value" {
t.Errorf("X-Content-Type-Options = %q, want the upstream value", got)
}
}
func TestRelayHardeningHeaders_PresentOnUnifiedRoute(t *testing.T) {
gw := relayHeaderGateway(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"id":"x","model":"gpt-5","choices":[],"usage":{"prompt_tokens":1,"completion_tokens":1}}`))
})
rec := residualPost(gw, "/v1/chat/completions", `{"model":"gpt-5","messages":[{"role":"user","content":"hi"}]}`)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200, body=%.200s", rec.Code, rec.Body.String())
}
if rec.Header().Get("X-Content-Type-Options") != "nosniff" || rec.Header().Get("Content-Security-Policy") != "sandbox" {
t.Errorf("headers = %v, want nosniff and sandbox", rec.Header())
}
}
func TestRelayHardeningHeaders_AbsentOnAdmin(t *testing.T) {
gw := relayHeaderGateway(t, func(w http.ResponseWriter, r *http.Request) {})
req := httptest.NewRequest(http.MethodGet, adminPagePath, nil)
rec := httptest.NewRecorder()
gw.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("admin status = %d, want 200", rec.Code)
}
csp := rec.Header().Get("Content-Security-Policy")
if csp != adminCSP || strings.TrimSpace(csp) == "sandbox" {
t.Errorf("admin Content-Security-Policy = %q, want the admin policy", csp)
}
}
func TestRelayHardeningHeaders_NotSetForDownstreamApp(t *testing.T) {
gw := relayHeaderGateway(t, func(w http.ResponseWriter, r *http.Request) {})
gw.cfg.PassthroughUnknown = true
var seen http.Header
gw.next = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
seen = w.Header().Clone()
w.Header().Set("Content-Security-Policy", "default-src 'self'")
})
rec := httptest.NewRecorder()
gw.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/some/app/page", nil))
if seen == nil {
t.Fatal("downstream handler was not called")
}
if seen.Get("X-Content-Type-Options") != "" || seen.Get("Content-Security-Policy") != "" {
t.Errorf("downstream saw gateway headers: %v", seen)
}
if got := rec.Header().Get("Content-Security-Policy"); got != "default-src 'self'" {
t.Errorf("Content-Security-Policy = %q, want the downstream app's own", got)
}
}
func TestRelayHardeningHeaders_OuterMiddlewareValuesSurviveForDownstreamApp(t *testing.T) {
gw := relayHeaderGateway(t, func(w http.ResponseWriter, r *http.Request) {})
gw.cfg.PassthroughUnknown = true
var seen http.Header
gw.next = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { seen = w.Header().Clone() })
rec := httptest.NewRecorder()
rec.Header().Set("Content-Security-Policy", "default-src 'none'")
rec.Header().Set("X-Content-Type-Options", "outer")
gw.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/some/app/page", nil))
if seen.Get("Content-Security-Policy") != "default-src 'none'" || seen.Get("X-Content-Type-Options") != "outer" {
t.Errorf("downstream saw %v, want the outer middleware values", seen)
}
}
+14 -3
View File
@@ -192,7 +192,12 @@ func (g *Gateway) callAnthropicMessagesPassthrough(ctx context.Context, w http.R
if g.cfg.StripClientAnthropicBeta && strings.EqualFold(name, "anthropic-beta") {
continue
}
for _, v := range clientHeaders.Values(name) {
values := clientHeaders.Values(name)
// The cache key treats a header of empty tokens as absent, so it must not reach the upstream.
if strings.EqualFold(name, "anthropic-beta") && normalizeBetaSet(values) == "" {
continue
}
for _, v := range values {
hdr.Add(name, v)
}
}
@@ -222,7 +227,7 @@ func (g *Gateway) callAnthropicMessagesPassthrough(ctx context.Context, w http.R
return relayAnthropicMessagesStream(w, resp.Body, requestedModel)
}
raw, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes))
raw, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes+1))
if err != nil {
// F5 fix, 2026-08-23 review: the upstream already answered 200
// (already billed server-side) — a body-read failure past that
@@ -261,7 +266,13 @@ func (g *Gateway) callAnthropicMessagesPassthrough(ctx context.Context, w http.R
out, err := rewriteModelField(raw, requestedModel)
if err != nil {
return billed, &responseTranslationError{err: err}
// Only a complete, valid JSON body passes unrewritten; anything else stays a translation failure.
if len(raw) > maxResponseBytes || !json.Valid(raw) {
return billed, &responseTranslationError{err: err}
}
g.warnf("messages route: could not rewrite the model field of an anthropic passthrough response (forwarding the response to the client regardless): %v", err)
out = raw
billed.noStore = true
}
if ct := resp.Header.Get("Content-Type"); ct != "" {
+399 -49
View File
@@ -52,6 +52,8 @@ const (
var sseDataMarker = []byte("data:")
var utf8BOM = []byte{0xEF, 0xBB, 0xBF}
// 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
@@ -276,6 +278,19 @@ var dangerousResponseHeaders = map[string]bool{
"Anthropic-Organization-Id": true,
}
// Hardening values on every non-admin response. Set before dispatch, so an
// upstream X-Content-Type-Options copied over them wins. An upstream
// Content-Security-Policy is stripped above, so the gateway value stays.
const (
relayContentTypeOptions = "nosniff"
relayContentSecurityPolicy = "sandbox"
)
func setRelayHardeningHeaders(h http.Header) {
h.Set("X-Content-Type-Options", relayContentTypeOptions)
h.Set("Content-Security-Policy", relayContentSecurityPolicy)
}
// dangerousResponseHeaderPrefixes strips every Access-Control-* header
// (Access-Control-Allow-Origin, Access-Control-Allow-Credentials, ...)
// an upstream response sets (security review finding 5, round 3,
@@ -441,10 +456,16 @@ func hasTraversalSegment(rest string) bool {
// retains the first maxAccountingTeeBytes of it for a best-effort usage
// parse afterward. truncated records whether the cap was hit, so the
// caller knows a parse would only fail on cut-off JSON and skips it.
// Bytes the buffer does not store also feed a rolling tail of
// sseAccountingTailBytes, so a trailing usage object stays readable. The
// tail sits outside teeBudget: under 2*sseAccountingTailBytes retained per
// truncated reply, with the allocation peaking above that during a trim.
type cappedAccountingBuffer struct {
budget *teeBudget
tail []byte
buf bytes.Buffer
reserved int64
overflow int64
truncated bool
}
@@ -494,28 +515,85 @@ func (c *cappedAccountingBuffer) release() {
func (c *cappedAccountingBuffer) Write(p []byte) (int, error) {
n := len(p)
if c.truncated {
c.addTail(p)
return n, nil
}
remaining := maxAccountingTeeBytes - c.buf.Len()
if remaining <= 0 {
c.truncated = true
c.addTail(p)
return n, nil
}
stored := p
var overflow []byte
if len(p) > remaining {
p = p[:remaining]
stored = p[:remaining]
overflow = p[remaining:]
c.truncated = true
}
if c.budget != nil {
if !c.budget.reserve(int64(len(p))) {
if !c.budget.reserve(int64(len(stored))) {
c.truncated = true
c.addTail(p)
return n, nil
}
c.reserved += int64(len(p))
c.reserved += int64(len(stored))
}
c.buf.Write(stored) //nolint:errcheck // bytes.Buffer.Write never errors
if len(overflow) > 0 {
c.addTail(overflow)
}
c.buf.Write(p) //nolint:errcheck // bytes.Buffer.Write never errors
return n, nil
}
func (c *cappedAccountingBuffer) addTail(p []byte) {
c.tail = appendRollingTail(c.tail, p)
c.overflow += int64(len(p))
}
// scanTail returns the bytes that end the reply: the tail, preceded by the
// end of the stored head when the tail still follows the head without a gap,
// so a usage object that straddles the cap stays readable.
func (c *cappedAccountingBuffer) scanTail() []byte {
if c.overflow != int64(len(c.tail)) {
return lastTailBytes(c.tail)
}
head := c.buf.Bytes()
if len(head) > sseAccountingTailBytes {
head = head[len(head)-sseAccountingTailBytes:]
}
joined := make([]byte, 0, len(head)+len(c.tail))
joined = append(joined, head...)
return append(joined, c.tail...)
}
// tailBytes returns the last (at most) sseAccountingTailBytes of the bytes
// Write did not store in buf.
func (c *cappedAccountingBuffer) tailBytes() []byte { return lastTailBytes(c.tail) }
// appendRollingTail appends p to tail, keeping at least the last
// sseAccountingTailBytes (up to twice that before a trim; read it via
// lastTailBytes). It copies p. When p alone reaches the cap, the result
// is p's own last sseAccountingTailBytes, which bounds memory for a single
// oversized write.
func appendRollingTail(tail, p []byte) []byte {
if len(p) >= sseAccountingTailBytes {
return append(tail[:0], p[len(p)-sseAccountingTailBytes:]...)
}
tail = append(tail, p...)
if len(tail) >= 2*sseAccountingTailBytes {
tail = append(tail[:0], tail[len(tail)-sseAccountingTailBytes:]...)
}
return tail
}
func lastTailBytes(tail []byte) []byte {
if len(tail) > sseAccountingTailBytes {
return tail[len(tail)-sseAccountingTailBytes:]
}
return tail
}
// sseAccountingBuffer is an io.Writer that keeps a bounded HEAD (the
// first sseAccountingHeadBytes, never overwritten once full — mirrors
// cappedAccountingBuffer's own cap-then-discard behavior) alongside a
@@ -559,29 +637,10 @@ func (b *sseAccountingBuffer) Write(p []byte) (int, error) {
return n, nil
}
// appendTail keeps b.tail holding at least the last sseAccountingTailBytes
// written so far (up to twice that before a trim; read it via tailBytes). When p alone is already at or past the cap, the tail becomes
// simply p's own last sseAccountingTailBytes — the fast path for the
// (rare) single oversized write, and what keeps memory bounded even if a
// caller ever writes one huge chunk instead of many small ones.
func (b *sseAccountingBuffer) appendTail(p []byte) {
if len(p) >= sseAccountingTailBytes {
b.tail = append(b.tail[:0], p[len(p)-sseAccountingTailBytes:]...)
return
}
b.tail = append(b.tail, p...)
if len(b.tail) >= 2*sseAccountingTailBytes {
b.tail = append(b.tail[:0], b.tail[len(b.tail)-sseAccountingTailBytes:]...)
}
}
func (b *sseAccountingBuffer) appendTail(p []byte) { b.tail = appendRollingTail(b.tail, p) }
// tailBytes returns the last (at most) sseAccountingTailBytes written.
func (b *sseAccountingBuffer) tailBytes() []byte {
if len(b.tail) > sseAccountingTailBytes {
return b.tail[len(b.tail)-sseAccountingTailBytes:]
}
return b.tail
}
func (b *sseAccountingBuffer) tailBytes() []byte { return lastTailBytes(b.tail) }
// passthroughUsagePayload captures every shape the three provider types'
// native non-streaming JSON responses report token usage in, plus the
@@ -621,6 +680,7 @@ type passthroughUsagePayload struct {
UsageMetadata struct {
PromptTokenCount int64 `json:"promptTokenCount"`
CandidatesTokenCount int64 `json:"candidatesTokenCount"`
ThoughtsTokenCount int64 `json:"thoughtsTokenCount"`
CachedContentTokenCount int64 `json:"cachedContentTokenCount"`
} `json:"usageMetadata"`
}
@@ -642,7 +702,7 @@ func openAIUsageOf(p *passthroughUsagePayload) usage {
}
func geminiUsageOf(p *passthroughUsagePayload) usage {
return usage{prompt: p.UsageMetadata.PromptTokenCount, completion: p.UsageMetadata.CandidatesTokenCount, cached: p.UsageMetadata.CachedContentTokenCount}
return usage{prompt: p.UsageMetadata.PromptTokenCount, completion: p.UsageMetadata.CandidatesTokenCount + p.UsageMetadata.ThoughtsTokenCount, cached: p.UsageMetadata.CachedContentTokenCount}
}
// decodeGeminiArrayUsage handles streamGenerateContent without alt=sse,
@@ -707,6 +767,265 @@ func extractPassthroughUsage(typeName, providerName string, body []byte) (usage,
}
}
// maxKeyDecodeAttempts bounds the candidate decodes of closedTailUsage: a
// failed decode rescans to the end of the tail, so unbounded attempts over
// nested keys are quadratic. More nested usage keys than this after the
// real one exhaust it, and the caller falls back to the estimate.
const maxKeyDecodeAttempts = 16
// usageFromDoc decodes doc as one top-level object (or, when array is set, an
// array of objects) and returns the usage of the last element that carries
// usageKey. Only the top level is read, and an unrelated field of another
// type does not reject the figures. version is that element's modelVersion.
func usageFromDoc(typeName, providerName string, doc []byte, array bool, usageKey string) (usage, string, bool) {
var elems []map[string]json.RawMessage
if array {
if json.Unmarshal(doc, &elems) != nil {
return usage{}, "", false
}
} else {
var m map[string]json.RawMessage
if json.Unmarshal(doc, &m) != nil {
return usage{}, "", false
}
elems = append(elems, m)
}
var zero usage
zeroVersion := ""
zeroFound := false
for i := len(elems) - 1; i >= 0; i-- {
raw, has := elems[i][usageKey]
if !has {
continue
}
u, _, err := extractPassthroughUsage(typeName, providerName, []byte(`{"`+usageKey+`":`+string(raw)+`}`))
if err != nil {
continue
}
version := ""
if rawVersion, hasVersion := elems[i]["modelVersion"]; hasVersion {
_ = json.Unmarshal(rawVersion, &version)
}
if u.total() > 0 || !array {
return u, version, true
}
if !zeroFound {
zero, zeroVersion, zeroFound = u, version, true
}
}
return zero, zeroVersion, zeroFound
}
// closedTailUsage reads the usage of a reply from its tail alone. Every
// `"usage":` key position is a candidate; the bytes from there to the end,
// prefixed with `{` (`[{` for a Gemini array reply), must decode as one whole
// document. A usage nested in another object leaves the parent's closing
// brace over, a reply cut short never closes, and neither is accepted. The
// last candidate that closes wins.
func closedTailUsage(typeName, providerName string, tail []byte, usageKey string, array bool) (usage, string, bool) {
needle := []byte(`"` + usageKey + `"`)
prefix := []byte("{")
if array {
prefix = []byte("[{")
}
end := len(tail)
attempts := 0
for end > 0 {
i := bytes.LastIndex(tail[:end], needle)
if i < 0 {
break
}
end = i
j := i - 1
for j >= 0 && (tail[j] == ' ' || tail[j] == '\n' || tail[j] == '\r' || tail[j] == '\t') {
j--
}
if j >= 0 && tail[j] != '{' && tail[j] != ',' {
continue
}
pos := i + len(needle)
for pos < len(tail) && (tail[pos] == ' ' || tail[pos] == '\n' || tail[pos] == '\r' || tail[pos] == '\t') {
pos++
}
if pos >= len(tail) || tail[pos] != ':' {
continue
}
if attempts >= maxKeyDecodeAttempts {
break
}
attempts++
doc := make([]byte, 0, len(tail)-i+len(prefix))
doc = append(doc, prefix...)
doc = append(doc, tail[i:]...)
u, version, ok := usageFromDoc(typeName, providerName, doc, array, usageKey)
if ok {
return u, version, true
}
}
return usage{}, "", false
}
// walkUsageObject reads the top-level keys of the object whose opening brace
// dec has consumed, skipping each value in one native decode. It returns the
// last usage found, the last modelVersion, whether a usage was found, and
// whether the object closed within the data.
func walkUsageObject(dec *json.Decoder, typeName, providerName, usageKey string) (usage, string, bool, bool) {
var found usage
version := ""
ok := false
for dec.More() {
keyTok, keyErr := dec.Token()
if keyErr != nil {
return found, version, ok, false
}
key, isString := keyTok.(string)
if !isString {
return found, version, ok, false
}
var raw json.RawMessage
if dec.Decode(&raw) != nil {
return found, version, ok, false
}
switch {
case strings.EqualFold(key, usageKey):
u, _, extractErr := extractPassthroughUsage(typeName, providerName, []byte(`{"`+usageKey+`":`+string(raw)+`}`))
if extractErr == nil {
found = u
ok = true
}
case key == "modelVersion":
var v string
if json.Unmarshal(raw, &v) == nil {
version = v
}
}
}
_, closeErr := dec.Token()
return found, version, ok, closeErr == nil
}
// headTopLevelUsage walks the top-level keys of head from the start (the
// elements of a Gemini array reply, one level down) and returns the last
// top-level usage complete within head, with the top-level modelVersion.
func headTopLevelUsage(typeName, providerName string, head []byte, usageKey string) (usage, string, bool) {
dec := json.NewDecoder(bytes.NewReader(head))
tok, err := dec.Token()
if err != nil {
return usage{}, "", false
}
delim, isDelim := tok.(json.Delim)
if !isDelim {
return usage{}, "", false
}
if delim == '{' {
u, version, ok, _ := walkUsageObject(dec, typeName, providerName, usageKey)
return u, version, ok
}
if delim != '[' || typeName != providerTypeGemini {
return usage{}, "", false
}
var found usage
version := ""
ok := false
for dec.More() {
elemTok, elemErr := dec.Token()
if elemErr != nil {
break
}
if d, isOpen := elemTok.(json.Delim); !isOpen || d != '{' {
break
}
u, v, elemOK, clean := walkUsageObject(dec, typeName, providerName, usageKey)
if elemOK && (u.total() > 0 || !ok) {
found = u
ok = true
}
if v != "" {
version = v
}
if !clean {
break
}
}
return found, version, ok
}
// firstNonSpace returns the first byte of b that is not JSON whitespace, or 0.
func firstNonSpace(b []byte) byte {
for i := 0; i < len(b); i++ {
if b[i] != ' ' && b[i] != '\n' && b[i] != '\r' && b[i] != '\t' {
return b[i]
}
}
return 0
}
// extractTruncatedJSONUsage reads the usage of a JSON reply that outgrew the
// accounting tee: head is the stored prefix, tail the last bytes. A usage
// that closes the reply in the tail wins, then a top-level usage inside the
// head. A reply whose copy was cut short (complete false) never closes, so
// its tail proves nothing and only the head counts. Zero usage when neither
// exists, which sends the caller to its estimate.
func extractTruncatedJSONUsage(typeName, providerName string, head, tail []byte, complete bool) (usage, string) {
usageKey := "usage"
if typeName == providerTypeGemini {
usageKey = "usageMetadata"
}
array := typeName == providerTypeGemini && firstNonSpace(head) == '['
var found usage
version := ""
ok := false
if complete {
found, version, ok = closedTailUsage(typeName, providerName, tail, usageKey, array)
}
if !ok {
var headVersion string
found, headVersion, _ = headTopLevelUsage(typeName, providerName, head, usageKey)
if version == "" {
version = headVersion
}
}
model := ""
if typeName == providerTypeGemini {
model = version
if model == "" && ok {
_, model, _ = headTopLevelUsage(typeName, providerName, head, usageKey)
}
} else {
model, _, _, _ = scanTopLevelModel(head)
}
if model == "" {
model = "unknown/" + providerName
}
return found, model
}
// relayHardeningHeaderNames are the headers setRelayHardeningHeaders owns.
var relayHardeningHeaderNames = []string{"X-Content-Type-Options", "Content-Security-Policy"}
// saveRelayHardeningHeaders copies the hardening headers already in h.
func saveRelayHardeningHeaders(h http.Header) http.Header {
saved := http.Header{}
for _, name := range relayHardeningHeaderNames {
if v, ok := h[name]; ok {
saved[name] = append([]string(nil), v...)
}
}
return saved
}
// restoreRelayHardeningHeaders drops the gateway's hardening headers and
// puts back the saved values, so a header an outer middleware set survives.
func restoreRelayHardeningHeaders(h, saved http.Header) {
for _, name := range relayHardeningHeaderNames {
h.Del(name)
if v, ok := saved[name]; ok {
h[name] = v
}
}
}
// extractPassthroughSSEUsage best-effort parses head and tail — the
// bounded first/last windows an sseAccountingBuffer captured, teed
// alongside the client-facing copy (verify-core fix, round 4: a single
@@ -924,7 +1243,7 @@ func parseSSEUsageChunk(typeName string, raw []byte) (usage, string) {
// 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) (string, bool, bool, error) {
model, hasModel, truncated, _, _, err := peekPassthroughModelUpTo(r, maxModelPeekBytes)
model, hasModel, truncated, _, _, _, err := peekPassthroughModelUpTo(r, maxModelPeekBytes)
return model, hasModel, truncated, err
}
@@ -933,15 +1252,15 @@ func peekPassthroughModel(r *http.Request) (string, bool, bool, error) {
// 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) {
// as undeterminable. isObject reports that the body opens a JSON object.
func peekPassthroughModelUpTo(r *http.Request, limit int64) (string, bool, bool, bool, bool, bool, error) {
if r.Body == nil || isPassthroughBinaryContentType(r.Header.Get("Content-Type")) {
return "", false, false, false, false, nil
return "", false, false, false, false, false, nil
}
head, readErr := io.ReadAll(io.LimitReader(r.Body, limit))
if readErr != nil {
return "", false, false, false, false, readErr
return "", false, false, false, false, false, readErr
}
// 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
@@ -949,9 +1268,13 @@ func peekPassthroughModelUpTo(r *http.Request, limit int64) (string, bool, bool,
capped := int64(len(head)) >= limit
r.Body = io.NopCloser(io.MultiReader(bytes.NewReader(head), r.Body))
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
// A leading BOM makes the scan fail at the first token; the forwarded
// body keeps its bytes.
scanned := bytes.TrimPrefix(head, utf8BOM)
model, hasModel, closed, duplicate := scanTopLevelModel(scanned)
isObject := bytes.HasPrefix(bytes.TrimLeft(scanned, " \t\r\n"), []byte("{"))
unparseable := !closed && isObject
return model, hasModel, capped && !closed, duplicate, unparseable, isObject, nil
}
// scanTopLevelModel walks head — a bounded, possibly-truncated PREFIX of
@@ -1007,6 +1330,12 @@ func scanTopLevelModel(head []byte) (string, bool, bool, bool) {
if !ok {
return model, found, false, false // malformed: expected an object key
}
if strings.EqualFold(key, "model") && key != "model" {
// A case-sensitive upstream ignores this key and runs its default
// model, a folding one runs this value; neither matches the
// model that would be gated.
return "", false, false, 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
@@ -1032,7 +1361,9 @@ func scanTopLevelModel(head []byte) (string, bool, bool, bool) {
// {"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.
// only safe answer is to refuse to answer. The key is matched
// case-insensitively because Go's encoding/json folds case, so
// {"model":"a","Model":"b"} runs "b" there.
if seenModel {
return "", false, false, true
}
@@ -1366,11 +1697,12 @@ func (g *Gateway) handlePassthrough(w http.ResponseWriter, r *http.Request, u *u
// 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.
// ungated: Gemini passthrough (model in the URL), a binary content
// type, whose body is never read, and a body under 64KiB that is
// not a JSON object.
var gatedModel string
if !g.cfg.AllowUnpricedWithCostBudget && scopesHaveCostBudget(scopes) {
model, hasModel, truncated, duplicate, unparseable, peekErr := peekPassthroughModelUpTo(r, maxModelPeekBytes)
model, hasModel, truncated, duplicate, unparseable, isObject, peekErr := peekPassthroughModelUpTo(r, maxModelPeekBytes)
widened := peekErr == nil && truncated
if widened {
// The first window cannot settle the model (a later key may add or
@@ -1392,7 +1724,7 @@ func (g *Gateway) handlePassthrough(w http.ResponseWriter, r *http.Request, u *u
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)
model, hasModel, truncated, duplicate, unparseable, isObject, peekErr = peekPassthroughModelUpTo(r, bound+1)
release()
if peekErr != nil {
writeOAIError(w, http.StatusBadRequest, "invalid_request_error", "cannot read request body")
@@ -1406,7 +1738,10 @@ func (g *Gateway) handlePassthrough(w http.ResponseWriter, r *http.Request, u *u
return
}
}
if peekErr == nil && (duplicate || unparseable || (!hasModel && widened)) {
// A JSON object that names no model is refused at any size; the
// model of a Gemini request is in the URL, so its body never has one.
noModelObject := isObject && !hasModel && adapter.typeName() != providerTypeGemini
if peekErr == nil && (duplicate || unparseable || (!hasModel && widened) || noModelObject) {
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",
@@ -1480,7 +1815,7 @@ func (g *Gateway) handlePassthrough(w http.ResponseWriter, r *http.Request, u *u
}))
}
result, complete := g.proxyUpstream(w, r, upstreamURL, adapter.httpClient(), adapter.injectAuth, providerCredentialRetargetHeaders, true, "passthrough (provider "+providerName+")", adapter.requestTimeout(), false)
result, complete := g.proxyUpstream(w, withConfiguredURL(r, upstreamBase), upstreamURL, adapter.httpClient(), adapter.injectAuth, providerCredentialRetargetHeaders, true, "passthrough (provider "+providerName+")", adapter.requestTimeout(), false)
defer result.tee.release()
g.recordProxyEvent(scopes, providerName, routePassthrough, result) // F3 hook 3 (v0.3 dashboard task)
@@ -1519,7 +1854,10 @@ func (g *Gateway) handlePassthrough(w http.ResponseWriter, r *http.Request, u *u
g.logf("passthrough: response body did not decode as JSON for usage accounting (provider %q): %v", providerName, unmarshalErr)
}
case result.isJSON:
g.logf("passthrough: response body exceeded %d bytes; falling back to an estimate (provider %q)", maxAccountingTeeBytes, providerName)
respUsage, respModel = extractTruncatedJSONUsage(adapter.typeName(), providerName, result.tee.buf.Bytes(), result.tee.scanTail(), complete)
if respUsage.total() == 0 {
g.logf("passthrough: response body exceeded %d bytes; falling back to an estimate (provider %q)", maxAccountingTeeBytes, providerName)
}
default: // result.isSSE
respUsage, respModel = extractPassthroughSSEUsage(adapter.typeName(), providerName, result.sseTee.head.Bytes(), result.sseTee.tailBytes())
}
@@ -1550,7 +1888,8 @@ func (g *Gateway) handlePassthrough(w http.ResponseWriter, r *http.Request, u *u
if !canEstimate || (respUsage.prompt == 0 && result.requestBytes <= 0) {
return
}
if respUsage.prompt == 0 {
promptEstimated := respUsage.prompt == 0
if promptEstimated {
respUsage.prompt = estimatePromptTokens(int64(result.requestBytes))
}
if sseNoCompletion {
@@ -1563,7 +1902,17 @@ func (g *Gateway) handlePassthrough(w http.ResponseWriter, r *http.Request, u *u
if respModel == "" {
respModel = "unknown/" + providerName
}
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)
var estimatedParts string
if promptEstimated {
estimatedParts = "prompt tokens estimated from the request size"
}
if sseNoCompletion {
if estimatedParts != "" {
estimatedParts += ", "
}
estimatedParts += "completion tokens estimated from the stream event count"
}
g.logf("passthrough: usage for provider %q logged as estimated (%s)", providerName, estimatedParts)
}
canonical := providerName + "/" + respModel
@@ -1811,6 +2160,7 @@ func (g *Gateway) proxyUpstream(w http.ResponseWriter, r *http.Request, upstream
writeOAIError(w, http.StatusRequestEntityTooLarge, "invalid_request_error", "request body exceeds the maximum allowed size")
return proxyResult{}, false
}
configuredURL := configuredURLOf(r)
body := &cappedBodyReader{r: r.Body, limit: maxPassthroughBytes}
// gosec G704 (SSRF via taint analysis) flags upstreamURL as
// request-derived: it is, by design — this is a reverse proxy, and its
@@ -1838,7 +2188,7 @@ func (g *Gateway) proxyUpstream(w http.ResponseWriter, r *http.Request, upstream
upstreamReq, err := http.NewRequestWithContext(reqCtx, r.Method, upstreamURL, body) //nolint:gosec // operator-fixed host, rest is traversal-checked and forwarded escaped; see comment above
if err != nil {
cancel()
g.errorf("%s: build upstream request: %v", logPrefix, err)
g.errorf("%s: build upstream request: %v", logPrefix, sanitizeProviderErr(err.Error(), configuredURL))
writeOAIError(w, http.StatusBadGateway, "server_error", "upstream connection error")
return proxyResult{}, false
}
@@ -1893,7 +2243,7 @@ func (g *Gateway) proxyUpstream(w http.ResponseWriter, r *http.Request, upstream
if err != nil {
cancel()
if errors.Is(err, context.Canceled) {
g.logf("%s: client canceled request: %v", logPrefix, err)
g.logf("%s: client canceled request: %v", logPrefix, sanitizeProviderErr(err.Error(), configuredURL))
return proxyResult{clientCanceled: true}, false
}
if errors.Is(err, errPassthroughBodyTooLarge) {
@@ -1915,7 +2265,7 @@ func (g *Gateway) proxyUpstream(w http.ResponseWriter, r *http.Request, upstream
// the same way every other target/upstream-URL-bearing log line
// in this codebase is (sanitizeBaseURL/sanitizeProviderErr,
// admin.go).
g.errorf("%s: upstream connection error: %v", logPrefix, sanitizeProviderErr(err.Error(), upstreamURL))
g.errorf("%s: upstream connection error: %v", logPrefix, sanitizeProviderErr(err.Error(), configuredURL))
writeOAIError(w, http.StatusBadGateway, "server_error", "upstream connection error")
return proxyResult{}, false
}
@@ -2011,10 +2361,10 @@ func (g *Gateway) proxyUpstream(w http.ResponseWriter, r *http.Request, upstream
// disconnect from this gateway's own idle-progress watchdog firing
// — the latter falls through to the errorf below, unchanged.
if errors.Is(err, context.Canceled) {
g.logf("%s: client canceled request: %v", logPrefix, err)
g.logf("%s: client canceled request: %v", logPrefix, sanitizeProviderErr(err.Error(), configuredURL))
return proxyResult{isJSON: isJSON, isSSE: isSSE, tee: tee, sseTee: sseTee, status: resp.StatusCode, clientCanceled: true, requestBytes: requestBytes}, false
}
g.errorf("%s: stream response body: %v", logPrefix, err)
g.errorf("%s: stream response body: %v", logPrefix, sanitizeProviderErr(err.Error(), configuredURL))
return proxyResult{isJSON: isJSON, isSSE: isSSE, tee: tee, sseTee: sseTee, status: resp.StatusCode, requestBytes: requestBytes}, false
}
return proxyResult{isJSON: isJSON, isSSE: isSSE, tee: tee, sseTee: sseTee, status: resp.StatusCode, requestBytes: requestBytes}, true
+12 -18
View File
@@ -606,12 +606,15 @@ func TestHandlePassthrough_DangerousResponseHeadersStripped(t *testing.T) {
}
for _, hdr := range []string{
"Set-Cookie", "Access-Control-Allow-Origin", "Access-Control-Allow-Credentials",
"Strict-Transport-Security", "Content-Security-Policy",
"Strict-Transport-Security",
} {
if v := rec.Header().Get(hdr); v != "" {
t.Errorf("client saw dangerous response header %s = %q, want stripped", hdr, v)
}
}
if v := rec.Header().Get("Content-Security-Policy"); v != "sandbox" {
t.Errorf("Content-Security-Policy = %q, want the gateway's sandbox, not the upstream value", v)
}
if rec.Header().Get("Content-Type") != "application/json" {
t.Error("client must still see Content-Type — the strip is a deny-list, not an allowlist")
}
@@ -1063,16 +1066,11 @@ func TestHandlePassthrough_EncodedSlashSegment_PreservedAtUpstream(t *testing.T)
}
}
// TestHandlePassthrough_OversizedJSONBody_ClientGetsFullBody_EstimatedAccounting
// TestHandlePassthrough_OversizedJSONBody_ClientGetsFullBody_ReportedUsageBilled
// proves a JSON response body larger than maxAccountingTeeBytes still
// reaches the client in full, while the accounting PARSE is skipped (the
// tee never captured the "usage" field, which sits past the cap) — but
// (finding 2 fix, review-routes.md, supersedes this test's own former
// "request only" name and assertions) the request is no longer billed
// zero usage just because its response happened to be too large to
// parse: it falls back to the same request-body-size estimate a
// streamed response with no usable usage now also gets.
func TestHandlePassthrough_OversizedJSONBody_ClientGetsFullBody_EstimatedAccounting(t *testing.T) {
// reaches the client in full, and that its usage object, which sits in the
// last bytes past the tee cap, is billed as reported rather than estimated.
func TestHandlePassthrough_OversizedJSONBody_ClientGetsFullBody_ReportedUsageBilled(t *testing.T) {
// Pad well past maxAccountingTeeBytes (4MiB) with an oversized field
// ahead of "usage", so the tee's cap is hit before "usage" is reached.
padding := strings.Repeat("x", maxAccountingTeeBytes+1024)
@@ -1115,17 +1113,13 @@ func TestHandlePassthrough_OversizedJSONBody_ClientGetsFullBody_EstimatedAccount
t.Errorf("client body = %d bytes, want the full %d bytes (client copy must never truncate)", rec.Body.Len(), len(respBody))
}
// The request body here is `{}` (2 bytes): ceil(2/4) = 1 estimated
// prompt token, 0 completion (finding 2's estimate has no basis for a
// completion-side number, matching the unified route's own identical
// estimate, routes_unified.go).
tokIn, ok := gw.limiter.getCounter("user", "alice", metricTokIn, windowDay, time.Now())
if !ok || tokIn != 1 {
t.Errorf("user tokin/day counter = %d (ok=%v), want 1 (estimated from the 2-byte request body)", tokIn, ok)
if !ok || tokIn != 7 {
t.Errorf("user tokin/day counter = %d (ok=%v), want 7 (reported)", tokIn, ok)
}
tokOut, ok := gw.limiter.getCounter("user", "alice", metricTokOut, windowDay, time.Now())
if !ok || tokOut != 0 {
t.Errorf("user tokout/day counter = %d (ok=%v), want 0", tokOut, ok)
if !ok || tokOut != 3 {
t.Errorf("user tokout/day counter = %d (ok=%v), want 3 (reported)", tokOut, ok)
}
reqCount, ok := gw.limiter.getCounter("user", "alice", metricReq, windowMin, time.Now())
if !ok || reqCount != 1 {
+39 -8
View File
@@ -723,10 +723,14 @@ 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.
completionEstimated := result.estimated && result.completion > 0
promptEstimated := false
inputEstimated := result.estimated && result.completion == 0 && result.prompt > 0
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
promptEstimated = true
}
if result.total() == 0 {
switch {
@@ -756,12 +760,14 @@ func (g *Gateway) runMeteredCall(sw *statusTrackingWriter, r *http.Request, scop
// the next candidate's real usage.
result.prompt = estimatePromptTokens(int64(len(body)))
result.estimated = true
promptEstimated = true
g.logf("%s: streaming response from model %q failed or was canceled after starting to write to the client with zero usage reported; accounting an estimate derived from request body size", logPrefix, cand.canonical)
case streaming:
g.logf("%s: zero usage reported for a streaming response from model %q; accounting the request only", logPrefix, cand.canonical)
case callErr == nil:
result.prompt = estimatePromptTokens(int64(len(body)))
result.estimated = true
promptEstimated = true
}
}
// Q1 fix (DECISIONS; pre-existing defect, WP-A step 7): kindModel's
@@ -825,7 +831,8 @@ func (g *Gateway) runMeteredCall(sw *statusTrackingWriter, r *http.Request, scop
g.recordPromptCache(providerName, cand.upstreamModel, result)
g.limiter.accountWith(acctScopes, result, unifiedCostMicros(cand.canonical, cand.upstreamModel, result, g.cfg.Pricing, g.cfg.ModelMeta, g.pricingWarn), extras)
if result.estimated {
g.logf("%s: usage for model %q logged as estimated (%d prompt tokens derived from request body size, not the provider's reported usage)", logPrefix, cand.canonical, result.prompt)
detail := estimatedUsageDetail(promptEstimated, completionEstimated, inputEstimated)
g.logf("%s: usage for model %q logged as estimated (%s, not the provider's reported usage)", logPrefix, cand.canonical, detail)
}
if calibrate {
@@ -869,7 +876,11 @@ func (g *Gateway) runMeteredCall(sw *statusTrackingWriter, r *http.Request, scop
// store's own maxBodyBytes check would reject it too, but only
// after being handed a silently truncated body — skip the call
// outright instead of ever constructing a corrupt cache entry.
if cacheable && callErr == nil && capture.status == http.StatusOK && !capture.oversize {
// result.noStore excludes a reply the route relayed without its
// own re-encoding (an unrewritten /v1/messages body): storing it
// would let a later request get a copy of a reply that was never
// valid for the cache's own key.
if cacheable && callErr == nil && capture.status == http.StatusOK && !capture.oversize && !result.noStore {
g.cache.store(cacheKeyStr, capture.status, capture.contentType, capture.buf.Bytes(), effectiveTTL(g.cache, grp))
}
@@ -1056,7 +1067,9 @@ func (g *Gateway) admitRequestForRoute(ctx context.Context, sw *statusTrackingWr
// will a slot free" answer the way a rate-limit window does (unlike
// writeLimitViolation's retryAfter, which names a real window boundary),
// and the in-flight cap is expected to drain within single-digit seconds
// under normal request latency.
// under normal request latency. That holds only when clients finish their
// bodies: a stalled body keeps its slot, and the ReadTimeout comment in
// cmd/gateway/main.go says why the binary sets no read timeout.
const bodyAdmissionRetryAfterSeconds = 2
// acquireBodyAdmission non-blockingly claims one of g.bodyAdmission's
@@ -1367,8 +1380,11 @@ func (g *Gateway) handleAdapterErrorEnvelope(sw *statusTrackingWriter, err error
// request that turned out not to succeed.
sw.Header().Del("X-Llmgw-Cache")
baseURL := g.providerBaseURL(providerName)
errText := sanitizeProviderErr(fmt.Sprint(err), baseURL)
if sw.wroteHeader {
g.errorf("%s: adapter error after response started (provider %q): %v", logPrefix, providerName, err)
g.errorf("%s: adapter error after response started (provider %q): %v", logPrefix, providerName, errText)
if errors.Is(err, errStreamErrorRelayed) {
return
}
@@ -1422,23 +1438,23 @@ func (g *Gateway) handleAdapterErrorEnvelope(sw *statusTrackingWriter, err error
// never exists twice — see handleAdapterErrorEnvelope's own doc
// comment (item 7).
if terr, ok := err.(*responseTranslationError); ok {
g.errorf("%s: response translation failed after a billed upstream call (provider %q): %v", logPrefix, providerName, terr.err)
g.errorf("%s: response translation failed after a billed upstream call (provider %q): %v", logPrefix, providerName, sanitizeProviderErr(fmt.Sprint(terr.err), baseURL))
envelope(sw, http.StatusBadGateway, "server_error", "failed to translate provider response")
return
}
if _, ok := err.(*firstByteTimeoutError); ok {
g.errorf("%s: %v", logPrefix, err)
g.errorf("%s: %v", logPrefix, errText)
envelope(sw, http.StatusGatewayTimeout, "timeout_error", routerSlowMessage)
return
}
if errors.Is(err, context.Canceled) {
g.logf("%s: client canceled request to provider %q: %v", logPrefix, providerName, err)
g.logf("%s: client canceled request to provider %q: %v", logPrefix, providerName, errText)
return
}
g.errorf("%s: upstream connection error (provider %q): %v", logPrefix, providerName, err)
g.errorf("%s: upstream connection error (provider %q): %v", logPrefix, providerName, errText)
envelope(sw, http.StatusBadGateway, "server_error", "upstream connection error")
}
@@ -1604,3 +1620,18 @@ func estimatePromptTokens(bodyBytes int64) int64 {
}
return est
}
// estimatedUsageDetail says which usage counts were estimated and from what.
func estimatedUsageDetail(prompt, completion, input bool) string {
switch {
case input && !prompt && !completion:
return "prompt tokens estimated by the adapter from the input text size"
case prompt && completion:
return "prompt tokens derived from request body size, completion tokens from streamed output size"
case completion:
return "completion tokens derived from streamed output size"
case prompt:
return "prompt tokens derived from request body size"
}
return "token counts derived from sizes"
}
+56
View File
@@ -0,0 +1,56 @@
package traefikllmgateway
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func estimateLogFor(t *testing.T, providerType, model string, frames []string) string {
t.Helper()
srv := hangupServer(t, "text/event-stream", frames)
defer srv.Close()
gw := newStreamBillingGateway(t, providerType, srv.URL, model)
body := map[string]any{"model": model, "stream": true, "max_tokens": 100, "messages": []any{map[string]any{"role": "user", "content": "hi"}}}
return captureStderr(t, func() {
gw.ServeHTTP(newRecordingWriter(), newUnifiedRequest(t, http.MethodPost, "/v1/chat/completions", "sk-alice", body))
})
}
func TestEstimatedUsageLog_NamesWhatWasEstimated(t *testing.T) {
t.Run("completion only", func(t *testing.T) {
out := estimateLogFor(t, providerTypeAnthropic, "claude-test", anthropicFrames(20, false))
if !strings.Contains(out, "logged as estimated (completion tokens derived from streamed output size") {
t.Errorf("log = %q, want completion-only estimate", out)
}
if strings.Contains(out, "prompt tokens derived from request body size") {
t.Errorf("log claims the prompt was estimated: %q", out)
}
})
t.Run("prompt and completion", func(t *testing.T) {
out := estimateLogFor(t, providerTypeOpenAI, "gpt-test", openAIContentFrames(12))
if !strings.Contains(out, "prompt tokens derived from request body size, completion tokens from streamed output size") {
t.Errorf("log = %q, want prompt and completion estimate", out)
}
})
}
func TestEstimatedUsageLog_GeminiEmbeddingsNamesInputEstimate(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"embedding":{"values":[0.1,0.2]}}`))
}))
defer srv.Close()
gw := newStreamBillingGateway(t, providerTypeGemini, srv.URL, "text-embedding-004")
body := map[string]any{"model": "text-embedding-004", "input": "hello world"}
out := captureStderr(t, func() {
gw.ServeHTTP(httptest.NewRecorder(), newUnifiedRequest(t, http.MethodPost, "/v1/embeddings", "sk-alice", body))
})
if !strings.Contains(out, "logged as estimated (prompt tokens estimated by the adapter from the input text size") {
t.Errorf("log = %q, want the adapter input estimate message", out)
}
if strings.Contains(out, "derived from sizes") {
t.Errorf("log fell through to the vague default: %q", out)
}
}
+135
View File
@@ -0,0 +1,135 @@
package traefikllmgateway
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"strings"
"testing"
"time"
)
const configuredSecret = "PLACEHOLDERSECRET"
// captureLargeStderr drains the pipe while fn runs; captureStderr reads
// afterwards and would block on output above the pipe buffer.
func captureLargeStderr(t *testing.T, fn func()) string {
t.Helper()
orig := os.Stderr
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
os.Stderr = w
done := make(chan string)
go func() {
b, _ := io.ReadAll(r)
done <- string(b)
}()
fn()
os.Stderr = orig
_ = w.Close()
return <-done
}
func TestSanitizeProviderErr_EveryContextRedacted(t *testing.T) {
passwordURL := "http://" + "user:" + configuredSecret + "@h.invalid:1/v1"
queryURL := "http://h.invalid:1/v1?key=" + configuredSecret
contexts := map[string]string{
"double quote": `"` + configuredSecret + `"`,
"single quote": `'` + configuredSecret + `'`,
"backtick": "`" + configuredSecret + "`",
"space": "token " + configuredSecret + " end",
"percent 3D": "a%3D" + configuredSecret,
"percent 2F": "http%3A%2F%2F" + configuredSecret,
"bracket": "[" + configuredSecret + "]",
"comma": "a," + configuredSecret,
"hash": "a#" + configuredSecret,
"line start": configuredSecret + " failed",
"after newline": "x\n" + configuredSecret,
}
for _, cfg := range []string{passwordURL, queryURL} {
for name, msg := range contexts {
t.Run(name, func(t *testing.T) {
if got := sanitizeProviderErr(msg, cfg); strings.Contains(got, configuredSecret) {
t.Errorf("credential leaked: %q", got)
}
})
}
}
}
func TestSanitizeProviderErr_ShortAndCommonComponentsKept(t *testing.T) {
cfg := "http://h.invalid:1/v1?a=true&b=api&c=v1&d=" + configuredSecret
const msg = "api v1 true http failed"
if got := sanitizeProviderErr(msg, cfg); got != msg {
t.Errorf("ordinary text redacted: %q", got)
}
}
func TestTargetProxy_ClientQueryContributesNoComponents(t *testing.T) {
addr := closedLoopbackAddr(t)
h := newTargetRedirectGateway(t, "http://"+addr+"/mcp?api-key="+configuredSecret, "http://"+addr+"/a2a")
pad := strings.Repeat("a", 950<<10)
q := "x=127.0.0.1&y=" + url.QueryEscape("context canceled") + "&pad=" + pad
req := httptest.NewRequest(http.MethodGet, "/mcp/alpha?"+q, nil)
req.Header.Set("Authorization", "Bearer sk-alice")
start := time.Now()
out := captureLargeStderr(t, func() { h.ServeHTTP(httptest.NewRecorder(), req) })
t.Logf("elapsed %v", time.Since(start))
if !strings.Contains(out, "upstream connection error") {
t.Fatalf("precondition: no connection error logged (len %d)", len(out))
}
if strings.Contains(out, configuredSecret) {
t.Error("log carries the configured credential")
}
if !strings.Contains(out, "x=127.0.0.1") {
t.Error("client query text was redacted")
}
}
func TestUnparseableConfiguredURL_NoSecretInAnyErrorText(t *testing.T) {
// Joined at run time: staticcheck rejects a constant invalid URL, and the invalid URL is the subject.
raw := strings.Join([]string{"http://user:", configuredSecret, "/x@h"}, "")
_, perr := url.Parse(raw)
if perr == nil || !strings.Contains(perr.Error(), configuredSecret) {
t.Fatalf("precondition: parse error must carry the secret: %v", perr)
}
t.Run("parse error", func(t *testing.T) {
if got := sanitizeProviderErr(perr.Error(), raw); strings.Contains(got, configuredSecret) {
t.Errorf("leaked: %q", got)
}
})
t.Run("transport error", func(t *testing.T) {
resp, err := http.Get(raw + "/v1/models") //nolint:gosec,noctx // unparseable URL, the error text is the subject
if err == nil {
_ = resp.Body.Close()
t.Fatal("expected an error")
}
if got := sanitizeProviderErr(err.Error(), raw); strings.Contains(got, configuredSecret) {
t.Errorf("leaked: %q", got)
}
})
t.Run("overview and log", func(t *testing.T) {
h, log := renderingsGateway(t, raw)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, adminRequest(http.MethodGet, adminOverviewPath, "sk-admin1"))
var got adminOverviewResponse
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil || len(got.Providers) != 1 {
t.Fatalf("overview decode: %v", err)
}
if strings.Contains(got.Providers[0].LastErr, configuredSecret) || strings.Contains(log, configuredSecret) {
t.Errorf("leaked: lastErr=%q log=%q", got.Providers[0].LastErr, log)
}
})
t.Run("unified route", func(t *testing.T) {
out := unifiedChatLog(t, raw, context.Background())
if strings.Contains(out, configuredSecret) {
t.Errorf("log leaked: %q", out)
}
})
}
+61
View File
@@ -0,0 +1,61 @@
package traefikllmgateway
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestPassthrough_ClientPathAndQueryStayIntact(t *testing.T) {
addr := closedLoopbackAddr(t)
env := newGateEnv(t, func(c *Config) {
c.Providers["openai"].BaseURL = "http://" + addr + "/v1?key=" + configuredSecret
})
req := httptest.NewRequest(http.MethodGet, "/openai/v1/x&connection&refused&dial?note=client-text", nil)
req.Header.Set("Authorization", "Bearer sk-alice")
out := captureStderr(t, func() { env.h.ServeHTTP(httptest.NewRecorder(), req) })
if !strings.Contains(out, "upstream connection error") {
t.Fatalf("precondition: no connection error logged: %q", out)
}
if strings.Contains(out, configuredSecret) {
t.Errorf("log carries the configured credential: %q", out)
}
for _, want := range []string{"connection refused", "note=client-text"} {
if !strings.Contains(out, want) {
t.Errorf("client text %q was redacted: %q", want, out)
}
}
}
func TestSanitizeProviderErr_QueryNamesAndMinimumLength(t *testing.T) {
t.Run("labelled query name kept", func(t *testing.T) {
const msg = "read tcp: i/o timeout"
if got := sanitizeProviderErr(msg, "http://h.invalid:1/v1?timeout=30"); got != msg {
t.Errorf("label redacted: %q", got)
}
})
t.Run("valueless query name redacted", func(t *testing.T) {
if got := sanitizeProviderErr("failed ?"+configuredSecret, "http://h.invalid:1/v1?"+configuredSecret); strings.Contains(got, configuredSecret) {
t.Errorf("leaked: %q", got)
}
})
t.Run("minimum length", func(t *testing.T) {
if got := sanitizeProviderErr("x abcd y", "http://h.invalid:1/v1?k=abcd"); got != "x *** y" {
t.Errorf("4-character secret not redacted: %q", got)
}
if got := sanitizeProviderErr("x abc y", "http://h.invalid:1/v1?k=abc"); got != "x abc y" {
t.Errorf("3-character value redacted: %q", got)
}
})
}
func TestConfiguredURLOf_NoGuessing(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "/p?q=client", nil)
if got := configuredURLOf(r); got != "" {
t.Errorf("configuredURLOf without a recorded URL = %q, want empty", got)
}
if got := configuredURLOf(withConfiguredURL(r, "http://h.invalid/v1")); got != "http://h.invalid/v1" {
t.Errorf("configuredURLOf = %q", got)
}
}
+178
View File
@@ -0,0 +1,178 @@
package traefikllmgateway
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
)
const renderingMarker = "TOKEN123"
func auditPayloads(addr string) map[string]string {
return map[string]string{
"quote in query": "http://" + addr + "?api-key=DUMMY\"" + renderingMarker,
"backslash in query": "http://" + addr + "?api-key=DUMMY\\" + renderingMarker,
"nbsp in query": "http://" + addr + "?api-key=DUMMY " + renderingMarker,
"quote in password": "http://user:DUMMY\"" + renderingMarker + "@" + addr,
"trailing newline": "http://user:DUMMY" + renderingMarker + "@" + addr + "\n",
"run3 upper scheme": "HTTP://" + renderingMarker + "@" + addr + "/v1",
"run3 escaped userinf": "http://us%40" + renderingMarker + "@" + addr + "/v1",
"run3 upper query": "HTTP://" + addr + "/v1?key=" + renderingMarker,
"plain query": "http://" + addr + "/v1?key=" + renderingMarker,
}
}
func TestSanitizeProviderErr_QuotedRenderings(t *testing.T) {
addr := closedLoopbackAddr(t)
for name, base := range auditPayloads(addr) {
if !strings.HasPrefix(name, "quote") && !strings.HasPrefix(name, "backslash") && !strings.HasPrefix(name, "nbsp") && !strings.HasPrefix(name, "trailing") {
continue
}
t.Run(name, func(t *testing.T) {
resp, err := http.Get(base + "/v1/models") //nolint:gosec,noctx // closed loopback port, the error text is the subject
if err == nil {
_ = resp.Body.Close()
t.Fatal("expected an error")
}
if !strings.Contains(err.Error(), renderingMarker) {
t.Fatalf("precondition: error does not carry the marker: %v", err)
}
if got := sanitizeProviderErr(err.Error(), base); strings.Contains(got, renderingMarker) || strings.Contains(got, "DUMMY") {
t.Fatalf("credential leaked: %q", got)
}
})
}
}
func TestSanitizeProviderErr_URLEncodedRendering(t *testing.T) {
base := "http://example.invalid/v1?api-key=DUMMY\"" + renderingMarker
for name, enc := range map[string]string{
"query escape": url.QueryEscape(base),
"path escape": url.PathEscape(base),
} {
t.Run(name, func(t *testing.T) {
got := sanitizeProviderErr("redirect_uri="+enc+" rejected", base)
if strings.Contains(got, renderingMarker) || strings.Contains(got, "DUMMY") {
t.Fatalf("credential leaked: %q", got)
}
})
}
}
func withUserinfo(userinfo, path string) string {
return "http://" + userinfo + "@h.invalid:1" + path
}
func TestSanitizeProviderErr_SecretComponentBackstop(t *testing.T) {
cases := map[string][2]string{
"query value": {"http://h.invalid:1/v1?key=BACKSTOPSECRET", "http://h.invalid:1/inserted/v1?key=BACKSTOPSECRET"},
"quoted query": {"http://h.invalid:1/v1?key=BACK\"STOPSECRET", "http://h.invalid:1/inserted/v1?key=BACK\"STOPSECRET"},
"password": {withUserinfo("user:BACKSTOPSECRET", "/v1"), withUserinfo("user:BACKSTOPSECRET", "/inserted/v1")},
"token as user": {withUserinfo("BACKSTOPSECRET", "/v1"), withUserinfo("BACKSTOPSECRET", "/inserted/v1")},
"escaped password": {withUserinfo("user:BACK%22STOPSECRET", "/v1"), withUserinfo("user:BACK%22STOPSECRET", "/inserted/v1")},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
msg := (&url.Error{Op: "Get", URL: c[1], Err: errors.New("refused")}).Error()
got := sanitizeProviderErr(msg, c[0])
if strings.Contains(got, "STOPSECRET") {
t.Fatalf("credential leaked: %q", got)
}
})
}
}
func TestSanitizeProviderErr_ShortValuesNotBlanked(t *testing.T) {
got := sanitizeProviderErr("dial tcp: lookup v1 failed", "http://h.invalid/v1?a=v1")
if got != "dial tcp: lookup v1 failed" {
t.Errorf("short query value blanked an unrelated substring: %q", got)
}
}
func renderingsGateway(t *testing.T, base string) (http.Handler, string) {
t.Helper()
cfg := CreateConfig()
cfg.Admin = &AdminConfig{Enabled: true}
cfg.Providers = map[string]*ProviderConfig{"p": {Type: "openai", BaseURL: base, APIKey: "k", Discovery: true}}
cfg.Groups = map[string]*GroupConfig{"g": {}}
cfg.Users = &UsersConfig{Inline: []*UserConfig{{Name: "admin1", Group: "g", APIKey: "sk-admin1", Admin: true}}}
var h http.Handler
var gw *Gateway
log := captureStderr(t, func() { h, gw = newAdminGatewayHandle(t, cfg) })
// An armed warm-fill retry would log from its own goroutine during a later test.
st := gw.registry.states["p"]
st.mu.Lock()
st.inFlight = true
st.mu.Unlock()
return h, log
}
func TestAdminOverview_DiscoveryErrorScrubsQuotedCredential(t *testing.T) {
addr := closedLoopbackAddr(t)
for name, base := range auditPayloads(addr) {
t.Run(name, func(t *testing.T) {
h, _ := renderingsGateway(t, base)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, adminRequest(http.MethodGet, adminOverviewPath, "sk-admin1"))
var got adminOverviewResponse
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil || len(got.Providers) != 1 {
t.Fatalf("overview decode: %v, %s", err, rec.Body.String())
}
if le := got.Providers[0].LastErr; le == "" || strings.Contains(le, renderingMarker) {
t.Errorf("lastErr = %q, want a non-empty scrubbed error", le)
}
})
}
}
func TestInitialDiscoveryLog_ScrubsQuotedCredential(t *testing.T) {
addr := closedLoopbackAddr(t)
for name, base := range auditPayloads(addr) {
t.Run(name, func(t *testing.T) {
_, log := renderingsGateway(t, base)
if !strings.Contains(log, "initial discovery") {
t.Fatalf("precondition: no discovery failure logged: %q", log)
}
if strings.Contains(log, renderingMarker) {
t.Errorf("log carries the credential: %q", log)
}
})
}
}
func TestNew_CredentialBearingBaseURLStillLoads(t *testing.T) {
addr := closedLoopbackAddr(t)
for name, base := range auditPayloads(addr) {
t.Run(name, func(t *testing.T) {
cfg := CreateConfig()
cfg.Providers = map[string]*ProviderConfig{"p": {Type: "openai", BaseURL: base, APIKey: "k"}}
if _, err := New(context.Background(), http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}), cfg, "llmgw"); err != nil {
t.Fatalf("New must keep accepting the config: %v", err)
}
})
}
}
func TestSanitizeProviderErr_Run3SpellingsStillScrubbed(t *testing.T) {
addr := closedLoopbackAddr(t)
for name, base := range auditPayloads(addr) {
if !strings.HasPrefix(name, "run3") && name != "plain query" {
continue
}
t.Run(name, func(t *testing.T) {
resp, err := http.Get(base) //nolint:gosec,noctx // closed loopback port, the error text is the subject
if err == nil {
_ = resp.Body.Close()
t.Fatal("expected a dial error")
}
if got := sanitizeProviderErr(err.Error(), base); strings.Contains(got, renderingMarker) {
t.Fatalf("credential leaked: %q", got)
}
})
}
}
+44
View File
@@ -0,0 +1,44 @@
package traefikllmgateway
import (
"errors"
"net/url"
"strings"
"testing"
)
func dialedErr(dialed string) string {
return (&url.Error{Op: "Get", URL: dialed, Err: errors.New("refused")}).Error()
}
func TestSanitizeProviderErr_ResidualShapes(t *testing.T) {
const base = "http://h.invalid:1/v1"
const dialedBase = "http://h.invalid:1/inserted/v1"
cases := []struct {
name, configured, dialed, leak string
}{
{"empty password username", "http://LONGSECRET1:@h.invalid:1/v1", "http://LONGSECRET1:@h.invalid:1/inserted/v1", "LONGSECRET1"},
{"lower-case percent escape", base + "?key=ABC%2FDEFGH", dialedBase + "?key=ABC%2fDEFGH", "DEFGH"},
{"valueless query key", base + "?LONGSECRET2", dialedBase + "?LONGSECRET2", "LONGSECRET2"},
{"semicolon separated", base + "?a=1;key=LONGSECRET3", dialedBase + "?a=1;key=LONGSECRET3", "LONGSECRET3"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got := sanitizeProviderErr(dialedErr(tc.dialed), tc.configured)
if strings.Contains(got, tc.leak) {
t.Fatalf("credential leaked: %q", got)
}
})
}
}
func TestSanitizeProviderErr_OverlappingSecretsDeterministic(t *testing.T) {
configured := "http://h.invalid:1/v1?a=LONGSECRET&b=LONGSECRET-EXTRA"
dialed := "http://h.invalid:1/inserted/v1?a=LONGSECRET&b=LONGSECRET-EXTRA"
for i := 0; i < 50; i++ {
got := sanitizeProviderErr(dialedErr(dialed), configured)
if strings.Contains(got, "EXTRA") || strings.Contains(got, "LONGSECRET") {
t.Fatalf("run %d: partial redaction left text behind: %q", i, got)
}
}
}
+61
View File
@@ -0,0 +1,61 @@
package traefikllmgateway
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
// cancelAfterWriter cancels the request context once it has received n writes, as a client hanging up mid-stream does.
type cancelAfterWriter struct {
*recordingWriter
cancel context.CancelFunc
n int
}
func (c *cancelAfterWriter) Write(b []byte) (int, error) {
n, err := c.recordingWriter.Write(b)
if len(c.events) >= c.n {
c.cancel()
}
return n, err
}
func TestOpenAIStreamClientCancel_BillsEstimatedCompletion(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.WriteHeader(http.StatusOK)
fl, _ := w.(http.Flusher)
for _, f := range openAIContentFrames(200) {
if _, err := w.Write([]byte(f)); err != nil {
return
}
fl.Flush()
select {
case <-r.Context().Done():
return
case <-time.After(5 * time.Millisecond):
}
}
}))
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"}}}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
req := newUnifiedRequest(t, http.MethodPost, "/v1/chat/completions", "sk-alice", body).WithContext(ctx)
w := &cancelAfterWriter{recordingWriter: newRecordingWriter(), n: 6, cancel: cancel}
out := captureStderr(t, func() { gw.ServeHTTP(w, req) })
in, tokOut := aliceTokens(gw)
if in <= 0 || tokOut <= 0 {
t.Fatalf("tokin/tokout = %d/%d, want both > 0 after a client cancel that followed forwarded output", in, tokOut)
}
if !strings.Contains(out, "logged as estimated (prompt tokens derived from request body size, completion tokens from streamed output size") {
t.Errorf("the estimated flag did not reach the accounting step; log = %q", out)
}
}
+116
View File
@@ -0,0 +1,116 @@
package traefikllmgateway
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"testing"
)
const hangupText40 = "0123456789012345678901234567890123456789"
func deltaFrames(n int, delta string) []string {
frames := make([]string, 0, n)
for i := 0; i < n; i++ {
frames = append(frames, fmt.Sprintf("data: {\"id\":\"c1\",\"object\":\"chat.completion.chunk\",\"choices\":[{\"index\":0,\"delta\":%s}]}\n\n", delta))
}
return frames
}
func hangupTokout(t *testing.T, frames []string) int64 {
t.Helper()
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))
_, out := aliceTokens(gw)
return out
}
func TestOpenAIStreamHangup_FunctionCallArgumentsBillEstimatedCompletion(t *testing.T) {
got := hangupTokout(t, deltaFrames(12, `{"function_call":{"arguments":"`+hangupText40+`"}}`))
if got != 120 {
t.Fatalf("tokout = %d, want 120", got)
}
}
func TestOpenAIStreamHangup_AudioTranscriptBillsEstimatedCompletion(t *testing.T) {
got := hangupTokout(t, deltaFrames(12, `{"audio":{"transcript":"`+hangupText40+`"}}`))
if got != 120 {
t.Fatalf("tokout = %d, want 120", got)
}
}
func TestOpenAIStreamHangup_RefusalBillsEstimatedCompletion(t *testing.T) {
got := hangupTokout(t, deltaFrames(12, `{"refusal":"`+hangupText40+`"}`))
if got != 120 {
t.Fatalf("tokout = %d, want 120", got)
}
}
func TestOpenAIStreamHangup_ArrayContentBillsEstimatedCompletion(t *testing.T) {
got := hangupTokout(t, deltaFrames(12, `{"content":[{"type":"text","text":"`+hangupText40+`"}]}`))
if got != 120 {
t.Fatalf("tokout = %d, want 120", got)
}
}
func TestOpenAIStreamHangup_AudioDataOnlyBillsChunkFloor(t *testing.T) {
got := hangupTokout(t, deltaFrames(12, `{"audio":{"data":"`+strings.Repeat("QUJD", 100)+`"}}`))
if got != 12 {
t.Fatalf("tokout = %d, want 12", got)
}
}
func TestOpenAIStreamHangup_ContentAndToolArgumentFiguresUnchanged(t *testing.T) {
frames := deltaFrames(6, `{"content":"`+hangupText40+`"}`)
frames = append(frames, deltaFrames(6, `{"tool_calls":[{"index":0,"id":"call_abcdef","type":"function","function":{"name":"lookup_weather","arguments":"`+hangupText40+`"}}]}`)...)
if got := hangupTokout(t, frames); got != 120 {
t.Fatalf("tokout = %d, want 120", got)
}
}
func TestOpenAIStreamHangup_RoleOnlyChunkBillsNoCompletion(t *testing.T) {
if got := hangupTokout(t, deltaFrames(12, `{"role":"assistant"}`)); got != 0 {
t.Fatalf("tokout = %d, want 0", got)
}
}
func TestChunkOutputBytes_SkipsMetadataKeysAndAudioData(t *testing.T) {
cases := []struct {
name string
delta string
want int64
}{
{"content", `{"content":"abcd"}`, 4},
{"role skipped", `{"role":"assistant","content":"ab"}`, 2},
{"null", `{"content":null}`, 0},
{"function_call", `{"function_call":{"name":"f","arguments":"12345"}}`, 5},
{"tool call metadata skipped", `{"tool_calls":[{"id":"call_1","type":"function","function":{"name":"fn","arguments":"xyz"}}]}`, 3},
{"audio data skipped", `{"audio":{"id":"a1","data":"QUJDRA==","transcript":"hey"}}`, 3},
{"array content", `{"content":[{"type":"text","text":"abc"},{"type":"text","text":"de"}]}`, 5},
{"refusal", `{"refusal":"nope"}`, 4},
{"reasoning", `{"reasoning_content":"ab","reasoning":"cde"}`, 5},
{"reasoning mirrored in details", `{"reasoning":"abcd","reasoning_details":[{"type":"reasoning.text","text":"abcd"}]}`, 4},
{"reasoning_content mirrored in reasoning", `{"reasoning_content":"abcd","reasoning":"abcd"}`, 4},
{"details alone", `{"reasoning_details":[{"type":"reasoning.text","text":"abcd"}]}`, 4},
{"non-string leaves", `{"content":[1,true,null]}`, 0},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
choice := []byte(`{"delta":` + c.delta + `}`)
if got, _ := chunkOutputBytes([]json.RawMessage{choice}); got != c.want {
t.Fatalf("chunkOutputBytes = %d, want %d", got, c.want)
}
})
}
}
func TestChunkOutputBytes_DepthCap(t *testing.T) {
deep := strings.Repeat(`{"x":`, 20) + `"abcd"` + strings.Repeat(`}`, 20)
if got, _ := chunkOutputBytes([]json.RawMessage{[]byte(`{"delta":` + deep + `}`)}); got != 0 {
t.Fatalf("deep delta counted %d bytes, want 0 past the depth cap", got)
}
}
+43
View File
@@ -0,0 +1,43 @@
package traefikllmgateway
import (
"context"
"net/http"
"strings"
"testing"
)
const targetErrMarker = "DUMMY-TARGET-SECRET-0006"
func TestNew_TargetURLErrorOmitsCredential(t *testing.T) {
urls := map[string]string{
"mistyped scheme": "htps://mcp.invalid/mcp?api-key=" + targetErrMarker,
"unparseable": "https://u:" + targetErrMarker + "@mcp.invalid:99x/mcp",
"scheme-less query": "mcp.invalid/mcp?api-key=" + targetErrMarker,
"scheme-less userinfo": targetErrMarker + ":[email protected]/mcp",
"scheme is the token": targetErrMarker + ":@mcp.invalid/mcp",
}
for name, raw := range urls {
for _, kind := range []string{"mcpServers", "agents"} {
t.Run(kind+"/"+name, func(t *testing.T) {
cfg := CreateConfig()
cfg.Providers = map[string]*ProviderConfig{"openai": {Type: "openai", APIKey: "k"}}
if kind == "mcpServers" {
cfg.MCPServers = map[string]*TargetConfig{"alpha": {URL: raw}}
} else {
cfg.Agents = map[string]*AgentConfig{"alpha": {URL: raw}}
}
_, err := New(context.Background(), http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}), cfg, "llmgw")
if err == nil {
t.Fatal("New accepted a bad target url")
}
if !strings.Contains(err.Error(), `"alpha"`) {
t.Errorf("error does not name the entry: %v", err)
}
if strings.Contains(err.Error(), targetErrMarker) {
t.Errorf("error carries the credential: %v", err)
}
})
}
}
}
+3 -1
View File
@@ -289,10 +289,12 @@ func (wb *watchdogBody) fire() {
return
}
atomic.StoreInt32(&wb.timedOut, 1)
wb.cancel()
// Record before cancelling: cancel unblocks a parked Read, and its
// caller must find the failure already recorded.
if wb.onTimeout != nil {
wb.onTimeout(nil, wb.timeoutError())
}
wb.cancel()
}
// timeoutError builds the error Read returns once timedOut is set, and
+29
View File
@@ -0,0 +1,29 @@
package traefikllmgateway
import (
"context"
"io"
"net/http"
"strings"
"testing"
"time"
)
// A reader unblocked by the watchdog's cancel must find the failure already recorded.
func TestWatchdogFire_RecordsTimeoutBeforeCancel(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cancelledAtRecord := make(chan bool, 1)
rec := func(_ *http.Response, _ error) {
time.Sleep(20 * time.Millisecond)
cancelledAtRecord <- ctx.Err() != nil
}
wb := newWatchdogBody(io.NopCloser(strings.NewReader("")), cancel, time.Hour, "p1", rec)
wb.fire()
if <-cancelledAtRecord {
t.Fatal("context was cancelled before onTimeout recorded the failure")
}
if ctx.Err() == nil {
t.Fatal("context not cancelled after fire")
}
}
+51
View File
@@ -0,0 +1,51 @@
// This file checks that withConfiguredURL keeps the attempt recorder reachable under Yaegi. Context keys of equal
// size match each other in the interpreter, so a lost recorder would silently stop provider accounting.
package main
import (
"fmt"
"strings"
"github.com/traefik/yaegi/interp"
)
const cuProbeOK = "ok"
const cuProbeSource = `
func configuredURLKeyProbe() string {
r, err := http.NewRequest("GET", "http://h.invalid/", nil)
if err != nil {
return "request: " + err.Error()
}
called := false
ctx := PKG.withAttemptRecorder(r.Context(), func(resp *http.Response, err error) { called = true })
r = PKG.withConfiguredURL(r.WithContext(ctx), "http://h.invalid/v1")
rec := PKG.attemptRecorderFromContext(r.Context())
if rec == nil {
return "attempt recorder lost after withConfiguredURL"
}
rec(nil, nil)
if !called {
return "attempt recorder did not fire"
}
return "ok"
}`
// exerciseConfiguredURLKey wraps a request with withConfiguredURL under the interpreter and checks the attempt recorder still fires.
func exerciseConfiguredURLKey(i *interp.Interpreter, pkgName string) error {
if _, err := i.Eval(`import "net/http"`); err != nil {
return fmt.Errorf("configured url probe: import net/http under yaegi: %w", err)
}
if _, err := i.Eval(strings.ReplaceAll(cuProbeSource, "PKG", pkgName)); err != nil {
return fmt.Errorf("configured url probe: declare the probe under yaegi: %w", err)
}
v, err := i.Eval("configuredURLKeyProbe()")
if err != nil {
return fmt.Errorf("configured url probe: run under yaegi: %w", err)
}
if got := v.String(); got != cuProbeOK {
return fmt.Errorf("configured url probe: %s", got)
}
fmt.Println("yaegi-check: the attempt recorder survived withConfiguredURL under the interpreter")
return nil
}
+10
View File
@@ -1097,6 +1097,16 @@ func run() error {
if err := exerciseSharedState(i, pkgName); err != nil {
return err
}
if err := exerciseConfiguredURLKey(i, pkgName); err != nil {
return err
}
// exerciseMessagesCacheUnrewritten runs after every shared-handler
// probe: it builds its own Gateway (own upstream, own fake Redis,
// cache enabled) and shares no counter or endpoint with any earlier
// probe, so it neither perturbs nor is perturbed by them.
if err := exerciseMessagesCacheUnrewritten(i, pkgName); err != nil {
return err
}
return exerciseAdminRedesignStats(i, pkgName)
}
+167
View File
@@ -0,0 +1,167 @@
// This file probes the /v1/messages response-cache rule that a reply
// relayed WITHOUT its model field rewritten must never be stored. The
// rule travels on the route's own usage value (usage.noStore), not on a
// type assertion against the response writer: under Yaegi v0.16.1 such
// an assertion never matches an interpreted wrapper type, so the array
// reply would be cached and the second identical request answered from
// it. A compiled test cannot observe that divergence; only this harness
// can.
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"sync/atomic"
"github.com/traefik/yaegi/interp"
)
const (
messagesCacheUserAPIKey = "sk-messages-cache-user" // #nosec G101 -- test fixture literal, not a real credential
messagesCacheGroupName = "mcgroup"
messagesCacheModel = "claude-cache-probe"
messagesCacheArrayBody = `[1,2,3]`
)
// messagesCacheObjectBody is a normal, rewritable Anthropic-shaped reply:
// the control case proving the cache still works on the same gateway.
const messagesCacheObjectBody = `{"id":"msg_cache_probe","type":"message","role":"assistant","model":"claude-upstream-real","content":[{"type":"text","text":"pong"}],"stop_reason":"end_turn","usage":{"input_tokens":7,"output_tokens":3}}`
// newMessagesCacheHandler builds one interpreted Gateway with the
// response cache enabled against a fake Redis, following
// newAdminRedesignHandler's shape (cache.go's buildResponseCache needs a
// real Redis client, not just cache.enabled).
func newMessagesCacheHandler(i *interp.Interpreter, pkgName, upstreamURL, redisAddr string) (http.Handler, error) {
cfgVal, err := i.Eval(pkgName + ".CreateConfig()")
if err != nil {
return nil, fmt.Errorf("messages-cache probe: call %s.CreateConfig() under yaegi: %w", pkgName, err)
}
if !cfgVal.CanInterface() {
return nil, fmt.Errorf("messages-cache probe: %s.CreateConfig() result cannot be used via reflect.Value.Interface", pkgName)
}
cfgJSON := `{` +
`"providers":{"anthropic":{"type":"anthropic","baseUrl":"` + upstreamURL + `","apiKey":"sk-anth","models":["` + messagesCacheModel + `"]}},` +
`"groups":{"` + messagesCacheGroupName + `":{}},` +
`"users":{"inline":[{"name":"mc-alice","group":"` + messagesCacheGroupName + `","apiKey":"` + messagesCacheUserAPIKey + `"}]},` +
`"redis":{"address":"` + redisAddr + `"},` +
`"cache":{"enabled":true,"ttl":"1m"}` +
`}`
if err = json.Unmarshal([]byte(cfgJSON), cfgVal.Interface()); err != nil {
return nil, fmt.Errorf("messages-cache probe: decode its own config into the interpreted Config: %w", err)
}
newVal, err := i.Eval(pkgName + ".New")
if err != nil {
return nil, fmt.Errorf("messages-cache probe: resolve %s.New under yaegi: %w", pkgName, err)
}
if newVal.Kind() != reflect.Func {
return nil, fmt.Errorf("messages-cache probe: %s.New is not a function (kind %s)", pkgName, newVal.Kind())
}
next := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})
results := newVal.Call([]reflect.Value{
reflect.ValueOf(context.Background()),
reflect.ValueOf(next),
cfgVal,
reflect.ValueOf("llmgw-check-messages-cache"),
})
if len(results) != 2 {
return nil, fmt.Errorf("messages-cache probe: %s.New returned %d values, want 2 (http.Handler, error)", pkgName, len(results))
}
if errVal := results[1]; !errVal.IsNil() {
return nil, fmt.Errorf("messages-cache probe: %s.New returned an error: %v", pkgName, errVal.Interface())
}
handler, ok := results[0].Interface().(http.Handler)
if !ok || handler == nil {
return nil, fmt.Errorf("messages-cache probe: %s.New's returned value is not a usable http.Handler", pkgName)
}
return handler, nil
}
// exerciseMessagesCacheUnrewritten sends the same /v1/messages request
// twice against a fake upstream that answers with a JSON array, and
// fails unless BOTH requests reach the upstream (a cache miss each time).
// It then repeats the pair against a normal JSON object reply and fails
// unless the second request is a cache hit, so the miss assertion above
// cannot pass by the cache being broken outright.
func exerciseMessagesCacheUnrewritten(i *interp.Interpreter, pkgName string) error {
var arrayHits, objectHits int64
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
raw, _ := io.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if strings.Contains(string(raw), "array-probe") {
atomic.AddInt64(&arrayHits, 1)
_, _ = w.Write([]byte(messagesCacheArrayBody))
return
}
atomic.AddInt64(&objectHits, 1)
_, _ = w.Write([]byte(messagesCacheObjectBody))
}))
defer upstream.Close()
redisLn, redisErr := newProbeRedisFake()
if redisErr != nil {
return redisErr
}
defer func() { _ = redisLn.Close() }()
handler, handlerErr := newMessagesCacheHandler(i, pkgName, upstream.URL, redisLn.Addr().String())
if handlerErr != nil {
return handlerErr
}
send := func(marker string) (*httptest.ResponseRecorder, error) {
body := `{"model":"` + messagesCacheModel + `","max_tokens":16,"messages":[{"role":"user","content":"` + marker + `"}]}`
req := httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-api-key", messagesCacheUserAPIKey)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
return rec, fmt.Errorf("messages-cache probe: POST /v1/messages (%s): status = %d, want 200, body=%s", marker, rec.Code, rec.Body.String())
}
return rec, nil
}
for attempt := 0; attempt < 2; attempt++ {
rec, err := send("array-probe")
if err != nil {
return err
}
if rec.Body.String() != messagesCacheArrayBody {
return fmt.Errorf("messages-cache probe: array reply %d body = %q, want %q verbatim", attempt, rec.Body.String(), messagesCacheArrayBody)
}
if got := rec.Header().Get("X-Llmgw-Cache"); got == "hit" {
return fmt.Errorf("messages-cache probe: array reply request %d was served from the response cache (X-Llmgw-Cache: hit) — a reply relayed without its model rewrite must never be stored", attempt)
}
}
if got := atomic.LoadInt64(&arrayHits); got != 2 {
return fmt.Errorf("messages-cache probe: unrewritten array reply reached the upstream %d times, want 2 (both requests must miss); the interpreted skip-store path did not take effect", got)
}
firstObj, err := send("object-probe")
if err != nil {
return err
}
if got := firstObj.Header().Get("X-Llmgw-Cache"); got != "miss" {
return fmt.Errorf("messages-cache probe: first object reply X-Llmgw-Cache = %q, want miss (body=%s)", got, firstObj.Body.String())
}
secondObj, err := send("object-probe")
if err != nil {
return err
}
if got := secondObj.Header().Get("X-Llmgw-Cache"); got != "hit" {
return fmt.Errorf("messages-cache probe: second object reply X-Llmgw-Cache = %q, want hit (a normal rewritable reply must still be cached; body=%s)", got, secondObj.Body.String())
}
if got := atomic.LoadInt64(&objectHits); got != 1 {
return fmt.Errorf("messages-cache probe: object reply reached the upstream %d times, want 1 (the second request must be a cache hit)", got)
}
return nil
}
+116
View File
@@ -0,0 +1,116 @@
package traefikllmgateway
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
)
const logScrubMarker = "LOGSCRUBMARKER42"
// holdingUpstream answers nothing: it signals held, then waits for the
// client to give up. The body is drained so the server notices the close.
func holdingUpstream() (chan struct{}, *httptest.Server) {
held := make(chan struct{})
var once sync.Once
return held, httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.Copy(io.Discard, r.Body)
once.Do(func() { close(held) })
select {
case <-r.Context().Done():
case <-time.After(10 * time.Second):
}
}))
}
func unifiedChatLog(t *testing.T, baseURL string, ctx context.Context) string {
t.Helper()
gw := newStreamBillingGateway(t, providerTypeOpenAI, baseURL, "gpt-test")
body := map[string]any{"model": "gpt-test", "messages": []any{map[string]any{"role": "user", "content": "hi"}}}
req := newUnifiedRequest(t, http.MethodPost, "/v1/chat/completions", "sk-alice", body).WithContext(ctx)
return captureStderr(t, func() {
gw.ServeHTTP(httptest.NewRecorder(), req)
})
}
func TestUnifiedRoute_ConnectionErrorLogOmitsBaseURLUserinfo(t *testing.T) {
out := unifiedChatLog(t, "http://"+logScrubMarker+"@"+closedLoopbackAddr(t)+"/v1", context.Background())
if !strings.Contains(out, "upstream connection error") {
t.Fatalf("precondition: no connection error logged: %q", out)
}
if strings.Contains(out, logScrubMarker) {
t.Errorf("log carries the base URL credential: %q", out)
}
}
func TestUnifiedRoute_BuildRequestErrorLogOmitsUnparseableBaseURL(t *testing.T) {
out := unifiedChatLog(t, "http://user:"+logScrubMarker+"@"+closedLoopbackAddr(t)+"\n", context.Background())
if !strings.Contains(out, "ERROR") {
t.Fatalf("precondition: nothing logged at error level: %q", out)
}
if strings.Contains(out, logScrubMarker) {
t.Errorf("log carries the unparseable base URL credential: %q", out)
}
}
func TestUnifiedRoute_ClientCancelLogOmitsBaseURLUserinfo(t *testing.T) {
held, up := holdingUpstream()
defer up.Close()
ctx, cancel := context.WithCancel(context.Background())
go func() {
<-held
cancel()
}()
out := unifiedChatLog(t, strings.Replace(up.URL, "http://", "http://"+logScrubMarker+"@", 1)+"/v1", ctx)
if !strings.Contains(out, "canceled") {
t.Fatalf("precondition: no cancel logged: %q", out)
}
if strings.Contains(out, logScrubMarker) {
t.Errorf("log carries the base URL credential: %q", out)
}
}
func targetProxyLog(t *testing.T, ctx context.Context, targetURL string) string {
t.Helper()
h := newTargetRedirectGateway(t, targetURL, targetURL)
req := httptest.NewRequest(http.MethodGet, "/mcp/alpha", nil).WithContext(ctx)
req.Header.Set("Authorization", "Bearer sk-alice")
return captureStderr(t, func() {
h.ServeHTTP(httptest.NewRecorder(), req)
})
}
func TestTargetProxy_ClientCancelLogOmitsTargetQuery(t *testing.T) {
held, up := holdingUpstream()
defer up.Close()
ctx, cancel := context.WithCancel(context.Background())
go func() {
select {
case <-held:
case <-time.After(10 * time.Second):
}
cancel()
}()
out := targetProxyLog(t, ctx, up.URL+"/mcp?api-key="+logScrubMarker)
if !strings.Contains(out, "client canceled request") {
t.Fatalf("precondition: no cancel logged: %q", out)
}
if strings.Contains(out, logScrubMarker) {
t.Errorf("log carries the target query credential: %q", out)
}
}
func TestTargetProxy_ConnectionErrorLogStillScrubbed(t *testing.T) {
out := targetProxyLog(t, context.Background(), "http://"+closedLoopbackAddr(t)+"/mcp?api-key="+logScrubMarker)
if !strings.Contains(out, "upstream connection error") {
t.Fatalf("precondition: no connection error logged: %q", out)
}
if strings.Contains(out, logScrubMarker) {
t.Errorf("log carries the target query credential: %q", out)
}
}