Skip to content

fix(audit-engine): keep the fetch deadline armed through the body read - #191

Merged
nc9 merged 4 commits into
mainfrom
fix/1729-script-fetcher-deadline
Sep 2, 2026
Merged

nc9 merged 4 commits into
mainfrom
fix/1729-script-fetcher-deadline

Conversation

@nc9

@nc9 nc9 commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

Five fetchers cleared their AbortController timer where the fetch resolved, i.e. when the response headers landed, leaving the body read with no time bound at all. readBodyCapped and response.text() cap bytes, not seconds, so an origin that answers 200 and then trickles or stalls its body parked the caller forever.

Same bug class as #187, which fixed it in the crawler. These are the stragglers.

Sites fixed

file unbounded read
packages/audit-engine/src/script-fetcher.ts readBodyCapped after clearTimeout
packages/audit-engine/src/external-checker.ts getResponse.text() on a 403, for WAF detection
apps/cli/src/crawler/script-fetcher.ts response.text() (fork of the engine fetcher)
apps/cli/src/crawler/external-checker.ts same WAF read (fork)
apps/cli/src/crawl/sitemaps.ts response.text() in a later Effect stage, outside the timer's scope

The two CLI files are forks, not re-exports: apps/cli/src/audit/adapter.ts imports @/crawler/*, so they are what the squirrel binary actually runs. Fixing only the package would have left every CLI user hanging.

Fix

clearTimeout moves into a finally that wraps the body read, matching packages/crawler/src/deadline.ts and packages/fetchers/src/index.ts. The script fetchers additionally split their retry loop out of the attempt, so each retry arms a fresh deadline rather than inheriting a spent one or keeping it alive across the backoff.

Impact

Scripts and external links are fetched during rules enrichment, after pages are collected, so the failure mode was the post-crawl hang class rather than a crawl-phase wedge: the audit has all its pages and never finishes. The sitemap read hangs the crawl preamble instead.

Behaviour changes only on the previously-hanging path. A stalled script body now returns error: "timeout"; a stalled WAF 403 body returns the plain 403 it already knew from the headers (the WAF verdict degrades to unknown, matching the existing "ignore body read errors" branch); a stalled sitemap returns a failure result.

Tests

apps/cli/tests/crawler/fetch-deadline.test.ts and packages/audit-engine/tests/fetch-deadline.test.ts serve headers immediately, then hold the body stream open forever. Verified by reverting each source file to main and re-running: all five cases hang and fail on Bun's test timeout without the fix, and return within the deadline with it. Each fetcher also has a fast-path test proving normal responses are still read in full.

packages/audit-engine/package.json's test:golden glob gains tests/*deadline*.test.ts — the CI engine job runs only that script, so a new test file would otherwise never execute in CI.

  • bun test in apps/cli: 1903 pass, 0 fail
  • bun run test:engine: 66 pass, 0 fail, golden baseline unchanged (pages=518 findings=98221 healthScore=48)
  • bun run typecheck (all workspaces), lint, format:check: clean

No HTML output bytes change, so REPORT_HTML_VERSION is untouched.

Follow-up, not in this PR

apps/cli/src/tools/request.ts (request / requestOnceWithTiming) has the same shape: it clears the deadline and hands the Response to callers that read the body later (robots.ts, reachability, and others). Fixing it properly means moving those call sites to a withRequestDeadline(timeoutMs, perform, use) contract, which is a wider refactor than this PR should carry. Filed separately.

Refs squirrelscan/repo#1729

@nc9

nc9 commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

Acceptance findings addressed in 37ac3b3. Two of the four needed a correction to the finding itself; details below.

HIGH — packages/crawler/src/fetcher.ts — real, fixed

Confirmed and fixed. requestWithTiming had the same clear-at-headers bug wearing a try/finally that looks correct: the finally closes at the fetch, but the Response escapes and its body is read much later in fetchPageStandard. The same finally also removed the fiber-interrupt bridge, so an interrupt could not reach the reader.

One correction to the framing: it was not an unbounded hang. crawler.ts:1299 wraps processUrl in Effect.timeout(max(120_000, timeoutMs * 6)), so a stalled page was bounded by the per-URL watchdog. The damage was that a stall burned the whole watchdog (at least 120s) instead of timeoutMs, and that the watchdog's abort never cancelled the read: readBodyCapped stayed parked on reader.read() for the life of the process, holding the socket and its buffered chunks.

requestWithTiming now returns a TimedResponse whose deadline stays armed. The caller owns it across the redirect loop and the body read, drops superseded hops (which the loop never did, leaking their sockets), and Effect.ensuring releases whatever is still held on every exit — a try/finally inside Effect.gen does not run on failure. The body read's interrupt bridge now aborts the request instead of only losing a race, and a deadline firing mid-body reports a timeout rather than a parse error. fetchPageStandard is split behind Effect.suspend so the held state is per run, since callers retry this same Effect value.

Both new cases fail against main: the stall case by hanging, and the interrupt case because the test server observes that the client never aborted (req.signal).

Not touched: deadline.ts, per your note about #194.

MED — WAF 403 — real, but the first fix I wrote was inert

Your diagnosis was right, and my initial fix was wrong in a way worth recording. I added a wafCheckInconclusive flag honored by filterBrokenLinks. A codex pass caught that filterBrokenLinks is not the production path: results flow through the adapters into storage.upsertLink (which has no such column) and are re-filtered by packages/rules/src/links/broken-external-links.ts. The flag would have been dead code that looked like a fix. Plumbing it properly needs a new SQLite column on links plus changes across 7 sites in 3 packages — too much for this PR, and a schema change I would not slip into a deadline fix.

What landed instead is smaller and actually reaches production: on a failed 403 body read, run WAF detection on the response headers rather than abandoning it. detectWaf(headers) treats an absent body as headers-only, and most WAFs are identifiable from cf-ray / x-sucuri-id / a provider server value alone. That is real evidence, not a guess, and it needs no new field. A 403 that stalls and carries no WAF header still reads as a plain 403 — the pre-existing ambiguity, which predates this PR (any body-read failure already fell through that way) and is now the only remaining gap.

MED — sitemap reason — substance right, mechanism wrong

HTTP 0 is not reachable. Effect.tryPromise's catch value goes to the error channel, so it never reaches Effect.map; result.status in the mapper is always a real HTTP status. Verified by running it — a stalled body and a DNS failure both produced "Unexpected error" (from the terminal catchAll), and a 404 produced "HTTP 404".

The substance holds: the reason was discarded, just at catchAll rather than at the mapper. catchAll now carries it, and the error-channel value no longer mimics the success shape — that overlap is what made HTTP 0 look reachable. The three modes are now distinct: Timed out after 300ms, HTTP 404, and the runtime's connect message.

LOW — retry freshness — added, and the first version was too weak

Added to both suites. Codex flagged that my first version passed against unfixed code, which was correct: the old recursive implementation already built a fresh controller per attempt. Attempt 2 now hits a stalled body, which pins three things at once — a retry happened, the retry's deadline covers its body read, and that deadline is fresh (a spent timer or aborted controller fails attempt 2 instantly, at about the backoff rather than backoff plus deadline). Both now fail against main.

Verification

Every new case was run against origin/main sources, not just asserted: 4 of 5 engine cases and 6 of 8 CLI cases fail there, plus both crawler stall cases.

  • packages/crawler: 268 pass
  • packages/audit-engine: 317 pass, 3 skip
  • apps/cli: 1906 pass
  • bun run test:engine: 68 pass, golden baseline unchanged (pages=518 findings=98221 healthScore=48)
  • root typecheck, lint, format:check: clean

nc9 added 4 commits September 2, 2026 14:34
Five fetchers cleared their AbortController timer where the fetch resolved,
i.e. when the response HEADERS landed, leaving the body read with no time
bound. readBodyCapped and response.text() cap BYTES, not seconds, so an
origin that answers 200 and then trickles or stalls its body parked the
caller forever. Same class as #187 fixed in the
crawler; these are the stragglers.

clearTimeout moves into a finally that wraps the body read. The script
fetchers split their retry loop out of the attempt so each retry arms a
fresh deadline instead of inheriting a spent one.

The CLI forks are the live path for the `squirrel` binary (apps/cli imports
its own crawler/, not the engine package), so fixing only the package would
have left users hanging.

Sites fixed:
- packages/audit-engine/src/script-fetcher.ts (body read)
- packages/audit-engine/src/external-checker.ts (WAF 403 body read)
- apps/cli/src/crawler/script-fetcher.ts (fork)
- apps/cli/src/crawler/external-checker.ts (fork)
- apps/cli/src/crawl/sitemaps.ts (text read ran after the timer cleared)

Scripts and external links are fetched during rules enrichment, after the
crawl, so the failure mode was a post-crawl hang: an audit with all its
pages that never finishes. The sitemap read hangs the crawl preamble.

Regression tests serve headers then hold the body stream open forever; all
five hang without the fix and time out at the deadline with it. The engine
tests are added to test:golden so CI actually runs them.

Refs squirrelscan/repo#1729

Signed-off-by: Nik Cubrilovic <[email protected]>
A bare `void body.cancel()` leaves a rejected cancel unhandled — an
already-errored stream rejects, and an unhandled rejection is a worse
outcome than an undrained socket.

Signed-off-by: Nik Cubrilovic <[email protected]>
…y read

Acceptance-review follow-ups on the #1729 deadline sweep.

packages/crawler/src/fetcher.ts had the same clear-at-headers bug wearing a
try/finally that looks correct: requestWithTiming cleared its timer in a
finally that closes at the fetch, then returned the Response for
fetchPageStandard to read much later. The same finally also removed the
fiber-interrupt bridge, so the watchdog's abort never reached the reader --
readBodyCapped stayed parked on reader.read() for the life of the process,
holding the socket and its buffered chunks.

Not an unbounded hang: crawler.ts's per-URL watchdog (>=120s) is the
backstop. But a stalled page burned the whole watchdog instead of timeoutMs.

requestWithTiming now returns a TimedResponse whose deadline stays armed;
the caller owns it across the redirect loop and the body read, drops
superseded hops (which the loop never did, leaking their sockets), and
Effect.ensuring releases whatever is still held on every exit -- a
try/finally inside Effect.gen would not run on failure. The body read's
interrupt bridge now aborts the request rather than only losing a race, and
a deadline that fires mid-body reports a timeout, not a parse error.
fetchPageStandard is split behind Effect.suspend so the held-response state
is per RUN: callers retry this same Effect value.

External checker (both copies): a 403 whose body could not be read no
longer abandons WAF detection. Detection runs on the response headers,
which are evidence in their own right -- most WAFs are identifiable from
cf-ray / x-sucuri-id / a provider server value alone. Giving up there
reported live, bot-guarded links as broken, and the deadline now makes that
read fail more often.

Sitemaps: the terminal catchAll carries the failure reason instead of
collapsing every non-HTTP failure to "Unexpected error", so a body-read
timeout, a connect failure and an HTTP error are distinguishable. Its
error-channel value no longer mimics the success shape.

Tests: each new case was verified against origin/main -- 4 of 5 engine and
6 of 8 CLI cases fail there, and both crawler stall cases fail, one by
hanging and one by observing that the server never saw the client abort.
The retry tests now stall attempt 2's body, so they pin that the retry's
deadline is fresh AND covers its body; the earlier form passed unfixed.

Refs squirrelscan/repo#1729

Signed-off-by: Nik Cubrilovic <[email protected]>
Round-2 review findings, both reproduced with an instrumented probe before
being fixed and re-probed after.

release() only disarmed the timer. Every path that releases WITHOUT a body
read therefore left the stalled body and its socket parked for the life of
the process -- the exact leak class this change exists to kill. Two such
paths: a terminal 403/429/5xx that fails applyStatusGuards before any read,
and a redirect hop still held when the NEXT request fails (the loop drops a
superseded hop only once a newer response arrives). Probe on both:
`server saw cancel: false`. release() now aborts as well. That is safe
unconditionally because release runs only as the effect leaves: on the
success path the stream is already drained and the abort is a no-op.

The 503 challenge read swallowed every failure via orElseSucceed, including
the timeout this PR newly maps, so a stalled 503 body came back as the
generic `network: Server error: 503` -- blaming the origin for our own
deadline. It now re-fails on a timeout and still degrades every other read
failure to "no body", so the guard can classify the 503 from headers alone.

Three tests added, each verified to fail against the previous commit: two
use a server-side `req.signal` observer to prove the connection is actually
cancelled (terminal status, failed hop), and one asserts the stalled-503
classification is `timeout`.

Rebased onto main after #193 merged.

Refs squirrelscan/repo#1729

Signed-off-by: Nik Cubrilovic <[email protected]>
@nc9
nc9 force-pushed the fix/1729-script-fetcher-deadline branch from 37ac3b3 to cea5229 Compare September 2, 2026 04:37
@nc9

nc9 commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

Both round-2 findings confirmed and fixed in cea5229. Branch rebased onto main after #193 merged.

I reproduced each with an instrumented probe before touching the code, so these are measured rather than reasoned:

A terminal 403      -> type: blocked | server saw cancel: false
B failed hop        -> type: network | server saw cancel: false
C stalled 503       -> type: network | msg: Server error: 503

and after:

A terminal 403      -> type: blocked | server saw cancel: true
B failed hop        -> type: network | server saw cancel: true
C stalled 503       -> type: timeout | msg: Crawl request timed out

HIGH — release() left unread bodies parked

Correct on both counts. release() only disarmed the timer, so every path that releases without a body read leaked the socket:

  • a terminal 403/429/5xx fails applyStatusGuards before readBody is ever yielded;
  • a redirect hop is still held when the next request fails, because the loop drops a superseded hop only once a newer response arrives.

release() now aborts as well as disarms. That is safe unconditionally rather than conditionally, and the reason is worth stating: release runs only from Effect.ensuring, i.e. as the effect leaves, after the gen body has already produced its return value and extracted everything it needs from the response. So there is no path where a body is read after release. On the success path the stream is already drained and the abort is a no-op; on every failure path nobody will ever consume it. No consumed-flag bookkeeping needed, and none added.

MED — 503 challenge read swallowed the timeout

Correct. Effect.orElseSucceed(readBody, () => undefined) caught everything, including the timeout this PR newly maps, so a stalled 503 surfaced as network: Server error: 503 — the origin blamed for our own deadline. It now re-fails on error.type === "timeout" and still degrades every other read failure to "no body", so the guard can classify the 503 from cf-mitigated and friends alone.

Tests

Three added to packages/crawler/tests/fetch-body-deadline.test.ts, all run locally and each verified to fail against the previous commit (37ac3b3):

  • a terminal status released without a read still cancels the connection — server-side req.signal observer, 403
  • a hop still held when the next request fails cancels that hop — 302 to a closed port, same observer
  • a stalled 503 body is classified as a timeout, not a server error

The two cancellation tests assert what the server observed, not what the client returned, since the client returns promptly either way — that distinction is what made the original leak invisible.

Verification

  • packages/crawler: 271 pass (was 268; +3)
  • apps/cli: 1907 pass
  • bun run test:engine: 68 pass, golden baseline unchanged (pages=518 findings=98221 healthScore=48)
  • root typecheck, lint, format:check: clean

Will confirm from the CI log that the three new cases executed there, not just locally.

@nc9
nc9 merged commit 9cd144e into main Sep 2, 2026
13 checks passed
@nc9
nc9 deleted the fix/1729-script-fetcher-deadline branch September 2, 2026 04:45
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