Skip to content

Fix HTMLRewriter use-after-free when handler rejects during end() - #30196

Merged
Jarred-Sumner merged 3 commits into
mainfrom
farm/7c4b72b5/fix-htmlrewriter-end-uaf
May 3, 2026
Merged

Jarred-Sumner merged 3 commits into
mainfrom
farm/7c4b72b5/fix-htmlrewriter-end-uaf

Conversation

@robobun

@robobun robobun commented May 3, 2026

Copy link
Copy Markdown
Collaborator

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
    #1 bun.js.bindings.JSRef.JSRef.finalize      src/bun.js/bindings/JSRef.zig:200
    #2 bun.js.webcore.Response.finalize          src/bun.js/webcore/Response.zig:474
    #3 ResponseClass__finalize                   codegen/ZigGeneratedClasses.zig:17250
    #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:

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.

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.
@github-actions github-actions Bot added the claude label May 3, 2026
@robobun

robobun commented May 3, 2026 •

Copy link
Copy Markdown
Collaborator Author

@coderabbitai

coderabbitai Bot commented May 3, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

The PR modifies BufferOutputSink.runOutputSink to use an immutable response binding and removes premature finalization and clearing logic in the synchronous completion path. A regression test suite is added to validate that repeated transform calls with end-phase rejections do not cause crashes.

Changes

HTMLRewriter Response Finalization Fix

Layer / File(s) Summary
Core Implementation
src/bun.js/api/html_rewriter.zig
Changed response binding from var to const and removed the sync-path cleanup that finalized and cleared sink.response, allowing the response to persist beyond immediate synchronous completion.
Regression Tests
test/js/workerd/html-rewriter-end-error.test.ts
Added two test cases (ArrayBuffer and string inputs) that repeatedly call transform with an onDocument.text handler rejecting during the end phase, followed by GC to ensure no crash occurs.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main fix: resolving a use-after-free bug in HTMLRewriter when a handler rejects during the end() phase.
Description check ✅ Passed The PR description includes both required sections with comprehensive technical detail. It explains what the PR does (fixes the use-after-free with stack trace and root cause analysis) and how it was verified (minimal repro and regression tests).
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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 @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between d484fd6 and b37208c.

📒 Files selected for processing (2)
  • src/bun.js/api/html_rewriter.zig
  • test/js/workerd/html-rewriter.test.js

Comment thread test/js/workerd/html-rewriter.test.js Outdated
Comment on lines +496 to +524
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);
}
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 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.

Suggested change
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.

@github-actions

github-actions Bot commented May 3, 2026

Copy link
Copy Markdown
Contributor

This PR may be a duplicate of:

  1. Fix use-after-free when HTMLRewriter document end handler throws #29466 - Fixes the same use-after-free in BufferOutputSink.runOutputSink by removing the same response.finalize() call from the end() catch path in html_rewriter.zig

🤖 Generated with Claude Code

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 win

Move these new regression cases into the existing HTMLRewriter test file.

Line 1 introduces a new standalone .test.ts file, but repo guidance for test/**/*.test.ts requires 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

📥 Commits

Reviewing files that changed from the base of the PR and between b37208c and fcc571c.

📒 Files selected for processing (1)
  • test/js/workerd/html-rewriter-end-error.test.ts

Comment on lines +9 to +37
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);
}
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ 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.

Suggested change
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.

Comment on lines +1 to +3
import { describe, expect, it } from "bun:test";

describe("HTMLRewriter", () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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

  1. 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").
  2. Commit fcc571c then created test/js/workerd/html-rewriter-end-error.test.ts and moved the tests there.
  3. 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.

@robobun

robobun commented May 3, 2026 •

Copy link
Copy Markdown
Collaborator Author

The CI failures in build 50654 are all pre-existing flakes unrelated to this change:

Test Platform Also failing on
test/js/web/fetch/fetch-http2-client.test.ts debian-asan builds 50649, 50637, 50636, 50634, 50632, 50623
test/js/bun/s3/s3-storage-class.test.ts darwin builds 50649, 50634
test/js/bun/test/parallel/test-http-should-emit-close-when-connection-is-aborted.ts — builds 50649, 50637, 50634
test/bake/dev-and-prod.test.ts windows bake dev server timing
test/cli/hot/hot.test.ts windows hot reload timing
test/cli/install/bun-upgrade.test.ts — network

None involve HTMLRewriter. The new html-rewriter-end-error.test.ts and the existing html-rewriter.test.js both pass on all platforms.

@Jarred-Sumner Jarred-Sumner left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How is this not a memory leak? When does the Response get finalized? Especilaly in the error path.

@robobun

robobun commented May 3, 2026

Copy link
Copy Markdown
Collaborator Author

How is this not a memory leak? When does the Response get finalized? Especially in the error path.

The Response is owned by its JS wrapper cell, which is created at line 489 (sink.response.toJS(sink.global)) and kept alive by a Strong in sink.response_value. The Response's ref_count is 1 at that point and the wrapper's m_ctx holds that single reference.

In the sync error path (end() fails):

  1. runOutputSink returns the error JSValue
  2. onFinishedBuffering stores it in sink_error and deref()s the sink (2→1)
  3. init() returns the error; its defer sink.deref() drops the sink to 0 → BufferOutputSink.deinit()
  4. deinit() calls this.response_value.deinit(), releasing the Strong on the JS wrapper
  5. transform_ sees toError() and throws
  6. The JS wrapper is now unreachable; on the next GC, JSResponse::~JSResponse() → ResponseClass__finalize(m_ctx) → Response.finalize() → unref() (1→0) → destroy()

This is identical to how the write() error branch right above it (lines 578–585) has always worked — that branch has never called response.finalize() either, and relies on the same JS-wrapper ownership.

The bug with the old code was that response.finalize() dropped ref_count to 0 and freed the struct while the JS wrapper's m_ctx still pointed at it, so GC later called Response.finalize() on freed memory.

Verified empirically (release build, 50k iterations each, Bun.gc(true) between rounds):

path Response count RSS after 50k iters
end() error (this fix) stays at 1 96.5 MB
write() error (pre-existing, unchanged) stays at 1 95.5 MB

Both plateau after allocator warmup; Response instances never accumulate.

@Jarred-Sumner
Jarred-Sumner merged commit 0561f87 into main May 3, 2026
74 of 77 checks passed
@Jarred-Sumner
Jarred-Sumner deleted the farm/7c4b72b5/fix-htmlrewriter-end-uaf branch May 3, 2026 23:41
xhjkl pushed a commit to xhjkl/bun that referenced this pull request May 14, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants