Skip to content

fix: harden the request path, streaming and completion metrics - #8

Merged
dinhdev666 merged 10 commits into
mainfrom
fix/security-perf-hardening
Dec 3, 2026
Merged

dinhdev666 merged 10 commits into
mainfrom
fix/security-perf-hardening

Conversation

@dinhdev666

Copy link
Copy Markdown
Owner

What changes

A hardening pass over the request path, the upstream event stream, the
completion metrics and the streamed adapters. Ten commits, one per
concern; the per-commit bodies explain each one.

Security

  • authentication and the rate limiter run onRequest, so an anonymous
    caller can no longer make the gateway buffer and JSON-parse up to
    64 MiB per connection before being rejected;
  • credential-less callers are rate-limited per client address (bounded
    bucket map) instead of sharing one anonymous bucket;
  • the public-path check is canonicalised, and the GET / index now
    lists every registered route.

Upstream

  • the connect-phase watchdog is disarmed after the response head, so a
    healthy /api/event stream is no longer aborted every 45 s;
  • the frame buffer is capped at 1 MiB and a stop()/start() race can
    no longer run two event loops;
  • completions_total counts pre-flight failures and its error_code
    label is closed; a failed first turn deletes the session it created;
  • an empty model refresh keeps the previous catalogue;
  • the retained stderr tail is bounded, reusedCount is incremented, and
    each message is serialised once per turn.

Streaming

  • /v1/chat/completions, /v1/completions and /v1/messages adopt a
    consolidated text_end like the other paths already did (they used to
    answer an empty 200 when the provider sent no deltas);
  • /v1/responses fixes output_index at announcement time and adopts a
    step-level reasoning_end only when it is longer;
  • /v1/messages keeps tool calls the buffered route returns after a
    stop-sequence match, and its stop-sequence scan is O(1) instead of
    O(n²) (64 KiB went from ~5 s to under 2 ms).

Docs, CI, Docker

  • route and metric documentation matches the code, with the
    docs-consistency test extended to enforce both;
  • the Docker job starts the built image and probes /health;
  • Dependabot tracks the base image; .dockerignore excludes .env.

Verification

Command Result
pnpm typecheck pass
pnpm build pass
pnpm test 24 files, 542 passed, 4 skipped
pnpm smoke:dist pass (dist/index.js answered /health with version 1.0.0)
docker build + docker run + GET /health pass (the new CI step, run locally)
docker compose config --quiet pass
pnpm exec commitlint --from main --to HEAD 0 problems

Authentication and the rate limiter were `preHandler` hooks, and
Fastify parses the body between `preParsing` and `preHandler`, so an
anonymous caller made the gateway buffer and JSON-parse up to
OPENCODE_MAX_BODY_BYTES (64 MiB) per connection with no credential.
Both hooks now run `onRequest`, after the CORS hooks.

Credential-less callers are bucketed by `request.ip` (proxy-aware when
`trustProxy` is on) instead of sharing one anonymous bucket, and the
bucket map is capped so a rotating address cannot grow it without
bound. The public-path check canonicalises trailing slashes and
repeated separators, so `/metrics/` can no longer fingerprint
`/metrics`. The public `GET /` index now lists every registered route,
with a test asserting the two sets stay equal.
`AbortSignal.timeout()` cannot be disarmed and undici keeps the signal
attached to the response body, so the connect-phase watchdog aborted
every healthy `/api/event` stream after 45 s. Each reconnect marked a
stream gap for every in-flight turn, which then failed with
`503 event_stream_lost` when its terminal event did not arrive within
the grace window. The connect deadline is now a cancellable timer that
is cleared once the response head arrives; reads stay bounded by the
same watchdog.

The frame-assembly buffer was also unbounded and rescanned from offset
zero on every chunk, so a stream without a blank line grew without
limit and cost quadratic CPU. It is capped at 1 MiB: an oversized
partial frame is dropped and counted instead of retained. Finally,
`stop()` retires the running loop with a generation stamp so a racing
`start()` cannot leave two consumers on the same response body.
`prepare()` ran outside the handler, so model resolution, modality
validation, session creation and `upstream_unavailable` failures never
reached `completions_total`, although the docs promise an outcome for
every exit. Pre-flight failures are now counted once, with the resolved
model or `unknown` when resolution itself failed.

The `error_code` label was also filled verbatim from upstream payloads
(`record.type` / `_tag`), which prom-client never evicts: every distinct
tag became a permanent time series. The label is now a closed
allow-list with `other` as the fallback.

When a turn fails before it settles, its sticky record is released;
for a session created for that turn no record exists yet, so the
eviction hook never fired and the upstream session leaked for the life
of the server. The same `finally` now deletes it, best effort, on every
failed fresh turn.
Only completed stderr lines were capped, so an unterminated line (a
child writing binary garbage, or simply never emitting a newline) grew
`#partial` without bound and made every later chunk cost O(partial).
The retained tail is now clamped to 8 KiB; an over-long line is
diagnostic only.
A forced refresh (`GET /v1/models?refresh=1`,
`POST /admin/models/refresh`) or a TTL expiry that answered an empty
model list cleared the previously good catalogue. Every later request
then failed with `model_not_found` and paid the cold-start retry on each
call until a non-empty answer happened to load. The previous catalogue
is kept (with a refreshed timestamp) while the real, empty answer is
still returned to the caller.
A turn hashes the conversation three times (acquire, commit and the
root message in `deriveKey`), re-serialising every base64 media payload
each time: about 40 ms of avoidable CPU and tens of MiB of transient
strings per attachment-heavy turn. Per-message JSON is memoised by
object identity and joined into the array form, which is byte-identical
to `JSON.stringify(messages)` so persisted prefix hashes stay valid.

`reusedCount` is incremented on commit as well: it was read from the
record and never written, so `/admin/sessions` always reported 0.
A provider that delivers its answer only in `session.text.ended`
produced an empty 200 SSE response on `/v1/chat/completions`,
`/v1/completions` and `/v1/messages`, while the buffered route for the
same request carried the answer. Those three streamed paths now adopt a
consolidated `text_end` / `reasoning_end` only when it is longer than
what the deltas already produced, which is the documented rule
`/v1/responses` and `collectCompletion()` already applied.

`/v1/responses` now fixes an item's `output_index` when the item is
announced and reuses it everywhere, so a text-then-reasoning turn no
longer announces two items at index 0 or ends with an `output[]` that
contradicts the stream. A step-level `reasoning_end` snapshot is adopted
only when longer, and the reasoning summary is closed once per turn
instead of once per step.

The Anthropic stream kept the `stop_sequences` filter between it and
the tool calls, so a matched sequence swallowed a call the buffered
route returns; every call is reported again. Its stop-sequence filter
was O(n²) in the length of the retained tail (64 KiB took about 5 s and
blocked the event loop); it now uses the O(1) hold rule the chat adapter
uses. The tool-envelope fence parsing is linear for the same reason.
`GET /` and `docs/API.md` omitted five registered routes (`/healthz`,
the model refresh, the two session routes and the upstream restart).
The metrics reference gave `upstream_request_duration_seconds` an
`outcome` label it does not have, README listed ten of the thirteen
exported series, and `/metrics` was missing from the rate-limit
exemptions. The verification addendum had stale counts and line
references.

The docs-consistency test now also compares the documented `GET /`
index against the routes `src/` registers, and every metric series
against both documents, so the next addition cannot drift unnoticed.
The docker job only built the image and validated the compose file, so
`pnpm prune --prod`, the copied file set and the HEALTHCHECK were never
exercised. It now starts the image with `OPENCODE_AUTOSTART=false` and
a test key, polls `/health` on a Docker-assigned port and fails when
the container exits. Dependabot gains the `docker` ecosystem so a
base-image security release arrives as a pull request, and
`.dockerignore` excludes `.env` so a real key file never enters the
build context.
`shuttingDown` is set before `performShutdown()` is awaited and later
signals are ignored, so a rejecting shutdown left the process alive with
the HTTP server closed and no exit code for the supervisor. The
rejection is logged and the process exits with status 1.
@dinhdev666
dinhdev666 force-pushed the fix/security-perf-hardening branch from 2dc29e9 to 44b5d39 Compare December 3, 2026 06:33
@dinhdev666
dinhdev666 merged commit 04b3a76 into main Dec 3, 2026
5 checks passed
@dinhdev666
dinhdev666 deleted the fix/security-perf-hardening branch December 3, 2026 06:35
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