WebSocket turns closed the connection with 1013 as soon as the user was
at its concurrency limit, after the client had already uploaded the full
request. Clients such as Codex then retry and eventually switch the
session to HTTP, which resends the whole context on every turn.
Wait in the same bounded per-user queue as HTTP requests instead. The
wait is 60 seconds, longer than the HTTP wait because a rejected
WebSocket turn is more expensive. Timeouts, a full queue and a closed
connection still end with 1013.
The golangci-lint CI job fails because check-type-assertions is enabled
and version.Load().(string) uses the unchecked single-value form.
Switch to the two-value form so the linter is satisfied.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add a channel-level toggle (features_config.expose_response_model, off by
default). When enabled, regular users see the final response model next to
the requested model in their usage records; the intermediate mapping chain
stays admin-only.
- Channel.IsResponseModelExposed + ChannelService.ResponseModelExposedChannels
read from the in-memory channel cache, so no extra DB queries
- User usage list/detail fill the new optional response_model field
(upstream_response_model -> upstream_model -> model, omitted when equal
to the requested model)
- Channel form toggle, UsageTable rendering and i18n
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A re-audit of ce86c1b30 found, and running code confirmed:
- scanJSONString re-scanned to the closing quote after every escape, so
scanning was quadratic in escapes (200k "\n": 0.56 s; a 10 MB code-like
body: 24 s). It now visits each quote once and counts the backslashes
before it: 6 us and 0.7 ms for the same bodies.
- A multipart body with a JSON preamble (RFC 2046; skipped by Go's
multipart reader) took the JSON branch only, bypassing both the group
allowlist and the multipart duplicate check. A multipart Content-Type
now always runs the multipart check, FromBodyCandidates merges JSON and
multipart candidates, and a body that is both JSON and a form with parts
is rejected as ambiguous. The JSON scan stops after the first top-level
value, matching gjson, so binary file parts are never tokenised.
- LooksLikeJSON now skips every byte <= 0x20 before the first value, as
gjson does.
- Freeform key spaces gained variables, headers, dependentRequired,
dependencies and labels, matched on the decoded name. metadata is no
longer freeform: Antigravity binds metadata.user_id case-insensitively
while sticky sessions read it with gjson.
- Multipart also rejects file parts named model/session, parts without a
parsable name, and parts carrying two Content-Disposition headers, and
counts file and text parts with the same name together.
- WebSocket: passthrough forwards session.update and every other client
event verbatim, and dedicated parsing reads fields from the raw frame
before any re-encode. Both now reject a frame with repeated fields
before reading it.
- The linear-compare limit rises to 32 to cut map churn for mid-sized
objects.
Tests that relied on duplicates passing now assert rejection: a dedicated
WS recovery test that sent two previous_response_id keys, and WS
allowlist cases whose close reason comes from the earlier duplicate check.
Refs: GHSA-p3r4-jcm3-2hph
An independent audit of the conflicting-field fix found, and running code
confirmed, the following. Each is fixed here.
- A JSON body labelled multipart/form-data skipped the check: the JSON
branch was chosen from the Content-Type header, but JSON handlers never
look at it. ConflictingField and FromBodyCandidates now detect JSON by
content. The same header-only branch, and a UTF-8 BOM prefix (stripped by
the handlers' lenient reader), also let a body bypass the group model
allowlist on main; both are closed.
- Identical duplicates passed and the gateway's own sjson rewrites then
split them: reasoning-effort downgrade, model mapping and the fast-policy
service_tier delete only touch the first occurrence. Every repeated member
is now rejected, whatever its value. Multipart rejects repeated scalar
fields (model, n, size, ...) except list fields (name[], image,
image[...], image_url).
- Nested case variants bound case-insensitively by struct-based protocol
conversions ({"reasoning":{"effort":"low","Effort":"xhigh"}}). Members
are now folded at every depth, except inside user-defined key spaces
(JSON Schema properties/$defs, tool arguments, metadata, ...), where id
and ID are distinct and only exact repeats are rejected.
- The recursive walker cost depth x size (1 MB at depth 9990: 1.6 s) and
stored every key as a string (~16x the body). It is replaced by one
linear byte scan with an explicit stack that compares 64-bit hashes
(random per-process seed) of the decoded, folded names: 0.6 ms for the
same body, ~3.7 GB/s on a Claude Code-shaped body. Subtrees deeper than
10000 levels are bracket-counted, so later same-level members are still
checked.
- text_max_body_size no longer bounded what group middleware buffered:
the route-level limit ran after them. The limit is now chosen per route
at group level.
- Body read failures in gateway middleware answered in the OpenAI shape
with a different message than the handlers. They now use the entry
protocol's shape and the handler's "limit is N" message. Rejections
are recorded as ingress reason conflicting_request_fields.
- The middleware strips a leading BOM and restores the body, so composite
routing and handlers parse the bytes that were checked.
Refs: GHSA-p3r4-jcm3-2hph
The first pass checked top-level members and the session object only.
Nested fields drive billing and policy as well: reasoning.effort selects
the reasoning-effort billing multiplier and the group effort ceiling, yet
gjson reads the first occurrence, sjson downgrades only the first, and
map re-encoding keeps the last. {"reasoning":{"effort":"low",
"effort":"xhigh"}} therefore passed admission as low and could be served
as xhigh.
ConflictingField now also walks every nested object, including array
elements, and reports the first member that repeats with a different raw
value by path (reasoning.effort, messages[1].role). Nested names are
compared exactly after unescaping, without case folding, because user
data such as tool JSON Schemas may legitimately carry both id and ID.
Identical duplicates still pass. The walk stops below encoding/json's
10000-level limit and only allocates a path string on conflict
(~660 MB/s, 9 allocs for a 225 KB Claude Code-shaped body).
Responses WebSocket frames now apply the full ConflictingField rule
instead of comparing model candidates only, so service_tier and nested
reasoning.effort conflicts close the connection as on HTTP.
Refs: GHSA-p3r4-jcm3-2hph
A body such as {"model":"cheap",...,"model":"expensive"} was scheduled and
billed under the first model, while paths that decode and re-encode the
body forwarded the last one. gjson returns the first member with a name;
encoding/json keeps the last and matches struct fields case-insensitively.
The group allowlist already validates every model candidate, but billing
did not, and groups without an allowlist had no check at all.
RejectConflictingRequestFields runs on every gateway chain after the
allowlist and before the composite rewrite. It answers 400 when a
top-level JSON member, a member of the session object, or a multipart
model/session field is declared more than once with different values.
Repeated fields with identical values still pass, as they do in the
allowlist. Responses WebSocket frames apply the same rule to their model
candidates on the first frame and on later turns.
The source-level chain assertion in gateway_model_allowlist_test.go is
updated for the new middleware position.
Not covered: repeated non-model members inside WebSocket frames (an
existing test accepts a repeated previous_response_id there), and nested
objects other than session.
Refs: GHSA-p3r4-jcm3-2hph
Co-Authored-By: claude-mythos-5-2 <noreply@anthropic.com>
A composite route that rewrites the request model left the client's thinking untouched, so a route from claude-sonnet-5 to claude-opus-5-5 forwarded thinking.type=enabled with budget_tokens and validateClaude55Request answered 400 before the request reached the upstream.
The route middleware now rewrites the model through RewriteCompositeRequestModel, which replaces a thinking mode that validateClaude55Request rejects for the new model with the nearest mode it accepts: enabled becomes adaptive without budget_tokens, and disabled becomes between_tools on Sonnet 5.5.
The mapping is shared with the Bedrock Sonnet 5.5 sanitizer, whose behavior is unchanged.
Modes the target still rejects stay with validateClaude55Request, and a request whose model the route does not rewrite keeps its thinking as sent.
Upstream added WithBodyReadTimeout (gateway.request_body_read_timeout_seconds)
and client-gone handling for body reads. Drop this branch's own server-level
idle-timeout wrapper and server.request_body_idle_timeout setting in favor of
it, and keep the classification and diagnostics on top:
- readRequestBodyChunksWithBudget reports the read error before ctx.Err():
on HTTP/1 a read deadline also cancels the request context, which turned
every timeout into context.Canceled. Read errors carry bytes read and
elapsed time in RequestBodyReadError.
- handleRequestBodyReadError and RejectRequestBodyReadError skip the
client-gone (empty 499) path for read timeouts, so they are reported as
408 instead of a client cancellation (HTTP/1) or a generic 400 (HTTP/2).
- Every gateway body read site and both body-reading middlewares log
payload-free diagnostics, including the client-gone path.
Problem: when GetByKey fails with anything other than not-found or
overloaded, the API key middlewares answer 500 "Failed to validate API
key" without logging the cause. Two client-side conditions end up there:
- The client goes away while the key is being looked up (connection
closed after the body was sent, or an HTTP/2 stream reset). net/http
cancels the request context, the cache/DB lookup returns
context.Canceled, and a pure client disconnect is recorded as an
internal server error. A key that is not in the 15 s L1 cache always
reaches Redis/Postgres, so infrequent clients hit this regularly.
- A key that is not valid UTF-8. Postgres rejects the parameter
(invalid byte sequence, SQLSTATE 22021), which surfaces as 500 instead
of 401. Generated and custom keys are always ASCII, so such a key can
never match.
Fix: GetByKey treats non-UTF-8 keys as not found before any cache or DB
access. Both middlewares (OpenAI/Anthropic and Google) end the request
with 499 when the request context is already done, which the ops error
logger already skips as a client-closed request; any other lookup error
is now logged before the 500.
Test: api_key_auth_test.go drives both middlewares with a lookup that is
cancelled mid-flight (499) and with a plain repository error (500), and
sends a non-UTF-8 x-api-key (401). api_key_service_cache_test.go checks
that a non-UTF-8 key never reaches the repository. All three fail
without the fix.
Gateway handlers such as Anthropic /v1/messages read the whole request body
before they know the model or account. The HTTP server sets no ReadTimeout
(large bodies may legitimately take long), so a stalled upload held the
handler until the client gave up, and every read failure then surfaced as a
generic 400 "Failed to read request body" with no diagnostics.
- Add server.request_body_idle_timeout (default 60s, 0 disables). A body
read that receives no bytes for that long fails with 408. Each Read re-arms
the deadline, so total upload time is not limited and handler pauses are
not counted. HTTP/2 deadlines are armed only during a Read; HTTP/1 keeps
one armed while the body is unfinished so net/http's own drain of an
unread body cannot hang an early error response.
- Classify body read failures in the shared reader: read timeout (408),
client disconnect (499), truncated body, decode errors and size limit.
Other failures keep the stable 400 message. Map 408 to DEADLINE_EXCEEDED
in Google-format errors.
- Log payload-free diagnostics for every gateway and middleware body read
failure: kind, protocol, declared length, encoding, bytes received and
read duration.
go-sdk v1.4.1 fixes GO-2026-4773 (cross-site tool execution) and
GO-2026-4770 (null Unicode JSON parsing), which fail govulncheck.
v1.4.1 also adds transport-level cross-origin and Content-Type checks
that would reject requests Authenticate already accepts:
- trust the same allowed origins in the SDK's CrossOriginProtection so
CORS-allowlisted browser clients are not refused with 403;
- accept application/json with parameters (e.g. charset) by normalizing
the header, while still refusing non-JSON bodies with 415.
Registration was capped at 1000 pending clients site-wide while the limit
per IP was 10 per minute, so one address could exhaust the cap and block
every new MCP client.
- Issue client IDs as HMAC-signed tokens carrying the client name,
redirect URI digests and grant types. Registration writes nothing;
rows are created only when a user approves a client, so there is no
shared capacity to exhaust.
- Persist the signing key in security_secrets via the existing
get-or-create helper, cached lock-free, so instances share it.
- Drop mcp_oauth_clients from migration 249 and keep the client name on
each grant. Prune expired grants on authorization, before the owner
row is locked.
- Fix an unchecked type assertion in managementmcp tests flagged by
golangci-lint v2.14.0.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Reject JSON-RPC batches and non-object bodies before the SDK; return each
tool result once as text and bound the encoded payload (H1).
- Enable MCP only when MCP_PUBLIC_URL is set; drop the frontend URL fallback
and expose a read-only mcp_enabled public setting (M1).
- Expire never-authorized clients after 24h, cap pending registrations
globally, aggregate MCP IP limits by IPv6 /64, and limit registration
bodies to 4 KiB (M2).
- Revoke MCP grants with revoke-all-sessions and always require step-up for
administrator write grants (M3).
- Rate limit /api/v1/mcp per IP before authentication and write last_used_at
at most once per minute (M4).
- Persistently revoke grants when an account is disabled or demoted, derive
result redaction from SensitiveCredentialKeys, allowlist browser sessions
for step-up, audit every MCP read, reject invisible characters in
client_name, and document site-root-only deployment (L1-L5, L7).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
POST /admin/accounts/:id/claude/reset-credits/redeem (Idempotency-Key
required, same middleware chain as the Codex reset-quota route). The server
re-queries eligibility and claims only the upstream next_grant_id when it is
redeemable; grant/org IDs never reach the client. Claims are serialized by
account and organization Redis leases, and a durable per-organization fence
in the idempotency table blocks further redemption after an unconfirmed
outcome (settles after 24h). Ported from upstream PR #7591.
Co-authored-by: korkin25 <eugeny.kuzakov@gmail.com>
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>