diff --git a/src/http/HTTPThread.rs b/src/http/HTTPThread.rs index ad7ede906832..3d4fc21ee488 100644 --- a/src/http/HTTPThread.rs +++ b/src/http/HTTPThread.rs @@ -1175,6 +1175,23 @@ fn abort_tracker() -> &'static mut ArrayHashMap { crate::abort_tracker() } +/// Debug+ASAN invariant check: every socket pointer in the abort tracker must +/// point at live (unfreed) memory. A stale entry here means some socket-close +/// path forgot `unregister_abort_tracker`, which later manifests as a +/// use-after-free in `drain_queued_shutdowns`/`drain_queued_writes` when the +/// JS thread aborts that request id. Runs before and after each loop tick so +/// the report fires at the tick that leaked, not at the eventual abort. +#[inline] +fn assert_abort_tracker_sockets_alive() { + if cfg!(debug_assertions) { + for socket in abort_tracker().values() { + if let Some(usocket) = socket.socket().get() { + bun_core::asan::assert_unpoisoned(usocket); + } + } + } +} + use core::cell::Cell; // ═══════════════════════════════════════════════════════════════════════════ @@ -1347,12 +1364,14 @@ mod _event_loop_draft { } } self.drain_events(); + assert_abort_tracker_sockets_alive(); Output::flush(); let uws_loop = self.uws_loop_mut(); uws_loop.inc(); uws_loop.tick(); uws_loop.dec(); + assert_abort_tracker_sockets_alive(); if cfg!(debug_assertions) { Output::flush(); diff --git a/src/runtime/webcore/fetch/FetchTasklet.rs b/src/runtime/webcore/fetch/FetchTasklet.rs index dbd9ba71d0d1..24ea04f47fc6 100644 --- a/src/runtime/webcore/fetch/FetchTasklet.rs +++ b/src/runtime/webcore/fetch/FetchTasklet.rs @@ -670,13 +670,16 @@ impl FetchTasklet { bytes.on_data(StreamResult::Err(StreamError::JSValue(js_err)))?; } } - if let Some(sink) = self.sink_mut() { - if js_err.is_empty() { - js_err = err.to_js(&global_this); - js_err.ensure_still_alive(); - } - sink.cancel(js_err); - return Ok(()); + // A failure result is terminal (`to_result` forces `has_more = + // false` once `fail` is set), so everything pending must settle + // here: a still-streaming request-body sink does not exempt the + // response body. Returning right after `sink.cancel()` used to + // leave a buffered `arrayBuffer()`/`text()` promise pending + // forever when a fetch with an in-flight streaming request body + // was aborted mid-response. + if self.sink_mut().is_some() && js_err.is_empty() { + js_err = err.to_js(&global_this); + js_err.ensure_still_alive(); } // if we are buffering resolve the promise if let Some(response) = self.current_response_mut() { @@ -688,6 +691,14 @@ impl FetchTasklet { body.to_error_instance(err, &global_this) .map_err(|_| bun_jsc::JsTerminated::JSTerminated)?; } + // Cancel the request-body sink last: `ResumableSink::cancel` + // invokes the stream's JS cancel callback synchronously via + // `run_callback`, which can re-enter the tasklet. + if !js_err.is_empty() { + if let Some(sink) = self.sink_mut() { + sink.cancel(js_err); + } + } return Ok(()); } diff --git a/test/js/web/fetch/fetch-abort-buffered-body-fixture.ts b/test/js/web/fetch/fetch-abort-buffered-body-fixture.ts new file mode 100644 index 000000000000..c33dd4283303 --- /dev/null +++ b/test/js/web/fetch/fetch-abort-buffered-body-fixture.ts @@ -0,0 +1,52 @@ +// Aborting a fetch whose request body stream is still uploading must also +// settle the response side. The failure callback used to return right after +// cancelling the request-body sink, so a buffered body promise +// (arrayBuffer/text/json) never rejected and awaiting it hung forever. +// Prints one line per consumer; a "timed out" line means the promise zombied. + +using server = Bun.serve({ + port: 0, + fetch() { + return new Response( + new ReadableStream({ + pull(c) { + c.enqueue(new Uint8Array(1024)); + // keep the response body open until the client aborts + return new Promise(() => {}); + }, + }), + ); + }, +}); + +async function run(method: "arrayBuffer" | "text"): Promise { + const controller = new AbortController(); + const res = await fetch(server.url, { + method: "POST", + signal: controller.signal, + body: new ReadableStream({ + pull(c) { + c.enqueue(new Uint8Array(64)); + // keep the upload stream open so the sink is active at abort time + return new Promise(() => {}); + }, + }), + }); + if (res.status !== 200) return method + " bad status " + res.status; + + const pendingBody = res[method](); + controller.abort(); + // Bounded sentinel only to convert the buggy "pending forever" state into a + // clean failure; the fixed path rejects immediately. + return Promise.race([ + pendingBody.then( + () => method + " resolved", + (err: any) => method + " rejected " + err?.name, + ), + Bun.sleep(2500).then(() => method + " timed out"), + ]); +} + +const results = await Promise.all([run("arrayBuffer"), run("text")]); +for (const line of results.sort()) console.log(line); +process.exit(results.every(r => r.includes("rejected AbortError")) ? 0 : 1); diff --git a/test/js/web/fetch/fetch-abort-stream-body.test.ts b/test/js/web/fetch/fetch-abort-stream-body.test.ts index 54a131732666..98ed1ebf5b0f 100644 --- a/test/js/web/fetch/fetch-abort-stream-body.test.ts +++ b/test/js/web/fetch/fetch-abort-stream-body.test.ts @@ -2,6 +2,30 @@ import { expect, test } from "bun:test"; import { bunEnv, bunExe } from "harness"; import { join } from "node:path"; +// Aborting a fetch whose request body stream is still uploading must also +// settle the response side. The failure callback used to return right after +// cancelling the request-body sink, so a buffered body promise +// (arrayBuffer/text/json) never rejected and awaiting it hung forever. +// Runs in a subprocess because the buggy build leaves zombie requests behind +// that keep the process from exiting. +test.concurrent( + "abort mid-response rejects buffered body promises while the request body stream is active", + async () => { + await using proc = Bun.spawn({ + cmd: [bunExe(), join(import.meta.dir, "fetch-abort-buffered-body-fixture.ts")], + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + + expect(stderr).toBe(""); + expect(stdout).toBe("arrayBuffer rejected AbortError\ntext rejected AbortError\n"); + expect(exitCode).toBe(0); + }, +); + test("aborting fetch with a ReadableStream request body does not double-cancel the sink", async () => { await using proc = Bun.spawn({ cmd: [bunExe(), join(import.meta.dir, "fetch-abort-stream-body-fixture.ts")],