Repository navigation
fix(proxy): mask secrets, bound bodies and fix the wire echo - #1
Merged
Merged
Conversation
Refusals on the chat route echoed client input through a local bounder that ran none of the masking rules, so a credential-shaped value came back in clear: the gateway's own API key (`messages[0].role` spelled `Bearer <key>`), a credential pair inside an image data URI and a URL's userinfo were all published on /v1/chat/completions while /v1/responses and /v1/messages masked them. boundedEcho() is gone and every echoed value goes through echoedValue(), the one chain the 415 sentences and the other two adapters already used. The by-id model body used a log bounder as well, so GET /v1/models/<credential-shaped-id> answered the value verbatim; it now goes through the echo chain too. `tools` was the one client-controlled array with no element ceiling: a 22 MB body of 600 000 definitions was accepted, which measured about 97 MB of heap and a 54 M-character prompt. It is refused above MAX_REQUEST_ENTRIES, with the sentence `messages` already uses. A chat `tool` message's `name` reached the <tool_result> element the model reads without the shared tool-name rule, so a quote could close the attribute, and the rendered attribute values are escaped now.
maskBackendUrl() refused to read a `@` as the end of the userinfo when the run before it carried whitespace, so a passphrase containing one (`http://alice:p@ss word@backend.internal`) was published as `http://***@ss word@backend.internal` - /health needs no key, so half of the operator's password reached every caller. maskQuotedCredentials() applied its 16-character floor to the text before the first control character, so a credential wrapped early (`Bearer abcdefghij\nklmnopqrst`) was published whole. The floor now applies to the entire run, across a run of separators, which also covers the `??` maskFreeText() writes for a CRLF. resolveBackendAuth() handed on an unparseable URL that still carried a credential, so the value reached the SDK and the readiness probe with its secret attached and unregistered; it now comes back flagged and registered, and createApp() refuses it by name.
Only the *served* body-less routes refused a declared body, so a path or method the router does not serve still had its body parsed before the 404: eight concurrent 4 MiB POST /v1/embeddings bodies grew the process by 78.7 MB, and a stalled upload waited out the 30 s body deadline instead of reading its 404. Unserved requests now get the same 404 sentence (one notFoundMessage() helper for the hook and the handler) before a byte is read; measured +0.5 MB and 1-3 ms. The Responses writer was handed the raw body where it reads the normal form, so `instructions` was always null, `tool_choice` always "auto", `reasoning` always null, and a chat-spelled tool definition echoed without a name or parameters. The backend password, the probe credentials and the health timings lived in module scope while createApp() is per instance: a second app in one process overwrote the first one's password and its child was spawned with the other app's value. They travel on the per-app config now. drainLiveSessions() started one delete per tracked session at once (up to 1000); it now runs fixed chunks of 16 inside its deadline.
The Anthropic normalizer refused the `thinking` block it emits itself, so a client with extended thinking enabled could not send its own history back next to the tool_use turn that produced it; an assistant block is skipped now (never rendered into the prompt), the emitted block carries `signature: ''` so a typed client can round-trip it, and a thinking block in a user message is still refused. Two reasoning items in one Responses stream reused `rs_<id>` when a reasoning delta arrived after a text delta - the same failure messageItemId() already documents for `msg_` - so the second item gets its own id. `tools` over MAX_REQUEST_ENTRIES is refused on both routes, and the Anthropic normalizer defaults maxMessages to that ceiling instead of depending on the caller remembering it.
`/\s+$/` retried its anchor at every position: 274 ms for 25 000 interior spaces, 996 ms for 50 000 and 4.0 s for 100 000, on the thread that answers /health, and the streaming scanner accumulates the run across deltas. trimEndWhitespace() walks back over the \s class and slices once (0.005 ms on the same 100 000). The scanner also released the whitespace in front of a tool-call block when text followed the closed block in the same push, so `before <block> tail` streamed as "before tail" while the JSON body answered "before tail". The hold-back is dropped at the block boundary now. A randomized differential (random answers, random chunk splits) improved 16 cases and introduced none; every documented tag shape keeps its spacing at every chunk size.
Number() accepts `0x10`, `1e3` and the other non-decimal spellings, so a tuning value written in one of those shapes took effect with no [Config] note - the one thing this module exists to prevent. The value is kept and the spelling is named by readLimit(), readMilliseconds() and resolveRequestTimeoutMs(). isLoopbackHost() classified by spelling and missed `::ffff:7f00:1`, the form new URL().hostname produces for an IPv4-mapped address, so the cleartext-credential warning fired for a loopback backend (the IPv4- translated `::ffff:0:...` stays remote, a different address class).
The pin gate's optional group required a `,` or `-` before `uses:` inside
a flow mapping, so `- {uses: actions/checkout@v4, name: X}` was invisible
and a movable reference passed the step that protects a workflow holding
a write-scoped Docker Hub token.
check-syntax.mjs guarded 19 credential patterns while .dockerignore
carried 23: id_dsa*, id_ecdsa*, *.keystore and *.jks could be dropped
with every check still green.
The new behaviour had no end-to-end check. Now: an announced body on an unserved path reads its 404 in under 500 ms with Connection: close; the Responses envelope echoes instructions, tool_choice and reasoning.effort in both modes; a replayed Anthropic thinking block is accepted while the same block in a user message stays a 400; the queue-full 503 is asserted in each route's own envelope with Retry-After; and the shutdown drain is asserted to keep at most one chunk of deletes in flight, which needed the stub to report maxDeletesInFlight. The abandoned-client gateway sets OPENCODE_PROXY_REQUEST_TIMEOUT_MS, the name that is actually read.
AGENTS.md and README.md described the old body policy, the module-level backend state, the Responses envelope built from the raw body, the Anthropic reasoning replay, the settings readers and the masking rules. Each changed behaviour is recorded next to the rule it serves, with the measurements the change was justified by, and test/lib/codec-checks.mjs is in both repository maps now.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What changed
A full audit of the gateway (security, resource safety, wire contract, parser performance) produced 24
proposals; this branch implements all of them. Nine commits, each one logical:
Security
/v1/chat/completionsechoed client input through a local bounder that ran none of the maskingrules: the gateway's own API key, a credential pair inside an image data URI and a URL's userinfo were
published in clear while the other two routes masked them.
boundedEcho()is gone; every echoed value goesthrough
echoedValue().GET /v1/models/<id>built its response body with a log bounder, so a credential-shaped path segment wasanswered verbatim; it uses the echo chain now.
loggableUrl()skipped the by-value redaction, so the configured key printed in the INFO request log (and inthe 404 body) when it travelled under a parameter whose name is not a credential (
?model=<key>).maskBackendUrl()published the tail of a passphrase userinfo (http://alice:p@ss word@host->http://***@ss word@host) andmaskQuotedCredentials()published a credential wrapped before its 16thcharacter.
OPENCODE_SERVER_URLthat still carried a credential was handed to the SDK and the readinessprobe; it is now refused at startup by name, masked.
uses, so a movable referencepassed the one control that protects a write-scoped Docker Hub token. The
.dockerignoreguard also missedfour key patterns the file carries.
Resource safety and performance
POST /v1/embeddingsbodies grew the process by 78.7 MB and a stalled upload waited out the 30 s bodydeadline. They are refused before a byte is read, with the same 404 sentence (measured +0.5 MB, 1-3 ms).
/\s+$/in the tool-call reader was quadratic: 4.0 s on 100 000 interior spaces on the thread that answers/health. Replaced with a linear backwards scan (0.005 ms).toolswas the one client-controlled array with no element ceiling (600 000 definitions measured about 97 MBof heap and a 54 M-character prompt); all three normalizers refuse it above
MAX_REQUEST_ENTRIES.Wire contract
instructionswas always
null,tool_choicealways"auto"andreasoningalwaysnull./v1/messagesrefused thethinkingblock it emits itself, so a client with extended thinking enabled couldnot replay its own history; an assistant block is skipped now and the emitted one carries
signature: ''.rs_id.Correctness and configuration
createApp()is perinstance; a second app in one process swapped the first one's password to its spawned child. They travel on
the per-app config now.
0x10,1e3) took effect with no[Config]note; it keeps its value and isnamed.
isLoopbackHost()missed::ffff:7f00:1, the spellingnew URL().hostnameproduces for IPv4 loopback.toolmessage'snameskipped the shared tool-name rule and could close the<tool_result>elementthe model reads; it is validated, and the rendered attribute values are escaped.
Tests and docs
(was 123), 245 responses (was 212), 56 anthropic (was 51), 151 chat (was 133). The queue-full refusal is now
asserted on
/v1/messagesand/v1/responses, and the stub reportsmaxDeletesInFlightso the drain'schunk size is observable.
AGENTS.mdandREADME.mdrecord each changed behaviour next to the rule it serves, including themeasurements;
test/lib/codec-checks.mjsis in both repository maps.Verification
Each new end-to-end check was shown to fail with its fix reverted (a throwaway copy under
/tmp), and theregression claim for the parser change is a randomized differential against
extractToolCalls()over randomchunk splits (16 cases improved, none introduced).