Repository navigation
Conversation
|
Updated 11:37 AM PT - May 4th, 2026
❌ @robobun, your commit 1612a9a has 2 failures in
🧪 To try this PR locally: bunx bun-pr 29466That installs a local version of the PR into your bun-29466 --bun |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (2)
💤 Files with no reviewable changes (1)
WalkthroughModified HTML rewriter error handling to skip synchronous cleanup during Changes
🚥 Pre-merge checks | ✅ 2✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
There was a problem hiding this comment.
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.
| 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; |
There was a problem hiding this comment.
🟣 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.
|
Confirmed independently — same crash signature ( Pushed an equivalent fix + subprocess-based regression test to |
|
Re-reported internally and independently root-caused to the same two lines — |
f28cfd7 to
1612a9a
Compare
There was a problem hiding this comment.
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.
| 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); | ||
| }); |
There was a problem hiding this comment.
🟣 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.
init()L448-450 setsvm.unhandled_pending_rejection_to_capture = &sink_errorandsink.tmp_sync_error = &sink_error. Both pointers alias the same stack slot.HandlerCallbackL938-944: theend(orelement) handler throws. The catch arm readsvm.unhandled_pending_rejection_to_capture(=&sink_error), writesexc_valueinto it, and callsexc_value.protect(). Protect count = 1. Thenscope.clearException()removes it from the JS engine.- lol-html's
end()(orwrite()) returns an error →runOutputSinkL592 / L583 (is_async=false) returnscreateLOLHTMLError(global). createLOLHTMLErrorL1092-1101:tryTakeException()isnull(cleared in step 2), so it readserr_ptr.*(=sink_error= the protected exception), setserr_ptr.* = .zero, and returns the value. Nounprotecthere. Count still = 1.onFinishedBufferingL562-565: receives that value asret_err, callsret_err.protect()again — count = 2 — and writes it back intosink.tmp_sync_error.?.*(=&sink_error).init()L521-525:sink_error != .zero, so it callssink_error.unprotect()— count = 1 — and returns it. Thedeferat L452-456 only doesensureStillAliveand restores the VM pointer; no furtherunprotect.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), callresult.unprotect()before returning the value taken fromerr_ptr.*— it was protected byHandlerCallbackand is being handed off, so the protection should travel with the consumer. - In
onFinishedBuffering(L562-565), skip theret_err.protect()when the value originated fromcreateLOLHTMLError'serr_ptrbranch (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.initruns;sink_error = .zero;vm.unhandled_pending_rejection_to_capture = &sink_error;sink.tmp_sync_error = &sink_error.- Body is an in-memory
Response, sobodyValueBufferer.runinvokesonFinishedBuffering(sink, bytes, null, is_async=false)synchronously insideinit(). runOutputSink→rewriter.write(bytes)succeeds →rewriter.end()invokes theendhandler →throw new Error("test").HandlerCallbackcatch:err_ptr = &sink_error;sink_error = exc;exc.protect()→ gcProtect[exc] = 1;scope.clearException(). Returnstrue→ lol-htmlend()returns error.runOutputSinkend()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_throwsexcto JS; the test'sexpect().toThrow("test")catches it and drops the reference.Bun.gc(true)runs, butexcis 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.
|
This was fixed on main by #30196, which removed the same Verified on current main (165dc9f) with a debug ASAN build:
Closing. |
What does this PR do?
Fixes a use-after-free in
HTMLRewriterfound by Fuzzilli.When a document
endhandler throws synchronously duringtransform(),BufferOutputSink.runOutputSinkwas callingresponse.finalize()on the outputResponse. However, by the timerunOutputSinkruns, thatResponsehas already been wrapped in a JS object viatoJS()(inBufferOutputSink.init), so its single ref is owned by the JS wrapper. Callingfinalize()here destroyed the nativeResponsewhile the JS wrapper still pointed at it; the next GC would invokeJSResponse::~JSResponse→Response.finalize()on freed memory.The adjacent
write()error path already handled this correctly (it doesn't finalize). This change makes theend()error path match.Repro
Before: ASAN
use-after-poisoninJSRef.deinit→Response.finalize.After: throws
Error: boomcleanly.How did you verify your code works?
onDocument({ end })throwing with bothResponseand string inputhtml-rewriter.test.jssuite (43 pass, 2 todo, 0 fail)htmlrewriter-additional-bugs,19219,html-rewriter-doctype)