Skip to content

Fix use-after-free when HTMLRewriter document end handler throws - #29466

Closed
robobun wants to merge 1 commit into
mainfrom
farm/14778d54/htmlrewriter-end-uaf
Closed

robobun wants to merge 1 commit into
mainfrom
farm/14778d54/htmlrewriter-end-uaf

Conversation

@robobun

@robobun robobun commented Apr 18, 2026

Copy link
Copy Markdown
Collaborator

What does this PR do?

Fixes a use-after-free in HTMLRewriter found by Fuzzilli.

When a document end handler throws synchronously during transform(), BufferOutputSink.runOutputSink was calling response.finalize() on the output Response. However, by the time runOutputSink runs, that Response has already been wrapped in a JS object via toJS() (in BufferOutputSink.init), so its single ref is owned by the JS wrapper. Calling finalize() here destroyed the native Response while the JS wrapper still pointed at it; the next GC would invoke JSResponse::~JSResponse → Response.finalize() on freed memory.

The adjacent write() error path already handled this correctly (it doesn't finalize). This change makes the end() error path match.

Repro

const rewriter = new HTMLRewriter();
rewriter.onDocument({ end() { throw new Error("boom"); } });
try { rewriter.transform(""); } catch {}
Bun.gc(true);

Before: ASAN use-after-poison in JSRef.deinit → Response.finalize.
After: throws Error: boom cleanly.

How did you verify your code works?

  • Verified the Fuzzilli crash script no longer crashes under ASAN
  • Added regression tests for onDocument({ end }) throwing with both Response and string input
  • Ran the full html-rewriter.test.js suite (43 pass, 2 todo, 0 fail)
  • Ran related regression tests (htmlrewriter-additional-bugs, 19219, html-rewriter-doctype)

@robobun

robobun commented Apr 18, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 11:37 AM PT - May 4th, 2026

❌ @robobun, your commit 1612a9a has 2 failures in Build #51071 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 29466

That installs a local version of the PR into your bun-29466 executable, so you can run:

bun-29466 --bun

@coderabbitai

coderabbitai Bot commented Apr 18, 2026

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 74480c42-34de-4db1-868c-a613ac90c1ca

📥 Commits

Reviewing files that changed from the base of the PR and between a962707 and f28cfd7.

📒 Files selected for processing (2)
  • src/bun.js/api/html_rewriter.zig
  • test/js/workerd/html-rewriter.test.js
💤 Files with no reviewable changes (1)
  • src/bun.js/api/html_rewriter.zig

Walkthrough

Modified HTML rewriter error handling to skip synchronous cleanup during rewriter.end() failures, returning errors directly for the sync path instead. Added test cases verifying that exceptions thrown in onDocument end handlers propagate correctly through HTMLRewriter.transform() for both Response and string inputs.

Changes

Cohort / File(s) Summary
HTML Rewriter Implementation
src/bun.js/api/html_rewriter.zig
Removed synchronous error cleanup in BufferOutputSink.runOutputSink when rewriter.end() fails; sync path now returns error directly without calling response.finalize() or clearing sink.response.
HTML Rewriter Tests
test/js/workerd/html-rewriter.test.js
Added two new test cases validating that exceptions thrown synchronously in onDocument({ end() { ... } }) handlers propagate out of HTMLRewriter().transform() for Response and string inputs.
🚥 Pre-merge checks | ✅ 2
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and specifically describes the main fix: addressing a use-after-free bug in HTMLRewriter when document end handlers throw.
Description check ✅ Passed The description fully addresses both template sections with comprehensive details about the bug, root cause, repro steps, and verification testing.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands and usage tips.

@claude claude 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.

LGTM — correct minimal fix: removing the erroneous / from the error path makes it consistent with the error path, since the Response's lifetime is already owned by the JS wrapper at that point.

Extended reasoning...

Overview

The PR modifies two files: (removing 2 lines) and (adding two regression tests). The fix targets — specifically the block.

Security Risks

None. This is a memory-safety fix (use-after-free), not a security-sensitive code path involving auth, crypto, or permissions. The fix actually improves safety by eliminating a UAF.

Analysis of the Fix

The root cause is clear and the fix is correct: after calls , the JS engine owns the native object's single reference. The old code's in the error catch block was double-freeing — the JS GC would later call again on already-freed memory. The error path was already correct (no finalize call there). This PR simply aligns the error path with the error path.

Flagged Pre-existing Bug

The inline comment about async exception propagation ( vs ) describes a pre-existing limitation that predates this PR, is acknowledged by existing comments in the code, and is unrelated to the use-after-free being fixed. It does not block this fix.

Test Coverage

Two targeted regression tests cover the fixed code paths (Response input and string input), and the author verified the full test suite passes.

Comment on lines 585 to 588
sink.rewriter.?.end() catch {
if (!is_async) response.finalize();
sink.response = undefined;
if (is_async) {
response.getBodyValue().toErrorInstance(.{ .Message = createLOLHTMLStringError() }, global) catch {}; // TODO: properly propagate exception upwards
return null;

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.

🟣 The async error paths in runOutputSink (lines 578 and 587) call createLOLHTMLStringError(), which only returns LOLHTML's internal error string, losing the user's actual JS exception (e.g., new Error('boom')). This is a pre-existing issue unrelated to this PR's fix; the PR correctly removes the use-after-free (response.finalize()/sink.response = undefined) but leaves the async exception propagation unchanged, as acknowledged by the existing // TODO: properly propagate exception upwards comments.

Extended reasoning...

What the bug is: In runOutputSink, both the write() error path (line 578) and the end() error path (line 587) use createLOLHTMLStringError() when is_async=true. This function only clones and returns the last LOLHTML internal error string. By contrast, createLOLHTMLError(global) first checks global.tryTakeException() and then vm.unhandled_pending_rejection_to_capture to retrieve the actual user-thrown JS exception. The synchronous else branches correctly call createLOLHTMLError(global).

The specific code path: When a document end handler throws synchronously during the async buffering flow, HandlerCallback attempts to store the user exception via if (this.global.bunVM().unhandled_pending_rejection_to_capture) |err_ptr| { err_ptr.* = exc_value; ... }. However, onFinishedBuffering is called after init() has returned, so its defer block has already executed, restoring vm.unhandled_pending_rejection_to_capture back to prev_unhandled_pending_rejection_to_capture (typically null). This means HandlerCallback cannot store the exception, and scope.clearException() also removes it from the JS scope.

Why existing code doesn't prevent it: The capture mechanism for the user exception (unhandled_pending_rejection_to_capture) is set up inside init() and torn down before onFinishedBuffering runs. In the async case, there is no valid capture pointer remaining when the handler callback executes. Even swapping to createLOLHTMLError() in the async paths would not fully fix this, because the exception is already gone by the time the error propagation code runs. Additionally, the two functions have incompatible return types: createLOLHTMLStringError() returns bun.String (used as .Message in toErrorInstance), while createLOLHTMLError() returns a JSValue, so the fix requires a structural refactor, not a simple swap.

Impact: When using HTMLRewriter with streaming or file-backed bodies (the async path), any JS exception thrown by a handler is silently swallowed and replaced by a generic LOLHTML internal error message. The user loses the original error type, message, and stack trace.

How to fix: A proper fix requires preserving the user exception before the init() defer runs — e.g., by capturing and passing the exception through the async callback chain, or by restructuring the error propagation so the async path can access the original thrown value. The TODO comment already acknowledges this gap.

Step-by-step proof: (1) User calls rewriter.transform(new Response(Bun.file(...))) with a throwing end handler. (2) init() sets vm.unhandled_pending_rejection_to_capture = &sink_error then starts async buffering and returns. (3) init()'s defer block fires: vm.unhandled_pending_rejection_to_capture = prev_unhandled_pending_rejection_to_capture (null). (4) Later, buffering completes; onFinishedBuffering calls runOutputSink. (5) rewriter.end() triggers the end handler; it throws new Error('boom'). (6) HandlerCallback checks unhandled_pending_rejection_to_capture — it is null, so the exception is not stored. scope.clearException() removes it from the JS engine. (7) LOLHTML returns an error; runOutputSink's catch block calls createLOLHTMLStringError(), which returns LOLHTML's generic string. The caller receives a generic error, not Error: boom.

@robobun

robobun commented May 2, 2026

Copy link
Copy Markdown
Collaborator Author

Confirmed independently — same crash signature (JSResponse::~JSResponse → Response.finalize → ASAN use-after-poison in JSRef.deinit) and same root cause at html_rewriter.zig:588.

Pushed an equivalent fix + subprocess-based regression test to farm/7e190275/htmlrewriter-end-uaf in case it's useful; the subprocess variant keeps the ASAN abort from killing the test runner in the fail-before case. Deferring to this PR.

@robobun

robobun commented May 2, 2026

Copy link
Copy Markdown
Collaborator Author

Re-reported internally and independently root-caused to the same two lines — response.finalize() + sink.response = undefined in the rewriter.end() sync catch path of BufferOutputSink.runOutputSink. Reproduced the ASAN use-after-poison in JSRef.deinit ← Response.finalize ← JSResponse::~JSResponse on current main (fcd764b) and verified this diff fixes it. No competing PR opened.

@Jarred-Sumner
Jarred-Sumner force-pushed the farm/14778d54/htmlrewriter-end-uaf branch from f28cfd7 to 1612a9a Compare May 4, 2026 10:30

@claude claude 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.

LGTM — after rebase this is test-only; the Zig fix already landed in #30196 and these add complementary sync-throw regression coverage.

Extended reasoning...

Overview

After rebasing onto main, this PR now contains only two regression tests in test/js/workerd/html-rewriter.test.js (26 lines added, 0 source changes). The actual html_rewriter.zig fix — removing response.finalize() / sink.response = undefined from the rewriter.end() sync catch path — was merged independently via #30196 (commit 0561f87). The tests added here exercise the same fixed code path with a different trigger: a synchronous throw from onDocument({ end }), complementing #30196's tests which use a rejected promise from onDocument({ text }) on lastInTextNode. Both new tests follow the exact pattern of the existing "error inside element handler" tests immediately above them, with an added Bun.gc(true) to surface the would-be UAF.

Security risks

None. Test-only change; no runtime, parsing, auth, or network code is touched.

Level of scrutiny

Low. This is a mechanical addition of two small regression tests that mirror existing test structure in the same file. There is no production logic to review. The author confirmed the full html-rewriter.test.js suite passes (43 pass, 2 todo), and two independent robobun investigations confirmed the underlying fix.

Other factors

  • The inline bug comment posted with this review concerns a pre-existing minor JSValue.protect() imbalance (one extra protect on the thrown Error in the sync handler error path). It applies equally to the long-standing "error inside element handler" tests and is not introduced or worsened by this diff — it's flagged for follow-up, not as a blocker.
  • My earlier 2026-04-18 inline comment was on the Zig file, which is no longer part of the diff after the rebase.
  • The PR description still references the Zig change, but that's expected drift after the rebase absorbed the source fix from #30196.

Comment on lines +47 to +58
it("error inside document end handler", () => {
expect(() =>
new HTMLRewriter()
.onDocument({
end() {
throw new Error("test");
},
})
.transform(new Response("<div>hello</div>")),
).toThrow("test");
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.

🟣 Pre-existing minor leak (not introduced by this PR, but in the same code path): in the sync error flow these new tests exercise, the thrown Error accumulates two JSValue.protect() calls (HandlerCallback at L940 + onFinishedBuffering at L564) but only one unprotect() (init() at L523), leaving it permanently rooted in JSC's counted protect set. The same imbalance already exists for the write() catch path (element/text/comment handler throws, L583), so this predates the diff; the fix is to have createLOLHTMLError unprotect when it consumes err_ptr.*, or skip the re-protect in onFinishedBuffering.

Extended reasoning...

What the bug is

When an HTMLRewriter handler throws synchronously and the body is processed via the sync BufferOutputSink path (is_async=false), the user's thrown Error (more precisely, the JSC::Exception cell wrapping it) ends up with a net gcProtect count of +1 that is never balanced. JSC's gcProtect is a counted set (JSValue.zig docs: "A value may be protected multiple times and must be unprotected an equal number of times before becoming eligible for garbage collection"), so the cell is permanently rooted for the lifetime of the VM.

This is pre-existing — the identical imbalance already occurs on the write() catch path (element/comment/text handler throws), which is exercised by the existing "error inside element handler" test. This PR's diff only removed response.finalize() / sink.response = undefined from the end() catch and did not touch any protect/unprotect bookkeeping. It is also distinct from the already-posted comment about async exception loss via createLOLHTMLStringError().

The specific code path

All line numbers refer to src/runtime/api/html_rewriter.zig after the restructure.

  1. init() L448-450 sets vm.unhandled_pending_rejection_to_capture = &sink_error and sink.tmp_sync_error = &sink_error. Both pointers alias the same stack slot.
  2. HandlerCallback L938-944: the end (or element) handler throws. The catch arm reads vm.unhandled_pending_rejection_to_capture (= &sink_error), writes exc_value into it, and calls exc_value.protect(). Protect count = 1. Then scope.clearException() removes it from the JS engine.
  3. lol-html's end() (or write()) returns an error → runOutputSink L592 / L583 (is_async=false) returns createLOLHTMLError(global).
  4. createLOLHTMLError L1092-1101: tryTakeException() is null (cleared in step 2), so it reads err_ptr.* (= sink_error = the protected exception), sets err_ptr.* = .zero, and returns the value. No unprotect here. Count still = 1.
  5. onFinishedBuffering L562-565: receives that value as ret_err, calls ret_err.protect() again — count = 2 — and writes it back into sink.tmp_sync_error.?.* (= &sink_error).
  6. init() L521-525: sink_error != .zero, so it calls sink_error.unprotect() — count = 1 — and returns it. The defer at L452-456 only does ensureStillAlive and restores the VM pointer; no further unprotect.
  7. beginTransform → transform_ (out.toError() → global.throwValue(err)) does not unprotect either.

Net: one outstanding gcProtect on the user's Error that is never balanced.

Why existing code doesn't prevent it

The sync error plumbing was designed as "protect on store, unprotect on consume," but createLOLHTMLError consumes err_ptr.* (zeroes it and returns it) without unprotecting, and onFinishedBuffering then unconditionally re-protects whatever runOutputSink returns before storing it back into the same slot. Because both vm.unhandled_pending_rejection_to_capture and sink.tmp_sync_error alias &sink_error, the value round-trips through the slot picking up two protects against init()'s single unprotect.

Impact

Minor: one small Error/Exception cell (plus its retained graph — message string, stack trace) is leaked per failed transform(). The new tests in this PR each leak one such object per run; the existing element-handler error tests already leak the same. Not user-visible in practice unless an application throws from a rewriter handler in a hot loop.

How to fix

Either of:

  • In createLOLHTMLError (L1095-1101), call result.unprotect() before returning the value taken from err_ptr.* — it was protected by HandlerCallback and is being handed off, so the protection should travel with the consumer.
  • In onFinishedBuffering (L562-565), skip the ret_err.protect() when the value originated from createLOLHTMLError's err_ptr branch (it's already protected). The first option is cleaner since it keeps protect/unprotect paired at the same conceptual layer.

Step-by-step proof (concrete example)

Take the new test at html-rewriter.test.js:47:

new HTMLRewriter()
  .onDocument({ end() { throw new Error("test"); } })
  .transform(new Response("<div>hello</div>"));
  • BufferOutputSink.init runs; sink_error = .zero; vm.unhandled_pending_rejection_to_capture = &sink_error; sink.tmp_sync_error = &sink_error.
  • Body is an in-memory Response, so bodyValueBufferer.run invokes onFinishedBuffering(sink, bytes, null, is_async=false) synchronously inside init().
  • runOutputSink → rewriter.write(bytes) succeeds → rewriter.end() invokes the end handler → throw new Error("test").
  • HandlerCallback catch: err_ptr = &sink_error; sink_error = exc; exc.protect() → gcProtect[exc] = 1; scope.clearException(). Returns true → lol-html end() returns error.
  • runOutputSink end() catch (is_async=false): return createLOLHTMLError(global).
  • createLOLHTMLError: tryTakeException() → null; err_ptr = &sink_error; result = sink_error (= exc); sink_error = .zero; return exc. gcProtect[exc] still = 1.
  • onFinishedBuffering: ret_err = exc; exc.protect() → gcProtect[exc] = 2; *&sink_error = exc.
  • Back in init(): sink_error = exc != .zero → exc.unprotect() → gcProtect[exc] = 1; return exc.
  • transform_ throws exc to JS; the test's expect().toThrow("test") catches it and drops the reference.
  • Bun.gc(true) runs, but exc is still in JSC's protected-cell set with count 1, so it survives. Nothing ever decrements it again.

Hence the Error("test") object leaks for the process lifetime. The exact same trace applies to the pre-existing "error inside element handler" test via the write() catch at L583, confirming this is not introduced by this PR.

@robobun

robobun commented Aug 12, 2026

Copy link
Copy Markdown
Collaborator Author

This was fixed on main by #30196, which removed the same response.finalize() / sink.response = undefined pair in the end() error path (after the rebase this PR no longer carries a src/ change, only the test). The HTMLRewriter implementation has since moved to src/runtime/api/html_rewriter.rs as well.

Verified on current main (165dc9f) with a debug ASAN build:

  • the string-input test from this PR passes as written
  • the repro from the description (end() throws, transform(""), Bun.gc(true)) runs 100 iterations with no sanitizer report
  • the Response-input test no longer applies as written because transform(Response) now reports handler errors through the body rejection instead of throwing; with the assertion adjusted for that, 50 iterations plus GC also run clean
  • test/js/workerd/html-rewriter-end-error.test.ts from Fix HTMLRewriter use-after-free when handler rejects during end() #30196 passes

Closing.

@robobun robobun closed this Aug 12, 2026
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.

1 participant