Repository navigation
Fix HTMLRewriter use-after-free when handler rejects during end() - #30196
Conversation
When HTMLRewriter.transform() is called with a string or ArrayBuffer and a document/element handler returns a rejected promise for the final text chunk (emitted from lol-html's end()), the synchronous error path in BufferOutputSink.runOutputSink called response.finalize() directly on the output Response. That Response is owned by its JS wrapper cell (created via sink.response.toJS()), so destroying it left the wrapper's m_ctx dangling. When the wrapper was later garbage collected, its destructor invoked Response.finalize() again on the freed memory, causing a use-after-free (and a flaky SIGSEGV in release builds). The write() error path already handled this correctly by simply returning the error and letting the JS wrapper own the Response lifetime. Make the end() error path do the same.
|
Updated 1:19 PM PT - May 3rd, 2026
❌ @robobun, your commit fcc571c has 6 failures in
🧪 To try this PR locally: bunx bun-pr 30196That installs a local version of the PR into your bun-30196 --bun |
WalkthroughThe PR modifies ChangesHTMLRewriter Response Finalization Fix
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Review rate limit: 4/5 reviews remaining, refill in 12 minutes. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@test/js/workerd/html-rewriter.test.js`:
- Around line 496-524: Change the tests to assert the exact rejection message
instead of a bare toThrow: for both loops that create an HTMLRewriter, register
the document text handler that returns Promise.reject(new Error("boom")), and
replace expect(() => rewriter.transform(...)).toThrow() with an assertion that
verifies the thrown error message contains "boom" (e.g., expect(() =>
rewriter.transform(...)).toThrowError("boom") or equivalent) for the
rewriter.transform calls (both the ArrayBuffer/Uint8Array.buffer and the string
"abc" cases) so the test specifically confirms the handler's rejected promise is
what surfaces.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 8b43e815-5148-4c24-aea5-e1b0598c6f3a
📒 Files selected for processing (2)
src/bun.js/api/html_rewriter.zigtest/js/workerd/html-rewriter.test.js
| it("does not crash when a document text handler rejects during end() on an ArrayBuffer input", () => { | ||
| for (let i = 0; i < 50; i++) { | ||
| const rewriter = new HTMLRewriter(); | ||
| rewriter.onDocument({ | ||
| text(chunk) { | ||
| if (chunk.lastInTextNode) { | ||
| return Promise.reject(new Error("boom")); | ||
| } | ||
| }, | ||
| }); | ||
| expect(() => rewriter.transform(new Uint8Array([97, 98, 99]).buffer)).toThrow(); | ||
| Bun.gc(true); | ||
| } | ||
| }); | ||
|
|
||
| it("does not crash when a document text handler rejects during end() on a string input", () => { | ||
| for (let i = 0; i < 50; i++) { | ||
| const rewriter = new HTMLRewriter(); | ||
| rewriter.onDocument({ | ||
| text(chunk) { | ||
| if (chunk.lastInTextNode) { | ||
| return Promise.reject(new Error("boom")); | ||
| } | ||
| }, | ||
| }); | ||
| expect(() => rewriter.transform("abc")).toThrow(); | ||
| Bun.gc(true); | ||
| } | ||
| }); |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial | ⚡ Quick win
Assert the rejected error message, not just that something throws.
A bare toThrow() would still pass if transform() started failing for the wrong synchronous reason, so these regressions would stop proving that the rejected handler promise is what surfaced here.
♻️ Suggested tightening
- expect(() => rewriter.transform(new Uint8Array([97, 98, 99]).buffer)).toThrow();
+ expect(() => rewriter.transform(new Uint8Array([97, 98, 99]).buffer)).toThrow("boom");
@@
- expect(() => rewriter.transform("abc")).toThrow();
+ expect(() => rewriter.transform("abc")).toThrow("boom");📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| it("does not crash when a document text handler rejects during end() on an ArrayBuffer input", () => { | |
| for (let i = 0; i < 50; i++) { | |
| const rewriter = new HTMLRewriter(); | |
| rewriter.onDocument({ | |
| text(chunk) { | |
| if (chunk.lastInTextNode) { | |
| return Promise.reject(new Error("boom")); | |
| } | |
| }, | |
| }); | |
| expect(() => rewriter.transform(new Uint8Array([97, 98, 99]).buffer)).toThrow(); | |
| Bun.gc(true); | |
| } | |
| }); | |
| it("does not crash when a document text handler rejects during end() on a string input", () => { | |
| for (let i = 0; i < 50; i++) { | |
| const rewriter = new HTMLRewriter(); | |
| rewriter.onDocument({ | |
| text(chunk) { | |
| if (chunk.lastInTextNode) { | |
| return Promise.reject(new Error("boom")); | |
| } | |
| }, | |
| }); | |
| expect(() => rewriter.transform("abc")).toThrow(); | |
| Bun.gc(true); | |
| } | |
| }); | |
| it("does not crash when a document text handler rejects during end() on an ArrayBuffer input", () => { | |
| for (let i = 0; i < 50; i++) { | |
| const rewriter = new HTMLRewriter(); | |
| rewriter.onDocument({ | |
| text(chunk) { | |
| if (chunk.lastInTextNode) { | |
| return Promise.reject(new Error("boom")); | |
| } | |
| }, | |
| }); | |
| expect(() => rewriter.transform(new Uint8Array([97, 98, 99]).buffer)).toThrow("boom"); | |
| Bun.gc(true); | |
| } | |
| }); | |
| it("does not crash when a document text handler rejects during end() on a string input", () => { | |
| for (let i = 0; i < 50; i++) { | |
| const rewriter = new HTMLRewriter(); | |
| rewriter.onDocument({ | |
| text(chunk) { | |
| if (chunk.lastInTextNode) { | |
| return Promise.reject(new Error("boom")); | |
| } | |
| }, | |
| }); | |
| expect(() => rewriter.transform("abc")).toThrow("boom"); | |
| Bun.gc(true); | |
| } | |
| }); |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@test/js/workerd/html-rewriter.test.js` around lines 496 - 524, Change the
tests to assert the exact rejection message instead of a bare toThrow: for both
loops that create an HTMLRewriter, register the document text handler that
returns Promise.reject(new Error("boom")), and replace expect(() =>
rewriter.transform(...)).toThrow() with an assertion that verifies the thrown
error message contains "boom" (e.g., expect(() =>
rewriter.transform(...)).toThrowError("boom") or equivalent) for the
rewriter.transform calls (both the ArrayBuffer/Uint8Array.buffer and the string
"abc" cases) so the test specifically confirms the handler's rejected promise is
what surfaces.
|
This PR may be a duplicate of:
🤖 Generated with Claude Code |
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
test/js/workerd/html-rewriter-end-error.test.ts (1)
1-39: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick winMove these new regression cases into the existing HTMLRewriter test file.
Line 1 introduces a new standalone
.test.tsfile, but repo guidance fortest/**/*.test.tsrequires extending the existing test file for the changed area instead of creating a separate one.As per coding guidelines: "
test/**/*.test.ts: Add new tests to existing test files for the code being changed, not in new separate files."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/js/workerd/html-rewriter-end-error.test.ts` around lines 1 - 39, The new regression tests for HTMLRewriter (the two it blocks titled "does not crash when a document text handler rejects during end() on an ArrayBuffer input" and "...on a string input") were added as a standalone test file; move these two it(...) blocks and the import line (describe, expect, it from "bun:test") into the existing HTMLRewriter test file that already covers HTMLRewriter behavior, remove the newly created html-rewriter-end-error.test.ts file, and ensure you preserve the HTMLRewriter usage, the onDocument text handler logic, the expect(...toThrow()) assertions, and the Bun.gc(true) calls so the tests run in the original test suite location.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@test/js/workerd/html-rewriter-end-error.test.ts`:
- Around line 9-37: Replace the two duplicated it(...) blocks with a
parameterized describe.each over the two input variants (ArrayBuffer and string)
so the same test body runs for each input; create a table like [{name:
"ArrayBuffer", input: new Uint8Array([97,98,99]).buffer}, {name: "string",
input: "abc"}], then inside describe.each use a single it that constructs new
HTMLRewriter(), attaches the document.text handler (checking
chunk.lastInTextNode and returning Promise.reject(new Error("boom"))), calls
rewriter.transform(input) and asserts expect(() => ...).toThrow(), and still
call Bun.gc(true) in the loop; keep references to HTMLRewriter,
rewriter.transform, and chunk.lastInTextNode so the test logic is identical.
---
Outside diff comments:
In `@test/js/workerd/html-rewriter-end-error.test.ts`:
- Around line 1-39: The new regression tests for HTMLRewriter (the two it blocks
titled "does not crash when a document text handler rejects during end() on an
ArrayBuffer input" and "...on a string input") were added as a standalone test
file; move these two it(...) blocks and the import line (describe, expect, it
from "bun:test") into the existing HTMLRewriter test file that already covers
HTMLRewriter behavior, remove the newly created html-rewriter-end-error.test.ts
file, and ensure you preserve the HTMLRewriter usage, the onDocument text
handler logic, the expect(...toThrow()) assertions, and the Bun.gc(true) calls
so the tests run in the original test suite location.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 5e13184c-aa83-48e4-b47c-2b1c6d6319e7
📒 Files selected for processing (1)
test/js/workerd/html-rewriter-end-error.test.ts
| it("does not crash when a document text handler rejects during end() on an ArrayBuffer input", () => { | ||
| for (let i = 0; i < 50; i++) { | ||
| const rewriter = new HTMLRewriter(); | ||
| rewriter.onDocument({ | ||
| text(chunk) { | ||
| if (chunk.lastInTextNode) { | ||
| return Promise.reject(new Error("boom")); | ||
| } | ||
| }, | ||
| }); | ||
| expect(() => rewriter.transform(new Uint8Array([97, 98, 99]).buffer)).toThrow(); | ||
| Bun.gc(true); | ||
| } | ||
| }); | ||
|
|
||
| it("does not crash when a document text handler rejects during end() on a string input", () => { | ||
| for (let i = 0; i < 50; i++) { | ||
| const rewriter = new HTMLRewriter(); | ||
| rewriter.onDocument({ | ||
| text(chunk) { | ||
| if (chunk.lastInTextNode) { | ||
| return Promise.reject(new Error("boom")); | ||
| } | ||
| }, | ||
| }); | ||
| expect(() => rewriter.transform("abc")).toThrow(); | ||
| Bun.gc(true); | ||
| } | ||
| }); |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
Parameterize the duplicated test bodies with describe.each().
These two it(...) blocks are structurally identical except for input shape. Consolidating them into a parameterized suite will reduce duplication and align with repo test style.
Refactor sketch
describe("HTMLRewriter", () => {
- it("does not crash when a document text handler rejects during end() on an ArrayBuffer input", () => {
- for (let i = 0; i < 50; i++) {
- const rewriter = new HTMLRewriter();
- rewriter.onDocument({
- text(chunk) {
- if (chunk.lastInTextNode) {
- return Promise.reject(new Error("boom"));
- }
- },
- });
- expect(() => rewriter.transform(new Uint8Array([97, 98, 99]).buffer)).toThrow();
- Bun.gc(true);
- }
- });
-
- it("does not crash when a document text handler rejects during end() on a string input", () => {
+ describe.each([
+ ["ArrayBuffer input", () => new Uint8Array([97, 98, 99]).buffer],
+ ["string input", () => "abc"],
+ ])("does not crash when a document text handler rejects during end() on %s", (_name, makeInput) => {
for (let i = 0; i < 50; i++) {
const rewriter = new HTMLRewriter();
rewriter.onDocument({
text(chunk) {
if (chunk.lastInTextNode) {
return Promise.reject(new Error("boom"));
}
},
});
- expect(() => rewriter.transform("abc")).toThrow();
+ expect(() => rewriter.transform(makeInput())).toThrow();
Bun.gc(true);
}
});
});As per coding guidelines: "test/**/*.test.{ts,js,jsx,tsx,mjs,cjs}: Use describe.each() for parameterized tests."
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| it("does not crash when a document text handler rejects during end() on an ArrayBuffer input", () => { | |
| for (let i = 0; i < 50; i++) { | |
| const rewriter = new HTMLRewriter(); | |
| rewriter.onDocument({ | |
| text(chunk) { | |
| if (chunk.lastInTextNode) { | |
| return Promise.reject(new Error("boom")); | |
| } | |
| }, | |
| }); | |
| expect(() => rewriter.transform(new Uint8Array([97, 98, 99]).buffer)).toThrow(); | |
| Bun.gc(true); | |
| } | |
| }); | |
| it("does not crash when a document text handler rejects during end() on a string input", () => { | |
| for (let i = 0; i < 50; i++) { | |
| const rewriter = new HTMLRewriter(); | |
| rewriter.onDocument({ | |
| text(chunk) { | |
| if (chunk.lastInTextNode) { | |
| return Promise.reject(new Error("boom")); | |
| } | |
| }, | |
| }); | |
| expect(() => rewriter.transform("abc")).toThrow(); | |
| Bun.gc(true); | |
| } | |
| }); | |
| describe.each([ | |
| ["ArrayBuffer input", () => new Uint8Array([97, 98, 99]).buffer], | |
| ["string input", () => "abc"], | |
| ])("does not crash when a document text handler rejects during end() on %s", (_name, makeInput) => { | |
| for (let i = 0; i < 50; i++) { | |
| const rewriter = new HTMLRewriter(); | |
| rewriter.onDocument({ | |
| text(chunk) { | |
| if (chunk.lastInTextNode) { | |
| return Promise.reject(new Error("boom")); | |
| } | |
| }, | |
| }); | |
| expect(() => rewriter.transform(makeInput())).toThrow(); | |
| Bun.gc(true); | |
| } | |
| }); |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@test/js/workerd/html-rewriter-end-error.test.ts` around lines 9 - 37, Replace
the two duplicated it(...) blocks with a parameterized describe.each over the
two input variants (ArrayBuffer and string) so the same test body runs for each
input; create a table like [{name: "ArrayBuffer", input: new
Uint8Array([97,98,99]).buffer}, {name: "string", input: "abc"}], then inside
describe.each use a single it that constructs new HTMLRewriter(), attaches the
document.text handler (checking chunk.lastInTextNode and returning
Promise.reject(new Error("boom"))), calls rewriter.transform(input) and asserts
expect(() => ...).toThrow(), and still call Bun.gc(true) in the loop; keep
references to HTMLRewriter, rewriter.transform, and chunk.lastInTextNode so the
test logic is identical.
| import { describe, expect, it } from "bun:test"; | ||
|
|
||
| describe("HTMLRewriter", () => { |
There was a problem hiding this comment.
🟡 Per the repo conventions in CLAUDE.md and test/CLAUDE.md ("add your test to the existing test file for the code you're changing. Do not create a new file"), these two regression tests should live in test/js/workerd/html-rewriter.test.js rather than a new standalone file. They were originally added there in b37208c and then moved out in fcc571c — note the PR description still says they were added to html-rewriter.test.js.
Extended reasoning...
What's the issue
Commit fcc571c ("Move regression tests to a standalone file") relocated the two new regression tests out of test/js/workerd/html-rewriter.test.js and into a brand-new file, test/js/workerd/html-rewriter-end-error.test.ts. This contradicts the repo's documented test-placement convention.
What the conventions say
Both guidance files are explicit:
CLAUDE.md(root, line ~55): "Default: add your test to the existing test file for the code you're changing. Do not create a new file."test/CLAUDE.md(line ~152): repeats the same rule verbatim.
test/js/workerd/html-rewriter.test.js already exists in the same directory and is the canonical suite for HTMLRewriter. The two tests added here exercise HTMLRewriter.transform() behavior and are a natural fit alongside the existing cases in that file.
Step-by-step
- In commit b37208c the tests were added inside
test/js/workerd/html-rewriter.test.js(the CodeRabbit inline comment on this PR still references lines 496–524 of that file, and the PR description still says "Added regression tests in test/js/workerd/html-rewriter.test.js"). - Commit fcc571c then created
test/js/workerd/html-rewriter-end-error.test.tsand moved the tests there. - The result is a new test file whose only contents are two cases that belong in the existing HTMLRewriter suite — exactly what both CLAUDE.md files say not to do.
Why it matters / impact
This is purely organizational, not a correctness issue — the tests will run fine either way. But keeping HTMLRewriter regressions in one file makes them easier to find, avoids fragmenting the suite, and keeps the PR consistent with its own description. There is some precedent for a separate file (html-rewriter-leak.test.ts), but the explicit written guidance still defaults to colocating with the existing file, and nothing about these tests (no special isolation, no long runtime) motivates a separate file.
Suggested fix
Move the two it(...) blocks (and their explanatory comment) back into the existing describe("HTMLRewriter", ...) block in test/js/workerd/html-rewriter.test.js, and delete test/js/workerd/html-rewriter-end-error.test.ts. That also brings the tree back in line with what the PR description claims.
|
The CI failures in build 50654 are all pre-existing flakes unrelated to this change:
None involve HTMLRewriter. The new |
Jarred-Sumner
left a comment
There was a problem hiding this comment.
How is this not a memory leak? When does the Response get finalized? Especilaly in the error path.
The In the sync error path (
This is identical to how the The bug with the old code was that Verified empirically (release build, 50k iterations each,
Both plateau after allocator warmup; Response instances never accumulate. |
…en-sh#30196) ## What does this PR do? Fixes a use-after-free in `HTMLRewriter.transform()` that caused flaky SIGSEGV crashes found by fuzzing. When transforming a string or ArrayBuffer, the body is buffered synchronously and fed to lol-html via `write()` followed by `end()`. If a document/element handler returns a rejected promise for the final `lastInTextNode` chunk (emitted from `end()`), the `end() catch` branch in `BufferOutputSink.runOutputSink` would call `response.finalize()` directly on the output `Response`. That `Response` is already owned by its JS wrapper cell (created earlier in `init()` via `sink.response.toJS()`), so destroying it in-place left the wrapper's `m_ctx` pointing at freed memory. When GC later swept the wrapper, its destructor invoked `Response.finalize()` again on that freed pointer: ``` AddressSanitizer: use-after-poison #0 bun.js.bindings.JSRef.JSRef.deinit src/bun.js/bindings/JSRef.zig:188 oven-sh#1 bun.js.bindings.JSRef.JSRef.finalize src/bun.js/bindings/JSRef.zig:200 oven-sh#2 bun.js.webcore.Response.finalize src/bun.js/webcore/Response.zig:474 oven-sh#3 ResponseClass__finalize codegen/ZigGeneratedClasses.zig:17250 oven-sh#4 WebCore::JSResponse::~JSResponse() codegen/ZigGeneratedClasses.cpp:54979 ``` The `write()` error path (just above it) already handled this correctly by returning the error and letting the JS wrapper own the Response lifetime. This PR makes the `end()` error path do the same — drop the manual `response.finalize()` and `sink.response = undefined`. ## How did you verify your code works? Minimal repro that reliably triggers the ASAN error before the fix and passes cleanly after: ```js const rewriter = new HTMLRewriter(); rewriter.onDocument({ text(chunk) { if (chunk.lastInTextNode) { return Promise.reject(new Error("boom")); } }, }); try { rewriter.transform(new Uint8Array([97, 98, 99]).buffer); } catch (e) {} Bun.gc(true); ``` Added regression tests in `test/js/workerd/html-rewriter.test.js` covering both ArrayBuffer and string inputs. All existing HTMLRewriter tests pass. --------- Co-authored-by: robobun <robobun@users.noreply.github.com>
What does this PR do?
Fixes a use-after-free in
HTMLRewriter.transform()that caused flaky SIGSEGV crashes found by fuzzing.When transforming a string or ArrayBuffer, the body is buffered synchronously and fed to lol-html via
write()followed byend(). If a document/element handler returns a rejected promise for the finallastInTextNodechunk (emitted fromend()), theend() catchbranch inBufferOutputSink.runOutputSinkwould callresponse.finalize()directly on the outputResponse.That
Responseis already owned by its JS wrapper cell (created earlier ininit()viasink.response.toJS()), so destroying it in-place left the wrapper'sm_ctxpointing at freed memory. When GC later swept the wrapper, its destructor invokedResponse.finalize()again on that freed pointer:The
write()error path (just above it) already handled this correctly by returning the error and letting the JS wrapper own the Response lifetime. This PR makes theend()error path do the same — drop the manualresponse.finalize()andsink.response = undefined.How did you verify your code works?
Minimal repro that reliably triggers the ASAN error before the fix and passes cleanly after:
Added regression tests in
test/js/workerd/html-rewriter.test.jscovering both ArrayBuffer and string inputs. All existing HTMLRewriter tests pass.