Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 2 additions & 0 deletions crates/bashkit-js/test-fixtures/random-fs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ impl SeededRandomFs {
};
let timestamp = UNIX_EPOCH + Duration::from_secs(self.seed % 86_400);
Some(Metadata {
uid: 1000,
gid: 1000,
file_type,
size,
mode: if file_type.is_dir() { 0o755 } else { 0o644 },
Expand Down
2 changes: 2 additions & 0 deletions crates/bashkit-python/test-fixtures/random-fs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ impl SeededRandomFs {
};
let timestamp = UNIX_EPOCH + Duration::from_secs(self.seed % 86_400);
Some(Metadata {
uid: 1000,
gid: 1000,
file_type,
size,
mode: if file_type.is_dir() { 0o755 } else { 0o644 },
Expand Down
21 changes: 19 additions & 2 deletions crates/bashkit-wasm/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,25 @@ const out = await bash.execute('echo "{ me { id } }" | graphql | jq .data');
console.log(out.stdout);
```

`ctx` is `{ name, argv, stdin, env, cwd, fs }`. Return the builtin's stdout as a
string (or a `Promise<string>`); throwing becomes stderr with exit code 1.
`ctx` is `{ name, argv, stdin, env, cwd, fs }`. Return stdout as a string, or
`{ stdout, stderr, exitCode }` with optional fields defaulting to empty streams
and status 0. Either result can be returned via a Promise. Nonzero status drives
`$?`, `if`, `&&`/`||`, and `set -e` without generating a diagnostic; throwing
still becomes stderr with exit code 1.

```js
const bash = new Bash({
customBuiltins: { check: () => ({ exitCode: 1 }) },
});
await bash.execute('check; echo $?'); // stdout: "1\n", stderr: ""
```

Host filesystem `stat` and `readDir` entries may also report `uid` and `gid`
(unsigned 32-bit integers, default 1000). Ownership tests `-O` and `-G` compare
them against sandbox user/group 1000; this does not enable permission enforcement.
Omitting these fields preserves the single-user model. Supplying a negative,
fractional, non-finite, non-numeric or out-of-range ID fails the metadata operation.
Extra properties on a structured custom-builtin result are ignored.

`ctx.fs` is a live handle to the **same** virtual filesystem the script sees, so
a builtin can read inputs and write outputs that later commands pick up:
Expand Down
40 changes: 40 additions & 0 deletions crates/bashkit-wasm/__test__/bashkit-wasm.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,37 @@ await initBashkit(wasmBytes);

// --- Sync execution --------------------------------------------------------

test("compat: bracket function overrides the builtin", () => {
const bash = new Bash();
const r = bash.executeSync('[() { echo override; return 7; }; [ x ]; echo status=$?');
assert.equal(r.stdout, "override\nstatus=7\n");
assert.equal(r.stderr, "");
});

test("compat: structured builtin results preserve output and status", async () => {
for (const asyncCallback of [false, true]) {
const result = { stdout: "out\n", stderr: "err\n", exitCode: 7, extra: "host metadata" };
const bash = new Bash({
customBuiltins: { probe: asyncCallback ? async () => result : () => result },
});
const r = await bash.execute('probe; echo status=$?; probe && echo wrong || echo failed');
assert.equal(r.stdout, "out\nstatus=7\nout\nfailed\n");
assert.equal(r.stderr, "err\nerr\n");
assert.equal((await bash.execute('probe')).exitCode, 7);
if (!asyncCallback) assert.equal(bash.executeSync('probe').exitCode, 7);
const stopped = await bash.execute('set -e; probe; echo unreachable');
assert.equal(stopped.exitCode, 7);
assert.equal(stopped.stdout, "out\n");
}
});

test("compat: false custom test is silent and drives shell control flow", async () => {
const bash = new Bash({ customBuiltins: { '[': () => ({ stdout: undefined, stderr: undefined, exitCode: 1 }) } });
const r = await bash.execute('[ x ]; echo status=$?; if [ x ]; then echo wrong; else echo false; fi');
assert.equal(r.stdout, "status=1\nfalse\n");
assert.equal(r.stderr, "");
});

test("sync: pipes and text tools", () => {
const bash = new Bash();
const r = bash.executeSync('echo "hello world" | tr a-z A-Z');
Expand Down Expand Up @@ -68,6 +99,15 @@ test("sync: binary stdout bytes are exact", () => {
});

// --- Child shell (bash / sh builtin) ---------------------------------------
test("compat: invalid builtin results fail with a plain diagnostic", async () => {
for (const result of [null, 7, { exitCode: 1.5 }, { exitCode: NaN }, { stdout: 7 }]) {
const bash = new Bash({ customBuiltins: { probe: () => result } });
const r = await bash.execute('probe');
assert.equal(r.exitCode, 1);
assert.match(r.stderr, /^probe: expected a stdout string or/);
}
});

// Regression: the bash/sh builtin re-parses its child script. On
// wasm32-unknown-unknown that parse must run inline — the native path wraps it
// in tokio::time::timeout + spawn_blocking, whose timer calls std::time, which
Expand Down
26 changes: 26 additions & 0 deletions crates/bashkit-wasm/__test__/host-fs.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,33 @@ class FakeHost {
const hostBash = (host, options = {}) =>
new Bash({ fs: host, cwd: "/workspace", ...options });

test("compat: host ownership controls -O and -G independently", async () => {
const host = new FakeHost({ '/workspace/f': 'data' });
const originalStat = host.stat.bind(host);
for (const [uid, gid, expected] of [
[0, 0, '1:1'], [1000, 0, '0:1'], [0, 1000, '1:0'], [1000, 1000, '0:0'],
[undefined, undefined, '0:0'],
]) {
host.stat = async (path) => ({ ...await originalStat(path), uid, gid });
const r = await hostBash(host).execute('[ -O f ]; o=$?; [ -G f ]; echo "$o:$?"; [[ -O f ]]; o=$?; [[ -G f ]]; echo "$o:$?"');
assert.equal(r.stdout, `${expected}\n${expected}\n`);
assert.equal(r.stderr, '');
}
const missing = await hostBash(host).execute('[ -O absent ]; echo $?; [ -G absent ]; echo $?; [[ -O absent ]]; echo $?; [[ -G absent ]]; echo $?');
assert.equal(missing.stdout, '1\n1\n1\n1\n');
});

// --- Reads and writes ------------------------------------------------------
test("compat: invalid host owner IDs are rejected instead of truncated", async () => {
for (const uid of [-1, 0.5, NaN, Infinity, 2 ** 32, '1000', null]) {
const host = new FakeHost({ '/workspace/f': 'data' });
const stat = host.stat.bind(host);
host.stat = async (path) => ({ ...await stat(path), uid });
const r = await hostBash(host).execute('stat f');
assert.notEqual(r.exitCode, 0);
}
});


test("host fs: a redirect lands in the host store", async () => {
const host = new FakeHost();
Expand Down
28 changes: 23 additions & 5 deletions crates/bashkit-wasm/js/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,22 @@ export interface BuiltinRequest {
readonly fs: FileSystem;
}

/** Buffered command result. Omitted streams are empty; extra host properties are ignored. */
export interface BuiltinResult {
readonly stdout?: string;
readonly stderr?: string;
/** Command status; defaults to 0. */
readonly exitCode?: number;
}
/**
* A JS callback registered as a bash builtin. Return the builtin's stdout, or a
* `Promise` of it. Async callbacks are only awaited by {@link Bash.execute}
* (not `executeSync`). Throwing / rejecting becomes stderr with exit code 1.
* A JS callback registered as a bash builtin. Return stdout or a structured
* result, directly or via `Promise`. Async callbacks are only awaited by
* {@link Bash.execute} (not `executeSync`). Throwing / rejecting becomes
* stderr with exit code 1.
*/
export type CustomBuiltin = (ctx: BuiltinRequest) => string | Promise<string>;
export type CustomBuiltin = (
ctx: BuiltinRequest,
) => string | BuiltinResult | Promise<string | BuiltinResult>;

/** Live byte I/O; handles are revoked when their execution ends. */
export interface CommandContext {
Expand Down Expand Up @@ -75,13 +85,21 @@ export declare const ExecutionProfile: Readonly<{
/** Entry kind reported by a {@link HostFileSystem}. */
export type HostFileType = "file" | "dir" | "directory" | "symlink" | "fifo";

/** Metadata a {@link HostFileSystem} reports for one entry. */
/**
* Metadata a {@link HostFileSystem} reports for one entry. Omitting uid/gid
* preserves the single-user model (1000); malformed supplied IDs fail the
* metadata operation. IDs must be integers from 0 through 4294967295.
*/
export interface HostStat {
readonly type: HostFileType;
/** Size in bytes. Defaults to 0. */
readonly size?: number;
/** Unix permission bits. Defaults to 0o644 for files, 0o755 for directories. */
readonly mode?: number;
/** Owner user ID. Defaults to the sandbox user (1000). */
readonly uid?: number;
/** Owner group ID. Defaults to the sandbox group (1000). */
readonly gid?: number;
/** Last modification time, ms since the epoch. Defaults to now. */
readonly mtimeMs?: number;
}
Expand Down
12 changes: 12 additions & 0 deletions crates/bashkit-wasm/src/hostfs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,8 @@ fn parse_metadata(value: &JsValue) -> Option<Metadata> {
let default_mode = if file_type.is_dir() { 0o755 } else { 0o644 };
Some(Metadata {
file_type,
uid: owner_id(value, "uid")?,
gid: owner_id(value, "gid")?,
size: get(value, "size").and_then(|v| v.as_f64()).unwrap_or(0.0) as u64,
mode: get(value, "mode")
.and_then(|v| v.as_f64())
Expand All @@ -303,6 +305,16 @@ fn parse_metadata(value: &JsValue) -> Option<Metadata> {
})
}

fn owner_id(value: &JsValue, key: &str) -> Option<u32> {
let value = get(value, key)?;
if value.is_undefined() {
return Some(1000);
}
let id = value.as_f64()?;
(id.is_finite() && id.fract() == 0.0 && (0.0..=u32::MAX as f64).contains(&id))
.then_some(id as u32)
}

fn from_epoch_ms(ms: f64) -> SystemTime {
let ms = if ms.is_finite() && ms > 0.0 { ms } else { 0.0 };
UNIX_EPOCH + std::time::Duration::from_millis(ms as u64)
Expand Down
31 changes: 28 additions & 3 deletions crates/bashkit-wasm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ use bashkit::{
};
use futures_util::future::FutureExt;
use send_wrapper::SendWrapper;
use serde::Serialize;
use serde::{Deserialize, Serialize};
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::{JsFuture, future_to_promise};

Expand Down Expand Up @@ -216,10 +216,18 @@ struct BuiltinRequest<'a> {
cwd: String,
}

#[derive(Deserialize, Default)]
#[serde(rename_all = "camelCase", default)]
struct BuiltinResult {
stdout: Option<String>,
stderr: Option<String>,
exit_code: Option<i32>,
}

/// Adapts a JS callback into a bash `Builtin`.
///
/// The callback receives one argument (a `BuiltinRequest` object) and returns
/// either a `string` or a `Promise<string>` resolving to the builtin's stdout.
/// a stdout string or `{ stdout?, stderr?, exitCode? }`, directly or via Promise.
/// Throwing / rejecting becomes stderr with exit code 1.
struct JsBuiltin {
name: String,
Expand Down Expand Up @@ -302,7 +310,24 @@ impl Builtin for JsBuiltin {
Err(v) => v,
};

Ok(CoreExecResult::ok(resolved.as_string().unwrap_or_default()))
if let Some(stdout) = resolved.as_string() {
return Ok(CoreExecResult::ok(stdout));
}
match serde_wasm_bindgen::from_value::<BuiltinResult>(resolved) {
Ok(result) => Ok(CoreExecResult {
stdout: result.stdout.unwrap_or_default().into(),
stderr: result.stderr.unwrap_or_default().into(),
exit_code: result.exit_code.unwrap_or_default(),
..CoreExecResult::default()
}),
Err(_) => Ok(CoreExecResult::err(
format!(
"{}: expected a stdout string or {{ stdout?, stderr?, exitCode? }} result\n",
self.name
),
1,
)),
}
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Host shell compatibility: filesystem overhead

Local Criterion comparison on macOS arm64, Rust 1.100.0. Baseline is
`290ebb01` (main); candidate is the ownership/bracket-function/WASM-result
change. Both runs use the same target directory, default features, 10 samples,
1-second warmup and 1-second measurement. This is a narrow local comparison,
not a full parallel-scaling run; other validation builds were active.

```sh
cargo bench -p bashkit --bench parallel_execution -- single_file_write_read \
--sample-size 10 --warm-up-time 1 --measurement-time 1 --save-baseline compat-before
cargo bench -p bashkit --bench parallel_execution -- single_file_write_read \
--sample-size 10 --warm-up-time 1 --measurement-time 1 --baseline compat-before
```

| Benchmark | Before | After | Change |
| --- | --- | --- | --- |
| single_file_write_read | 41.961 µs | 42.349 µs | +0.6296% |

Candidate 95% interval: 42.268–42.441 µs. Relative-change 95% interval:
−0.2007% to +1.4212%.

Criterion reports no statistically significant performance change
(`p = 0.16`). This covers the metadata-layout change's basic VFS path; semantic
regressions are covered by the native specs, RealFs suite and WASM integration tests.
6 changes: 6 additions & 0 deletions crates/bashkit/examples/custom_backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,13 +156,17 @@ impl FsBackend for SimpleStorage {

match entries.get(&path) {
Some(StorageEntry::File(content)) => Ok(Metadata {
uid: 1000,
gid: 1000,
file_type: FileType::File,
size: content.len() as u64,
mode: 0o644,
modified: SystemTime::now(),
created: SystemTime::now(),
}),
Some(StorageEntry::Directory) => Ok(Metadata {
uid: 1000,
gid: 1000,
file_type: FileType::Directory,
size: 0,
mode: 0o755,
Expand Down Expand Up @@ -204,6 +208,8 @@ impl FsBackend for SimpleStorage {
result.push(DirEntry {
name: name.to_string(),
metadata: Metadata {
uid: 1000,
gid: 1000,
file_type,
size,
mode: 0o644,
Expand Down
6 changes: 6 additions & 0 deletions crates/bashkit/examples/custom_filesystem_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,8 @@ impl FileSystem for SessionFileSystemAdapter {
if let Some(content) = files.get(&path) {
let is_dir = content.is_empty() && self.store.is_directory(&path);
Ok(Metadata {
uid: 1000,
gid: 1000,
file_type: if is_dir {
FileType::Directory
} else {
Expand Down Expand Up @@ -271,6 +273,8 @@ impl FileSystem for SessionFileSystemAdapter {
entries.push(DirEntry {
name: name.to_string(),
metadata: Metadata {
uid: 1000,
gid: 1000,
file_type: FileType::Directory,
size: 0,
mode: 0o755,
Expand All @@ -284,6 +288,8 @@ impl FileSystem for SessionFileSystemAdapter {
entries.push(DirEntry {
name: remainder.to_string(),
metadata: Metadata {
uid: 1000,
gid: 1000,
file_type: if is_dir {
FileType::Directory
} else {
Expand Down
4 changes: 3 additions & 1 deletion crates/bashkit/src/builtins/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,9 @@ pub use split::Split;
pub use strings::Strings;
pub use sysextra::{Arch, Free, Getconf, Hostid, RunAs, SyncCmd, Tty, Uptime, UserInfo};
pub use system::{DEFAULT_HOSTNAME, DEFAULT_USERNAME, Hostname, Id, Nproc, Uname, Whoami};
pub(crate) use system::{VIRTUAL_KERNEL_RELEASE, VIRTUAL_KERNEL_VERSION, VIRTUAL_NPROC};
pub(crate) use system::{
SANDBOX_GID, SANDBOX_UID, VIRTUAL_KERNEL_RELEASE, VIRTUAL_KERNEL_VERSION, VIRTUAL_NPROC,
};
pub use template::Template;
pub use test::{Bracket, Test};
pub use textrev::{Rev, Tac};
Expand Down
10 changes: 7 additions & 3 deletions crates/bashkit/src/builtins/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -456,11 +456,15 @@ async fn evaluate_unary(op: &str, arg: &str, env: &Env<'_>) -> TestResult {
let path = resolve_file_path(cwd, arg);
Ok(fs.stat(&path).await.is_ok_and(|meta| meta.mode & bit != 0))
}
// Owned by the effective user / group: the sandbox user owns every
// file, so this is "exists".
"-O" | "-G" => {
let path = resolve_file_path(cwd, arg);
Ok(fs.exists(&path).await.unwrap_or(false))
Ok(fs.stat(&path).await.is_ok_and(|meta| {
if op == "-O" {
meta.uid == super::system::SANDBOX_UID
} else {
meta.gid == super::system::SANDBOX_GID
}
}))
}
"-S" => Ok(false), // socket (not supported)
"-b" => Ok(false), // block device (not supported)
Expand Down
Loading
Loading