Image requests rejected by the upstream safety system (for example
"Your request was rejected by the safety system") were only visible in
the ops error log. They are now also written to the risk control center
as log-only evidence (action=image_safety, mode=risk_control_log_only):
no hash blacklist, no auto-ban count, no email, response unchanged.
Detection covers HTTP 400 from the native Images API, SSE/Responses
error events, model refusal text and content_filter incompletes. 400s
carrying error.param (e.g. an invalid `moderation` value) are excluded.
The record uses the gateway request ID from context so it joins with the
ops error log; the response header may carry the upstream x-request-id.
Refs #8992
TestUserFacingGroupDTOsAreLocalized statically requires every user-facing
dto.*FromService call to chain .Localized( on the same line.
Co-Authored-By: Claude Opus 5.5 <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>
- Expose latency_checked_at (from cached UpdatedAt) on admin proxy list
- Show exit IP under location and last check time under created_at
- Include region/city in quality check result
- Quality check now updates row latency/IP/location on failure too,
matching the backend snapshot
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Problem: on /v1/responses passthrough accounts with
gateway.stream_keepalive_interval enabled, a failover-eligible upstream
error (e.g. an overloaded `event: error` before any visible output) is
only failed over once. If the first attempt has already written a
keepalive comment, the next attempt that fails the same way is treated
as if semantic output had reached the client: the error is delivered as
response.failed and the remaining schedulable accounts are never tried.
Root cause: handleStreamingResponsePassthrough starts a new SSE
keepalive for every attempt, and startOpenAISSEKeepalive replaces the
instance stored on the gin.Context. Keepalive bytes were tracked per
instance, so OpenAICompactKeepaliveAdjustedWrittenSize subtracted only
the current instance's bytes from c.Writer.Size(); comments written by
an earlier attempt stayed in Size() and were counted as real output.
openAIStreamClientOutputStarted therefore reported output as started
and the passthrough stream stopped proposing failover.
StopOpenAICompactSSEKeepaliveCommitted had the same per-instance blind
spot and reported "not committed" when only an earlier instance had
committed the 200 response.
Fix: keep the keepalive byte count in a request-scoped atomic counter
stored on the gin.Context and shared by every keepalive instance of the
request (retries and nested starts). AdjustedWrittenSize subtracts the
cumulative count, and the committed check also reports true once any
keepalive of the request has written a comment. Single-keepalive
behaviour is unchanged.
Tests: a handler-level regression test drives the real Responses
handler with three passthrough accounts (the first attempt emits a real
keepalive and then fails over, the second fails immediately, the third
succeeds); on the previous code only accounts [1 2] are called and the
client receives response.failed. Service-level tests cover cumulative
accounting across restarts, the committed check after a previous
attempt, restarts without beats, and nested keepalives; they drive beats
manually instead of relying on timer scheduling.
GatewayHandler.Messages writes the sticky binding back after a successful forward. The write was a plain SET, so a long request put its account back over a binding another request made while it was forwarding.
The write now runs a Lua compare in the Redis cache. It sets the key when the key is missing or holds an account this request was admitted on under profit control and failed over from, refreshes the TTL when the key already holds the served account, and leaves any other value alone.
The compare sits behind GatewayStickySessionCompareCache, an optional capability; a cache without it keeps the plain write.
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>
Empty-mapping OpenAI OAuth accounts accepted claude-* models, and OAuth or
setup-token accounts with openai_passthrough accepted every model. Both send
requests to chatgpt.com/backend-api/codex, which answers foreign models with
a non-retryable 400 ("not supported when using Codex with a ChatGPT
account"), so mixed groups handed claude-* requests from Codex clients to
the OAuth account instead of the API-key account that serves them.
- Add "claude-" to openAIOAuthForeignModelPrefixes.
- Apply the foreign-prefix check to OAuth and setup-token passthrough too;
API-key passthrough keeps allowing every model.
- Schedule /v1/messages by the channel-mapped model, as Responses, Chat
Completions and the Responses WebSocket already do, so a channel mapping
a claude-* alias to a GPT model still lands on OAuth accounts.
Same shape as the responses handler: the body is validated at the top of
ChatCompletions, the only later rewrite is
applyOpenAIReasoningEffortPolicyForRequest (sjson), and the parse error was
already being ignored. Nothing between the two points mutates the bytes:
parseOpenAICompatibleStream, checkSecurityAudit and tokenInflightEstimate only
read them.
The /v1/responses handler validates the request body with gjson.ValidBytes
before doing anything else, then hands the same bytes to ParseGatewayRequest,
which validates them a second time. After the single-root-walk change the
validation is the majority of what that call does: at 1MiB it is about 510us
of the remaining 730us.
Add ParseGatewayRequestValidated for callers that have already established the
body is valid JSON, and use it in the handler, where the only rewrite between
the two points is applyOpenAIReasoningEffortPolicyForRequest (sjson, which
preserves validity).
The validating entry point is unchanged, so invalid JSON keeps producing a
clean error everywhere else. ReplaceBody / CloneForBody keep validating as
well, because their bytes can differ from the ones a caller validated.
Equivalence tests assert the trusted variant produces identical results to the
validating one on valid JSON, and the fuzz target checks the same for every
input that parses.
Benchmark (Apple M5 Pro, 3 allocs unchanged):
responses 1MiB: 735us -> 239us
anthropic 1MiB: 723us -> 207us (not yet wired: that handler has no earlier
validation, so it keeps the validating path)
The handler validates the request body at gateway_handler_responses.go:66 and
ParseGatewayRequest validates it again at gateway_request.go:240. For bodies
that do carry image declarations the byte-level precheck cannot fire, so the
intent classifier still ran gjson.ValidBytes over the same bytes a third time.
That is the dominant remaining cost for Codex traffic, because Codex
advertises the image_gen namespace on ordinary responses requests.
Add IsImageGenerationIntentForPlatformValidated for callers that have already
established the body is valid JSON, and use it at the two call sites where
that holds:
- gateway_handler_responses.go: the body is validated at the top of the
handler, and afterwards it is only rewritten through sjson
(applyOpenAIReasoningEffortPolicyForRequest), which preserves validity.
- openai_ws_forwarder_ingress.go: the payload is validated in
parseClientPayload, and every later rewrite is sjson, a decode/re-marshal
round trip, or a no-op.
Both call sites carry the reasoning in a comment. The validating entry points
are unchanged, so invalid-JSON semantics stay exactly as they were for every
other caller.
Benchmark (Apple M5 Pro, 1MiB Codex body, 0 allocs):
intent classifier: 562us -> 50us
Refs #8865
Keep the stable content session hash from this PR, but restore
ForceCacheBilling on the native v1beta entry. Dropping it changed
billing policy: a sticky session that failed over would be charged
full input price instead of cache-read price. That also hit
Antigravity accounts served by this handler, and made it inconsistent
with /v1/messages, which still forces cache billing. Billing on this
entry is now identical to main.
#8769 renamed normalizeCodexPageContext to normalizeCodexUntrustedContext;
the call-output gate test still referenced the old name, so go vet -tags unit
failed once both changes were on main.