Skip to content

fix(proxy): mask secrets, bound bodies and fix the wire echo - #1

Merged
dinhdev666 merged 9 commits into
mainfrom
fix/security-perf-audit
Nov 24, 2026
Merged

dinhdev666 merged 9 commits into
mainfrom
fix/security-perf-audit

Conversation

@dinhdev666

Copy link
Copy Markdown
Owner

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

  • Refusals on /v1/chat/completions echoed client input through a local bounder that ran none of the masking
    rules: 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 goes
    through echoedValue().
  • GET /v1/models/<id> built its response body with a log bounder, so a credential-shaped path segment was
    answered verbatim; it uses the echo chain now.
  • loggableUrl() skipped the by-value redaction, so the configured key printed in the INFO request log (and in
    the 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) and maskQuotedCredentials() published a credential wrapped before its 16th
    character.
  • An unparseable OPENCODE_SERVER_URL that still carried a credential was handed to the SDK and the readiness
    probe; it is now refused at startup by name, masked.
  • The CI action-pin gate could not see a flow-style step whose first key is uses, so a movable reference
    passed the one control that protects a write-scoped Docker Hub token. The .dockerignore guard also missed
    four key patterns the file carries.

Resource safety and performance

  • Unserved paths and methods still parsed the whole announced body before answering 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. 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).
  • tools was the one client-controlled array with no element ceiling (600 000 definitions measured about 97 MB
    of heap and a 54 M-character prompt); all three normalizers refuse it above MAX_REQUEST_ENTRIES.
  • The shutdown drain started up to 1000 session deletes at once; it runs chunks of 16 now.

Wire contract

  • The Responses envelope was built from the raw body where the module reads the normal form, so instructions
    was always null, tool_choice always "auto" and reasoning always null.
  • /v1/messages refused the thinking block it emits itself, so a client with extended thinking enabled could
    not replay its own history; an assistant block is skipped now and the emitted one carries signature: ''.
  • A second reasoning item in a Responses stream reused the first one's rs_ id.
  • A streaming tool-call answer gained a space the non-streaming body does not carry.

Correctness and configuration

  • The backend password, probe credentials and health timings were module globals while createApp() is per
    instance; a second app in one process swapped the first one's password to its spawned child. They travel on
    the per-app config now.
  • A non-decimal tuning value (0x10, 1e3) took effect with no [Config] note; it keeps its value and is
    named.
  • isLoopbackHost() missed ::ffff:7f00:1, the spelling new URL().hostname produces for IPv4 loopback.
  • A chat tool message's name skipped the shared tool-name rule and could close the <tool_result> element
    the model reads; it is validated, and the rendered attribute values are escaped.

Tests and docs

  • New coverage for every item above, end to end and in the codec suites: 661 → smoke (was 653), 133 protocols
    (was 123), 245 responses (was 212), 56 anthropic (was 51), 151 chat (was 133). The queue-full refusal is now
    asserted on /v1/messages and /v1/responses, and the stub reports maxDeletesInFlight so the drain's
    chunk size is observable.
  • AGENTS.md and README.md record each changed behaviour next to the rule it serves, including the
    measurements; test/lib/codec-checks.mjs is in both repository maps.

Verification

pnpm run check                     # [check] syntax OK in 37 files + invariants OK
pnpm test                          # 661 + 133 + 245 + 56 + 151 = 1246 checks passed, exit 0
sh -n docker/docker-entrypoint.sh  # OK
shellcheck -S warning -s sh docker/docker-entrypoint.sh   # OK
node test/checks/check-commit-messages.mjs main..HEAD     # 9 commits, all follow the convention

Each new end-to-end check was shown to fail with its fix reverted (a throwaway copy under /tmp), and the
regression claim for the parser change is a randomized differential against extractToolCalls() over random
chunk splits (16 cases improved, none introduced).

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.
@dinhdev666
dinhdev666 merged commit 68e2039 into main Nov 24, 2026
5 checks passed
@dinhdev666
dinhdev666 deleted the fix/security-perf-audit branch November 24, 2026 10:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant