From 2d740674221298fae0a4fc5c39056e96a36d6d78 Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Sat, 21 Nov 2026 20:10:20 -0600 Subject: [PATCH 1/2] fix(wasm): unblock host-backed shell compatibility --- .../test-fixtures/random-fs/src/lib.rs | 2 + .../test-fixtures/random-fs/src/lib.rs | 2 + crates/bashkit-wasm/README.md | 18 +++++++- .../__test__/bashkit-wasm.test.mjs | 40 +++++++++++++++++ crates/bashkit-wasm/__test__/host-fs.test.mjs | 26 +++++++++++ crates/bashkit-wasm/js/index.d.ts | 22 ++++++++-- crates/bashkit-wasm/src/hostfs.rs | 12 +++++ crates/bashkit-wasm/src/lib.rs | 31 +++++++++++-- ...lel-shell-compat-macos-arm64-1795313253.md | 25 +++++++++++ crates/bashkit/examples/custom_backend.rs | 6 +++ .../examples/custom_filesystem_impl.rs | 6 +++ crates/bashkit/src/builtins/mod.rs | 4 +- crates/bashkit/src/builtins/test.rs | 10 +++-- crates/bashkit/src/fs/memory.rs | 44 +++++++++++++++++++ crates/bashkit/src/fs/mountable.rs | 2 + crates/bashkit/src/fs/namespace.rs | 2 + crates/bashkit/src/fs/proc_sub_fds.rs | 2 + crates/bashkit/src/fs/realfs.rs | 9 ++++ crates/bashkit/src/fs/rootfs.rs | 2 + crates/bashkit/src/fs/std_streams.rs | 2 + crates/bashkit/src/fs/traits.rs | 10 +++++ crates/bashkit/src/interop/fs.rs | 2 + crates/bashkit/src/interpreter/mod.rs | 7 +++ crates/bashkit/src/parser/lexer.rs | 5 +++ .../tests/integration/custom_fs_tests.rs | 6 +++ .../tests/integration/dev_null_tests.rs | 4 ++ crates/bashkit/tests/realfs_tests.rs | 18 ++++++++ .../tests/spec_cases/bash/functions.test.sh | 10 +++++ docs/filesystem.md | 12 +++++ docs/start-browser.md | 12 +++++ knowledge/foundations/parser.md | 5 +++ knowledge/foundations/vfs.md | 9 ++++ knowledge/log.md | 4 ++ knowledge/operations/limitations.md | 2 +- knowledge/runtimes/browser-package.md | 14 ++++++ site/src/data/performance-timeline.json | 37 +++++++++++++++- 36 files changed, 408 insertions(+), 16 deletions(-) create mode 100644 crates/bashkit/benches/results/criterion-parallel-shell-compat-macos-arm64-1795313253.md diff --git a/crates/bashkit-js/test-fixtures/random-fs/src/lib.rs b/crates/bashkit-js/test-fixtures/random-fs/src/lib.rs index e6198fde5..210e0003f 100644 --- a/crates/bashkit-js/test-fixtures/random-fs/src/lib.rs +++ b/crates/bashkit-js/test-fixtures/random-fs/src/lib.rs @@ -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 }, diff --git a/crates/bashkit-python/test-fixtures/random-fs/src/lib.rs b/crates/bashkit-python/test-fixtures/random-fs/src/lib.rs index c2c77bf4a..754933257 100644 --- a/crates/bashkit-python/test-fixtures/random-fs/src/lib.rs +++ b/crates/bashkit-python/test-fixtures/random-fs/src/lib.rs @@ -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 }, diff --git a/crates/bashkit-wasm/README.md b/crates/bashkit-wasm/README.md index 90625544a..fcdc80b06 100644 --- a/crates/bashkit-wasm/README.md +++ b/crates/bashkit-wasm/README.md @@ -79,8 +79,22 @@ 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`); 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. `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: diff --git a/crates/bashkit-wasm/__test__/bashkit-wasm.test.mjs b/crates/bashkit-wasm/__test__/bashkit-wasm.test.mjs index 6e752bb47..77d994f65 100644 --- a/crates/bashkit-wasm/__test__/bashkit-wasm.test.mjs +++ b/crates/bashkit-wasm/__test__/bashkit-wasm.test.mjs @@ -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 }; + 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'); @@ -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 diff --git a/crates/bashkit-wasm/__test__/host-fs.test.mjs b/crates/bashkit-wasm/__test__/host-fs.test.mjs index 72468d050..ca5c26fbf 100644 --- a/crates/bashkit-wasm/__test__/host-fs.test.mjs +++ b/crates/bashkit-wasm/__test__/host-fs.test.mjs @@ -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(); diff --git a/crates/bashkit-wasm/js/index.d.ts b/crates/bashkit-wasm/js/index.d.ts index 916c975ef..537dcfda6 100644 --- a/crates/bashkit-wasm/js/index.d.ts +++ b/crates/bashkit-wasm/js/index.d.ts @@ -30,12 +30,22 @@ export interface BuiltinRequest { readonly fs: FileSystem; } +/** Buffered command result. Omitted streams are empty. */ +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; +export type CustomBuiltin = ( + ctx: BuiltinRequest, +) => string | BuiltinResult | Promise; /** Live byte I/O; handles are revoked when their execution ends. */ export interface CommandContext { @@ -82,6 +92,10 @@ export interface HostStat { 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; } diff --git a/crates/bashkit-wasm/src/hostfs.rs b/crates/bashkit-wasm/src/hostfs.rs index 16f73c103..356df9ec2 100644 --- a/crates/bashkit-wasm/src/hostfs.rs +++ b/crates/bashkit-wasm/src/hostfs.rs @@ -292,6 +292,8 @@ fn parse_metadata(value: &JsValue) -> Option { 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()) @@ -303,6 +305,16 @@ fn parse_metadata(value: &JsValue) -> Option { }) } +fn owner_id(value: &JsValue, key: &str) -> Option { + 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) diff --git a/crates/bashkit-wasm/src/lib.rs b/crates/bashkit-wasm/src/lib.rs index 12de543d5..639938159 100644 --- a/crates/bashkit-wasm/src/lib.rs +++ b/crates/bashkit-wasm/src/lib.rs @@ -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}; @@ -216,10 +216,18 @@ struct BuiltinRequest<'a> { cwd: String, } +#[derive(Deserialize, Default)] +#[serde(rename_all = "camelCase", default, deny_unknown_fields)] +struct BuiltinResult { + stdout: Option, + stderr: Option, + exit_code: Option, +} + /// Adapts a JS callback into a bash `Builtin`. /// /// The callback receives one argument (a `BuiltinRequest` object) and returns -/// either a `string` or a `Promise` 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, @@ -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::(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, + )), + } } } diff --git a/crates/bashkit/benches/results/criterion-parallel-shell-compat-macos-arm64-1795313253.md b/crates/bashkit/benches/results/criterion-parallel-shell-compat-macos-arm64-1795313253.md new file mode 100644 index 000000000..34b1793d8 --- /dev/null +++ b/crates/bashkit/benches/results/criterion-parallel-shell-compat-macos-arm64-1795313253.md @@ -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. diff --git a/crates/bashkit/examples/custom_backend.rs b/crates/bashkit/examples/custom_backend.rs index 9df224459..74486fa07 100644 --- a/crates/bashkit/examples/custom_backend.rs +++ b/crates/bashkit/examples/custom_backend.rs @@ -156,6 +156,8 @@ 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, @@ -163,6 +165,8 @@ impl FsBackend for SimpleStorage { created: SystemTime::now(), }), Some(StorageEntry::Directory) => Ok(Metadata { + uid: 1000, + gid: 1000, file_type: FileType::Directory, size: 0, mode: 0o755, @@ -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, diff --git a/crates/bashkit/examples/custom_filesystem_impl.rs b/crates/bashkit/examples/custom_filesystem_impl.rs index 1a1a17241..482fd387f 100644 --- a/crates/bashkit/examples/custom_filesystem_impl.rs +++ b/crates/bashkit/examples/custom_filesystem_impl.rs @@ -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 { @@ -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, @@ -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 { diff --git a/crates/bashkit/src/builtins/mod.rs b/crates/bashkit/src/builtins/mod.rs index d6a2f4197..dd76990da 100644 --- a/crates/bashkit/src/builtins/mod.rs +++ b/crates/bashkit/src/builtins/mod.rs @@ -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}; diff --git a/crates/bashkit/src/builtins/test.rs b/crates/bashkit/src/builtins/test.rs index d9703b0cf..ddadd5c14 100644 --- a/crates/bashkit/src/builtins/test.rs +++ b/crates/bashkit/src/builtins/test.rs @@ -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) diff --git a/crates/bashkit/src/fs/memory.rs b/crates/bashkit/src/fs/memory.rs index 57d08f96a..14fd31dd9 100644 --- a/crates/bashkit/src/fs/memory.rs +++ b/crates/bashkit/src/fs/memory.rs @@ -452,6 +452,8 @@ impl InMemoryFs { PathBuf::from("/"), FsEntry::Directory { metadata: Metadata { + uid: 1000, + gid: 1000, file_type: FileType::Directory, size: 0, mode: 0o755, @@ -467,6 +469,8 @@ impl InMemoryFs { PathBuf::from(dir), FsEntry::Directory { metadata: Metadata { + uid: 1000, + gid: 1000, file_type: FileType::Directory, size: 0, // `/tmp` is world-writable and sticky, as on Linux. @@ -485,6 +489,8 @@ impl InMemoryFs { FsEntry::File { content: Vec::new(), metadata: Metadata { + uid: 1000, + gid: 1000, file_type: FileType::File, size: 0, mode: 0o666, @@ -501,6 +507,8 @@ impl InMemoryFs { FsEntry::File { content: Vec::new(), metadata: Metadata { + uid: 1000, + gid: 1000, file_type: FileType::File, size: 0, mode: 0o666, @@ -516,6 +524,8 @@ impl InMemoryFs { PathBuf::from("/dev/fd"), FsEntry::Directory { metadata: Metadata { + uid: 1000, + gid: 1000, file_type: FileType::Directory, size: 0, mode: 0o755, @@ -818,6 +828,8 @@ impl InMemoryFs { FsEntry::File { content: content.clone(), metadata: Metadata { + uid: 1000, + gid: 1000, file_type: FileType::File, size: content.len() as u64, mode: entry.mode, @@ -832,6 +844,8 @@ impl InMemoryFs { entry.path.clone(), FsEntry::Directory { metadata: Metadata { + uid: 1000, + gid: 1000, file_type: FileType::Directory, size: 0, mode: entry.mode, @@ -847,6 +861,8 @@ impl InMemoryFs { FsEntry::Symlink { target: target.clone(), metadata: Metadata { + uid: 1000, + gid: 1000, file_type: FileType::Symlink, size: 0, mode: entry.mode, @@ -862,6 +878,8 @@ impl InMemoryFs { FsEntry::Fifo { content: Vec::new(), metadata: Metadata { + uid: 1000, + gid: 1000, file_type: FileType::Fifo, size: 0, mode: entry.mode, @@ -938,6 +956,8 @@ impl InMemoryFs { current.clone(), FsEntry::Directory { metadata: Metadata { + uid: 1000, + gid: 1000, file_type: FileType::Directory, size: 0, mode: 0o755, @@ -955,6 +975,8 @@ impl InMemoryFs { FsEntry::File { content: content.to_vec(), metadata: Metadata { + uid: 1000, + gid: 1000, file_type: FileType::File, size: content.len() as u64, mode, @@ -977,6 +999,8 @@ impl InMemoryFs { FsEntry::Symlink { target, metadata: Metadata { + uid: 1000, + gid: 1000, file_type: FileType::Symlink, size, mode: 0o777, @@ -1039,6 +1063,8 @@ impl InMemoryFs { current.clone(), FsEntry::Directory { metadata: Metadata { + uid: 1000, + gid: 1000, file_type: FileType::Directory, size: 0, mode, @@ -1104,6 +1130,8 @@ impl InMemoryFs { current.clone(), FsEntry::Directory { metadata: Metadata { + uid: 1000, + gid: 1000, file_type: FileType::Directory, size: 0, mode: 0o755, @@ -1121,6 +1149,8 @@ impl InMemoryFs { FsEntry::LazyFile { loader, metadata: Metadata { + uid: 1000, + gid: 1000, file_type: FileType::File, size: size_hint, mode, @@ -1301,6 +1331,8 @@ impl FileSystem for InMemoryFs { FsEntry::Fifo { content: content.to_vec(), metadata: Metadata { + uid: 1000, + gid: 1000, file_type: FileType::Fifo, size: content.len() as u64, mode: 0o644, @@ -1315,6 +1347,8 @@ impl FileSystem for InMemoryFs { FsEntry::File { content: content.to_vec(), metadata: Metadata { + uid: 1000, + gid: 1000, file_type: FileType::File, size: content.len() as u64, mode: 0o644, @@ -1370,6 +1404,8 @@ impl FileSystem for InMemoryFs { FsEntry::File { content: content.to_vec(), metadata: Metadata { + uid: 1000, + gid: 1000, file_type: FileType::File, size: content.len() as u64, mode: 0o644, @@ -1512,6 +1548,8 @@ impl FileSystem for InMemoryFs { current.clone(), FsEntry::Directory { metadata: Metadata { + uid: 1000, + gid: 1000, file_type: FileType::Directory, size: 0, mode: 0o755, @@ -1551,6 +1589,8 @@ impl FileSystem for InMemoryFs { path, FsEntry::Directory { metadata: Metadata { + uid: 1000, + gid: 1000, file_type: FileType::Directory, size: 0, mode: 0o755, @@ -1837,6 +1877,8 @@ impl FileSystem for InMemoryFs { FsEntry::Symlink { target: target.to_path_buf(), metadata: Metadata { + uid: 1000, + gid: 1000, file_type: FileType::Symlink, size: target_size as u64, mode: 0o777, @@ -1952,6 +1994,8 @@ impl FileSystemExt for InMemoryFs { FsEntry::Fifo { content: Vec::new(), metadata: Metadata { + uid: 1000, + gid: 1000, file_type: FileType::Fifo, size: 0, mode, diff --git a/crates/bashkit/src/fs/mountable.rs b/crates/bashkit/src/fs/mountable.rs index 973eed1e4..ba6d7f381 100644 --- a/crates/bashkit/src/fs/mountable.rs +++ b/crates/bashkit/src/fs/mountable.rs @@ -640,6 +640,8 @@ impl FileSystem for MountableFs { }; for (name, mfs) in children { let metadata = mfs.stat(Path::new("/")).await.unwrap_or_else(|_| Metadata { + uid: 1000, + gid: 1000, file_type: FileType::Directory, size: 0, mode: 0o755, diff --git a/crates/bashkit/src/fs/namespace.rs b/crates/bashkit/src/fs/namespace.rs index 37f9414c8..7312fc9dd 100644 --- a/crates/bashkit/src/fs/namespace.rs +++ b/crates/bashkit/src/fs/namespace.rs @@ -144,6 +144,8 @@ impl NamespaceFsBuilder { mounts, synthetic_dirs, synthetic_metadata: Metadata { + uid: 1000, + gid: 1000, file_type: FileType::Directory, size: 0, mode: 0o755, diff --git a/crates/bashkit/src/fs/proc_sub_fds.rs b/crates/bashkit/src/fs/proc_sub_fds.rs index 45202c934..2a1220e92 100644 --- a/crates/bashkit/src/fs/proc_sub_fds.rs +++ b/crates/bashkit/src/fs/proc_sub_fds.rs @@ -172,6 +172,8 @@ impl ProcSubFs { fn pipe_metadata() -> Metadata { Metadata { + uid: 1000, + gid: 1000, file_type: FileType::Fifo, size: 0, mode: 0o600, diff --git a/crates/bashkit/src/fs/realfs.rs b/crates/bashkit/src/fs/realfs.rs index 9e07fff75..078f00605 100644 --- a/crates/bashkit/src/fs/realfs.rs +++ b/crates/bashkit/src/fs/realfs.rs @@ -472,6 +472,13 @@ fn file_type_from_std(ft: std::fs::FileType) -> FileType { } fn metadata_from_std(m: &std::fs::Metadata) -> Metadata { + #[cfg(unix)] + let (uid, gid) = { + use std::os::unix::fs::MetadataExt; + (m.uid(), m.gid()) + }; + #[cfg(not(unix))] + let (uid, gid) = (1000, 1000); let file_type = file_type_from_std(m.file_type()); let size = if file_type.is_dir() { 0 } else { m.len() }; #[cfg(unix)] @@ -486,6 +493,8 @@ fn metadata_from_std(m: &std::fs::Metadata) -> Metadata { 0o644 }; Metadata { + uid, + gid, file_type, size, mode, diff --git a/crates/bashkit/src/fs/rootfs.rs b/crates/bashkit/src/fs/rootfs.rs index 802e535ec..44068f7c0 100644 --- a/crates/bashkit/src/fs/rootfs.rs +++ b/crates/bashkit/src/fs/rootfs.rs @@ -303,6 +303,8 @@ impl RootFs { fn stub_metadata(&self, name: &str) -> Metadata { Metadata { + uid: 1000, + gid: 1000, file_type: super::traits::FileType::File, size: stub(name).len() as u64, mode: 0o755, diff --git a/crates/bashkit/src/fs/std_streams.rs b/crates/bashkit/src/fs/std_streams.rs index 216ac551e..dbdd373da 100644 --- a/crates/bashkit/src/fs/std_streams.rs +++ b/crates/bashkit/src/fs/std_streams.rs @@ -160,6 +160,8 @@ impl StdStreamsFs { fn stream_metadata(&self) -> Metadata { Metadata { + uid: 1000, + gid: 1000, file_type: FileType::Fifo, size: 0, mode: 0o620, diff --git a/crates/bashkit/src/fs/traits.rs b/crates/bashkit/src/fs/traits.rs index f1aec93e7..39a5b8b3d 100644 --- a/crates/bashkit/src/fs/traits.rs +++ b/crates/bashkit/src/fs/traits.rs @@ -592,6 +592,10 @@ pub struct Metadata { pub size: u64, /// Unix permission mode (e.g., `0o644` for files, `0o755` for directories). pub mode: u32, + /// Owner user ID. Defaults to the sandbox user (1000). + pub uid: u32, + /// Owner group ID. Defaults to the sandbox group (1000). + pub gid: u32, /// Last modification time. pub modified: SystemTime, /// Creation time. @@ -604,6 +608,8 @@ impl Default for Metadata { file_type: FileType::File, size: 0, mode: 0o644, + uid: 1000, + gid: 1000, modified: SystemTime::now(), created: SystemTime::now(), } @@ -819,6 +825,8 @@ mod tests { fn metadata_custom_fields() { let now = SystemTime::now(); let m = Metadata { + uid: 1000, + gid: 1000, file_type: FileType::Directory, size: 4096, mode: 0o755, @@ -857,6 +865,8 @@ mod tests { let entry = DirEntry { name: "subdir".into(), metadata: Metadata { + uid: 1000, + gid: 1000, file_type: FileType::Directory, size: 0, mode: 0o755, diff --git a/crates/bashkit/src/interop/fs.rs b/crates/bashkit/src/interop/fs.rs index 4334afcea..82d3d640e 100644 --- a/crates/bashkit/src/interop/fs.rs +++ b/crates/bashkit/src/interop/fs.rs @@ -688,6 +688,8 @@ fn path_buf_from_abi(path: BashkitFsAbiStrRef) -> io::Result { fn abi_metadata_to_metadata(meta: BashkitFsAbiMetadata) -> io::Result { Ok(Metadata { + uid: 1000, + gid: 1000, file_type: match meta.file_type { BashkitFsAbiFileType::File => FileType::File, BashkitFsAbiFileType::Directory => FileType::Directory, diff --git a/crates/bashkit/src/interpreter/mod.rs b/crates/bashkit/src/interpreter/mod.rs index 02465087f..026fc0c27 100644 --- a/crates/bashkit/src/interpreter/mod.rs +++ b/crates/bashkit/src/interpreter/mod.rs @@ -6094,6 +6094,13 @@ impl Interpreter { "-r" | "-w" | "-x" => { self.fs.exists(&resolve(&args[1])).await.unwrap_or(false) } + "-O" | "-G" => self.fs.stat(&resolve(&args[1])).await.is_ok_and(|meta| { + if args[0] == "-O" { + meta.uid == builtins::SANDBOX_UID + } else { + meta.gid == builtins::SANDBOX_GID + } + }), "-s" => self .fs .stat(&resolve(&args[1])) diff --git a/crates/bashkit/src/parser/lexer.rs b/crates/bashkit/src/parser/lexer.rs index 6a29bd1bc..57953e4cf 100644 --- a/crates/bashkit/src/parser/lexer.rs +++ b/crates/bashkit/src/parser/lexer.rs @@ -2870,6 +2870,11 @@ impl<'a> Lexer<'a> { } continue; } + // Parentheses delimit words outside extglobs. In particular, + // `[()` is a function definition, not one bracket-pattern word. + if matches!(ch, '(' | ')') { + break; + } word.push(ch); self.advance(); if ch == ']' { diff --git a/crates/bashkit/tests/integration/custom_fs_tests.rs b/crates/bashkit/tests/integration/custom_fs_tests.rs index 2b7347160..9acfb7c80 100644 --- a/crates/bashkit/tests/integration/custom_fs_tests.rs +++ b/crates/bashkit/tests/integration/custom_fs_tests.rs @@ -95,6 +95,8 @@ impl FileSystem for MinimalFs { if let Some(content) = files.get(&path) { let is_dir = content.is_empty(); Ok(Metadata { + uid: 1000, + gid: 1000, file_type: if is_dir { FileType::Directory } else { @@ -157,6 +159,8 @@ impl FileSystem for MinimalFs { entries.push(DirEntry { name: name.to_string(), metadata: Metadata { + uid: 1000, + gid: 1000, file_type: if is_dir { FileType::Directory } else { @@ -251,6 +255,8 @@ async fn test_custom_fs_exports_available() { let _: fn() -> FileType = || FileType::Symlink; let metadata = Metadata { + uid: 1000, + gid: 1000, file_type: FileType::File, size: 0, mode: 0o644, diff --git a/crates/bashkit/tests/integration/dev_null_tests.rs b/crates/bashkit/tests/integration/dev_null_tests.rs index 852bde5c5..008f9fbec 100644 --- a/crates/bashkit/tests/integration/dev_null_tests.rs +++ b/crates/bashkit/tests/integration/dev_null_tests.rs @@ -432,6 +432,8 @@ impl FileSystem for MaliciousDevFs { async fn stat(&self, path: &Path) -> Result { Ok(Metadata { + uid: 1000, + gid: 1000, file_type: if path.ends_with("null") { FileType::File } else { @@ -448,6 +450,8 @@ impl FileSystem for MaliciousDevFs { Ok(vec![DirEntry { name: "null".to_string(), metadata: Metadata { + uid: 1000, + gid: 1000, file_type: FileType::File, size: 0, mode: 0o666, diff --git a/crates/bashkit/tests/realfs_tests.rs b/crates/bashkit/tests/realfs_tests.rs index 680d6b8d8..0446d907c 100644 --- a/crates/bashkit/tests/realfs_tests.rs +++ b/crates/bashkit/tests/realfs_tests.rs @@ -9,6 +9,24 @@ use bashkit::{Bash, BashBuilder}; use std::path::Path; +#[cfg(unix)] +#[tokio::test] +async fn realfs_reports_host_ownership() { + use bashkit::{FileSystem, PosixFs, RealFs, RealFsMode}; + use std::os::unix::fs::MetadataExt; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("file"); + std::fs::write(&path, b"data").unwrap(); + let expected = std::fs::metadata(path).unwrap(); + let fs = PosixFs::new( + RealFs::open(dir.path(), RealFsMode::ReadOnly) + .await + .unwrap(), + ); + let meta = fs.stat(Path::new("/file")).await.unwrap(); + assert_eq!((meta.uid, meta.gid), (expected.uid(), expected.gid())); +} + #[cfg(windows)] mod windows_containment { use super::*; diff --git a/crates/bashkit/tests/spec_cases/bash/functions.test.sh b/crates/bashkit/tests/spec_cases/bash/functions.test.sh index e6eadb948..8a428cacc 100644 --- a/crates/bashkit/tests/spec_cases/bash/functions.test.sh +++ b/crates/bashkit/tests/spec_cases/bash/functions.test.sh @@ -239,3 +239,13 @@ f ### expect 1 main main ### end + +### func_bracket_overrides_builtin +[() { echo override; return 7; }; [ x ]; echo status=$? +unset -f '[' +[ x ]; echo builtin=$? +### expect +override +status=7 +builtin=0 +### end diff --git a/docs/filesystem.md b/docs/filesystem.md index a289dc4dc..76c2af540 100644 --- a/docs/filesystem.md +++ b/docs/filesystem.md @@ -10,6 +10,18 @@ default; you grant access deliberately, never by accident. This is the foundation of the [security model](security.md): there is no real filesystem to escape to unless you mount one. +## Ownership metadata + +File metadata carries numeric `uid` and `gid` ownership, defaulting to sandbox +user/group 1000. `[ -O path ]` and `[ -G path ]` (also inside `[[ ... ]]`) +compare the reported owner or group against that sandbox identity. Host-backed +filesystems can supply different owners; Unix `RealFs` reports the host values. +Ownership metadata does not enable permission enforcement. + +Rust custom filesystems constructing `Metadata` literals must include `uid` and +`gid` or use `..Metadata::default()` for the sandbox defaults. Browser host +`stat` objects accept optional `uid` and `gid` fields. + ## Copying directory contents Use `cp -r source/. destination` to merge a directory's contents into an existing diff --git a/docs/start-browser.md b/docs/start-browser.md index 8b15456e5..83404430d 100644 --- a/docs/start-browser.md +++ b/docs/start-browser.md @@ -116,6 +116,18 @@ const out = await bash.execute('echo "{ me { id } }" | graphql | jq .data'); console.log(out.stdout); ``` +Custom callbacks may return stdout as a string or +`{ stdout?: string, stderr?: string, exitCode?: number }`, directly or via a +Promise. Omitted streams are empty and status defaults to 0. For example, +`customBuiltins: { check: () => ({ exitCode: 1 }) }` makes +`check; echo $?` print `1` with no stderr. Status drives normal shell control +flow; throwing still reports an error and status 1. + +Host filesystem `stat` and `readDir` metadata may include optional unsigned +32-bit `uid` and `gid` values. They default to sandbox ID 1000; `-O` and `-G` +compare explicit owners against that fixed sandbox identity. Metadata does +not enable file permission enforcement. + ## Caveats - It's a `wasm-bindgen` module: it runs in any **JavaScript** host but **not** a diff --git a/knowledge/foundations/parser.md b/knowledge/foundations/parser.md index 61becb358..f8c4319d4 100644 --- a/knowledge/foundations/parser.md +++ b/knowledge/foundations/parser.md @@ -66,6 +66,11 @@ Bash/POSIX `-p` plus `--` and the practical GNU report flags `-f/--format`, ### Context-Aware Lexing +**Bracket command functions.** Unquoted parentheses terminate a bracket-prefixed +word outside extglobs, so `[() { ...; }` defines the `[` function just like +`function [ { ...; }`. Normal function lookup overrides the test builtin; +`unset -f '['` restores it. The functions spec covers both dispatch and status. + **Parameter subscript boundaries.** Parameter parsing, preliminary braced-name validation, and indirect-target admission use one subscript scanner. Quotes, ordinary and lexer-sentinel escapes, nested brackets, and braced expansions diff --git a/knowledge/foundations/vfs.md b/knowledge/foundations/vfs.md index 1315c2636..dff636089 100644 --- a/knowledge/foundations/vfs.md +++ b/knowledge/foundations/vfs.md @@ -10,6 +10,15 @@ tags: # Virtual Filesystem Design +`Metadata.uid` and `Metadata.gid` describe entry ownership; both default to the +sandbox identity 1000. `test -O` / `-G` and `[[ -O ... ]]` / `[[ -G ... ]]` +compare that metadata with the fixed sandbox user/group, rather than treating +every existing host entry as owned. Ownership is descriptive, not permission +enforcement. Existing backends that do not report owners retain the single-user +model. Rust backends constructing `Metadata` literals must supply the new fields +or use `..Metadata::default()`. The v1 filesystem ABI retains its existing layout +and uses sandbox ownership when converting metadata. + ## Status Implemented diff --git a/knowledge/log.md b/knowledge/log.md index 3eaec06e5..169362952 100644 --- a/knowledge/log.md +++ b/knowledge/log.md @@ -1,5 +1,9 @@ # Bashkit Knowledge Update Log +## 2026-11-21 + +* **Host shell compatibility**: [Virtual Filesystem](foundations/vfs.md) records ownership metadata and accurate `-O`/`-G` comparisons against sandbox ID 1000; absent owners retain existing defaults. [Parser](foundations/parser.md) records `[()` function syntax. [Browser Package](runtimes/browser-package.md) records structured custom-builtin results so nonzero statuses reach shell control flow without thrown errors. WASM integration regressions exercise the public host API, and the function spec compares bracket overrides against Bash. + ## 2026-11-20 * **Agent pull request rules**: after an agent squash-merged external PR #2959 on green CI with a review-bot finding still open, the maintainer set three rules for agents: never merge external contributions (non-maintainers or forks; a maintainer merges by hand), never merge while any review comment is unaddressed, and never reply on their own to human-written comments (bring them to the maintainer instead). See [Agent Pull Request Rules](operations/agent-pr-rules.md). diff --git a/knowledge/operations/limitations.md b/knowledge/operations/limitations.md index d4b43599d..8a57896aa 100644 --- a/knowledge/operations/limitations.md +++ b/knowledge/operations/limitations.md @@ -55,7 +55,7 @@ execution model. Evidence is a threat-model ID, a test, or `stance` | L-DOC-001 | `markkit`/`fetchkit` builtins (features `markkit`, `fetchkit`, off by default, native only) refuse `mcp`, markkit `--ocr`, and fetchkit `--allow-env-proxy`, `--render-rakers`, `--bot-auth-key`/`--bot-auth-agent`, `--allow-remote-conversion` with exit 1 (`Error: is not available in bashkit`); markkit `--max-*`/`--timeout` cannot raise limits above markkit defaults | Host binaries, host files, host proxy env, a second signer and third-party uploads all cross the sandbox; `mcp` and rakers decided never in the sandbox (user, 2026-11-01). Help text stays identical to the standalone CLIs | `ocr_and_mcp_are_refused`, `host_only_flags_and_mcp_are_refused_before_any_request` | | L-FS-001 | Symlinks are followed, but `..` after a linked directory resolves lexically (`/link/..` is the link's parent, the `cd -L` view), and `ln` without `-s` (and `link`) makes a symlink, not a hard link | The interpreter normalizes paths before the VFS sees them; the VFS has no inodes to share | `symlink.test.sh`, `ln_default_symbolic` | | L-ROOTFS-001 | Default rootfs is static and read-only: `/proc` has no `self`, pid dirs, `uptime` or live counters; `/etc/passwd` has no root entry; `/dev/zero` yields 1 MiB per read; `/dev/full` is a plain file, so writes to it succeed (bash: `No space left on device`); `/bin`, `/usr/bin` are stubs that dispatch builtins | Host state must not leak (TM-INF-003, TM-ISO-018); fixed values keep runs deterministic | `rootfs_layout`, `threat_etc_passwd_blocked` | -| L-FS-002 | No file permission enforcement in the VFS | Single-tenant virtual FS; permissions would be theater | `l_fs_002_no_permission_enforcement` | +| L-FS-002 | No file permission enforcement in the VFS; ownership metadata affects `-O`/`-G` tests only | Single-tenant virtual FS; permissions would be theater | `l_fs_002_no_permission_enforcement` | | L-FS-003 | On Windows, `RealFs::symlink()` validates the target but creates an empty host file rather than a symlink/reparse point; pre-existing host symlinks and junctions remain readable subject to containment checks | Windows requires choosing file-vs-directory link semantics and may require link privileges; the portable VFS symlink contract does not carry that host metadata | TM-ESC-033 | | L-FS-004 | File names cannot contain control characters (newline, tab, ESC, ...) or bidi overrides: creating `$'a\nb'` fails with `unsafe character U+000A in path component`, so tools never print the quoted forms (`stat -c %N` as `'a'$'\n''b'`, `md5sum`'s `\` escape) for such names | Control characters in names let output forge extra lines or terminal escapes (TM-DOS-015) | `bashbox-checksum.test.sh`, `bashbox-stat.test.sh` (skipped) | | L-FS-005 | On Windows hosts, `\` in a path is a separator, not a file-name character: `touch 'g\h'` names `g/h` | The VFS normalizer parses paths with `std::path`, which splits on both separators on Windows; host-path namespace stripping (TM-ESC-033) relies on that parse | `ls.test.sh` (`skip_windows`) | diff --git a/knowledge/runtimes/browser-package.md b/knowledge/runtimes/browser-package.md index 197e6568d..76c8bb3cf 100644 --- a/knowledge/runtimes/browser-package.md +++ b/knowledge/runtimes/browser-package.md @@ -190,6 +190,20 @@ a later microtask so the suspend/resume path is the one under test. ## Execution model +Custom builtins return a stdout string or a `BuiltinResult` object with optional +`stdout`, `stderr`, and `exitCode` fields (empty streams and status 0 by default), +directly or via a Promise. Explicit nonzero status reaches `$?`, conditionals, +AND/OR lists and errexit without throwing or generating a diagnostic. Throwing +still produces stderr and status 1. Invalid result shapes fail with a plain +diagnostic rather than silently succeeding. Live `commands` continue to accept +numeric statuses and `{ exitCode }`. + +Host `stat` and directory metadata accept optional integer `uid`/`gid` in the +unsigned 32-bit range. Omitted values default to sandbox ID 1000; malformed +values reject the metadata instead of truncating or implying ownership. +The async host-filesystem suite covers independent owner/group comparisons, +missing entries and omitted/invalid IDs. + `wasm32-unknown-unknown` is single-threaded; the whole future chain runs on the browser's one event loop. Two entry points: diff --git a/site/src/data/performance-timeline.json b/site/src/data/performance-timeline.json index 099b4c9b4..ec3d0e1f4 100644 --- a/site/src/data/performance-timeline.json +++ b/site/src/data/performance-timeline.json @@ -1,5 +1,5 @@ { - "generatedAt": "2026-11-20T20:33:29.000Z", + "generatedAt": "2026-11-22T02:07:33.000Z", "sources": { "bench": "crates/bashkit-bench/results/*.json", "criterion": "crates/bashkit/benches/results/*.md", @@ -9,7 +9,7 @@ }, "summary": { "benchRuns": 13, - "criterionRuns": 21, + "criterionRuns": 22, "evalRuns": 58, "latestBench": { "id": "bench-79f1c12bcc44-linux-x86_64-1792175675", @@ -2382,6 +2382,30 @@ "bestChangePct": null, "fastestCase": null, "bestImprovement": null + }, + { + "id": "criterion-parallel-shell-compat-macos-arm64-1795313253", + "kind": "criterion", + "family": "parallel", + "label": "Host shell compatibility: filesystem overhead", + "date": "2026-11-22", + "timestamp": "2026-11-22T02:07:33.000Z", + "source": "crates/bashkit/benches/results/criterion-parallel-shell-compat-macos-arm64-1795313253.md", + "reportSource": "crates/bashkit/benches/results/criterion-parallel-shell-compat-macos-arm64-1795313253.md", + "cases": 1, + "medianUs": 42.35, + "p95Us": 42.35, + "medianChangePct": 0.6, + "meanChangePct": 0.6, + "bestChangePct": 0.6, + "fastestCase": { + "name": "single_file_write_read", + "us": 42.35 + }, + "bestImprovement": { + "name": "single_file_write_read", + "changePct": 0.6 + } } ], "evalRuns": [ @@ -10143,6 +10167,15 @@ "detail": "72/88 tasks passed. Weakest category: error_handling (0%).", "metric": 81.8, "source": "crates/bashkit-eval/results/mira/20261120T203329Z-1c3d/report.json" + }, + { + "date": "2026-11-22", + "timestamp": "2026-11-22T02:07:33.000Z", + "kind": "Criterion", + "title": "parallel", + "detail": "0.6% faster in single_file_write_read", + "metric": 0.6, + "source": "crates/bashkit/benches/results/criterion-parallel-shell-compat-macos-arm64-1795313253.md" } ] } From a121a2474ffc17b4cfad55ff8cd47752f1eb554f Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Sat, 21 Nov 2026 20:23:08 -0600 Subject: [PATCH 2/2] chore(wasm): clarify host result and ownership contracts --- crates/bashkit-wasm/README.md | 3 +++ .../__test__/bashkit-wasm.test.mjs | 2 +- crates/bashkit-wasm/js/index.d.ts | 8 ++++++-- crates/bashkit-wasm/src/lib.rs | 2 +- crates/bashkit/src/fs/realfs.rs | 8 ++++++++ crates/bashkit/tests/realfs_tests.rs | 20 +++++++++++++++++-- docs/filesystem.md | 4 ++++ knowledge/foundations/vfs.md | 3 +++ knowledge/operations/limitations.md | 1 + knowledge/runtimes/browser-package.md | 3 ++- 10 files changed, 47 insertions(+), 7 deletions(-) diff --git a/crates/bashkit-wasm/README.md b/crates/bashkit-wasm/README.md index fcdc80b06..4c06de9d1 100644 --- a/crates/bashkit-wasm/README.md +++ b/crates/bashkit-wasm/README.md @@ -95,6 +95,9 @@ 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: diff --git a/crates/bashkit-wasm/__test__/bashkit-wasm.test.mjs b/crates/bashkit-wasm/__test__/bashkit-wasm.test.mjs index 77d994f65..7179f4e3d 100644 --- a/crates/bashkit-wasm/__test__/bashkit-wasm.test.mjs +++ b/crates/bashkit-wasm/__test__/bashkit-wasm.test.mjs @@ -33,7 +33,7 @@ test("compat: bracket function overrides the builtin", () => { 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 }; + const result = { stdout: "out\n", stderr: "err\n", exitCode: 7, extra: "host metadata" }; const bash = new Bash({ customBuiltins: { probe: asyncCallback ? async () => result : () => result }, }); diff --git a/crates/bashkit-wasm/js/index.d.ts b/crates/bashkit-wasm/js/index.d.ts index 537dcfda6..acd4def29 100644 --- a/crates/bashkit-wasm/js/index.d.ts +++ b/crates/bashkit-wasm/js/index.d.ts @@ -30,7 +30,7 @@ export interface BuiltinRequest { readonly fs: FileSystem; } -/** Buffered command result. Omitted streams are empty. */ +/** Buffered command result. Omitted streams are empty; extra host properties are ignored. */ export interface BuiltinResult { readonly stdout?: string; readonly stderr?: string; @@ -85,7 +85,11 @@ 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. */ diff --git a/crates/bashkit-wasm/src/lib.rs b/crates/bashkit-wasm/src/lib.rs index 639938159..db7c15f19 100644 --- a/crates/bashkit-wasm/src/lib.rs +++ b/crates/bashkit-wasm/src/lib.rs @@ -217,7 +217,7 @@ struct BuiltinRequest<'a> { } #[derive(Deserialize, Default)] -#[serde(rename_all = "camelCase", default, deny_unknown_fields)] +#[serde(rename_all = "camelCase", default)] struct BuiltinResult { stdout: Option, stderr: Option, diff --git a/crates/bashkit/src/fs/realfs.rs b/crates/bashkit/src/fs/realfs.rs index 078f00605..d80a9d3ca 100644 --- a/crates/bashkit/src/fs/realfs.rs +++ b/crates/bashkit/src/fs/realfs.rs @@ -23,6 +23,14 @@ //! and checking it stays under the root. //! - Readonly mode rejects all write operations at the backend level. //! +//! # Ownership +//! +//! On Unix, metadata reports the host file's UID/GID. The shell still uses +//! sandbox UID/GID 1000 (`id`, `UID`, `EUID`); `-O`/`-G` compare against those +//! sandbox IDs, not the embedding process's effective IDs. Thus a host file +//! owned by another account can fail these tests even when that account runs +//! the process. This does not impersonate users or change host permissions. +//! //! # Modes //! //! | Mode | Reads | Writes | Use case | diff --git a/crates/bashkit/tests/realfs_tests.rs b/crates/bashkit/tests/realfs_tests.rs index 0446d907c..33d525090 100644 --- a/crates/bashkit/tests/realfs_tests.rs +++ b/crates/bashkit/tests/realfs_tests.rs @@ -14,17 +14,33 @@ use std::path::Path; async fn realfs_reports_host_ownership() { use bashkit::{FileSystem, PosixFs, RealFs, RealFsMode}; use std::os::unix::fs::MetadataExt; + use std::sync::Arc; let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("file"); std::fs::write(&path, b"data").unwrap(); let expected = std::fs::metadata(path).unwrap(); - let fs = PosixFs::new( + let fs = Arc::new(PosixFs::new( RealFs::open(dir.path(), RealFsMode::ReadOnly) .await .unwrap(), - ); + )); let meta = fs.stat(Path::new("/file")).await.unwrap(); assert_eq!((meta.uid, meta.gid), (expected.uid(), expected.gid())); + let owner = i32::from(meta.uid != 1000); + let group = i32::from(meta.gid != 1000); + let mut bash = Bash::builder().fs(fs).build(); + let result = bash + .exec( + "id -u; [ -O /file ]; echo $?; [ -G /file ]; echo $?; \ + [[ -O /file ]]; echo $?; [[ -G /file ]]; echo $?", + ) + .await + .unwrap(); + assert_eq!( + result.stdout, + format!("1000\n{owner}\n{group}\n{owner}\n{group}\n") + ); + assert!(result.stderr.is_empty()); } #[cfg(windows)] diff --git a/docs/filesystem.md b/docs/filesystem.md index 76c2af540..7308a1bfe 100644 --- a/docs/filesystem.md +++ b/docs/filesystem.md @@ -17,6 +17,10 @@ user/group 1000. `[ -O path ]` and `[ -G path ]` (also inside `[[ ... ]]`) compare the reported owner or group against that sandbox identity. Host-backed filesystems can supply different owners; Unix `RealFs` reports the host values. Ownership metadata does not enable permission enforcement. +The shell identity remains 1000 even with `RealFs`: a file owned by a different +host account fails `-O`/`-G`, including when that account owns the embedding +process. These tests describe ownership relative to the sandbox identity, not +the host process's effective UID/GID. Rust custom filesystems constructing `Metadata` literals must include `uid` and `gid` or use `..Metadata::default()` for the sandbox defaults. Browser host diff --git a/knowledge/foundations/vfs.md b/knowledge/foundations/vfs.md index dff636089..f3e723f6b 100644 --- a/knowledge/foundations/vfs.md +++ b/knowledge/foundations/vfs.md @@ -18,6 +18,9 @@ enforcement. Existing backends that do not report owners retain the single-user model. Rust backends constructing `Metadata` literals must supply the new fields or use `..Metadata::default()`. The v1 filesystem ABI retains its existing layout and uses sandbox ownership when converting metadata. +Unix `RealFs` reports real file owners, but tests still compare against the +sandbox identity, not the embedding process's effective IDs. This deliberate +divergence is recorded as L-FS-006 in [Limitations](../operations/limitations.md). ## Status Implemented diff --git a/knowledge/operations/limitations.md b/knowledge/operations/limitations.md index 8a57896aa..b2c5ea5ef 100644 --- a/knowledge/operations/limitations.md +++ b/knowledge/operations/limitations.md @@ -59,6 +59,7 @@ execution model. Evidence is a threat-model ID, a test, or `stance` | L-FS-003 | On Windows, `RealFs::symlink()` validates the target but creates an empty host file rather than a symlink/reparse point; pre-existing host symlinks and junctions remain readable subject to containment checks | Windows requires choosing file-vs-directory link semantics and may require link privileges; the portable VFS symlink contract does not carry that host metadata | TM-ESC-033 | | L-FS-004 | File names cannot contain control characters (newline, tab, ESC, ...) or bidi overrides: creating `$'a\nb'` fails with `unsafe character U+000A in path component`, so tools never print the quoted forms (`stat -c %N` as `'a'$'\n''b'`, `md5sum`'s `\` escape) for such names | Control characters in names let output forge extra lines or terminal escapes (TM-DOS-015) | `bashbox-checksum.test.sh`, `bashbox-stat.test.sh` (skipped) | | L-FS-005 | On Windows hosts, `\` in a path is a separator, not a file-name character: `touch 'g\h'` names `g/h` | The VFS normalizer parses paths with `std::path`, which splits on both separators on Windows; host-path namespace stripping (TM-ESC-033) relies on that parse | `ls.test.sh` (`skip_windows`) | +| L-FS-006 | `-O`/`-G` always compare against sandbox UID/GID 1000, even with Unix `RealFs`; a host process owned by another account does not make that account's files sandbox-owned | `id`, `UID` and `EUID` retain the fixed sandbox identity; host ownership metadata does not change execution identity | `realfs_reports_host_ownership` | | L-NET-001 | No raw network sockets; HTTP only via `curl`/`wget`/`http` builtins | Allowlist-mediated egress is the only network surface | `l_net_001_no_raw_sockets` | | L-NET-002 | No DNS resolution; hosts must appear in the allowlist | Resolution would bypass allowlist intent | `l_net_002_default_deny_no_resolution` | | L-ARITH-001 | A variable's value read as an arithmetic expression or subscript never runs command substitution: `x='a[$(cmd)]'; echo $((x))` and `unset "a[$(cmd)]"` built from data are arithmetic syntax errors, and an indirect target holding `$(`, `` ` ``, `<(` or `>(` (`r='a[$(cmd)]'; ${!r}`) is `invalid variable name`, where bash runs `cmd` | Values are data; re-parsing them as code is the classic bash arithmetic injection, and a sandboxed agent shell must not execute text it only read | stance | diff --git a/knowledge/runtimes/browser-package.md b/knowledge/runtimes/browser-package.md index 76c8bb3cf..38de5732b 100644 --- a/knowledge/runtimes/browser-package.md +++ b/knowledge/runtimes/browser-package.md @@ -194,7 +194,8 @@ Custom builtins return a stdout string or a `BuiltinResult` object with optional `stdout`, `stderr`, and `exitCode` fields (empty streams and status 0 by default), directly or via a Promise. Explicit nonzero status reaches `$?`, conditionals, AND/OR lists and errexit without throwing or generating a diagnostic. Throwing -still produces stderr and status 1. Invalid result shapes fail with a plain +still produces stderr and status 1. Extra host properties on result objects +are ignored. Invalid result shapes fail with a plain diagnostic rather than silently succeeding. Live `commands` continue to accept numeric statuses and `{ exitCode }`.