Skip to content
Closed
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions src/runtime/server/RequestContext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1944,10 +1944,12 @@ where

/// # Safety
/// `this` must be a `*mut RequestContext` previously registered as `lock.task`.
pub(crate) fn do_render_with_body_locked(this: *mut c_void, value: &mut Body::Value) {
pub(crate) fn do_render_with_body_locked(this: *mut c_void, value: *mut Body::Value) {
// SAFETY: caller upholds the fn-level contract — `this` is the
// `*mut RequestContext` previously registered as `lock.task`.
Self::do_render_with_body(unsafe { bun_ptr::callback_ctx::<Self>(this) }, value, None);
let this = unsafe { bun_ptr::callback_ctx::<Self>(this) };
// SAFETY: live `&mut Value` reborrowed by `resolve`/`to_error_instance`.
Self::do_render_with_body(this, unsafe { &mut *value }, None);
}

fn render_with_blob_from_body_value(&mut self) {
Expand Down Expand Up @@ -3247,7 +3249,11 @@ where
}
}

if lock.on_receive_value.is_some() || lock.task.is_some() {
if lock.on_receive_value.is_some() {
this.render_missing();
return;
}
if lock.task.is_some() {
// someone else is waiting for the stream or waiting for `onStartStreaming`
let Ok(readable) = value.to_readable_stream(global_this) else {
return;
Expand Down
10 changes: 10 additions & 0 deletions src/runtime/shell/Builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -732,6 +732,16 @@ impl Builtin {
// SAFETY: returned a live JSC-owned `*mut Value` borrowed
// from a Response/Request wrapper.
let body = unsafe { &mut *body };
body.to_blob_if_possible();
if crate::shell::states::cmd::Cmd::reject_unbufferable_body(
body,
global,
redirect.stdin(),
)
.is_err()
{
return Some(Yield::failed());
}
let is_file_blob = matches!(body, crate::webcore::body::Value::Blob(b)
if !b.needs_to_read_file());
if (redirect.stdout() || redirect.stderr()) && !is_file_blob {
Comment thread
robobun marked this conversation as resolved.
Resolved
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/shell/shell_body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -446,7 +446,7 @@ pub fn handle_template_value(
return Ok(());
}

if let Some(_req) = template_value.as_::<crate::webcore::Response>() {
if crate::webcore::body::Value::from_request_or_response(template_value).is_some() {
let idx = out_jsobjs.len();
marked_argument_buffer.append(template_value);
out_jsobjs.push(template_value);
Expand Down
177 changes: 170 additions & 7 deletions src/runtime/shell/states/Cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,18 @@
ExpandingRedirect {
idx: u32,
},
BufferingRedirectBody,
Exec,
WaitingWriteErr,
Done,
}

struct RedirectBodyBufferCtx {
interp: *mut Interpreter,
cmd: NodeId,
keep_alive: bun_io::KeepAlive,
}

#[derive(Default)]
pub enum Exec {
#[default]
Expand Down Expand Up @@ -263,9 +270,13 @@
// "already expanded" re-entry (`idx > 0`).
_ => {}
}
if Self::try_buffer_redirect_body(interp, this, n) {
return Yield::suspended();
}
interp.as_cmd_mut(this).state = CmdState::ExpandingArgs { idx: 0 };
continue;
}
CmdState::BufferingRedirectBody => return Yield::suspended(),
CmdState::ExpandingArgs { idx } => {
let args = n.name_and_args;
if (idx as usize) >= args.len() {
Expand Down Expand Up @@ -311,6 +322,154 @@
interp.child_done(parent, this, 1)
}

fn try_buffer_redirect_body(interp: &Interpreter, this: NodeId, node: &ast::Cmd) -> bool {
if !node.redirect.stdin() {
return false;
}
let Some(ast::Redirect::JsBuf(jsbuf)) = &node.redirect_file else {
return false;
};
if interp.global_this_ref().is_none() {
return false;
}
let idx = jsbuf.idx as usize;
if idx >= interp.jsobjs.len() {
return false;
}
let Some(body_ptr) =
crate::webcore::body::Value::from_request_or_response(interp.jsobjs[idx])
else {
return false;
};
let start = {
// SAFETY: live JSC-owned `*mut Value` borrowed from the wrapper
// while `jsobjs[idx]` is rooted; the borrow ends before `start.fire()`.
let body = unsafe { &mut *body_ptr };
body.to_blob_if_possible();
let crate::webcore::body::Value::Locked(locked) = body else {
return false;
};
let ctx = bun_core::heap::alloc(RedirectBodyBufferCtx {
interp: interp.as_ctx_ptr(),
cmd: this,
keep_alive: bun_io::KeepAlive::default(),
});
// SAFETY: fresh heap allocation; freed by `on_redirect_body_received`
// or reclaimed below when the hook is not installed / was dropped.
unsafe {
(*ctx)
.keep_alive
.ref_(interp.event_loop.as_event_loop_ctx())
};
interp.as_cmd_mut(this).state = CmdState::BufferingRedirectBody;
match locked.hook_native_receiver(
ctx.cast::<core::ffi::c_void>(),
Self::on_redirect_body_received,
) {
Some(start) => (start, ctx),
None => {
interp.as_cmd_mut(this).state = CmdState::ExpandingRedirect { idx: 0 };
// SAFETY: `ctx` was not published; reclaim and drop.
unsafe {
(*ctx)
.keep_alive
.unref(interp.event_loop.as_event_loop_ctx());
bun_core::heap::destroy(ctx);
};
return false;
}
}
};
let (start, ctx) = start;
start.fire();
if matches!(interp.as_cmd(this).state, CmdState::BufferingRedirectBody) {
// SAFETY: same JSC-owned location as above, re-read after the
// producer callback — which may have resolved the body in place.
let still_locked =
matches!(unsafe { &*body_ptr }, crate::webcore::body::Value::Locked(_));
if !still_locked {
// SAFETY: the producer resolved synchronously and dropped the
// hook without firing it (server empty-body path); `ctx` is
// still the live heap allocation we hold.
unsafe {
(*ctx)
.keep_alive
.unref(interp.event_loop.as_event_loop_ctx());
bun_core::heap::destroy(ctx);
};
interp.as_cmd_mut(this).state = CmdState::ExpandingRedirect { idx: 0 };
return false;
}
}
true
}

pub(crate) fn reject_unbufferable_body(
body: &crate::webcore::body::Value,
global: &crate::jsc::JSGlobalObject,
stdin: bool,
) -> crate::jsc::JsResult<()> {
match body {
crate::webcore::body::Value::Locked(_) => {
Err(global.throw_invalid_arguments(format_args!(
"Request/Response body is a ReadableStream, which cannot be redirected in \
Bun Shell yet{}",
if stdin {
". Read it first: $`cmd < ${await response.bytes()}`"
} else {
""
},
)))
}
crate::webcore::body::Value::Used => Err(global
.err(
crate::jsc::ErrorCode::BODY_ALREADY_USED,
format_args!("Body already used"),
)
.throw()),
crate::webcore::body::Value::Error(err) => {
Err(global.throw_value(err.dupe(global).to_js(global)))
}
_ => Ok(()),
}
}
Comment thread
robobun marked this conversation as resolved.
Resolved

fn on_redirect_body_received(
ctx: *mut core::ffi::c_void,
value: *mut crate::webcore::body::Value,
) {
// SAFETY: `ctx` is the `heap::alloc`'d `RedirectBodyBufferCtx`
// installed by `try_buffer_redirect_body`; consumed here.
let mut ctx = unsafe { bun_core::heap::take(ctx.cast::<RedirectBodyBufferCtx>()) };
// SAFETY: the interpreter outlives the run (`has_pending_activity > 0`
// from `run()` to `finish()`), and we are on the JS thread.
let interp = unsafe { &*ctx.interp };
ctx.keep_alive.unref(interp.event_loop.as_event_loop_ctx());
let this = ctx.cmd;
debug_assert!(matches!(
interp.as_cmd(this).state,
CmdState::BufferingRedirectBody
));
// SAFETY: `value` aliases the owning body already written in place by
// the producer; no other borrow is live once we return.
if let crate::webcore::body::Value::Error(err) = unsafe { &*value } {
let global = interp.global_this_ref().expect("buffering only on Js loop");
let js_err = err.dupe(global).to_js(global);
Builtin::cmd_write_failing_error(
interp,
this,
format_args!(
"bun: failed to read Response body for stdin redirect: {}\n",

Check warning on line 462 in src/runtime/shell/states/Cmd.rs

View check run for this annotation

Claude / Claude Code Review

Error message hardcodes 'Response' but redirect may be from a Request

nit: this error message hardcodes "Response body", but `try_buffer_redirect_body` reaches this callback via `from_request_or_response`, so a server-side incoming `Request` (Bun.serve handler's `req`, whose `Locked` body has `task = RequestContext`) that the client aborts mid-upload will print "failed to read Response body" for a Request. `reject_unbufferable_body` already uses the neutral "Request/Response body" wording — consider matching it here (and updating the `/failed to read Response body
Comment thread
robobun marked this conversation as resolved.
Resolved
js_err.fmt_string(global),
),
)
.run(interp);
return;
}
interp.as_cmd_mut(this).state = CmdState::ExpandingArgs { idx: 0 };
Yield::Next(this).run(interp);
Comment thread
robobun marked this conversation as resolved.
Resolved
}
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

pub fn child_done(
interp: &Interpreter,
this: NodeId,
Expand Down Expand Up @@ -764,20 +923,24 @@
}
} else if crate::webcore::ReadableStream::from_js(jsval, global)?.is_some() {
panic!("TODO SHELL READABLE STREAM");
Comment thread
robobun marked this conversation as resolved.
Resolved
} else if let Some(req) = jsval.as_::<crate::webcore::Response>() {
// SAFETY: `as_` returns a live JSC-owned `*mut Response`.
let req = unsafe { &mut *req };
req.get_body_value().to_blob_if_possible();
} else if let Some(body) =
crate::webcore::body::Value::from_request_or_response(jsval)
{
// SAFETY: live JSC-owned `*mut Value` borrowed from the
// Request/Response wrapper while `jsval` is rooted.
let body = unsafe { &mut *body };
body.to_blob_if_possible();
Self::reject_unbufferable_body(body, global, flags.stdin())?;
if flags.stdin() {
let b = req.get_body_value().use_as_any_blob();
let b = body.use_as_any_blob();
stdio[STDIN_NO].extract_blob(global, b, STDIN_NO as i32)?;
}
if flags.stdout() {
let b = req.get_body_value().use_as_any_blob();
let b = body.use_as_any_blob();
stdio[STDOUT_NO].extract_blob(global, b, STDOUT_NO as i32)?;
}
if flags.stderr() {
let b = req.get_body_value().use_as_any_blob();
let b = body.use_as_any_blob();
stdio[STDERR_NO].extract_blob(global, b, STDERR_NO as i32)?;
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
} else {
Expand Down
17 changes: 13 additions & 4 deletions src/runtime/webcore/Blob.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5227,6 +5227,19 @@
"ReadableStream has already been used"
)));
}
// SAFETY: re-borrow after the early-return paths.
let BodyValue::Locked(locked) = (unsafe { &mut *body_value }) else {
unreachable!()
};
if locked.is_disturbed2(global_this) {
destination_blob.detach();
return Err(global_this
.err(
jsc::ErrorCode::BODY_ALREADY_USED,
format_args!("Body already used"),
)
.throw());

Check warning on line 5241 in src/runtime/webcore/Blob.rs

View check run for this annotation

Claude / Claude Code Review

c48deb82 rejection guards (Bun.write / serve / HTMLRewriter) ship without tests

The three rejection guards added in c48deb82 — `Bun.write` now throwing `ERR_BODY_ALREADY_USED` when a native receiver is installed (Blob.rs:5234-5241), `do_render_with_body` rendering 204 (RequestContext.rs:3252-3254), and `ValueBufferer` returning `StreamAlreadyUsed` (Body.rs:2538-2540) — ship without tests; the added bunshell.test.ts cases only exercise shell-side paths, so deleting the `is_disturbed2` check in Blob.rs would not fail anything in this PR. A cheap test like ``const p = $`cat <
Comment thread
robobun marked this conversation as resolved.
Resolved
}
let task =
bun_core::heap::into_raw(Box::new(WriteFileWaitFromLockedValueTask {
global_this: bun_ptr::BackRef::new(global_this),
Expand All @@ -5238,10 +5251,6 @@
promise: jsc::JSPromiseStrong::init(global_this),
mkdirp_if_not_exists: options.mkdirp_if_not_exists.unwrap_or(true),
}));
// SAFETY: re-borrow after the early-return paths.
let BodyValue::Locked(locked) = (unsafe { &mut *body_value }) else {
unreachable!()
};
locked.task = Some(task.cast::<c_void>());
locked.on_receive_value = Some(WriteFileWaitFromLockedValueTask::then_wrap);
Comment thread
robobun marked this conversation as resolved.
Resolved
// SAFETY: `task` was just heap-allocated; consumed in `then_wrap`.
Expand Down
Loading
Loading