Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 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 @@ pub enum OutKind {
// 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()}}`"
)))
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))),
Comment thread
robobun marked this conversation as resolved.
Resolved
_ => Ok(()),
}
}
67 changes: 67 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,73 @@ 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";
const wrap = {
Response: (b: BodyInit) => new Response(b),
Request: (b: BodyInit) => new Request("http://example.com", { method: "POST", body: b }),
} as const;

// A Request/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. On POSIX `cat` resolves to a spawned subprocess
// (Cmd::init_subproc_redirections); on Windows it is the shell builtin
// (Builtin::init_redirections); both paths route through
// check_body_for_redirect.
describe.each(["Response", "Request"] as const)("%s", kind => {
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;
})(),
],
])("with a %s body", (_name, body) => {
test("rejects instead of delivering zero bytes", async () => {
await expect($`cat < ${wrap[kind](body())}`.text()).rejects.toThrow(/body is a ReadableStream/);
});
});

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

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

test("with a Blob body still works", async () => {
const { stdout } = await $`cat < ${wrap[kind](new Blob([P]))}`;
expect(stdout.toString()).toBe(P);
});
});
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
});

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