Skip to content

fix(fetchers): decode compressed bodies as they are read, never inflate a bomb (repo#2717) - #699

Merged
nc9 merged 3 commits into
mainfrom
fix/content-encoding-bombs-2717
Oct 12, 2026
Merged

nc9 merged 3 commits into
mainfrom
fix/content-encoding-bombs-2717

Conversation

@nc9

@nc9 nc9 commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes squirrelscan/repo#2717. Bun's fetch inflates a Content-Encoding body in full as soon as it arrives. It does this whether the body is read under a byte cap, cancelled unread, or thrown away with a redirect, so no cap in the crawl stopped a compression bomb. Measured on the parent commit: a 1 MB gzip page that inflates to 1 GiB cost 2.5 to 2.8 GB of RSS on Bun 1.3.14, and a whole audit of a bomb site cost 2.3 to 2.8 GB on the released v0.0.108 (Bun 1.4.0).

  • packages/utils/src/response-body.ts, one shared helper:
    • fetchUndecoded fetches with decompress: false and sends the Accept-Encoding Bun would have sent (gzip, deflate, br, zstd, or the caller's own value). In Bun it records each response that still carries a coding. Other runtimes get a plain fetch.
    • decodedBody / readBodyCapped decode through a pull bridge over node:zlib. A chunk goes to the decoder only once its output has been read, and node:zlib pauses while its output is unread, so nothing is inflated past what the reader pulls. Cancelling stops the raw body too.
    • Not DecompressionStream: on Bun 1.4.0 it rejects bytes after a complete stream (gzip with appended junk or zero padding, br, deflate and zstd with junk) and drops the output it still held. The runtime's own decoding read those pages fine. node:zlib ignores trailing bytes. gzip is read past its header (parsed here, RFC 1952) as raw deflate, up to the end of its first member, the way browsers read it.
    • deflate is sniffed as zlib or raw deflate. An empty encoded body reads as "", as it did before.
    • A deadline abort is still an AbortError. A body that does not decode throws ContentDecodingError, and isDecompressionError (now shared) recognises it, so CrawlError.decode and the fetchers' docs(changelog): add the v0.0.92 numbers table #292 raw refetch behave as before.
  • safeRedirectFetch(url, init, send) sends every manual hop through send. safeFetchWithDeadline passes fetchUndecoded, which covers robots, rsl, llms, markdown, well-known, agent-access and sitemaps.
  • Switched to undecoded fetches:
    • the crawler page fetcher, on every hop
    • the fetchers document fetcher, on every hop
    • seed redirect resolution
    • engine script, cloaking, soft-404, resource and external-link checks
    • the CLI's reachability probe, script fetcher and external-link checker
  • Two unbounded reads are now bounded:
    • the CLI script fetcher's .text() reads up to the cap + 1, matching the engine's.
    • the external-link 403 body used for WAF detection reads up to 1 MB.
  • The resource checker's no-length fallback counts decoded bytes and no longer buffers the body. The size is still the decoded size.
  • accept-encoding is now kept on cross-origin redirect hops. Without it, a sitemap hop would ask for the default codings, including zstd, which the sitemap reader does not decode (found in the codex review).

The "too-large outcome" (AC 1). A decoded body over its cap is handled the same way as an uncompressed one over the cap. For pages that means truncation at the 10 MiB document cap, and the audit reports it: in the end-to-end run, crawl/html-size fails /bomb at 10.0 MB and crawl/robots-txt warns that robots.txt is very large (512 KB). Scripts still report script too large. I did not add a separate "too large" field for pages, because that would change what happens to oversized uncompressed pages too.

On "about 2x the cap". A bomb now costs the same as an uncompressed body over the same cap; the control row in the record shows this. Through readBodyCapped that is 3 to 5 times the 10 MiB page cap. The overhead comes from the existing reader, not from decoding: 10 MiB of bytes plus the string decoded from them is 21 MB on its own. Brotli has one more fixed cost. Each open stream keeps a window of up to 16 MiB, so 20 concurrent large-window bombs measured 357 to 367 MB, where inflating them would take 20 GiB.

Behaviour changes for ordinary responses. Bun sent no Accept-Encoding at all with its decoding off, so the header is now set explicitly to Bun's own value, and origins see the same request. x-gzip and an upper-case GZIP are now decoded; Bun used to pass them through as raw bytes. Stacked and unknown codings still pass through untouched. Bytes after a complete compressed body are still ignored. A multi-member gzip body is read to the end of its first member, as Chrome and Bun 1.3.14 read it; Bun 1.4.0's own decoding read every member. The text of a decode-failure message is now the decoder's reason (for example gzip body does not decode (no gzip header)), and the runtime no longer prints its own Decompression error: line.

Docs: new "Compressed responses" section in docs/configuration/crawler.mdx, the decode-failure example is updated, and there is a CHANGELOG entry under Unreleased. Benchmark record: benchmarks/2026-10-content-encoding-bombs.md, with a reproducible harness at benchmarks/harness/encoding-bomb.ts (server in a separate process, --root to measure another checkout).

Skills: no change needed in squirrelscan/skills. CLI usage and output are unchanged.

Verification

Peak RSS growth. The bomb server runs in its own process and the figures are min to max over the repeats. Full table: benchmarks/2026-10-content-encoding-bombs.md.

case cap before 1.3.14 after 1.3.14 before 1.4.0 after 1.4.0
page, uncompressed 1 GiB (control) 10 MiB 50 MB 46-58 MB 44-46 MB 42-47 MB
page, gzip bomb 10 MiB 2,484-2,807 MB 39-44 MB 126-137 MB 36 MB
page behind a 302 whose body is a br bomb 10 MiB 1,998-2,740 MB 1.3-2.0 MB 213-437 MB 1.9-2.1 MB
robots.txt, br bomb 512 KiB 2,620-2,733 MB 8-12 MB 659-667 MB 11-13 MB
well-known sweep, 20 chunked gzip bombs 256 KiB each 3,196-3,324 MB 67-77 MB 1,952-2,405 MB 53-62 MB

End to end, squirrel audit http://127.0.0.1:<port>/ --offline --http --max-pages 10 (fake HOME). The site's page, redirect, robots.txt and llms.txt are 1 GiB bombs. Max RSS is from /usr/bin/time -l:

  • released v0.0.108: 2,275 to 2,816 MB (163 MB on the same site without bombs)
  • this branch compiled with Bun 1.3.14: 362 to 365 MB (221 MB without)

Both reports are identical: 4 pages, score 46, same findings.

Tests. The spy tests in crawler, fetchers and audit-engine were run against the parent commit, where they fail only on the decompress assertions; their decoded-content assertions pass on both. The RSS bound was checked against the runtime's own decoding, which used 1,388 MB against the 256 MiB bound:

  • packages/utils/tests/fetch-undecoded.test.ts: decoding of gzip, x-gzip, GZIP, deflate (zlib and raw), br and zstd; bytes after a complete stream ignored (gzip with junk, zero padding, a second member and a header with FEXTRA, FNAME and FCOMMENT; br, deflate and zstd with junk); identity, unknown and stacked codings pass through; an empty body; liar and truncated bodies raise ContentDecodingError; a cancel in flight; an abort stays AbortError; 1 GiB gzip and br bombs read to a 1 MiB cap stay under 256 MiB of RSS; the native-redirect final hop arrives undecoded; Accept-Encoding survives a cross-origin hop; safeRedirectFetch sends every hop through send.
  • packages/crawler/tests/content-encoding-bombs.test.ts: a page bomb is cut at 10 MiB under 256 MiB of RSS; a 302 hop bomb is never inflated; robots and llms bombs are read to their caps. A full crawl with a global fetch spy (seed redirect, robots, llms, markdown, the well-known paths, sitemaps, pages and a redirect hop, with gzip, br, deflate, raw deflate and zstd pages) checks that every request went out with decompress: false and that every page was stored decoded.
  • packages/fetchers/src/fetch-fetcher.test.ts: three manual hops, each with decompress: false, and the page is decoded.
  • packages/audit-engine/tests/undecoded-probe-fetches.test.ts: script, resource (decoded size, plus a 1 GiB bomb counted without being held), external link (decoded 403 WAF page), cloaking and soft-404, each undecoded with decoded results.
  • apps/cli/tests/crawler/undecoded-fetches.test.ts: CLI script fetch, a 1 GiB script refused as script too large under 256 MiB, external links, and requestOnceScoped.

Local gates:

  • tsgo --noEmit in utils, crawler, fetchers, audit-engine and apps/cli
  • apps/cli format:check and lint
  • detect-secrets-hook on the changed files
  • docs [email protected] check --strict: 426 pages, all checks passed
  • about 1,000 existing tests across the touched fetch paths, in batches of 5 files: all pass. The one exception is apps/cli/tests/tools/request-deadline.test.ts > "checkReachability returns instead of hanging on a stalled body", which also times out on main on this Mac: 127.0.0.2 is not routable on macOS. It is not related to this change.
  • the new tests also pass on Bun 1.4.0

Codex review: one full pass and two delta passes. Its findings are fixed: the resource-checker fallback was still buffering the body, and the sitemap Accept-Encoding was lost on cross-origin hops. It found no blockers in the node:zlib bridge (lost wakeups, the write callbacks, backpressure, the gzip header parser). The trailing-bytes regression came from a hint in the PR review; it is fixed in a8fb476.

After merge: a private gitlink bump in squirrelscan/repo.

Checklist

  • I added or updated tests for behavioral changes.
  • I did not include secrets, customer data, or incompatible third-party material.
  • Every commit includes a DCO Signed-off-by line (git commit -s).

…te a bomb (repo#2717)

Bun's fetch inflates a Content-Encoding body in full as soon as it arrives,
read or not, so no byte cap in the crawl bounded a compression bomb: a 1 MB
gzip page that inflates to 1 GiB cost 2.5-2.8 GB, a robots.txt or a
discarded redirect body the same.

fetchUndecoded fetches with decompress: false (and the Accept-Encoding the
runtime would have sent); readBodyCapped and decodedBody decode lazily,
no further than the read's cap. Every crawl and audit fetch of a site URL
goes through it: page fetchers on every redirect hop, root probes,
sitemaps, seed resolution, scripts, assets, external links, soft-404 and
cloaking re-checks, the CLI reachability probe. Decode failures stay
decode failures; Accept-Encoding now survives a cross-origin hop.

Signed-off-by: Nik Cubrilovic <[email protected]>
@nc9
nc9 marked this pull request as ready for review October 12, 2026 06:51
@claude

claude Bot commented Oct 12, 2026

Copy link
Copy Markdown

Review of #699 (undecoded fetches and pull-based decoding). I read the diff, mainly response-body.ts and safe-fetch.ts, and grepped every fetchUndecoded call site. I did not run the tests.

The design holds up. decodingStream is pull-based, cancel propagates to the raw body, and source failures (deadline abort) are kept separate from decode failures. I found no correctness problem that should block merge.

  • (low) packages/utils/src/response-body.ts:~91: the "still encoded" tag lives in a WeakMap<Response, Coding> keyed on the response object. response.clone() or new Response(res.body, ...) drops the tag, and the consumer then silently reads compressed bytes. I grepped packages/crawler/src and packages/fetchers/src/index.ts for .text(), .json() and .clone() on these responses and found no such use today. Consider a note in the fetchUndecoded docs that callers must read bodies through decodedBody or readBodyCapped, or a lint or test guard. Otherwise a later .text() on one of these responses returns garbage with no error.
  • (low) packages/utils/src/response-body.ts:~27: FETCH_RETURNS_RAW_BODY = "Bun" in globalThis is fixed at import time. This is fine for the CLI and the containers. Tests that stub fetch or run under Node take the plain-fetch path, so the Bun-only branch is only covered when tests run under Bun. Please confirm CI runs them under Bun.
  • (low) decompressionFormat: zstd is passed to DecompressionStream. Confirm that the minimum supported Bun version accepts "zstd" and "brotli" there. An unsupported format would throw a TypeError that gets wrapped as ContentDecodingError, which would send the page into the docs(changelog): add the v0.0.92 numbers table #292 raw-refetch path instead of failing visibly.
  • (nit) fetchTolerant in packages/fetchers/src/index.ts falls back to a plain fetch(..., { decompress: false }) and does not go through fetchUndecoded. That is intentional, since the body is then read raw, but a short comment saying so would help the next reader.
  • (nit) Stacked codings such as gzip, br and unknown codings pass through undecoded. This matches Bun's behavior as the PR says, but it is worth a test, if one is not already there, that these are not accidentally decoded as the first coding.

Test coverage is good. There are new tests for the utils helper, the crawler bomb cases, the engine probes, the fetchers and the CLI, plus a benchmark harness.

#292 fallback is plain fetch (repo#2717)

Signed-off-by: Nik Cubrilovic <[email protected]>
@nc9

nc9 commented Oct 12, 2026

Copy link
Copy Markdown
Contributor Author

Triage of the review, at 83afcc9:

  • WeakMap tag / raw reads (low): fixed in the docs. fetchUndecoded now says that a body must be read only through decodedBody or readBodyCapped, and that .text(), .json(), .arrayBuffer(), a reader on .body or a clone() get the bytes still encoded. No current caller does that: codex swept every call site, and so did this review.
  • FETCH_RETURNS_RAW_BODY under CI (low): CI runs every suite with bun test on Bun 1.4.0, through .github/actions/setup-bun. No suite runs under Node, so the Bun branch is the one that gets tested.
  • "zstd" / "brotli" support (low): the CLI is compiled with Bun 1.4.0 and the cloud containers run 1.4.0. I ran the new tests on both 1.3.14 and 1.4.0, including decoding zstd and brotli through DecompressionStream, and the benchmark has a column for each version.
  • fetchTolerant comment (nit): added a note that the plain fetch(..., { decompress: false }) is deliberate, because the fallback reads the body raw.
  • Stacked and unknown codings (nit): already covered in packages/utils/tests/fetch-undecoded.test.ts. "passes stacked codings through untouched" (gzip, gzip) checks that the raw bytes come back exactly, and "reads /unknown as it arrived" does the same for an unknown coding.

@claude

claude Bot commented Oct 12, 2026

Copy link
Copy Markdown

Review of #699 (undecoded fetch + lazy decoding for #2717). I read the diff and the core helper in packages/utils/src/response-body.ts closely. I did not run the test suite or the benchmark harness, and I only skimmed the call-site changes.

The approach is sound. Decoding is pull-based and the redirect hops go through send. Cancellation propagates to the raw stream. The error split (ContentDecodingError against a passed-through source failure) keeps the deadline AbortError intact. Test coverage is broad: utils, crawler, audit-engine, fetchers and CLI.

  • (medium) packages/utils/src/response-body.ts fetchUndecoded: the hazard is a silent footgun. The response is still encoded, and .text(), .json(), .clone() or .body on it returns compressed bytes with no error. The doc comment warns about this, but nothing enforces it. Consider a lint or test guard that fails if a fetchUndecoded or safeFetchWithDeadline result is read any other way. safeFetchWithDeadline now feeds robots, sitemaps, llms, rsl, markdown, well-known and agent-access. I grepped those crawler files for .text(), .json() and .arrayBuffer() and found none. Future callers are the risk.
  • (medium) packages/utils/src/response-body.ts FETCH_RETURNS_RAW_BODY = "Bun" in globalThis: this detects the runtime, not whether decompress: false is honored. If a future Bun version changes or ignores the option, the body arrives already decoded while Content-Encoding is still set. stillEncoded would then make decodingStream try to decode plain data and throw ContentDecodingError on every compressed page. A cheap self-check or a fallback is worth considering. A fallback could sniff the gzip magic bytes (1f 8b), or retry once with plain fetch on a decode error at the first chunk. The existing docs(changelog): add the v0.0.92 numbers table #292 raw refetch only partly covers this.
  • (low) packages/utils/src/response-body.ts CODINGS: the lookup uses the whole header value. The code comment says stacked codings pass through, matching Bun. Content-Encoding: gzip, gzip therefore skips the cap protection, so a double-encoded bomb is still inflated by the runtime. Bun inflates only single codings, so this may not be reachable. Please confirm, ideally with a test.
  • (low) decodingStream: a decoded stream that hits trailing garbage after a valid gzip member, or a truncated body, throws ContentDecodingError. Bun's own decoder may be more lenient with trailing bytes. This is a behaviour difference that could turn previously readable pages into CrawlError.decode. The regression tests do not obviously cover it.
  • (low) fetchUndecoded sends Accept-Encoding: gzip, deflate, br, zstd unless the caller set one. If a caller sets identity or a narrower list, that is respected. That is fine. A short test that an explicit header is preserved would document it.
  • (nit) isDecompressionError is re-exported from fetcher.ts as export { isDecompressionError }. That is fine for compatibility. Consider a deprecation note if the old import path should eventually go away.
  • (nit) The as RequestInit cast on decompress: false is unavoidable, but a small typed BunRequestInit alias would make the intent clearer.

No security or performance problems found beyond the above. This is a strong mitigation for a real memory-exhaustion vector. Nothing here blocks the merge, but the decompress: false assumption and the unguarded raw-body reads deserve a look.

…re ignored (repo#2717)

Bun 1.4's DecompressionStream rejects bytes after a complete stream (gzip,
br, deflate and zstd with appended junk, gzip with zero padding) and drops
the output it still held, where the runtime's own decoding read those
pages. Decoding now runs through node:zlib, whose decoders ignore trailing
bytes; gzip is read past its header as raw deflate to the end of its first
member, as browsers read it. Still lazy and bounded on Bun 1.3.14 and 1.4.0.

Signed-off-by: Nik Cubrilovic <[email protected]>
@nc9

nc9 commented Oct 12, 2026

Copy link
Copy Markdown
Contributor Author

Triage of the second review. The trailing-bytes point was a real regression, fixed in a8fb476:

  • Trailing junk (low → fixed): confirmed on Bun 1.4.0. DecompressionStream rejected bytes after a complete stream and dropped the output it still held (65,536 of 70,034 bytes delivered). That covered gzip with junk or zero padding, and br, deflate and zstd with junk, all of which the runtime's own decoding read. Decoding now runs through node:zlib, which ignores trailing bytes. gzip is read past its header as raw deflate, up to the end of its first member, as browsers read it. New tests cover each case, plus a gzip header with FEXTRA, FNAME and FCOMMENT. Still bounded on 1.3.14 and 1.4.0 (benchmark record updated).
  • gzip, gzip stacked (low): with decompress: false the runtime decodes nothing, so a stacked coding arrives raw and readBodyCapped caps the raw bytes. No bomb path. Covered by "passes stacked codings through untouched".
  • Runtime detection vs decompress: false being honoured (medium): the Bun version is pinned exactly (setup-bun 1.4.0, worker-agent Dockerfile BUN_VERSION=1.4.0), and every bump goes through CI. These tests decode every coding through fetchUndecoded, so a Bun that stopped honouring the option would fail them on the bump PR. I'd rather fail loudly there than add a runtime sniff that hides it.
  • Unguarded raw reads (medium): documented on fetchUndecoded, and every current caller was audited (codex plus this review). The crawl-wide spy test also checks that every page arrives decoded, so a raw read on the main paths fails a test.
  • Explicit Accept-Encoding preserved (low): covered by "keeps the caller's own Accept-Encoding", and now also across a cross-origin hop.
  • Nits (re-export note, a BunRequestInit alias): leaving as is.

@claude

claude Bot commented Oct 12, 2026

Copy link
Copy Markdown

Review of #699: undecoded fetches for Content-Encoding bombs

I read the diff and the existing packages/utils/src/response-body.ts helpers it builds on. I did not run the tests or the benchmark harness. The approach is sound: fetchUndecoded is applied at each call site, and decodedBody and readBodyCapped bound the inflation. Findings:

  • (medium) apps/cli/src/crawl/sitemaps.ts:164: this site-controlled fetch still uses plain fetch() with an unbounded response.text(). The runtime inflates the body in full here, so a gzip-bomb sitemap still exhausts memory in the CLI crawl preamble. The CHANGELOG says "every request the crawl and the audit send to the site", and the sitemap fetch is not covered. Either switch it to fetchUndecoded plus readBodyCapped (with a sitemap-sized cap), or narrow the changelog wording and open a follow-up.

  • (medium) packages/audit-engine/src/resource-checker.ts (the sizeBytes === null && getResponse.ok branch): the new loop never holds the body, so memory is bounded. It still inflates the entire body to count bytes, so a 1 GiB bomb costs seconds of CPU per resource. Only the request deadline limits that, and with many concurrent resources it could stall the audit. Consider a decoded-size ceiling, after which it records "larger than N" and cancels the reader. Also confirm the reader is cancelled when the loop throws on abort, since there is no try/finally { reader.cancel() }.

  • (low) packages/audit-engine/src/resource-checker.ts: the loop's reader ? await reader.read() : { done: true as const } is awkward, because it re-checks reader on every iteration. An early if (reader) around the loop would read more clearly.

  • (low) fetchUndecoded in packages/utils/src/response-body.ts is a silent footgun. A caller that fetches undecoded and then reads .text(), .json() or .clone() gets raw compressed bytes with no error, as its own doc comment says. The tests cover the intended call sites, but a lint rule or a Response wrapper that throws on non-decodedBody access would keep future call sites from regressing. apps/cli/src/tools/request.ts requestOnceScoped now hands every use callback an undecoded response, so each existing caller needs auditing. I did not check them all.

  • (nit) packages/audit-engine/src/cloaking-probe.ts and soft404-confirm.ts now have long import lines. Wrap them to match the surrounding formatting.

  • (nit) fetcher.ts re-exports isDecompressionError from response-body to preserve the old public name. That is fine, but a short note on when to drop the shim would help.

Tests: coverage is good. There are tests for undecoded fetches in the CLI, the audit-engine and the crawler, plus a memory-bound check on a 1 GiB bomb. The RSS-delta assertion (< 256 MiB, sampled every 1 ms) is likely to be flaky on loaded CI runners. Asserting that decompress: false was passed, which the tests already do, carries most of the value.

Security: this is a net improvement, and I found no new issues. The remaining gap is the sitemap fetch above.

Two of the findings are medium and none is blocking.

@nc9

nc9 commented Oct 12, 2026

Copy link
Copy Markdown
Contributor Author

Triage of the third review, at a8fb476. No code change in this round.

  • apps/cli/src/crawl/sitemaps.ts (medium): this module is unreachable. No file in apps/cli/src imports src/crawl/sitemaps.ts, robots.ts or index.ts. Only src/crawl/hybrid-fetcher.ts is imported, from controllers/audit.ts. Audits discover sitemaps through packages/crawler/src/sitemaps.ts, which reads undecoded within 50 MB (fix(crawler): read gzip sitemaps within 50 MB, a guessed path that answers HTML is no sitemap (#662, #670) #686, and every hop since this PR). It is not in the compiled binary, so the CHANGELOG wording holds. Filed Remove the CLI's unreachable legacy crawl modules (apps/cli/src/crawl/sitemaps, robots, index) #700 to delete the dead modules so they cannot be wired back in.
  • Resource checker counts the whole decoded body (medium): that branch already inflated the whole body before this PR (arrayBuffer()), so the CPU cost is unchanged. What changed is memory: 1 GiB held before, a stream counted now (test: "a body that inflates to 1 GiB is counted, never held"). The request deadline still bounds the time. A decoded-size ceiling would change what sizeBytes reports for large chunked assets, so I'd keep it out of this fix. On an abort or decode error the read rejects, and the decoding stream cancels the raw body itself before erroring.
  • Loop style (low): leaving as is.
  • Raw-read footgun (low): documented on fetchUndecoded. requestOnceScoped has one caller, utils/reachability.ts, which reads through decodedBody. That is covered by the "reachability probe's request is undecoded" test.
  • Import line length / shim note (nits): the two imports are under 100 columns, and packages/* are not format-checked. Leaving as is.
  • RSS tests (flakiness): the bombs are built before the baseline. The bounds are 4 to 10 times the growth measured on both Bun versions, while the unfixed shapes measured 1.3 to 3 GB, so I'm keeping them.

@nc9
nc9 merged commit 78c512f into main Oct 12, 2026
15 checks passed
@nc9
nc9 deleted the fix/content-encoding-bombs-2717 branch October 12, 2026 07:36
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