Skip to content

Commit 7ff1181

Browse files
authored
Fix use-after-free of stream error objects parked in ByteStream (#31963)
### What does this PR do? Fixes a use-after-free found by Fuzzilli (fingerprint `StructureID.h(93)`, `ASSERTION FAILED: decontaminate()` in `StructureID::decode()`). `StreamError::JSValue` held a raw `JSValue` with no GC root. When an S3 download stream failed before a consumer attached (missing credentials fail synchronously inside `.stream()`), the error object was parked in `ByteStream.pending.result` across event-loop turns. A GC before the stream was consumed freed it, so `.text()` rejected with whatever now lived in the recycled cell, or crashed on a dead cell. Deterministic on an unfixed build: ```js const stream = Bun.S3Client.file("some-key").stream(); Bun.gc(true); for (let i = 0; i < 100; i++) new TypeError("decoy " + i); await stream.text().catch(e => e); // rejects with TypeError: decoy 0 (recycled cell) ``` The fetch, request body size limit, and `Body::ValueError::to_stream_error` producers had the same shape. ### The fix `StreamError::JSValue` now holds `jsc::strong::Optional`, which keeps the value rooted while held and releases it on `Drop` (implements the existing TODO on the variant). This deletes most of the surrounding machinery: `to_js_weak` becomes `to_js`, the `WasStrong` enum and every consumer-side `if was_strong == Strong { unprotect() }` branch are gone, the unused `WeakJSValue` variant is gone, `StreamError` is no longer `Clone`, `RequestContext::on_pipe` drops its raw-pointer `scopeguard::defer!`/`unsafe` block (the by-value result drops naturally in the trait impl), and `ByteStream::on_data` moves a parked error instead of cloning it. ### How did you verify your code works? - New test `test/js/bun/s3/s3-stream-error-gc.test.ts` fails on the unfixed build (rejects with a recycled decoy object) and passes with this change. - The original fuzzer script no longer asserts. - Ran the S3 test directory, `test/js/web/streams/streams.test.js`, `test/js/web/fetch/{body-stream,body-mixin-errors,fetch.stream}.test.ts`, `test/js/web/streams/readable-stream-blob-consumed.test.ts`, and `test/js/bun/http/serve-pending-promise-abort-leak.test.ts` against the debug build; only behavioral delta vs an unmodified build is the new test passing (the remaining failures are pre-existing 5s debug+ASAN timeouts that reproduce identically on the unmodified debug build). - `cargo clippy -p bun_runtime` and `bun run rust:check-all` pass.
1 parent cbcec93 commit 7ff1181

9 files changed

Lines changed: 105 additions & 132 deletions

File tree

‎src/runtime/server/RequestContext.rs‎

Lines changed: 3 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -3022,30 +3022,10 @@ where
30223022
this.do_render_blob();
30233023
}
30243024

3025-
pub fn on_pipe(this: &mut Self, mut stream: WebCore::streams::Result) {
3026-
let stream_needs_deinit = matches!(
3027-
stream,
3028-
WebCore::streams::Result::Owned(_) | WebCore::streams::Result::OwnedAndDone(_)
3029-
);
3025+
pub fn on_pipe(this: &mut Self, stream: &WebCore::streams::Result) {
30303026
let is_done = stream.is_done();
3031-
// NOTE: reshaped for borrowck — the defer reads `stream` through a
3032-
// raw ptr so the body below can keep borrowing it.
3033-
let stream_ptr: *mut WebCore::streams::Result = &raw mut stream;
30343027
// Drop one ref only when the stream signals completion.
30353028
let _ref = is_done.then(|| RequestContextRef(std::ptr::from_mut::<Self>(this)));
3036-
scopeguard::defer! {
3037-
if stream_needs_deinit {
3038-
// SAFETY: stream lives on the caller's stack frame past the guard.
3039-
match unsafe { &mut *stream_ptr } {
3040-
WebCore::streams::Result::OwnedAndDone(owned)
3041-
| WebCore::streams::Result::Owned(owned) => {
3042-
// Vec::deinit → Drop in Rust.
3043-
*owned = Vec::<u8>::default();
3044-
}
3045-
_ => unreachable!(),
3046-
}
3047-
}
3048-
}
30493029

30503030
if this.is_aborted_or_ended() {
30513031
return;
@@ -3628,11 +3608,9 @@ where
36283608
let mut err = Body::ValueError::Message(BunString::static_(
36293609
"Request body exceeded maxRequestBodySize",
36303610
));
3631-
let js_err = err.to_js(global_this);
3632-
js_err.ensure_still_alive();
36333611
// TODO: properly propagate exception upwards
36343612
let _ = bytes.on_data(WebCore::streams::Result::Err(
3635-
WebCore::streams::StreamError::JSValue(js_err),
3613+
err.to_stream_error(global_this),
36363614
));
36373615
err.reset();
36383616
}
@@ -4088,7 +4066,7 @@ where
40884066
fn on_pipe(&mut self, stream: WebCore::streams::Result) {
40894067
// Forward to the inherent associated fn (not method-dispatched to avoid
40904068
// recursing into this trait impl).
4091-
RequestContext::on_pipe(self, stream)
4069+
RequestContext::on_pipe(self, &stream)
40924070
}
40934071
}
40944072

‎src/runtime/webcore/Body.rs‎

Lines changed: 8 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -628,7 +628,10 @@ impl ValueError {
628628
) -> streams::result::StreamError {
629629
match self {
630630
ValueError::AbortReason(reason) => streams::result::StreamError::AbortReason(*reason),
631-
_ => streams::result::StreamError::JSValue(self.to_js(global_object)),
631+
_ => streams::result::StreamError::JSValue(jsc::strong::Optional::create(
632+
self.to_js(global_object),
633+
global_object,
634+
)),
632635
}
633636
}
634637

@@ -2307,30 +2310,15 @@ impl<'a> ValueBufferer<'a> {
23072310
}
23082311
}
23092312

2310-
fn on_stream_pipe(&mut self, stream: streams::Result) {
2311-
let stream_ = stream;
2312-
let stream_needs_deinit = matches!(
2313-
stream_,
2314-
streams::Result::Owned(_) | streams::Result::OwnedAndDone(_)
2315-
);
2316-
2317-
let chunk = stream_.slice();
2313+
fn on_stream_pipe(&mut self, stream: &streams::Result) {
2314+
let chunk = stream.slice();
23182315
bun_core::scoped_log!(BodyValueBufferer, "onStreamPipe chunk {}", chunk.len());
23192316
let _ = self.stream_buffer.write(chunk);
2320-
if stream_.is_done() {
2317+
if stream.is_done() {
23212318
let bytes = self.stream_buffer.list.as_slice();
23222319
bun_core::scoped_log!(BodyValueBufferer, "onStreamPipe done {}", bytes.len());
23232320
(self.on_finished_buffering)(self.ctx, bytes, None, true);
23242321
}
2325-
2326-
if stream_needs_deinit {
2327-
match stream_ {
2328-
streams::Result::OwnedAndDone(owned) | streams::Result::Owned(owned) => {
2329-
drop(owned);
2330-
}
2331-
_ => unreachable!(),
2332-
}
2333-
}
23342322
}
23352323

23362324
/// Reclaim the `*mut Self` smuggled through a `NativePromiseContext` cell
@@ -2531,7 +2519,7 @@ impl<'a> ValueBufferer<'a> {
25312519
// `webcore::Wrap<T>` requires `T: PipeHandler`.
25322520
impl<'a> crate::webcore::PipeHandler for ValueBufferer<'a> {
25332521
fn on_pipe(&mut self, stream: streams::Result) {
2534-
self.on_stream_pipe(stream)
2522+
self.on_stream_pipe(&stream)
25352523
}
25362524
}
25372525

‎src/runtime/webcore/ByteStream.rs‎

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ impl ByteStream {
158158
});
159159
}
160160

161-
pub(crate) fn on_data(&self, stream: streams::Result) -> Result<(), bun_jsc::JsTerminated> {
161+
pub(crate) fn on_data(&self, mut stream: streams::Result) -> Result<(), bun_jsc::JsTerminated> {
162162
bun_jsc::mark_binding!();
163163
if self.done.get() {
164164
// The owned `Vec<u8>`/`Vec`
@@ -285,6 +285,7 @@ impl ByteStream {
285285
let pending_buffer_len = pending_buf.len();
286286
debug_assert!(pending_buf.as_ptr() != chunk.as_ptr());
287287
pending_buf[..to_copy_len].copy_from_slice(&chunk[..to_copy_len]);
288+
let has_remaining = chunk.len() > to_copy_len;
288289
self.pending_buffer.set(Self::empty_pending_buffer());
289290

290291
let is_really_done =
@@ -294,9 +295,9 @@ impl ByteStream {
294295
self.done.set(true);
295296

296297
if to_copy_len == 0 {
297-
if let streams::Result::Err(err) = &stream {
298-
self.pending
299-
.with_mut(|p| p.result = streams::Result::Err(err.clone()));
298+
if matches!(stream, streams::Result::Err(_)) {
299+
let err = core::mem::replace(&mut stream, streams::Result::Done);
300+
self.pending.with_mut(|p| p.result = err);
300301
} else {
301302
self.pending.with_mut(|p| p.result = streams::Result::Done);
302303
}
@@ -319,10 +320,7 @@ impl ByteStream {
319320
});
320321
}
321322

322-
let remaining = &chunk[to_copy_len..];
323-
if !remaining.is_empty() && !chunk.is_empty() {
324-
// `chunk` borrows `stream`; passing both requires re-slicing inside
325-
// `append`.
323+
if has_remaining {
326324
self.append(stream, to_copy_len)
327325
.unwrap_or_else(|_| panic!("Out of memory while copying request body"));
328326
}
@@ -577,8 +575,9 @@ impl ByteStream {
577575
}
578576

579577
if let streams::Result::Err(err) = &self.pending.get().result {
580-
let (err_js, _) = err.to_js_weak(global_this);
581-
self.pending.with_mut(|p| p.result.release());
578+
let err_js = err.to_js(global_this);
579+
err_js.ensure_still_alive();
580+
self.pending.with_mut(|p| p.result = streams::Result::Done);
582581
self.done.set(true);
583582
self.buffer.with_mut(|b| {
584583
b.clear();

‎src/runtime/webcore/ReadableStream.rs‎

Lines changed: 5 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1076,21 +1076,11 @@ impl<C: SourceContext> NewSource<C> {
10761076
mut result: streams::Result,
10771077
) -> JsResult<JSValue> {
10781078
match &result {
1079-
streams::Result::Err(err) => match err {
1080-
streams::StreamError::Error(e) => {
1081-
Err(global_this.throw_value(e.to_js(global_this)))
1082-
}
1083-
// Always throw on `.err`: `to_js_weak` handles all four variants
1084-
// and reports whether the value was strong-protected (needs `unprotect()`).
1085-
_ => {
1086-
let (js_err, was_strong) = err.to_js_weak(global_this);
1087-
js_err.ensure_still_alive();
1088-
if was_strong == streams::WasStrong::Strong {
1089-
js_err.unprotect();
1090-
}
1091-
Err(global_this.throw_value(js_err))
1092-
}
1093-
},
1079+
streams::Result::Err(err) => {
1080+
let js_err = err.to_js(global_this);
1081+
js_err.ensure_still_alive();
1082+
Err(global_this.throw_value(js_err))
1083+
}
10941084
streams::Result::Pending(_) => {
10951085
let out = result.to_js(global_this)?;
10961086
<Self as NewSourceCodegen>::pending_promise_set_cached(

‎src/runtime/webcore/ResumableSink.rs‎

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -200,11 +200,8 @@ impl<Js: ResumableSinkJs, Context: ResumableSinkContext> ResumableSink<Js, Conte
200200
let err: Option<JSValue> = 'brk_err: {
201201
let pending = &byte_stream.pending.get().result;
202202
if let StreamResult::Err(e) = pending {
203-
let (js_err, was_strong) = e.to_js_weak(global_this);
203+
let js_err = e.to_js(global_this);
204204
js_err.ensure_still_alive();
205-
if was_strong == crate::webcore::streams::WasStrong::Strong {
206-
js_err.unprotect();
207-
}
208205
break 'brk_err Some(js_err);
209206
}
210207
None
@@ -483,11 +480,8 @@ impl<Js: ResumableSinkJs, Context: ResumableSinkContext> ResumableSink<Js, Conte
483480
if is_done {
484481
let err: Option<JSValue> = 'brk_err: {
485482
if let StreamResult::Err(e) = &stream {
486-
let (js_err, was_strong) = e.to_js_weak(self.global_this.get());
483+
let js_err = e.to_js(self.global_this.get());
487484
js_err.ensure_still_alive();
488-
if was_strong == crate::webcore::streams::WasStrong::Strong {
489-
js_err.unprotect();
490-
}
491485
break 'brk_err Some(js_err);
492486
}
493487
None

‎src/runtime/webcore/fetch/FetchTasklet.rs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -667,7 +667,9 @@ impl FetchTasklet {
667667
if let Some(bytes) = readable.ptr.bytes() {
668668
js_err = err.to_js(&global_this);
669669
js_err.ensure_still_alive();
670-
bytes.on_data(StreamResult::Err(StreamError::JSValue(js_err)))?;
670+
bytes.on_data(StreamResult::Err(StreamError::JSValue(
671+
bun_jsc::strong::Optional::create(js_err, &global_this),
672+
)))?;
671673
}
672674
}
673675
// A failure result is terminal (`to_result` forces `has_more =

‎src/runtime/webcore/s3/client.rs‎

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -798,10 +798,7 @@ pub fn upload_stream(
798798
result: crate::webcore::streams::StreamResult::Done,
799799
..Default::default()
800800
});
801-
let (js_err, was_strong) = err.to_js_weak(global_this);
802-
if was_strong == crate::webcore::streams::WasStrong::Strong {
803-
js_err.unprotect();
804-
}
801+
let js_err = err.to_js(global_this);
805802
js_err.ensure_still_alive();
806803
credentials.deref();
807804
return Ok(bun_jsc::JSPromise::rejected_promise(global_this, js_err).to_js());
@@ -826,10 +823,7 @@ pub fn upload_stream(
826823
result: crate::webcore::streams::StreamResult::Done,
827824
..Default::default()
828825
});
829-
let (js_err, was_strong) = err.to_js_weak(global_this);
830-
if was_strong == crate::webcore::streams::WasStrong::Strong {
831-
js_err.unprotect();
832-
}
826+
let js_err = err.to_js(global_this);
833827
js_err.ensure_still_alive();
834828
credentials.deref();
835829
return Ok(bun_jsc::JSPromise::rejected_promise(global_this, js_err).to_js());
@@ -1151,11 +1145,12 @@ pub fn readable_stream(
11511145
if let Some(bytes) = readable.ptr.bytes() {
11521146
if let Some(err) = request_err {
11531147
bytes.on_data(crate::webcore::streams::StreamResult::Err(
1154-
crate::webcore::streams::StreamError::JSValue(s3_error_to_js(
1155-
&err,
1156-
&self_.global,
1157-
Some(&self_.path),
1158-
)),
1148+
crate::webcore::streams::StreamError::JSValue(
1149+
bun_jsc::strong::Optional::create(
1150+
s3_error_to_js(&err, &self_.global, Some(&self_.path)),
1151+
&self_.global,
1152+
),
1153+
),
11591154
))?;
11601155
return Ok(());
11611156
}

‎src/runtime/webcore/streams.rs‎

Lines changed: 12 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -319,48 +319,29 @@ pub enum StreamResult {
319319
}
320320

321321
impl StreamResult {
322-
// Intentionally not Drop — Result is bitwise-copied in the to_js() shutdown path, so
323-
// ownership is contextual and a Drop impl would double-free.
324-
// Named `release` (not `deinit`) per PORTING.md — `pub fn deinit` is forbidden as a public API.
325322
pub fn release(&mut self) {
326323
match self {
327-
StreamResult::Owned(owned) => owned.clear_and_free(),
328-
StreamResult::OwnedAndDone(owned_and_done) => owned_and_done.clear_and_free(),
329-
StreamResult::Err(err) => {
330-
if let StreamError::JSValue(v) = err {
331-
v.unprotect();
332-
}
324+
StreamResult::Owned(owned) | StreamResult::OwnedAndDone(owned) => {
325+
owned.clear_and_free()
333326
}
327+
StreamResult::Err(StreamError::JSValue(s)) => s.deinit(),
334328
_ => {}
335329
}
336330
}
337331
}
338332

339-
#[derive(Clone)]
340333
pub enum StreamError {
341334
Error(SysError),
342335
AbortReason(CommonAbortReason),
343-
// TODO: use an explicit jsc.Strong.Optional here.
344-
JSValue(JSValue),
345-
WeakJSValue(JSValue),
346-
}
347-
348-
#[derive(Copy, Clone, Eq, PartialEq)]
349-
pub enum WasStrong {
350-
Strong,
351-
Weak,
336+
JSValue(jsc::strong::Optional),
352337
}
353338

354339
impl StreamError {
355-
pub fn to_js_weak(&self, global_object: &JSGlobalObject) -> (JSValue, WasStrong) {
340+
pub fn to_js(&self, global_object: &JSGlobalObject) -> JSValue {
356341
match self {
357-
StreamError::Error(err) => (err.to_js(global_object), WasStrong::Weak),
358-
StreamError::JSValue(v) => (*v, WasStrong::Strong),
359-
StreamError::WeakJSValue(v) => (*v, WasStrong::Weak),
360-
StreamError::AbortReason(reason) => {
361-
let value = reason.to_js(global_object);
362-
(value, WasStrong::Weak)
363-
}
342+
StreamError::Error(err) => err.to_js(global_object),
343+
StreamError::JSValue(v) => v.get().unwrap_or(JSValue::UNDEFINED),
344+
StreamError::AbortReason(reason) => reason.to_js(global_object),
364345
}
365346
}
366347
}
@@ -817,14 +798,8 @@ impl StreamResult {
817798

818799
match result {
819800
StreamResult::Err(err) => {
820-
let value = 'brk: {
821-
let (js_err, was_strong) = err.to_js_weak(global_this);
822-
js_err.ensure_still_alive();
823-
if was_strong == WasStrong::Strong {
824-
js_err.unprotect();
825-
}
826-
break 'brk js_err;
827-
};
801+
let value = err.to_js(global_this);
802+
value.ensure_still_alive();
828803
*result = StreamResult::Temporary(RawSlice::EMPTY);
829804
// S008: `JSPromise` is an `opaque_ffi!` ZST — safe `*mut → &mut`
830805
// deref. Fresh temp `&mut` is the sole borrow across this
@@ -909,10 +884,7 @@ impl StreamResult {
909884
Ok(promise_js)
910885
}
911886
StreamResult::Err(err) => {
912-
let (js_err, was_strong) = err.to_js_weak(global_this);
913-
if was_strong == WasStrong::Strong {
914-
js_err.unprotect();
915-
}
887+
let js_err = err.to_js(global_this);
916888
js_err.ensure_still_alive();
917889
Ok(JSPromise::rejected_promise(global_this, js_err).to_js())
918890
}
@@ -2507,7 +2479,7 @@ impl BufferAction {
25072479
err: &StreamError,
25082480
) -> core::result::Result<(), jsc::JsTerminated> {
25092481
// S008: `JSPromise` is an `opaque_ffi!` ZST — safe `*mut → &mut` deref.
2510-
JSPromise::opaque_mut(self.swap()).reject(global, Ok(err.to_js_weak(global).0))
2482+
JSPromise::opaque_mut(self.swap()).reject(global, Ok(err.to_js(global)))
25112483
}
25122484

25132485
pub fn resolve(

0 commit comments

Comments
 (0)