Skip to content

fix: repair the defects a third audit found - #4

Merged
dinhdev666 merged 8 commits into
mainfrom
fix/audit-round-3-2026-11
Nov 23, 2026
Merged

dinhdev666 merged 8 commits into
mainfrom
fix/audit-round-3-2026-11

Conversation

@dinhdev666

Copy link
Copy Markdown
Owner

A third pass over the code that landed in the first two, as the loop asks: the merged result re-read, nothing assumed correct.

What was wrong

Where Defect
TRUST_PROXY believed whatever sat at index 0 of the forwarded chain whenever the peer was private — on a Docker bridge or a VPC that is every client, so a rotating X-Forwarded-For chose its own request.ip and defeated the login lockout and both rate limiters at once. New TRUSTED_PROXIES matches by address; an unlisted host is answered with its own socket address, and an empty list trusts nothing.
admin-routes 2026-02-29 parsed as 2026-03-01, minting a key one to three days longer than the date typed, silently. The day is checked against the calendar now.
engine/router + queue queueWaitMs was summed per attempt, and the queue deadline restarted per attempt, so MAX_QUEUE_WAIT_MS bounded each attempt instead of the request. A slot granted to a waiter whose deadline had passed stretched the bound by however long the loop was blocked.
db migration 4 added latency_count, so every pre-upgrade rollup had a zero denominator and the latency average over exactly those rows read null. Migration 5 backfills it. NO_PROVIDER_ID is 0, so every filter read the unassigned bucket as "no filter" and it was the one thing the dashboard could not show.
gateway/sse the appended [DONE] ignored how the upstream's last byte ended, so a provider killed mid-line left the terminator glued into the previous event's payload — the hang invariant 2 exists to prevent. An error frame was also synthesised after the terminator, cooling down a provider that had already delivered its answer.
gateway/completions recordLog/recordMetric claimed to tolerate failure but called the repository bare; the metric write is the statement before the slot is released, so a throw leaked the slot.
dashboard the endpoint check refused every DNS name and every IPv6 literal; one server refusal disabled Save for the rest of the dialog; a saved numeric setting kept its "modified" badge; the export name ignored RFC 5987.

Verification

  • pnpm run check — 58 files, syntax + import resolution, no console.* outside the logger, 14 pinned action references.
  • pnpm run typecheck — clean.
  • pnpm run test:unit — 6 of 6 files, 774 checks.
  • SMOKE_SLOW=1 pnpm run test:smoke — 317 of 317.
  • pnpm run check:commits main..HEAD — 8 of 8.
  • pnpm run build — the dashboard bundle builds.

No new dependency. TRUSTED_PROXIES is boot-only and documented in the README, docker/README.md, config.json.example, .env.example and AGENTS.md.

Two defects in the same accounting, both of which made a healthy fleet
look worse than it is.

`queueWaitMs` was summed across attempts. The reservation reports the
wait from the original `enqueuedAt`, so a request that lost two slot
races and then succeeded reported the first leg twice - a dashboard
showing 90 ms of queueing for a request that waited 30.

The queue deadline also restarted per attempt, so `MAX_QUEUE_WAIT_MS`
bounded each attempt instead of the request: three attempts at the
default 30 s meant 90 s in the queue before `503 queue_full`, which is
not what the setting documents and not what a client's timeout assumes.
The context is now threaded through `execute()` and reused by every
attempt of that request.

`release()` granted a slot to a waiter whose deadline had already
passed when the event loop stalled past the timer, stretching the bound
by however long the loop was blocked. It now settles the expired head
as a timeout and serves the next waiter that still has time.
`stop()` cleared the timer and awaited `inFlight`, but a callback that
was already running when a reconfigure replaced the timer set
`inFlight` to a new promise afterwards, so the awaited one was not the
batch that was still in the air. A shutdown could therefore resolve
while a probe was mid-flight, and the next start probed against a
provider that was still being torn down.

The callback now returns without arming anything while the loop is
stopped, which keeps `inFlight` naming the batch that is actually
running.
Two readings of the same "no value yet" sentinel.

`latency_count` was added in migration 4, so every rollup row written
before the upgrade has samples in `latency_sum` and a zero denominator.
`latencyAvg` skips a row whose count is zero, which turned the average
over exactly those rows into `null` - and into 81700 ms once new
requests folded into the same bucket, because the bucket then held both
old and new latency. Migration 5 backfills the denominator for the rows
that have a sum, once, before any new write lands.

The other half is `NO_PROVIDER_ID`, which is `0` and therefore falsy:
every filter tested the value for truthiness and read "the provider
whose id is 0" as "no filter", so the unassigned bucket was the one
thing the dashboard could not show. The filters now test for null and
undefined.
`TRUST_PROXY` believed whatever sat at index 0 of the forwarded chain
when the peer was on a private network. "The peer is private" is not
"the peer is my proxy": on a Docker bridge, a VPC or a tailnet every
client is at a private address, so any of them could write
`X-Forwarded-For` and choose its own `request.ip`. The login lockout
and both rate limiters key on that address, so a rotating header
defeated all three at once - verified end to end, with 20 guesses that
never locked and a dashboard limiter that never fired.

A hop count on its own cannot fix it, and the count has a second
failure: a reverse proxy on a public address is never believed, so
every client shares one bucket and three wrong passwords lock the
operator out.

The proxies are therefore stated by address in a new `TRUSTED_PROXIES`
setting, matched by value rather than by position: an entry the
operator did not list truncates the chain, so a host that can reach
the port but is not the proxy is answered with its own socket address.
Both spellings of an IPv4-mapped peer are recognised, since that is
what a dual-stack socket reports. With the list empty nothing is
believed and the boot log says why.

BREAKING CHANGE: `TRUST_PROXY` without `TRUSTED_PROXIES` no longer
reads `X-Forwarded-For`; set the proxy address to keep per-client
limits.
`Date.parse` rolls an impossible day into the next month instead of
refusing it, so `2026-02-29` minted a key expiring on 2026-03-01 and
`2026-04-31` one expiring on 2026-05-01 - one to three days longer
than the date the operator typed, with nothing on screen to say so. A
full timestamp rolled the same way, and the zone offset it carries
moves the mismatch out of sight.

The day is now checked against the calendar before parsing, in both
spellings. A real leap day still works.
The appended `data: [DONE]` ignored how the upstream's last byte ended.
A provider killed mid-line left the client holding `data: {"a":1}` with
no newline, and the terminator glued to it produced one event whose
payload was `{"a":1}data: [DONE]` - a strict client never sees the
terminator and waits until its own timeout, which is the hang invariant
2 exists to prevent. The append now closes the open line first.

An error frame was also synthesised after the terminator: a socket that
reset once the provider had written `[DONE]` and closed the response
was recorded as a 502, cooled the provider down and counted toward its
breaker for an answer it delivered in full. The route now treats a
failure after the terminator as the completion it is.

Both `recordLog()` and `recordMetric()` claimed to tolerate a failure
but called the repository bare. On the non-streaming path the log write
runs before `reply.send()`, so a full disk turned a delivered answer
into a 500; in the streaming path the metric write is the statement
before the slot is released, so a throw left the request holding a
provider slot. Both are guarded now.
Four defects in the dashboard, each one leaving the operator stuck
rather than merely annoyed.

The endpoint check decided "private" by falling through to `true`
whenever `hostname.split('.')` was not four parts long, so every DNS
name and every IPv6 literal was refused - an ordinary provider could not
be saved at all. It now mirrors `src/upstream/url.js`: a name is not
private, an unparseable host is left to the server, and both spellings
of a mapped address are recognised. The path rule also matches the
server's own `endsWith('/v1')`, so a fleet mounted behind a prefix
saves.

A server refusal was held in `formError` and cleared only by a
successful submit, so one 400 disabled Save for the rest of the dialog
and re-selecting a value did not help. Every field now clears its own
message on edit, and the button consults only local validation.

`numericDrafts` survived a successful save, so a row that had just been
stored kept its "modified" badge and its raw text. Both maps are
cleared, and a reset clears only the keys the server reported instead of
the whole form.

The export name ignored RFC 5987, so a server naming its export with
`filename*=UTF-8''…` handed the browser the percent escapes as the file
name. The extended form wins and is decoded, with the basename check
run after decoding so `%2F` cannot smuggle a separator.
`quota.js` and `upstream/client.js` each carried an identical copy of
`parseRetryAfter`. The unit test imported the engine's copy while the
gateway route called the client's, so the parser in production could
regress with the suite still green. The client keeps it and the engine
re-exports, because the dependency may only run one way.
@dinhdev666
dinhdev666 merged commit b2074f1 into main Nov 23, 2026
6 checks passed
@dinhdev666
dinhdev666 deleted the fix/audit-round-3-2026-11 branch November 23, 2026 18:17
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