Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 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
3 changes: 3 additions & 0 deletions src/runtime/shell/Builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -732,6 +732,9 @@ impl Builtin {
// SAFETY: returned a live JSC-owned `*mut Value` borrowed
// from a Response/Request wrapper.
let body = unsafe { &mut *body };
if crate::shell::util::check_body_for_redirect(body, global).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 {
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 @@ -467,7 +467,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() {
Comment thread
robobun marked this conversation as resolved.
Resolved
let idx = out_jsobjs.len();
marked_argument_buffer.append(template_value);
out_jsobjs.push(template_value);
Expand Down
17 changes: 10 additions & 7 deletions src/runtime/shell/states/Cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -766,20 +766,23 @@ impl Cmd {
}
} else if crate::webcore::ReadableStream::from_js(jsval, global)?.is_some() {
panic!("TODO SHELL READABLE STREAM");
} 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: returns a live JSC-owned `*mut Value` borrowed
// from the Request/Response wrapper while `jsval` is rooted.
let body = unsafe { &mut *body };
crate::shell::util::check_body_for_redirect(body, global)?;
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)?;
}
} else {
Expand Down
31 changes: 31 additions & 0 deletions src/runtime/shell/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,34 @@
// low-level `PosixStdio`/`WindowsStdio` spawn-option shape that the
// `bun_spawn` *crate* re-exports under the same name.
pub use crate::api::bun_spawn::stdio::Stdio;

/// Reject a Request/Response body that cannot be used as a shell redirect.
///
/// Called after `from_request_or_response`; runs `to_blob_if_possible()` so a
/// native-backed stream (Bun.file, Blob.stream()) is converted first. After
/// that, `Locked` (a JS-driven ReadableStream), `Used` and `Error` all have no
/// synchronous bytes to hand to the command, and `use_as_any_blob()` / `use_()`
/// would substitute an empty `Blob` for each of them, so the command would run
/// on zero bytes and succeed.
pub fn check_body_for_redirect(
body: &mut crate::webcore::body::Value,
global: &crate::jsc::JSGlobalObject,
) -> crate::jsc::JsResult<()> {
body.to_blob_if_possible();
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. Read it first: $`cmd < ${{await response.bytes()}}`"
)))

Check warning on line 31 in src/runtime/shell/util.rs

View check run for this annotation

Claude / Claude Code Review

Locked-body error message gives stdin-specific remedy for stdout/stderr redirects

`check_body_for_redirect` is called before the `flags.stdin()`/`stdout()`/`stderr()` branches at both call sites, so ``echo hi > ${new Response(stream)}`` throws with the stdin-only remedy `` Read it first: $`cmd < ${await response.bytes()}` `` — which is nonsensical for an output redirect. Consider either passing the direction into the helper and dropping the hint for stdout/stderr, or only running this check on the stdin path and letting the existing "immutable blob" guard handle output. The p
Comment thread
robobun marked this conversation as resolved.
Resolved
}
crate::webcore::body::Value::Used => Err(global
.err(
crate::jsc::ErrorCode::BODY_ALREADY_USED,
format_args!("Body already used"),
)
.throw()),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
crate::webcore::body::Value::Error(err) => Err(global.throw_value(err.to_js(global))),

Check warning on line 39 in src/runtime/shell/util.rs

View check run for this annotation

Claude / Claude Code Review

Value::Error arm of check_body_for_redirect is untested

The new tests cover the `Locked` (3 flavors) and `Used` arms of `check_body_for_redirect`, but the `Value::Error(err) => throw_value(err.to_js(global))` arm has no test. REVIEW.md § Tests: *"Cover the variant matrix, not just the repro … error paths"*. If `Value::Error` is reachable at redirect-setup time (e.g. a `Response` whose body was put into the error state by a prior failed read), add a test asserting the stored error is rethrown; if it is not reachable from JS, a one-line comment on the
Comment thread
robobun marked this conversation as resolved.
Resolved
_ => Ok(()),
}
}
63 changes: 63 additions & 0 deletions test/js/bun/shell/bunshell.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1666,6 +1666,69 @@ describe("deno_task", () => {
TestBuilder.command`BUN_DEBUG_QUIET_LOGS=1 ${BUN} -e ${code} > /dev/null`
.quiet()
.runAsTest("bunception redirect /dev/null");

describe("stdin from Request/Response", () => {
const P = "hello-shell-stdin-0123456789";

// A Response whose body is a JS-driven ReadableStream cannot be drained
// synchronously at redirect setup time. It used to be substituted with an
// empty blob, so the command ran on zero bytes and reported success.
describe.each([
[
"ReadableStream start()",
() =>
new ReadableStream({
start(c) {
c.enqueue(new TextEncoder().encode(P));
c.close();
},
}),
],
[
"TransformStream readable",
() => {
const ts = new TransformStream();
const w = ts.writable.getWriter();
w.write(new TextEncoder().encode(P));
w.close();
return ts.readable;
},
],
[
"async generator",
() =>
(async function* () {
yield P;
})(),
],
])("Response(%s) as stdin", (_name, body) => {
test("rejects instead of delivering zero bytes", async () => {
await expect($`cat < ${new Response(body())}`.text()).rejects.toThrow(/body is a ReadableStream/);
});
});

test("Response with an already-consumed body rejects", async () => {
const res = new Response(P);
await res.text();
await expect($`cat < ${res}`.text()).rejects.toThrow(/already used/i);
});

test("Response with a string body still works", async () => {
const { stdout } = await $`cat < ${new Response(P)}`;
expect(stdout.toString()).toBe(P);
});

test("Response with a Blob body still works", async () => {
const { stdout } = await $`cat < ${new Response(new Blob([P]))}`;
expect(stdout.toString()).toBe(P);
});

test("Request as stdin", async () => {
const req = new Request("http://example.com", { method: "POST", body: P });
const { stdout } = await $`cat < ${req}`;
expect(stdout.toString()).toBe(P);
});
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
});

describe("pwd", async () => {
Expand Down
Loading