Skip to content

fix(server): remediate the second audit pass - #22

Merged
dinhdev666 merged 9 commits into
mainfrom
fix/second-audit-pass
Dec 5, 2026
Merged

dinhdev666 merged 9 commits into
mainfrom
fix/second-audit-pass

Conversation

@dinhdev666

Copy link
Copy Markdown
Owner

Second independent audit pass (security, upstream layer, surface adapters, infrastructure + documentation drift), with the accepted findings implemented and covered by regression tests. The proposal file that drove the work has been deleted, because this pass is now complete.

What changed

fix(upstream) — an interrupted turn is reported as cancelled instead of a successful stop; the caller's abort signal reaches the first createSession(); a cache-disabled turn records and persists nothing and deletes the session it created; the first-token watchdog counts session.step.started and session.tool.* frames as liveness; a failed spawn leaves the process-exit registry; a 2xx body without a usable data field is 503 upstream_invalid_json instead of a bare TypeError; the supervised child's log file is bounded (OPENCODE_UPSTREAM_LOG_MAX_BYTES, default 32 MiB).

fix(openai) — stop / stop_sequences are capped (16 entries, 256 characters each, 1024 in total), which removes a measured ~6 s event-loop stall per request; a request whose messages all normalise to nothing is 400 invalid_request instead of a billed "Continue." turn; /v1/responses head frames carry the resolved x_opencode values.

fix(anthropic) — a terminal error frame is preceded by the content_block_stop of the block the turn opened, so a failed stream can still be assembled; media blocks go through the shared bounded download pool instead of one Promise.all (320 MiB to 80 MiB in flight at the defaults).

fix(security) — throttled auth failures are audited at warn instead of debug; the configured key digests are memoised (2xN SHA-256 per request becomes one digest plus N comparisons); the buffered request bound is attached to the socket so its callback actually runs; a non-base64 data: URI is refused before decoding; the RFC 2765 ::ffff:0:a.b.c.d prefix is classified private.

fix(scripts) — pnpm setup sees the export / : / OPENCODE_API_KEY= spellings and rewrites in place instead of appending a duplicate that silently replaced the operator's key with sk-dummy-123; pnpm smoke:dist fails on a failed or hung shutdown; pnpm smoke bounds the body read; every loopback spelling is classified correctly; CI checkouts no longer persist the repository token while install scripts run.

docs — the README /metrics paragraph is corrected, docs/API.md documents the caps, the validation rule and the frame contracts, docs/ARCHITECTURE.md follows the frozen contract, and docs/VERIFICATION.md has the addendum with the current counts.

Verification

pnpm typecheck      # clean
pnpm test           # 37 files, 861 passed, 2 skipped
pnpm build          # clean, 80 files in dist/
pnpm smoke:dist     # /health answered, clean SIGTERM shutdown (exit status checked)
pnpm audit --prod   # No known vulnerabilities found
pnpm exec commitlint --from main --to HEAD   # 0 problems

Every fix ships with a regression test in test/upstream-invariants.test.ts, test/openai-validation.test.ts, test/anthropic-streaming.test.ts, test/http-guards.test.ts or test/setup-scripts.test.ts, and each new test was confirmed to fail before its fix.

@dinhdev666 dinhdev666 changed the title fix: remediate the second audit pass fix(server): remediate the second audit pass Dec 5, 2026
@dinhdev666 dinhdev666 closed this Dec 5, 2026
@dinhdev666 dinhdev666 reopened this Dec 5, 2026
Seven defects found by the second audit of the upstream layer:

- `session.execution.interrupted`, and `session.idle` with outcome
  `interrupted`, ended the turn as a normal `stop`, so an incomplete
  answer was returned as complete and counted as a success.
  `FinishReason` already has a `cancelled` member that the Anthropic
  surface keys `x_opencode.interrupted` on; both branches now set it.

- the first `prepare()` dropped the caller's abort signal, so a
  disconnect while a session was being created parked the handler for
  the full request budget before creating (and deleting) a session for a
  caller that was already gone.

- a completed turn committed, and with `OPENCODE_SESSION_PERSIST=true`
  wrote to disk, a session record even when the sticky cache was
  disabled, where nothing can ever reuse it. That path now records
  nothing and deletes the session it created.

- the first-token watchdog ignored `session.step.started` and every
  `session.tool.*` frame, so a request whose agent was running a long
  native command was killed with a false "produced no output".

- a spawn `error` never re-checked the process-exit registry once the
  start promise settled, so a dead instance was retained for the
  lifetime of the process.

- a 2xx body without a usable `data` field escaped `createSession()` and
  `prompt()` as a bare `TypeError` (HTTP 500) instead of `503
  upstream_invalid_json`.

- the supervised child's log file was appended to for the whole life of
  the server and across restarts; it is now rotated at
  `OPENCODE_UPSTREAM_LOG_MAX_BYTES` (default 32 MiB, `0` disables the
  cap), seeded from the file that survived an earlier run.

`OPENCODE_LOG_LEVEL` also accepts `silent` now: `scripts/smoke-dist.mjs`
already used it and pino already understood it, so the closed set was
narrower than the logger and warned on every smoke run.
The streamed stop filters re-scanned their held lookahead window for
every declared delimiter on every delta, and nothing bounded the number
or the length of those delimiters: a 1.3 MB body carrying 20 000
near-matching 64-byte sequences blocked the event loop for about 6 s on
a 64 KiB answer, against the default 64 MiB body limit. `stop` is now
capped at 16 entries, 256 characters each and 1024 characters in total,
shared by the three stop-capable surfaces through the new
`src/adapter/common/stop.ts`; past a cap the request is `400
invalid_request` naming the field. An empty entry keeps its historical
meaning and is dropped by both paths again, so the streamed filter can
no longer truncate an answer at offset 0.

A request whose messages all normalised to nothing ran a billed turn on
the literal `"Continue."` and answered `200`, although `docs/API.md`
already promised the opposite for `/v1/responses`, and `/v1/messages`
rejects it with COR-05. The chat and Responses surfaces now drop a
message or input item that carries no text, no media and no tool call,
and reject an empty result with `400 invalid_request` naming `messages`
/ `input`. The check runs after media resolution, so a media-only
message whose attachment was omitted still keeps the omission note.

`/v1/responses` applied the already-pulled `start` event only after
emitting `response.created` / `response.in_progress`, so both head
frames carried an empty `x_opencode.session_id`/`agent` while the
terminal object carried the real values. The event is now applied before
the head frames, idempotently, with the pre-flight error guard still
first.
A mid-stream `error` event, the real failure path from the orchestrator
(timeouts, `event_stream_lost`, queue overflow, step and execution
failures), was written after returning immediately, leaving every
content block the turn had opened without its `content_block_stop`. The
Anthropic `error` frame carries no partial message, so the client could
not close or reassemble the block at all. The in-band error branch and
the outer catch now flush the stop-sequence lookahead and close the open
block first, exactly like the `finishReason: "error"` path, and reorder
nothing else.

The surface also resolved one media block per `Promise.all` instead of
through the shared bounded pool, so a `/v1/messages` request could hold
`maxAttachments x maxAttachmentBytes` in flight (320 MiB by default)
rather than the pool's 80 MiB, and a hard failure left its siblings
downloading. Every block that needs bytes now goes through one pooled
`resolveAttachments()` call and is mapped back by declaration order,
keeping the omission semantics: an omitted source keeps the placeholder
its slot was seeded with.

`stop_sequences` uses the shared caps from `src/adapter/common/stop.ts`,
and the P-24 scan-cost regression now drives 20 000 deltas at the
documented 256-character cap instead of a 64 KiB sequence the cap
rejects.
- A throttled authentication failure answers `429`, and the error
  handler logged everything that is neither `>= 500` nor `401` at
  `debug`: once the always-on failed-auth bucket was drained, a
  credential-guessing flood disappeared from the default log level. The
  limiter marks the requests it throttled and the error handler audits
  them at `warn` with the same fields as the `401`; status,
  `retry-after`, body and `code` are unchanged.

- `isAuthorized()` digested both operands on every iteration, i.e. `2 x
  N` SHA-256 per request (about 0.9 ms at 1000 keys) for a value that
  never changes between requests. The configured digests are memoised
  per `Config` and the presented value is digested once, while every
  `timingSafeEqual` over a fixed-width digest still runs, so the timing
  property is preserved.

- `applyRequestTimeout()` installed its callback with
  `IncomingMessage#setTimeout`, whose listener Node only emits while the
  body is still incomplete: for a buffered completion the callback never
  ran and the socket was reclaimed by a Node-internal fallback instead
  of the gateway's own bound. The timer now lives on the socket.

- A non-base64 `data:` URI was decoded before the byte cap was applied,
  so an oversized payload materialised up to three times its length
  before its `400`; the encoded length is now refused first, mirroring
  the base64 branch. The post-decode check stays authoritative.

- The RFC 2765 IPv4-translated prefix `::ffff:0:a.b.c.d`, whose last 32
  bits can embed a private IPv4 address, fell through the IPv6 prefix
  checks and was classified public. Every IPv4-embedding prefix is
  decoded now, and unrelated public literals stay public.
`pnpm setup` only understood a bare `OPENCODE_API_KEYS=` line at the
start of a line, so an `export OPENCODE_API_KEYS=...`, an
`OPENCODE_API_KEYS: ...` or an `OPENCODE_API_KEY=...` assignment was
invisible to it. It then appended a duplicate line, and because `dotenv`
resolves duplicate keys last-wins the gateway accepted `sk-dummy-123`
instead of the operator's secret, silently replacing it or publishing
the repository's key next to it.

The script now parses the file with dotenv's own parser, treats a
non-default value in either spelling as already configured, and rewrites
every matching line in place instead of appending a duplicate.
`pnpm smoke:dist` never looked at the child's exit status, so a failed
or hung shutdown still exited 0 while the documentation presented the
script as the clean-shutdown check. It now arms an exit listener before
the SIGTERM, bounds the wait for the drain, and fails on a non-zero code
or on a shutdown that outlives its watchdog.

`pnpm smoke` cleared its abort timer as soon as the response headers
arrived, which left a stream that stalls mid-body unbounded; the
deadline now covers the body read.
`isLoopbackHost()` only knew the compressed `::1` spelling, so the
expanded `0:0:0:0:0:0:0:1` and the IPv4-mapped `::ffff:7f00:1` were
treated as network-reachable: the published-default-key guard refused a
bind no other machine can reach, and the SSRF/metrics warnings fired on
a loopback interface.

`node:net`'s `BlockList` now classifies the address, and every spelling
that is not genuinely loopback still fails closed.
The workflow pins every action to a commit SHA because each job runs
with a repository token, but none of the four checkouts set
`persist-credentials: false`, so that token stayed in `.git/config`
while `pnpm install --frozen-lockfile` executed dependency build scripts
(esbuild's install script is explicitly allowed).
`docs/API.md` now documents the `stop`/`stop_sequences` caps, the `400
invalid_request` an empty turn is rejected with on the chat and
Responses surfaces, the `content_block_stop` that precedes a terminal
Anthropic `error` frame, the streamed block order (arrival order,
against the buffered `thinking` -> `text` -> `tool_use`), the
interrupted-turn reporting, and the `/v1/responses` head frames that
carry the resolved `x_opencode` values.

`docs/ARCHITECTURE.md` follows every changed contract: the
interrupted-turn `cancelled` finish reason, the signal that now reaches
the first session creation, the cache-disabled turn that records and
persists nothing, the first-token watchdog that counts upstream
liveness, the bounded upstream log file, the `{ data: ... }` envelope
validation, and the new `src/adapter/common/stop.ts` in the frozen
`adapter/common` contract.

`docs/VERIFICATION.md` gains the addendum for this pass with the
commands that were run and the current counts (40 modules, 80 emitted
files, 37 unit test files, 861 passing tests, 52 environment variables).
@dinhdev666
dinhdev666 force-pushed the fix/second-audit-pass branch from 9a87a17 to 1a10f11 Compare December 5, 2026 10:13
@dinhdev666
dinhdev666 merged commit 44fcf14 into main Dec 5, 2026
5 checks passed
@dinhdev666
dinhdev666 deleted the fix/second-audit-pass branch December 5, 2026 10:15
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