From be7e14e97e920ef8d57a5d8d4fd3d8a016b8b00e Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Tue, 10 Nov 2026 21:31:35 +0000 Subject: [PATCH 1/8] fix(ts): enforce max_memory and wall-clock limit for TypeScript ZapCode 1.5.1 never reads memory_limit_bytes, and a failed allocation aborts the process with every tenant. Template-literal, concat and spread doubling all aborted the host. Each ts run now gets its own vm_meter (the Monty meter, renamed from python_meter): every instruction stops the run past max_memory, and output-amplifying builtins (join, toString, JSON.stringify, console.log, concat, repeat, split, replace) size their result before allocating. Native ts fails closed without MeteredAllocator. A new multi-tenant stress suite found a host-call loop ran 30 s under a 500 ms limit because ZapCode restarts its clock at every resume. The host-call loop now checks the run's wall-clock deadline, caps callbacks at the remaining time, and yields. TM-TS-026, TM-TS-027. --- crates/bashkit-capi/src/lib.rs | 2 +- crates/bashkit-js/src/lib.rs | 2 +- crates/bashkit-python/src/lib.rs | 2 +- .../tests/tool_registry_tests.rs | 2 +- crates/bashkit-wasm/src/lib.rs | 4 +- crates/bashkit/docs/threat-model.md | 4 +- .../examples/typescript_external_functions.rs | 4 + crates/bashkit/examples/typescript_scripts.rs | 4 + crates/bashkit/src/builtins/python.rs | 8 +- crates/bashkit/src/builtins/typescript.rs | 104 +++++-- crates/bashkit/src/lib.rs | 16 +- .../src/{python_meter.rs => vm_meter.rs} | 131 +++++++-- crates/bashkit/src/zapcode_guard.rs | 176 ++++++++++++ crates/bashkit/src/zapcode_vendor/README.md | 4 +- .../src/zapcode_vendor/fork-edits.json | 57 ++++ crates/bashkit/src/zapcode_vendor/sandbox.rs | 2 + crates/bashkit/src/zapcode_vendor/value.rs | 3 + .../bashkit/src/zapcode_vendor/vm/builtins.rs | 18 ++ crates/bashkit/tests/integration/main.rs | 5 +- .../tests/integration/threat_model_tests.rs | 112 ++++++++ .../integration/ts_tenant_stress_tests.rs | 257 ++++++++++++++++++ knowledge/log.md | 2 + knowledge/runtimes/python-builtin.md | 2 +- knowledge/runtimes/zapcode-runtime.md | 65 ++++- knowledge/security/threat-model.md | 4 +- scripts/check_zapcode_vendor.py | 16 +- 26 files changed, 924 insertions(+), 82 deletions(-) rename crates/bashkit/src/{python_meter.rs => vm_meter.rs} (64%) create mode 100644 crates/bashkit/src/zapcode_guard.rs create mode 100644 crates/bashkit/src/zapcode_vendor/fork-edits.json create mode 100644 crates/bashkit/tests/integration/ts_tenant_stress_tests.rs diff --git a/crates/bashkit-capi/src/lib.rs b/crates/bashkit-capi/src/lib.rs index cbd703959..4895e4e30 100644 --- a/crates/bashkit-capi/src/lib.rs +++ b/crates/bashkit-capi/src/lib.rs @@ -26,7 +26,7 @@ use std::sync::{Arc, Mutex}; use std::time::Duration; use tokio::runtime::{Builder, Runtime}; -// Monty python3 charges each VM for its own allocations through this +// Monty python3 and ZapCode ts charge each VM for its own allocations through this // allocator (see bashkit::MeteredAllocator). In a cdylib it only governs this // library's Rust allocations, never the host runtime's allocator. #[global_allocator] diff --git a/crates/bashkit-js/src/lib.rs b/crates/bashkit-js/src/lib.rs index 09406a1a4..3e8eae902 100644 --- a/crates/bashkit-js/src/lib.rs +++ b/crates/bashkit-js/src/lib.rs @@ -45,7 +45,7 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex as StdMutex}; use tokio::sync::{Mutex, OwnedSemaphorePermit, Semaphore}; -// Monty python3 charges each VM for its own allocations through this +// Monty python3 and ZapCode ts charge each VM for its own allocations through this // allocator (see bashkit::MeteredAllocator). In a cdylib it only governs this // library's Rust allocations, never the host runtime's allocator. #[global_allocator] diff --git a/crates/bashkit-python/src/lib.rs b/crates/bashkit-python/src/lib.rs index 2197dac56..64b7afe0b 100644 --- a/crates/bashkit-python/src/lib.rs +++ b/crates/bashkit-python/src/lib.rs @@ -35,7 +35,7 @@ use bashkit::{ }; use bashkit_scripted_tool::{ScriptedTool as RustScriptedTool, ToolArgs, ToolDef}; -// Monty python3 charges each VM for its own allocations through this +// Monty python3 and ZapCode ts charge each VM for its own allocations through this // allocator (see bashkit::MeteredAllocator). In a cdylib it only governs this // library's Rust allocations, never the host runtime's allocator. #[global_allocator] diff --git a/crates/bashkit-scripted-tool/tests/tool_registry_tests.rs b/crates/bashkit-scripted-tool/tests/tool_registry_tests.rs index dfae49110..92c3fae86 100644 --- a/crates/bashkit-scripted-tool/tests/tool_registry_tests.rs +++ b/crates/bashkit-scripted-tool/tests/tool_registry_tests.rs @@ -7,7 +7,7 @@ use std::sync::{ }; use std::time::Duration; -// Monty python3 charges each VM for its own allocations through this +// Monty python3 and ZapCode ts charge each VM for its own allocations through this // allocator (see bashkit::MeteredAllocator). In a cdylib it only governs this // library's Rust allocations, never the host runtime's allocator. #[cfg(feature = "python")] diff --git a/crates/bashkit-wasm/src/lib.rs b/crates/bashkit-wasm/src/lib.rs index 2998ff57e..63b65b062 100644 --- a/crates/bashkit-wasm/src/lib.rs +++ b/crates/bashkit-wasm/src/lib.rs @@ -35,10 +35,10 @@ use serde::Serialize; use wasm_bindgen::prelude::*; use wasm_bindgen_futures::{JsFuture, future_to_promise}; -// Monty python3 charges each VM for its own allocations through this +// Monty python3 and ZapCode ts charge each VM for its own allocations through this // allocator (see bashkit::MeteredAllocator). In a cdylib it only governs this // library's Rust allocations, never the host runtime's allocator. -#[cfg(feature = "python")] +#[cfg(any(feature = "python", feature = "typescript"))] #[global_allocator] static METERED_ALLOC: bashkit::MeteredAllocator = bashkit::MeteredAllocator; diff --git a/crates/bashkit/docs/threat-model.md b/crates/bashkit/docs/threat-model.md index 3dcd55457..b8a11bb9a 100644 --- a/crates/bashkit/docs/threat-model.md +++ b/crates/bashkit/docs/threat-model.md @@ -893,9 +893,11 @@ access is bridged through Bashkit's VFS, never the host filesystem. | Shebang line injection (TM-TS-023) | `#!...` header | Shebang stripped safely | MITIGATED | | Deeply nested source aborts the host (TM-TS-024) | A few KB of `[[[...` or `1+1+...` overflows ZapCode's recursive parser/compiler | Nesting estimate rejects depth over 1000; ZapCode steps run on a 128 MiB-stack thread | MITIGATED | | Huge `padStart`/`padEnd` aborts the host (TM-TS-025) | `'a'.padStart(2**40)` asks the allocator for ~1 TiB | Vendored ZapCode caps the target length at 10,000,000, like `repeat`; the run fails cleanly | MITIGATED | +| Memory growth past `max_memory` aborts the host (TM-TS-026) | Doubling a string or array, or joining/printing an array that shares one big string, until an allocation fails | A per-run meter stops the script once its heap passes `max_memory`; output-amplifying builtins size the result first; `ts` refuses to run without `MeteredAllocator` | MITIGATED | +| Host-call loop outruns the time limit (TM-TS-027) | `while (true) { await writeFile(...) }` resumes ZapCode's clock at every call | Wall-clock deadline checked at every host call; callbacks capped at the remaining time; the loop yields to the executor | MITIGATED | | Bash var expansion injection (TM-TS-020) | Unquoted `$VAR` expanded before TS runs | By design; use single quotes to prevent expansion | MITIGATED | -Per-threat coverage (TM-TS-001 … TM-TS-025), including error-isolation and +Per-threat coverage (TM-TS-001 … TM-TS-027), including error-isolation and exit-code propagation cases, is also exercised by the `threat_ts_*` tests. ### Request Signing & Snapshot Integrity (TM-CRY-*, TM-SNAP-*) diff --git a/crates/bashkit/examples/typescript_external_functions.rs b/crates/bashkit/examples/typescript_external_functions.rs index 70a69dda5..eaa33872b 100644 --- a/crates/bashkit/examples/typescript_external_functions.rs +++ b/crates/bashkit/examples/typescript_external_functions.rs @@ -7,6 +7,10 @@ use bashkit::{Bash, TypeScriptExternalFnHandler, TypeScriptLimits, ZapcodeValue}; use std::sync::Arc; +// ts memory limits need the metered allocator (see bashkit::MeteredAllocator). +#[global_allocator] +static ALLOC: bashkit::MeteredAllocator = bashkit::MeteredAllocator; + #[tokio::main] async fn main() -> bashkit::Result<()> { let handler: TypeScriptExternalFnHandler = Arc::new(|name, args| { diff --git a/crates/bashkit/examples/typescript_scripts.rs b/crates/bashkit/examples/typescript_scripts.rs index 8da85351f..98c9f1ef5 100644 --- a/crates/bashkit/examples/typescript_scripts.rs +++ b/crates/bashkit/examples/typescript_scripts.rs @@ -9,6 +9,10 @@ use bashkit::Bash; +// ts memory limits need the metered allocator (see bashkit::MeteredAllocator). +#[global_allocator] +static ALLOC: bashkit::MeteredAllocator = bashkit::MeteredAllocator; + #[tokio::main] async fn main() -> anyhow::Result<()> { println!("=== Bashkit TypeScript Integration ===\n"); diff --git a/crates/bashkit/src/builtins/python.rs b/crates/bashkit/src/builtins/python.rs index 09ac5343f..f3c4f7ca4 100644 --- a/crates/bashkit/src/builtins/python.rs +++ b/crates/bashkit/src/builtins/python.rs @@ -483,16 +483,16 @@ async fn run_python( } else { format!("{code}\nNone\n") }; - // Per-VM memory meter + shared-budget checkpoints (python_meter.rs). - if let Err(msg) = crate::python_meter::ensure_metering() { + // Per-VM memory meter + shared-budget checkpoints (vm_meter.rs). + if let Err(msg) = crate::vm_meter::ensure_metering() { return Ok(ExecResult::err(format!("{msg}\n"), 1)); } - let meter = crate::python_meter::VmMeter::new(execution_budget.clone()); + let meter = crate::vm_meter::VmMeter::new(execution_budget.clone()); let mut vm_time = Duration::ZERO; // Runs one synchronous Monty call inside this VM's metering window. macro_rules! in_vm { ($e:expr) => {{ - let _window = crate::python_meter::VmWindow::enter(&meter); + let _window = crate::vm_meter::VmWindow::enter(&meter); let started = Instant::now(); let r = $e; vm_time += started.elapsed(); diff --git a/crates/bashkit/src/builtins/typescript.rs b/crates/bashkit/src/builtins/typescript.rs index 407d3cac8..5b6b53d44 100644 --- a/crates/bashkit/src/builtins/typescript.rs +++ b/crates/bashkit/src/builtins/typescript.rs @@ -908,7 +908,20 @@ async fn run_typescript( )); } + // Per-run heap meter (vm_meter.rs); ZapCode itself never enforces + // max_memory, so without the metered allocator `ts` fails closed. + #[cfg(not(target_arch = "wasm32"))] + if !crate::vm_meter::allocator_installed() { + return Ok(ExecResult::err(METER_MISSING_ERROR.to_string(), 1)); + } + let meter = crate::vm_meter::VmMeter::with_limit(ts_limits.common.max_memory); + let started = Instant::now(); + // Important security decision (TM-TS-027): ZapCode's clock restarts at + // every resume, so `max_duration` alone bounds one VM step and a loop of + // cheap host calls ran until the shell timeout. The host-call loop checks + // this wall-clock deadline at every call. + let deadline = started.checked_add(time_limit); let runner = match ZapcodeRun::new( code.to_string(), Vec::new(), @@ -922,7 +935,7 @@ async fn run_typescript( } }; - let result = on_vm_stack(|| runner.run(Vec::new())); + let result = on_vm_stack(&meter, || runner.run(Vec::new())); charge_vm_time(execution_budget.as_ref(), started)?; let result = match result { Some(Ok(r)) => r, @@ -938,6 +951,8 @@ async fn run_typescript( external_fns, execution_budget.as_ref(), time_limit, + deadline, + &meter, ) .await } @@ -945,18 +960,29 @@ async fn run_typescript( /// Message when no VM thread could be started (resource exhaustion). const VM_THREAD_ERROR: &str = "ts: cannot start execution thread\n"; -/// Run one synchronous ZapCode step (parse/compile/run, or a resume). Off -/// wasm this runs on a dedicated thread with a [`TS_VM_STACK_BYTES`] stack; -/// see that constant. `None` means no thread could be started: the caller -/// fails the command rather than running accepted-depth source on a small -/// stack. +/// Message when `MeteredAllocator` is not the global allocator. #[cfg(not(target_arch = "wasm32"))] -fn on_vm_stack(step: impl FnOnce() -> T + Send) -> Option { +const METER_MISSING_ERROR: &str = + "ts: TypeScript memory limits need bashkit::MeteredAllocator as the global allocator\n"; + +/// Run one synchronous ZapCode step (parse/compile/run, or a resume) inside +/// `meter`'s window. Off wasm this runs on a dedicated thread with a +/// [`TS_VM_STACK_BYTES`] stack; see that constant. `None` means no thread +/// could be started: the caller fails the command rather than running +/// accepted-depth source on a small stack. +#[cfg(not(target_arch = "wasm32"))] +fn on_vm_stack( + meter: &crate::vm_meter::VmMeter, + step: impl FnOnce() -> T + Send, +) -> Option { std::thread::scope(|scope| { let handle = std::thread::Builder::new() .name("bashkit-ts".into()) .stack_size(TS_VM_STACK_BYTES) - .spawn_scoped(scope, step) + .spawn_scoped(scope, move || { + let _window = crate::vm_meter::VmWindow::enter(meter); + step() + }) .ok()?; match handle.join() { Ok(result) => Some(result), @@ -968,7 +994,8 @@ fn on_vm_stack(step: impl FnOnce() -> T + Send) -> Option { /// wasm32 has no threads: run on the current stack. The nesting cap still /// applies; see the zapcode-runtime knowledge page for the residual risk. #[cfg(target_arch = "wasm32")] -fn on_vm_stack(step: impl FnOnce() -> T) -> Option { +fn on_vm_stack(meter: &crate::vm_meter::VmMeter, step: impl FnOnce() -> T) -> Option { + let _window = crate::vm_meter::VmWindow::enter(meter); Some(step()) } @@ -990,6 +1017,8 @@ async fn process_vm_result( external_fns: Option<&TypeScriptExternalFns>, execution_budget: Option<&crate::limits::ExecutionBudget>, time_limit: std::time::Duration, + deadline: Option, + meter: &crate::vm_meter::VmMeter, ) -> Result { let stdout = result.stdout; let mut state = result.state; @@ -1004,7 +1033,15 @@ async fn process_vm_result( // If the result is not undefined and there was no print output, // display the result (like Node REPL behavior for expressions) if !matches!(value, Value::Undefined) && out.is_empty() { - out = format!("{}\n", value.to_js_string()); + // Format inside the run's meter: a result array can share + // one large string many times (zapcode_guard.rs). + let _window = crate::vm_meter::VmWindow::enter(meter); + let text = value.to_js_string(); + if crate::zapcode_guard::over_limit() { + let error = crate::zapcode_guard::limit_error(); + return Ok(format_error_with_output(error, &out, time_limit)); + } + out = format!("{text}\n"); } return Ok(ExecResult::ok(out)); } @@ -1016,21 +1053,41 @@ async fn process_vm_result( if let Some(budget) = execution_budget { budget.consume_work(100)?; } - let return_value = match handle_external_call( - &function_name, - &args, - fs, - cwd, - external_fns, - ) - .await + // Wall-clock bound (TM-TS-027), then yield: the VM never yields + // on its own, so without this a caller-side timeout cannot + // cancel the call and co-tenants on the worker thread starve. + if deadline.is_some_and(|d| Instant::now() >= d) { + return Ok(format_error_with_output( + zapcode_core::ZapcodeError::TimeLimitExceeded, + &stdout, + time_limit, + )); + } + tokio::task::yield_now().await; + // Host callbacks share the same deadline, so a slow external + // function cannot pin the run between VM steps. + let call = handle_external_call(&function_name, &args, fs, cwd, external_fns); + let outcome = match deadline.and_then(|d| d.checked_duration_since(Instant::now())) { - Ok(value) => value, - Err(error) => return Ok(ExecResult::err(format!("{error}\n"), 1)), + Some(remaining) => crate::time_compat::timeout(remaining, call).await.ok(), + // No representable deadline (huge max_duration): run uncapped. + None if deadline.is_none() => Some(call.await), + None => None, + }; + let return_value = match outcome { + Some(Ok(value)) => value, + Some(Err(error)) => return Ok(ExecResult::err(format!("{error}\n"), 1)), + None => { + return Ok(format_error_with_output( + zapcode_core::ZapcodeError::TimeLimitExceeded, + &stdout, + time_limit, + )); + } }; let started = Instant::now(); - let resumed = on_vm_stack(move || snapshot.resume(return_value)); + let resumed = on_vm_stack(meter, move || snapshot.resume(return_value)); charge_vm_time(execution_budget, started)?; state = match resumed { Some(Ok(s)) => s, @@ -1123,6 +1180,11 @@ async fn handle_write_file(args: &[Value], fs: &Arc, cwd: &Path) }; let content = match args.get(1) { Some(Value::String(s)) => s.as_ref().as_bytes().to_vec(), + Some(Value::Array(a)) if !crate::zapcode_guard::fits_js_string(a) => { + return Value::String(Arc::from( + "Error: writeFile content exceeds the memory limit", + )); + } Some(v) => v.to_js_string().into_bytes(), None => { return Value::String(Arc::from("Error: writeFile requires a content argument")); diff --git a/crates/bashkit/src/lib.rs b/crates/bashkit/src/lib.rs index 1915d1c99..ad237c73a 100644 --- a/crates/bashkit/src/lib.rs +++ b/crates/bashkit/src/lib.rs @@ -456,8 +456,6 @@ mod network; /// Parser module - exposed for fuzzing and testing pub mod parser; mod profile; -#[cfg(feature = "python")] -mod python_meter; #[cfg(any(feature = "python", feature = "typescript"))] mod runtime_call; #[cfg(any(feature = "python", feature = "typescript"))] @@ -472,6 +470,10 @@ pub mod terminal; /// invariants enforced (TM-INF-013, TM-INF-016, TM-INF-022). #[doc(hidden)] pub mod testing; +#[cfg(any(feature = "python", feature = "typescript"))] +mod vm_meter; +#[cfg(feature = "typescript")] +mod zapcode_guard; /// Clock and timer that match the interpreter's target. /// /// Native targets use tokio's clock (it follows paused/advanced test time), @@ -576,13 +578,13 @@ pub use builtins::ssh::{SshClient, SshHandler, SshOutput, SshTarget}; #[cfg(feature = "python")] pub use builtins::{Python, PythonExternalFnHandler, PythonExternalFns, PythonLimits}; -#[cfg(feature = "python")] -pub use python_meter::MeteredAllocator; +#[cfg(any(feature = "python", feature = "typescript"))] +pub use vm_meter::MeteredAllocator; -// Monty python3 fails closed without the metered allocator. -#[cfg(all(test, feature = "python"))] +// Monty python3 and ZapCode ts fail closed without the metered allocator. +#[cfg(all(test, any(feature = "python", feature = "typescript")))] #[global_allocator] -static TEST_ALLOC: python_meter::MeteredAllocator = python_meter::MeteredAllocator; +static TEST_ALLOC: vm_meter::MeteredAllocator = vm_meter::MeteredAllocator; // Shared resource-limit core for embedded language VMs (Python, TypeScript). #[cfg(any(feature = "python", feature = "typescript", feature = "cpython"))] diff --git a/crates/bashkit/src/python_meter.rs b/crates/bashkit/src/vm_meter.rs similarity index 64% rename from crates/bashkit/src/python_meter.rs rename to crates/bashkit/src/vm_meter.rs index 81cd89c44..6f30f9883 100644 --- a/crates/bashkit/src/python_meter.rs +++ b/crates/bashkit/src/vm_meter.rs @@ -1,42 +1,47 @@ -//! Per-VM memory metering for the embedded Monty interpreter. +//! Per-VM memory metering for the embedded Monty and ZapCode interpreters. //! -//! Important decision (security): Monty 1.x enforces `max_memory` through a +//! Important decision (security): neither interpreter can safely bound its own +//! heap in a multi-tenant process. Monty 1.x enforces `max_memory` through a //! process-wide counter that only `monty-alloc` (installed as the global -//! allocator, aborting the process at its hard limit) writes. Bashkit runs many -//! tenants' Python in one process, so a shared counter charges tenants for each -//! other and an abort kills all of them. Instead: +//! allocator, aborting the process at its hard limit) writes, and ZapCode 1.5.1 +//! never reads `memory_limit_bytes` at all. Instead: //! //! - [`MeteredAllocator`] wraps `System` and charges each allocation to the -//! meter of the Monty VM currently running *on this thread*, if any. -//! Monty's `start`/`resume` calls are synchronous, so the "VM window" is -//! exact: no other task can run on the thread while it is open. +//! meter of the VM currently running *on this thread*, if any. Monty's +//! `start`/`resume` calls and ZapCode's run/resume steps are synchronous, so +//! the "VM window" is exact: no other task can run on the thread while it is +//! open. //! - Monty's memory probe (`set_memory_probe`, pydantic/monty#740) reads that //! thread's meter, so every in-VM memory check sees only its own VM. -//! - Monty's checkpoint hook runs bashkit's shared `ExecutionBudget` check +//! Monty's checkpoint hook runs bashkit's shared `ExecutionBudget` check //! (cancellation, deadline, work units) at VM time checkpoints. +//! - ZapCode (vendored, `bashkit fork:` edits) checks [`over_limit`] at every +//! instruction and calls [`reserve`] before operations whose output can be +//! far larger than their inputs (see `zapcode_guard.rs`). //! -//! The allocator never aborts and never refuses: Monty raises an uncatchable -//! `MemoryError` at its next checkpoint. Frees outside a window are not -//! refunded, so the meter can only over-count (the safe direction). +//! The allocator never aborts and never refuses: the VM stops with a memory +//! error at its next checkpoint. Frees outside a window are not refunded, so +//! the meter can only over-count (the safe direction). //! //! A `#[global_allocator]` in a `cdylib` only governs that library's Rust //! allocations, so the Python/Node/C bindings can install this without touching //! CPython's or Node's allocator. Rust embedders opt in explicitly; without it, -//! Monty `python3` fails closed (see `metering_installed`). +//! `python3` and `ts`/`node` fail closed (see [`allocator_installed`]). //! -//! See knowledge/runtimes/python-builtin.md. +//! See knowledge/runtimes/python-builtin.md and runtimes/zapcode-runtime.md. use std::alloc::{GlobalAlloc, Layout, System}; use std::cell::Cell; use std::sync::OnceLock; -use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +#[cfg(feature = "python")] use monty_types::ResourceError; /// Monty heap bytes per shared work unit (matches the 0.0.19 accounting). const BYTES_PER_WORK_UNIT: usize = 64; -/// Accounting for one Monty run. Only touched from inside a VM window on the +/// Accounting for one VM run. Only touched from inside a VM window on the /// thread running that window, so relaxed atomics suffice (they exist only to /// make the type `Sync` for the raw pointer the allocator reads). #[derive(Debug, Default)] @@ -46,9 +51,15 @@ pub(crate) struct VmMeter { checkpoints: AtomicU64, charged: AtomicUsize, budget: Option, + /// Byte limit checked by [`over_limit`]/[`reserve`]; 0 = none (Monty + /// enforces its own limit through the probe). + limit: usize, + /// Set when a [`reserve`] call refused; the VM fails at its next check. + exceeded: AtomicBool, } impl VmMeter { + #[cfg_attr(not(feature = "python"), allow(dead_code))] pub(crate) fn new(budget: Option) -> Self { Self { budget, @@ -56,6 +67,15 @@ impl VmMeter { } } + /// Meter that refuses growth past `limit` bytes (ZapCode). + #[cfg_attr(not(feature = "typescript"), allow(dead_code))] + pub(crate) fn with_limit(limit: usize) -> Self { + Self { + limit, + ..Self::default() + } + } + /// Bytes this VM currently holds. pub(crate) fn live(&self) -> usize { self.live.load(Ordering::Relaxed) @@ -87,6 +107,7 @@ impl VmMeter { /// Shared-budget work at one VM checkpoint: cancellation/deadline check, /// one unit per 64 checkpoints, and heap peak growth past what was already /// charged (one unit per [`BYTES_PER_WORK_UNIT`]). + #[cfg_attr(not(feature = "python"), allow(dead_code))] fn checkpoint(&self) -> Result<(), crate::limits::LimitExceeded> { let Some(budget) = &self.budget else { return Ok(()); @@ -199,12 +220,14 @@ impl Drop for VmWindow { } } +#[cfg(feature = "python")] fn probe() -> usize { let mut used = 0; with_current(|m| used = m.live()); used } +#[cfg(feature = "python")] fn checkpoint_hook() -> Result<(), ResourceError> { let mut result = Ok(()); with_current(|m| { @@ -218,19 +241,81 @@ fn checkpoint_hook() -> Result<(), ResourceError> { result } -/// Install Monty's memory probe and checkpoint hook (once per process) and -/// report whether [`MeteredAllocator`] is the global allocator. Returns an -/// error message when Monty must fail closed. -pub(crate) fn ensure_metering() -> Result<(), &'static str> { - static STATE: OnceLock> = OnceLock::new(); - *STATE.get_or_init(|| { +/// Whether [`MeteredAllocator`] is the global allocator (checked once). +pub(crate) fn allocator_installed() -> bool { + static INSTALLED: OnceLock = OnceLock::new(); + *INSTALLED.get_or_init(|| { let meter = VmMeter::default(); { let _w = VmWindow::enter(&meter); let probe_alloc = std::hint::black_box(vec![0u8; 256]); drop(probe_alloc); } - if meter.peak() == 0 { + meter.peak() > 0 + }) +} + +/// True when the VM running on this thread holds more than its limit, or a +/// [`reserve`] call already refused. False outside a window or without a limit. +#[cfg_attr(not(feature = "typescript"), allow(dead_code))] +pub(crate) fn over_limit() -> bool { + let mut over = false; + with_current(|m| { + over = m.limit > 0 && (m.exceeded.load(Ordering::Relaxed) || m.live() > m.limit); + }); + over +} + +/// Ask whether the VM on this thread may grow by `bytes` more. Refusal is +/// sticky ([`over_limit`] then reports it), so callers that cannot return an +/// error can return a cheap placeholder and let the next check stop the VM. +/// Outside a window there is no meter, and growth is refused past +/// [`UNMETERED_LIMIT`] so a stray conversion cannot request unbounded memory. +#[cfg_attr(not(feature = "typescript"), allow(dead_code))] +pub(crate) fn reserve(bytes: usize) -> bool { + let mut metered = false; + let mut ok = true; + with_current(|m| { + if m.limit > 0 { + metered = true; + ok = m.live().saturating_add(bytes) <= m.limit; + if !ok { + m.exceeded.store(true, Ordering::Relaxed); + } + } + }); + if metered { + ok + } else { + bytes <= UNMETERED_LIMIT + } +} + +/// Bytes the VM on this thread may still grow by ([`UNMETERED_LIMIT`] +/// outside a metered window). +#[cfg_attr(not(feature = "typescript"), allow(dead_code))] +pub(crate) fn remaining() -> usize { + let mut left = UNMETERED_LIMIT; + with_current(|m| { + if m.limit > 0 { + left = m.limit.saturating_sub(m.live()); + } + }); + left +} + +/// Growth cap for [`reserve`] outside any metered window: the default +/// `RuntimeLimits::max_memory`. +pub(crate) const UNMETERED_LIMIT: usize = 64 * 1024 * 1024; + +/// Install Monty's memory probe and checkpoint hook (once per process) and +/// report whether [`MeteredAllocator`] is the global allocator. Returns an +/// error message when Monty must fail closed. +#[cfg(feature = "python")] +pub(crate) fn ensure_metering() -> Result<(), &'static str> { + static STATE: OnceLock> = OnceLock::new(); + *STATE.get_or_init(|| { + if !allocator_installed() { return Err( "python3: Monty memory limits need bashkit::MeteredAllocator as the global allocator", ); diff --git a/crates/bashkit/src/zapcode_guard.rs b/crates/bashkit/src/zapcode_guard.rs new file mode 100644 index 000000000..aa18d514a --- /dev/null +++ b/crates/bashkit/src/zapcode_guard.rs @@ -0,0 +1,176 @@ +//! Memory guards called from `bashkit fork:` edits in the vendored ZapCode VM. +//! +//! Decision (security, TM-TS-026): ZapCode 1.5.1 never enforces +//! `memory_limit_bytes`, and Rust aborts the whole process when an allocation +//! fails. Two layers keep one tenant's script from reaching that abort: +//! +//! 1. Every instruction checks the per-VM live heap ([`crate::vm_meter`], +//! charged by `MeteredAllocator`), so gradual growth stops at the limit. +//! 2. Operations whose output can dwarf their inputs (strings are shared +//! `Arc`, so `[s, s, s].join()` costs 3 pointers but yields 3 copies) +//! size the output first and refuse before allocating it. Sizing walks the +//! value once and stops as soon as it passes the remaining budget, so the +//! walk costs at most one step per byte the VM may still allocate. +//! +//! Plain copies (array literals, `concat`, spread, template literals) need no +//! pre-check: each is at most a small multiple of memory already charged, and +//! layer 1 stops the run at the next instruction. +//! +//! See knowledge/runtimes/zapcode-runtime.md. + +use std::cell::Cell; + +use crate::vm_meter; +use crate::zapcode_vendor::{Value, ZapcodeError}; + +/// Upper bound for the text of one number (`-1.7976931348623157e308`). +const NUMBER_TEXT_BYTES: usize = 24; +/// Rough heap cost of one `Value` in a fresh array (the enum plus a small +/// `Arc` allocation for a one-character string). +const VALUE_BYTES: usize = 64; + +thread_local! { + // Nested `to_js_string` calls (arrays of arrays) are covered by the + // outermost sizing pass; skip re-sizing inside it. + static SIZING: Cell = const { Cell::new(false) }; +} + +/// The message for a refused reservation or a VM over its limit. +pub(crate) fn limit_error() -> ZapcodeError { + ZapcodeError::MemoryLimitExceeded("script heap reached max_memory".to_string()) +} + +/// True when the run must stop for memory (checked at every instruction). +pub(crate) fn over_limit() -> bool { + vm_meter::over_limit() +} + +/// Reserve `bytes` for an output about to be built. +pub(crate) fn reserve(bytes: usize) -> Result<(), ZapcodeError> { + if vm_meter::reserve(bytes) { + Ok(()) + } else { + Err(limit_error()) + } +} + +/// Reserve room for `n` new values (e.g. `split("")`). +pub(crate) fn reserve_values(n: usize) -> Result<(), ZapcodeError> { + reserve(n.saturating_mul(VALUE_BYTES)) +} + +/// Size check for `Value::to_js_string` on an array. Returns false when the +/// text would not fit; the caller returns an empty string and the VM stops at +/// its next instruction (the refusal is sticky). +pub(crate) fn fits_js_string(arr: &[Value]) -> bool { + if SIZING.with(Cell::get) { + return true; + } + let len = js_text_len(arr, vm_meter::remaining()).unwrap_or(usize::MAX); + vm_meter::reserve(len) +} + +/// Mark the start of a guarded `to_js_string`; nested calls skip sizing. +pub(crate) struct SizingScope(bool); + +impl SizingScope { + pub(crate) fn enter() -> Self { + Self(SIZING.with(|s| s.replace(true))) + } +} + +impl Drop for SizingScope { + fn drop(&mut self) { + SIZING.with(|s| s.set(self.0)); + } +} + +/// Size check for `Array.prototype.join(sep)`. +pub(crate) fn reserve_join(arr: &[Value], sep: &str) -> Result<(), ZapcodeError> { + let seps = arr.len().saturating_sub(1).saturating_mul(sep.len()); + let items = js_items_len(arr, vm_meter::remaining()).unwrap_or(usize::MAX); + reserve(items.saturating_add(seps)) +} + +/// Size check for `JSON.stringify(value)`. +pub(crate) fn reserve_json(value: &Value) -> Result<(), ZapcodeError> { + let len = json_len(value, vm_meter::remaining()).unwrap_or(usize::MAX); + reserve(len) +} + +/// Size check for `String.prototype.replace`/`replaceAll`. +pub(crate) fn reserve_replace( + s: &str, + search: &str, + replacement: &str, + all: bool, +) -> Result<(), ZapcodeError> { + let matches = if search.is_empty() { + if all { s.chars().count() + 1 } else { 1 } + } else if all { + s.matches(search).count() + } else { + usize::from(s.contains(search)) + }; + let grow = replacement.len().saturating_sub(search.len()); + reserve(s.len().saturating_add(matches.saturating_mul(grow))) +} + +/// Text length of `arr.join(",")` with nested arrays flattened the way +/// `to_js_string` does. `None` once it passes `budget`. +fn js_text_len(arr: &[Value], budget: usize) -> Option { + let commas = arr.len().saturating_sub(1); + let items = js_items_len(arr, budget.checked_sub(commas)?)?; + items.checked_add(commas).filter(|n| *n <= budget) +} + +fn js_items_len(arr: &[Value], budget: usize) -> Option { + let mut total = 0usize; + for v in arr { + let left = budget.checked_sub(total)?; + total = total.checked_add(js_value_len(v, left)?)?; + if total > budget { + return None; + } + } + Some(total) +} + +fn js_value_len(v: &Value, budget: usize) -> Option { + match v { + Value::String(s) => Some(s.len()), + Value::Array(inner) => js_text_len(inner, budget), + Value::Object(_) => Some("[object Object]".len()), + Value::Generator(_) => Some("[object Generator]".len()), + _ => Some(NUMBER_TEXT_BYTES), + } + .filter(|n| *n <= budget) +} + +/// Worst-case `value_to_json` length (every quote/backslash escaped). +fn json_len(v: &Value, budget: usize) -> Option { + let n = match v { + Value::String(s) => json_str_len(s), + Value::Array(arr) => { + let mut total = 2 + arr.len().saturating_sub(1); + for item in arr { + total = total.checked_add(json_len(item, budget.checked_sub(total)?)?)?; + } + total + } + Value::Object(map) => { + let mut total = 2 + map.len().saturating_sub(1); + for (k, item) in map { + total = total.checked_add(json_str_len(k) + 1)?; + total = total.checked_add(json_len(item, budget.checked_sub(total)?)?)?; + } + total + } + _ => NUMBER_TEXT_BYTES, + }; + (n <= budget).then_some(n) +} + +fn json_str_len(s: &str) -> usize { + s.len() + 2 + s.bytes().filter(|b| *b == b'"' || *b == b'\\').count() +} diff --git a/crates/bashkit/src/zapcode_vendor/README.md b/crates/bashkit/src/zapcode_vendor/README.md index 613fa5ded..d1348e8bb 100644 --- a/crates/bashkit/src/zapcode_vendor/README.md +++ b/crates/bashkit/src/zapcode_vendor/README.md @@ -4,7 +4,9 @@ Upstream `zapcode-core` 1.5.1, MIT, https://github.com/TheUncharted/zapcode. Every target (native, WASI, browser) builds this copy; the registry crate is no longer a dependency. The copy replaces std clocks that panic on wasm32-unknown-unknown and carries `bashkit fork:` resource-limit fixes -upstream has not shipped (listed in `scripts/check_zapcode_vendor.py`). It adds +upstream has not shipped (listed in `fork-edits.json`, checked by +`scripts/check_zapcode_vendor.py`), including the `max_memory` hooks into +`src/zapcode_guard.rs` that upstream never enforced. It adds no JS eval, imports, network or filesystem access. `upstream-sha256.json` records every original source file. Mechanical change: diff --git a/crates/bashkit/src/zapcode_vendor/fork-edits.json b/crates/bashkit/src/zapcode_vendor/fork-edits.json new file mode 100644 index 000000000..4c12a5183 --- /dev/null +++ b/crates/bashkit/src/zapcode_vendor/fork-edits.json @@ -0,0 +1,57 @@ +[ + { + "file": "vm/builtins.rs", + "insert": " // bashkit fork: cap like `repeat`; unbounded take() aborted the host.\n if target_len > 10_000_000 { return Err(ZapcodeError::AllocationLimitExceeded); }\n crate::zapcode_guard::reserve(target_len)?;\n", + "count": 2 + }, + { + "file": "sandbox.rs", + "insert": " // bashkit fork: per-VM heap limit; upstream never read memory_limit_bytes.\n if crate::zapcode_guard::over_limit() { return Err(crate::zapcode_guard::limit_error()); }\n", + "count": 1 + }, + { + "file": "value.rs", + "insert": " // bashkit fork: size shared-string arrays before building their text.\n if !crate::zapcode_guard::fits_js_string(arr) { return String::new(); }\n let _sizing = crate::zapcode_guard::SizingScope::enter();\n", + "count": 1 + }, + { + "file": "vm/builtins.rs", + "insert": " // bashkit fork: size the JSON text before building it.\n crate::zapcode_guard::reserve_json(val)?;\n", + "count": 1 + }, + { + "file": "vm/builtins.rs", + "insert": " // bashkit fork: the 10 MB cap can exceed a tighter per-run limit.\n crate::zapcode_guard::reserve(result_len)?;\n", + "count": 1 + }, + { + "file": "vm/builtins.rs", + "insert": " // bashkit fork: one new value per part.\n crate::zapcode_guard::reserve_values(if separator.is_empty() { s.len() } else { s.matches(&*separator).count() + 1 })?;\n", + "count": 1 + }, + { + "file": "vm/builtins.rs", + "insert": " // bashkit fork: a large replacement multiplies per match.\n crate::zapcode_guard::reserve_replace(s, &search, &replacement, false)?;\n", + "count": 1 + }, + { + "file": "vm/builtins.rs", + "insert": " // bashkit fork: a large replacement multiplies per match.\n crate::zapcode_guard::reserve_replace(s, &search, &replacement, true)?;\n", + "count": 1 + }, + { + "file": "vm/builtins.rs", + "insert": " // bashkit fork: arguments may share one large string many times.\n crate::zapcode_guard::reserve_join(args, \"\")?;\n", + "count": 1 + }, + { + "file": "vm/builtins.rs", + "insert": " // bashkit fork: elements may share one large string; size before joining.\n crate::zapcode_guard::reserve_join(arr, &sep)?;\n", + "count": 1 + }, + { + "file": "vm/builtins.rs", + "insert": " // bashkit fork: spread arguments may share one large string.\n crate::zapcode_guard::reserve_join(args, \" \")?;\n", + "count": 1 + } +] diff --git a/crates/bashkit/src/zapcode_vendor/sandbox.rs b/crates/bashkit/src/zapcode_vendor/sandbox.rs index 546345a4f..7c06396eb 100644 --- a/crates/bashkit/src/zapcode_vendor/sandbox.rs +++ b/crates/bashkit/src/zapcode_vendor/sandbox.rs @@ -34,6 +34,8 @@ impl ResourceTracker { } pub fn check_time(&self, limits: &ResourceLimits) -> crate::zapcode_vendor::error::Result<()> { + // bashkit fork: per-VM heap limit; upstream never read memory_limit_bytes. + if crate::zapcode_guard::over_limit() { return Err(crate::zapcode_guard::limit_error()); } if let Some(start) = self.start_time { if start.elapsed().as_millis() as u64 > limits.time_limit_ms { return Err(crate::zapcode_vendor::ZapcodeError::TimeLimitExceeded); diff --git a/crates/bashkit/src/zapcode_vendor/value.rs b/crates/bashkit/src/zapcode_vendor/value.rs index 5991fecc4..fb8997df5 100644 --- a/crates/bashkit/src/zapcode_vendor/value.rs +++ b/crates/bashkit/src/zapcode_vendor/value.rs @@ -126,6 +126,9 @@ impl Value { } Value::String(s) => s.to_string(), Value::Array(arr) => { + // bashkit fork: size shared-string arrays before building their text. + if !crate::zapcode_guard::fits_js_string(arr) { return String::new(); } + let _sizing = crate::zapcode_guard::SizingScope::enter(); let items: Vec = arr.iter().map(|v| v.to_js_string()).collect(); items.join(",") } diff --git a/crates/bashkit/src/zapcode_vendor/vm/builtins.rs b/crates/bashkit/src/zapcode_vendor/vm/builtins.rs index 84bae2b2c..b73993d17 100644 --- a/crates/bashkit/src/zapcode_vendor/vm/builtins.rs +++ b/crates/bashkit/src/zapcode_vendor/vm/builtins.rs @@ -68,6 +68,8 @@ pub fn call_global_method( fn call_console_method(method: &str, args: &[Value], stdout: &mut String) -> Result> { match method { "log" | "info" | "warn" | "error" | "debug" => { + // bashkit fork: spread arguments may share one large string. + crate::zapcode_guard::reserve_join(args, " ")?; let output: Vec = args.iter().map(|v| v.to_js_string()).collect(); let line = output.join(" "); stdout.push_str(&line); @@ -216,6 +218,8 @@ fn call_json_method(method: &str, args: &[Value]) -> Result> { match method { "stringify" => { let val = args.first().unwrap_or(&Value::Undefined); + // bashkit fork: size the JSON text before building it. + crate::zapcode_guard::reserve_json(val)?; let json = value_to_json(val); Ok(Some(Value::String(Arc::from(json.as_str())))) } @@ -493,6 +497,8 @@ fn call_string_method(s: &Arc, method: &str, args: &[Value]) -> Result 10_000_000 { return Err(ZapcodeError::AllocationLimitExceeded); } + // bashkit fork: the 10 MB cap can exceed a tighter per-run limit. + crate::zapcode_guard::reserve(result_len)?; Value::String(Arc::from(s.repeat(count).as_str())) } "padStart" => { @@ -509,6 +515,7 @@ fn call_string_method(s: &Arc, method: &str, args: &[Value]) -> Result 10_000_000 { return Err(ZapcodeError::AllocationLimitExceeded); } + crate::zapcode_guard::reserve(target_len)?; let padding: String = pad.chars().cycle().take(pad_len).collect(); Value::String(Arc::from(format!("{}{}", padding, s).as_str())) } @@ -527,12 +534,15 @@ fn call_string_method(s: &Arc, method: &str, args: &[Value]) -> Result 10_000_000 { return Err(ZapcodeError::AllocationLimitExceeded); } + crate::zapcode_guard::reserve(target_len)?; let padding: String = pad.chars().cycle().take(pad_len).collect(); Value::String(Arc::from(format!("{}{}", s, padding).as_str())) } } "split" => { let separator = arg_str(args, 0); + // bashkit fork: one new value per part. + crate::zapcode_guard::reserve_values(if separator.is_empty() { s.len() } else { s.matches(&*separator).count() + 1 })?; let parts: Vec = if separator.is_empty() { s.chars() .map(|c| Value::String(Arc::from(c.to_string().as_str()))) @@ -547,14 +557,20 @@ fn call_string_method(s: &Arc, method: &str, args: &[Value]) -> Result { let search = arg_str(args, 0); let replacement = arg_str(args, 1); + // bashkit fork: a large replacement multiplies per match. + crate::zapcode_guard::reserve_replace(s, &search, &replacement, false)?; Value::String(Arc::from(s.replacen(&*search, &replacement, 1).as_str())) } "replaceAll" => { let search = arg_str(args, 0); let replacement = arg_str(args, 1); + // bashkit fork: a large replacement multiplies per match. + crate::zapcode_guard::reserve_replace(s, &search, &replacement, true)?; Value::String(Arc::from(s.replace(&*search, &replacement).as_str())) } "concat" => { + // bashkit fork: arguments may share one large string many times. + crate::zapcode_guard::reserve_join(args, "")?; let mut result = s.to_string(); for arg in args { result.push_str(&arg.to_js_string()); @@ -604,6 +620,8 @@ fn call_array_method(arr: &[Value], method: &str, args: &[Value]) -> Result = arr.iter().map(|v| v.to_js_string()).collect(); Value::String(Arc::from(joined.join(&sep).as_str())) } diff --git a/crates/bashkit/tests/integration/main.rs b/crates/bashkit/tests/integration/main.rs index e6e6cc442..c8c4decce 100644 --- a/crates/bashkit/tests/integration/main.rs +++ b/crates/bashkit/tests/integration/main.rs @@ -183,6 +183,7 @@ pub mod threat_model_doc_tests; pub mod threat_model_tests; pub mod time_command_tests; pub mod time_compat_scan_tests; +pub mod ts_tenant_stress_tests; pub mod tty_tests; pub mod typescript_integration_tests; pub mod typescript_security_tests; @@ -192,7 +193,7 @@ pub mod urandom_tests; pub mod workflow_security_tests; pub mod yq_integration_tests; -// Monty python3 fails closed without bashkit's metered allocator. -#[cfg(feature = "python")] +// Monty python3 and ZapCode ts fail closed without bashkit's metered allocator. +#[cfg(any(feature = "python", feature = "typescript"))] #[global_allocator] static ALLOC: bashkit::MeteredAllocator = bashkit::MeteredAllocator; diff --git a/crates/bashkit/tests/integration/threat_model_tests.rs b/crates/bashkit/tests/integration/threat_model_tests.rs index 94724f421..9b47064eb 100644 --- a/crates/bashkit/tests/integration/threat_model_tests.rs +++ b/crates/bashkit/tests/integration/threat_model_tests.rs @@ -7642,6 +7642,118 @@ mod typescript_security { assert_eq!(result.stdout.trim(), "007|abxyx"); } + /// Run `script` from a VFS file so template literals and quotes need no + /// shell escaping. + async fn run_ts_file(bash: &mut Bash, script: &str) -> bashkit::ExecResult { + bash.exec(&format!( + "cat > /tmp/m.ts <<'TSEOF'\n{script}\nTSEOF\nts /tmp/m.ts" + )) + .await + .unwrap() + } + + fn bash_with_ts_mem(bytes: usize) -> Bash { + Bash::builder() + .typescript_with_limits(TypeScriptLimits::default().max_memory(bytes)) + .build() + } + + fn assert_ts_memory_refused(result: &bashkit::ExecResult, case: &str) { + assert_ne!(result.exit_code, 0, "{case} should fail"); + assert!( + // Upstream's own size caps report "allocation limit exceeded". + result.stderr.contains("limit exceeded"), + "{case}: stderr {:?}", + result.stderr + ); + assert!( + result.stdout.is_empty(), + "{case} printed {:?}", + result.stdout + ); + } + + /// TM-TS-026: growth past `max_memory` stops the run instead of aborting + /// the host. Upstream ZapCode never read the limit; each case aborted. + #[tokio::test] + async fn threat_ts_memory_doubling_fails_cleanly() { + let mut bash = bash_with_ts_mem(32 * 1024 * 1024); + let cases = [ + ( + "template", + "let s = 'x'.repeat(1e6); for (let i = 0; i < 30; i++) { s = `${s}${s}`; } console.log(s.length)", + ), + ( + "concat", + "let a = [1]; for (let i = 0; i < 40; i++) { a = a.concat(a); } console.log(a.length)", + ), + ( + "spread", + "let a = [1]; for (let i = 0; i < 40; i++) { a = [...a, ...a]; } console.log(a.length)", + ), + ( + "plus", + "let s = 'x'.repeat(1e6); for (let i = 0; i < 30; i++) { s = s + s; } console.log(s.length)", + ), + ]; + for (case, script) in cases { + let result = run_ts_file(&mut bash, script).await; + assert_ts_memory_refused(&result, case); + } + } + + /// TM-TS-026: strings are shared, so an array of one big string costs a + /// few pointers but joins, stringifies or prints to many copies. These are + /// sized before allocating. + #[tokio::test] + async fn threat_ts_shared_string_amplification_fails_cleanly() { + let mut bash = bash_with_ts_mem(32 * 1024 * 1024); + let setup = "const s = 'x'.repeat(4e6); const a = [s, s, s, s, s, s, s, s, s, s, s, s, s, s, s, s];"; + let cases = [ + ("join", "console.log(a.join('').length)"), + ( + "join_sep", + "console.log([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].join(s).length)", + ), + ("stringify", "console.log(JSON.stringify(a).length)"), + ("to_string", "console.log(`${a}!`.length)"), + ("console_log", "console.log(...a)"), + ("string_concat", "console.log(''.concat(...a).length)"), + ("result_value", "a"), + ]; + for (case, tail) in cases { + let result = run_ts_file(&mut bash, &format!("{setup}\n{tail}")).await; + assert_ts_memory_refused(&result, case); + } + } + + /// TM-TS-026: the limit is per run. Work under the limit succeeds, and a + /// refused run leaves nothing charged for the next one. + #[tokio::test] + async fn threat_ts_memory_limit_is_per_run() { + let mut bash = bash_with_ts_mem(32 * 1024 * 1024); + let ok = "const s = 'x'.repeat(4e6); console.log([s, s].join('-').length, JSON.stringify({ s }).length)"; + for _ in 0..3 { + let result = run_ts_file(&mut bash, ok).await; + assert_eq!(result.exit_code, 0, "stderr: {}", result.stderr); + assert_eq!(result.stdout.trim(), "8000001 4000008"); + let big = run_ts_file( + &mut bash, + "let s = 'x'.repeat(1e6); while (true) { s = s + s; }", + ) + .await; + assert_ts_memory_refused(&big, "loop"); + } + // Ordinary scripts are unaffected. + let result = run_ts_file( + &mut bash, + "console.log(['a', 'b'].join(','), JSON.stringify([1, 'x']), 'ab'.repeat(3), 'a-b'.split('-').length, 'aXa'.replace('X', 'yy'))", + ) + .await; + assert_eq!(result.exit_code, 0, "stderr: {}", result.stderr); + assert_eq!(result.stdout.trim(), "a,b [1,\"x\"] ababab 2 ayya"); + } + /// TM-TS-003: TypeScript stack overflow blocked #[tokio::test] async fn threat_ts_stack_overflow() { diff --git a/crates/bashkit/tests/integration/ts_tenant_stress_tests.rs b/crates/bashkit/tests/integration/ts_tenant_stress_tests.rs new file mode 100644 index 000000000..b1934ea9d --- /dev/null +++ b/crates/bashkit/tests/integration/ts_tenant_stress_tests.rs @@ -0,0 +1,257 @@ +//! Multi-tenant stress for the vendored ZapCode `ts` (TM-TS-026). +//! +//! Many tenants share one process and a few worker threads. Hostile ones +//! (memory doubling, shared-string amplification, runaway loops, deep +//! recursion, abandoned calls) run next to well-behaved ones, round after +//! round. Each tenant must hit only its own limits, well-behaved output must +//! be exact, and the process must survive. +//! +//! Decision: sized to finish in seconds so it runs on every PR. Set +//! `BASHKIT_STRESS_ROUNDS` for a longer soak locally or in a nightly job. + +#![cfg(feature = "typescript")] + +use bashkit::{Bash, SessionLimits, TypeScriptLimits}; +use std::time::Duration; + +/// Largest `BASHKIT_STRESS_ROUNDS` accepted; also sizes the session exec() +/// headroom in `tenant` so the soak never fails on that cap instead. +const MAX_ROUNDS: usize = 1000; + +fn rounds() -> usize { + std::env::var("BASHKIT_STRESS_ROUNDS") + .ok() + .map(|v| { + v.parse::() + .ok() + .filter(|n| (1..=MAX_ROUNDS).contains(n)) + .unwrap_or_else(|| { + panic!("BASHKIT_STRESS_ROUNDS must be 1..={MAX_ROUNDS}, got {v:?}") + }) + }) + .unwrap_or(3) +} + +fn tenant(limit_mib: usize, max_ms: u64) -> Bash { + Bash::builder() + .typescript_with_limits( + TypeScriptLimits::default() + .max_memory(limit_mib * 1024 * 1024) + .max_duration(Duration::from_millis(max_ms)), + ) + .session_limits(SessionLimits::default().max_exec_calls(20 * MAX_ROUNDS as u64)) + .build() +} + +/// Run `script` from a VFS file so template literals need no shell escaping. +async fn exec_ts(bash: &mut Bash, script: &str) -> bashkit::ExecResult { + bash.exec(&format!( + "cat > /tmp/t.ts <<'TSEOF'\n{script}\nTSEOF\nts /tmp/t.ts" + )) + .await + .unwrap() +} + +#[derive(Clone, Copy, Debug)] +enum Load { + /// Computes and prints a known value. + Good, + /// Doubles a string until past the limit. + Doubling, + /// One big string shared many times, then joined. + Amplify, + /// Never terminates on its own. + Spin, + /// Unbounded recursion. + Recurse, +} + +const LOADS: [Load; 5] = [ + Load::Good, + Load::Doubling, + Load::Amplify, + Load::Spin, + Load::Recurse, +]; + +fn script(load: Load) -> &'static str { + match load { + Load::Good => "let t = 0; for (let i = 0; i < 20000; i++) { t += i * i; } console.log(t)", + Load::Doubling => { + "let s = 'x'.repeat(1e6); for (let i = 0; i < 30; i++) { s = `${s}${s}`; } console.log(s.length)" + } + Load::Amplify => { + "const s = 'x'.repeat(2e6); const a = [s, s, s, s, s, s, s, s, s, s]; console.log(a.join('').length)" + } + Load::Spin => "while (true) {}", + Load::Recurse => "function f(n) { return f(n + 1); } f(0)", + } +} + +async fn run(load: Load) { + // Only the runaway loop should end on time; the rest must end on their + // own limit (memory, stack) or finish, even in a slow debug build. + let max_ms = if matches!(load, Load::Spin) { + 300 + } else { + 10_000 + }; + let mut bash = tenant(16, max_ms); + let r = exec_ts(&mut bash, script(load)).await; + match load { + Load::Good => { + assert_eq!(r.exit_code, 0, "{load:?} stderr: {}", r.stderr); + assert_eq!(r.stdout, "2666466670000\n", "{load:?}"); + } + Load::Doubling | Load::Amplify => { + assert_ne!(r.exit_code, 0, "{load:?} stdout: {}", r.stdout); + assert!( + r.stderr.contains("limit exceeded"), + "{load:?} stderr: {}", + r.stderr + ); + } + Load::Spin => { + assert_eq!(r.exit_code, 124, "{load:?} stderr: {}", r.stderr); + } + Load::Recurse => { + assert_ne!(r.exit_code, 0, "{load:?}"); + assert!( + r.stderr.contains("stack overflow"), + "{load:?} stderr: {}", + r.stderr + ); + } + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn ts_mixed_hostile_and_good_tenants_stay_isolated() { + for _ in 0..rounds() { + let mut handles = Vec::new(); + // 4 of each load = 20 tenants on 4 worker threads. + for i in 0..20 { + handles.push(tokio::spawn(run(LOADS[i % LOADS.len()]))); + } + for h in handles { + h.await.unwrap(); + } + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn ts_abandoned_calls_do_not_poison_the_worker_threads() { + // Drop ts calls while they are suspended on a host call (caller-side + // timeout), holding 4 MiB (each host call also snapshots the VM heap). If + // dropping them corrupted the per-thread meter, later runs on the same + // threads and session would fail or pass wrongly. + const HOLD_AND_YIELD: &str = "const x = 'a'.repeat(4 * 1024 * 1024); while (true) { await writeFile('/tmp/spin', 'x'); }"; + const AFTER: &str = "const x = 'a'.repeat(9 * 1024 * 1024); console.log(x.length / 1048576)"; + for _ in 0..rounds() { + let mut abandoned = Vec::new(); + for _ in 0..8 { + abandoned.push(tokio::spawn(async { + let mut bash = tenant(16, 5000); + let script = + format!("cat > /tmp/h.ts <<'TSEOF'\n{HOLD_AND_YIELD}\nTSEOF\nts /tmp/h.ts"); + let outcome = + tokio::time::timeout(Duration::from_millis(50), bash.exec(&script)).await; + assert!( + outcome.is_err(), + "call finished instead of being abandoned: {:?}", + outcome.map(|r| r.map(|r| (r.exit_code, r.stderr.to_string()))) + ); + let r = exec_ts(&mut bash, AFTER).await; + assert_eq!(r.exit_code, 0, "after abandon stderr: {}", r.stderr); + assert_eq!(r.stdout, "9\n"); + })); + } + for h in abandoned { + h.await.unwrap(); + } + let mut after = Vec::new(); + for i in 0..8 { + let load = if i % 2 == 0 { + Load::Good + } else { + Load::Doubling + }; + after.push(tokio::spawn(run(load))); + } + for h in after { + h.await.unwrap(); + } + } +} + +#[tokio::test] +async fn ts_one_session_reuses_its_budget_across_many_calls() { + // Keeps 10 of 16 MiB live per call, many times over. Memory charged in one + // call must be released at its end, or later calls would trip the limit. + let mut bash = tenant(16, 2000); + for i in 0..(10 * rounds()) { + let r = exec_ts( + &mut bash, + "const x = 'a'.repeat(9 * 1024 * 1024); console.log(x.length / 1048576)", + ) + .await; + assert_eq!(r.exit_code, 0, "call {i} stderr: {}", r.stderr); + assert_eq!(r.stdout, "9\n", "call {i}"); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn ts_huge_single_allocations_are_refused_up_front() { + // A request bigger than the machine has makes the global allocator fail, + // and Rust aborts the whole process (every tenant). These must be refused + // by size before allocating; run them next to a well-behaved tenant. + let bombs = [ + "'a'.padStart(2 ** 40)", + "'a'.padEnd(2 ** 40, 'xy')", + "'a'.repeat(2 ** 40)", + "'ab'.repeat(5e6).repeat(5e6)", + "const s = 'x'.repeat(5e6); [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16].join(s)", + "const s = 'x'.repeat(5e6); JSON.stringify([s, s, s, s, s, s, s, s, s, s, s, s, s, s, s, s])", + "const s = 'x'.repeat(5e6); `${[s, s, s, s, s, s, s, s, s, s, s, s, s, s, s, s]}!`", + "const s = 'x'.repeat(5e6); console.log(s, s, s, s, s, s, s, s, s, s, s, s, s, s, s, s)", + "'x'.repeat(5e6).split('')", + "'x'.repeat(1e5).replace(/x/g, 'y'.repeat(1e4))", + "'x'.repeat(1e4).replaceAll('x', 'y'.repeat(1e5))", + ]; + let mut handles = Vec::new(); + for code in bombs { + handles.push(tokio::spawn(async move { + let mut bash = tenant(64, 10_000); + let r = exec_ts(&mut bash, code).await; + assert_ne!(r.exit_code, 0, "{code}: stdout {}", r.stdout); + assert!( + r.stdout.len() < 1024, + "{code}: printed {} bytes", + r.stdout.len() + ); + })); + } + handles.push(tokio::spawn(run(Load::Good))); + for h in handles { + h.await.unwrap(); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn ts_host_call_loops_stop_at_the_wall_clock_limit() { + // A loop of cheap host calls must still stop at max_duration (wall clock), + // not only at VM time. + let mut bash = tenant(16, 500); + let started = std::time::Instant::now(); + let r = exec_ts( + &mut bash, + "while (true) { await writeFile('/tmp/spin', 'x'); }", + ) + .await; + let elapsed = started.elapsed(); + assert_eq!(r.exit_code, 124, "stderr: {}", r.stderr); + assert!( + elapsed < Duration::from_secs(2), + "ran {elapsed:?} past a 500 ms limit" + ); +} diff --git a/knowledge/log.md b/knowledge/log.md index a492d6062..681d0a217 100644 --- a/knowledge/log.md +++ b/knowledge/log.md @@ -2,6 +2,8 @@ ## 2026-11-10 +* **TypeScript `max_memory` enforced**: probing ZapCode builtins after the padStart fix found three more ways to abort the host: doubling a string with a template literal, and doubling an array with `concat` or spread. Root cause: ZapCode 1.5.1 never reads `memory_limit_bytes`; it only counts allocations and time. `ts` now runs each script under its own `vm_meter` window (the Monty meter, renamed from `python_meter`), checks live heap at every instruction, and sizes output-amplifying builtins (`join`, `JSON.stringify`, array `toString`, `console.log`, string `concat`, `repeat`, `split`, `replace`) before allocating, since shared strings make `[s, s, s].join()` cost pointers but produce copies. Native `ts` fails closed without `MeteredAllocator`. Fork edits moved to `zapcode_vendor/fork-edits.json`. See [ZapCode Runtime](runtimes/zapcode-runtime.md#memory-limit), TM-TS-026. +* **TypeScript wall-clock limit at host calls**: the new `ts_tenant_stress_tests` (modelled on the Monty suite) found `while (true) { await writeFile(...) }` ran 30 s under a 500 ms `max_duration`, because ZapCode restarts its clock at every resume. The host-call loop now checks the run's wall-clock deadline, caps callbacks at the remaining time, and yields. See [ZapCode Runtime](runtimes/zapcode-runtime.md#wall-clock-limit-and-stress), TM-TS-027. * **ZapCode vendored on every target; padStart/padEnd capped**: the pre-release check reproduced security audit F5 on main: `ts -c "'a'.padStart(2**40)"` makes zapcode-core 1.5.1 (latest on crates.io) reserve ~1 TiB, and the failed allocation aborts the process with every tenant. Native builds now use the in-tree ZapCode copy that wasm32-unknown-unknown already used (renamed `zapcode_browser` to `zapcode_vendor`), the registry `zapcode-core` dependency is gone, and the copy carries a `bashkit fork:` edit capping the pad target length at 10,000,000 like upstream `repeat`. `scripts/check_zapcode_vendor.py` now lists fork edits and fails on unlisted markers. A crates.io fork like `bashkit-monty` was not needed since the copy ships inside `bashkit`. See [ZapCode Runtime](runtimes/zapcode-runtime.md#vendored-source), [Threat Model](security/threat-model.md), TM-TS-025. ## 2026-11-09 diff --git a/knowledge/runtimes/python-builtin.md b/knowledge/runtimes/python-builtin.md index 8763693a0..3ef869d7b 100644 --- a/knowledge/runtimes/python-builtin.md +++ b/knowledge/runtimes/python-builtin.md @@ -139,7 +139,7 @@ fork adds two process-wide hooks in `monty_types::resource`: time checkpoint before the tracker's own time check; `Err` stops the run uncatchably. -Per-VM memory metering (`src/python_meter.rs`): `bashkit::MeteredAllocator` +Per-VM memory metering (`src/vm_meter.rs`): `bashkit::MeteredAllocator` wraps `System` and charges each allocation to the `VmMeter` of the Monty VM currently running on that thread (a const thread-local pointer, set by an RAII `VmWindow` around `MontyRun::new`, `start` and every `resume`). Those calls are diff --git a/knowledge/runtimes/zapcode-runtime.md b/knowledge/runtimes/zapcode-runtime.md index 90686da7c..38355f9cf 100644 --- a/knowledge/runtimes/zapcode-runtime.md +++ b/knowledge/runtimes/zapcode-runtime.md @@ -155,14 +155,15 @@ for the full threat analysis. - **Code injection via bash variable expansion**: variables expand before reaching the builtin, by-design consistent with all builtins. Use single quotes to prevent expansion. -- **Resource exhaustion**: ZapCode enforces independent time/memory/stack caps - even if shell limits are generous. +- **Resource exhaustion**: time, stack and allocation-count caps apply even if + shell limits are generous. Memory is enforced by Bashkit, not ZapCode (see + [Memory limit](#memory-limit)). - **Sandbox escape via filesystem**: no direct FS access; bridged functions go through the VFS (`/etc/passwd` reads VFS, not host). - **Sandbox escape via eval/import**: `eval()`, `Function()`, `import`, `require` blocked at the language level (not implemented). -- **DoS via large output**: console.log output captured in memory; ZapCode - memory limit bounds it. +- **DoS via large output**: console.log output captured in memory; the memory + limit bounds it. ### Error Handling @@ -198,6 +199,54 @@ a hint to `help()` and `system_prompt()`: > File I/O via readFile()/writeFile() async functions. No npm/import/require. > No HTTP/network. No eval(). +### Memory limit + +Decision (2026-11-10, TM-TS-026): ZapCode 1.5.1 stores `memory_limit_bytes` but +never reads it, and a failed Rust allocation aborts the process with every +tenant. Bashkit enforces `max_memory` itself with the meter Monty uses +(`crate::vm_meter`, charged by `MeteredAllocator`): + +- Each `ts` run gets its own `VmMeter`. Every ZapCode step (start, each resume + after an external call, formatting the result value) runs inside a + `VmWindow` for it, on the same thread, so only that run's allocations count. +- Every instruction (`check_time`) stops the run with `memory limit exceeded` + once live heap passes the limit. That catches gradual growth: doubling a + string with `+` or a template literal, `concat`, spread, `push` loops. +- Strings are shared `Arc`, so `[s, s, s]` costs pointers but `join`, + array `toString`, `JSON.stringify`, `''.concat(...)` and `console.log(...)` + produce full copies. `src/zapcode_guard.rs` sizes those outputs before + allocating (the walk stops once past the remaining budget) and refuses. + `repeat`, `split`, `replace`/`replaceAll` and `padStart`/`padEnd` reserve + their computed size the same way. Refusal is sticky, so a caller that cannot + return an error (array `toString`) returns an empty string and the next + instruction stops the run. +- Without `MeteredAllocator` as the global allocator the meter would read + zero, so native `ts` fails closed with an error naming the allocator. Every + bashkit binary, binding, example and test harness that enables + `typescript` installs it. On wasm32 the check is skipped (no probe), and + bashkit-wasm installs the allocator for its `typescript` feature. + +Not metered: memory allocated by the host between steps (VFS bridging, the +external-function callbacks), which is bounded by Bashkit's own limits. + +### Wall-clock limit and stress + +Decision (2026-11-10, TM-TS-027): ZapCode restarts its time tracker at every +resume, so `max_duration` alone bounded one VM step, not the run. The host-call +loop in `typescript.rs` checks a wall-clock deadline (run start plus +`max_duration`) before every host call, caps the call itself at the remaining +time, and yields to the executor, so caller-side timeouts can cancel a run and +co-tenants on the worker thread keep running. A single VM step can still run +up to `max_duration`, so a run ends within about twice the limit. + +`tests/integration/ts_tenant_stress_tests.rs` mixes hostile `ts` tenants +(memory doubling, shared-string amplification, spin, recursion, abandoned +calls, huge single allocations) with good ones on shared worker threads; each +must hit only its own limit. It runs 3 rounds on every PR; +`BASHKIT_STRESS_ROUNDS` sets a longer soak. Each host call snapshots the VM +heap, so a held 8 MiB string costs about 3x that during the call and counts +against `max_memory`. + ### Vendored source Decision (2026-11-10): every target builds the in-tree copy of ZapCode 1.5.1 in @@ -206,9 +255,11 @@ longer a dependency. Two reasons: 1. **Resource-limit fixes.** Upstream allocates unchecked in places, and an allocation failure aborts the whole process (all tenants). Bashkit carries - those fixes as `bashkit fork:` edits. Current: `padStart`/`padEnd` reject a - target length above 10,000,000 with `AllocationLimitExceeded`, the same cap - upstream applies to `repeat` (TM-TS-025, security audit run-1 F5). + those fixes as `bashkit fork:` edits, listed in `fork-edits.json`. Current: + `padStart`/`padEnd` reject a target length above 10,000,000 with + `AllocationLimitExceeded`, the same cap upstream applies to `repeat` + (TM-TS-025, security audit run-1 F5), and the memory-limit hooks in + [Memory limit](#memory-limit) (TM-TS-026). 2. **Browser clocks.** ZapCode uses std Instant in its resource tracker and Instant/SystemTime in tracing, which panic on wasm32-unknown-unknown. The copy reads Bashkit's clock shim (`crate::time`), which is std::time on diff --git a/knowledge/security/threat-model.md b/knowledge/security/threat-model.md index adf3397c5..bdfb2538c 100644 --- a/knowledge/security/threat-model.md +++ b/knowledge/security/threat-model.md @@ -2206,7 +2206,7 @@ TypeScript execution requires two explicit opt-in steps, matching the Python bui | ID | Threat | Severity | Mitigation | Test | |----|--------|----------|------------|------| | TM-TS-001 | Infinite loop via `while (true) {}` | High | ZapCode time limit (default 30s) | `threat_ts_infinite_loop` | -| TM-TS-002 | Memory exhaustion via large allocation | High | ZapCode max_memory (64MB) + max_allocations (1M) | `threat_ts_memory_exhaustion` | +| TM-TS-002 | Memory exhaustion via large allocation | High | Bashkit-enforced max_memory (64MB, TM-TS-026) + ZapCode max_allocations (1M) | `threat_ts_memory_exhaustion` | | TM-TS-003 | Stack overflow via deep recursion | High | ZapCode max_stack_depth (512) | `threat_ts_stack_overflow` | | TM-TS-004 | Allocation bomb (many small objects) | High | ZapCode max_allocations (1M) | `threat_ts_allocation_bomb` | | TM-TS-005 | Real filesystem access via VFS | Critical | VFS bridge reads only from Bashkit VFS, not host | `threat_ts_vfs_no_real_fs` | @@ -2230,6 +2230,8 @@ TypeScript execution requires two explicit opt-in steps, matching the Python bui | TM-TS-023 | Shebang line injection | Low | Shebang stripped safely | `threat_ts_shebang_stripped` | | TM-TS-024 | Deeply nested source overflows the native stack in ZapCode's parser/compiler and aborts the host process | Critical | Conservative nesting estimate rejects depth > 1000 before ZapCode; parse/compile run on a 128 MiB-stack thread (4x debug margin) | `deeply_nested_source_fails_cleanly`, `deep_nesting_at_the_limit_does_not_overflow`, `deep_nesting_past_the_limit_is_rejected` | | TM-TS-025 | `'a'.padStart(2**40)` / `padEnd` asks the allocator for ~1 TiB and aborts the host process (all tenants) | High | Vendored ZapCode `bashkit fork:` edit caps the target length at 10,000,000 (same cap as `repeat`) and fails the run with `AllocationLimitExceeded` | `threat_ts_pad_huge_length_fails_cleanly` | +| TM-TS-026 | Script grows memory past `max_memory` (doubling strings/arrays, or joining/stringifying/printing an array that shares one big string many times) and the failed allocation aborts the host process (all tenants) | Critical | ZapCode 1.5.1 never read `memory_limit_bytes`. Each run gets a per-VM `vm_meter` (charged by `MeteredAllocator`); every instruction stops the run once live heap passes `max_memory`, and amplifying operations (`join`, array `toString`, `JSON.stringify`, `concat`, `console.log`, `repeat`, `split`, `replace`, `padStart`) size their output first and refuse. ts fails closed when `MeteredAllocator` is not the global allocator | `threat_ts_memory_doubling_fails_cleanly`, `threat_ts_shared_string_amplification_fails_cleanly`, `threat_ts_memory_limit_is_per_run`, `ts_tenant_stress_tests::*` | +| TM-TS-027 | Host-call loop outruns the time limit / starves the worker thread | High | ZapCode restarts its clock at every resume, so `max_duration` bounded one VM step and `while (true) { await writeFile(...) }` ran until the shell timeout (30 s under a 500 ms limit). The host-call loop checks the wall-clock deadline at every call, caps each host callback at the remaining time, and yields to the executor there | `ts_tenant_stress_tests::ts_host_call_loops_stop_at_the_wall_clock_limit`, `ts_tenant_stress_tests::ts_abandoned_calls_do_not_poison_the_worker_threads` | ### Blocked Language Features diff --git a/scripts/check_zapcode_vendor.py b/scripts/check_zapcode_vendor.py index 274ffb546..904e94ebc 100644 --- a/scripts/check_zapcode_vendor.py +++ b/scripts/check_zapcode_vendor.py @@ -4,8 +4,9 @@ Allowed differences, each reversed before hashing: - namespace: `crate::` -> `crate::zapcode_vendor::`, lib.rs -> mod.rs - platform clock: sandbox.rs/trace.rs read `crate::time::` (Bashkit's shim) -- `bashkit fork:` edits listed in FORK_EDITS (resource-limit fixes upstream - has not shipped). Every marker in the tree must be listed here. +- `bashkit fork:` insertions listed in zapcode_vendor/fork-edits.json + (resource-limit fixes upstream has not shipped). Every marker in the tree + must be listed there. """ import hashlib import json @@ -13,12 +14,11 @@ root = Path(__file__).resolve().parents[1] / "crates/bashkit/src/zapcode_vendor" -PAD_CAP = ( - " // bashkit fork: cap like `repeat`; unbounded take() aborted the host.\n" - " if target_len > 10_000_000 { return Err(ZapcodeError::AllocationLimitExceeded); }\n" -) -# (file, inserted text, number of occurrences). TM-TS-025: padStart/padEnd. -FORK_EDITS = [("vm/builtins.rs", PAD_CAP, 2)] +# Each entry: file, inserted text (whole lines), occurrences. TM-TS-025/026. +FORK_EDITS = [ + (e["file"], e["insert"], e["count"]) + for e in json.loads((root / "fork-edits.json").read_text()) +] expected = json.loads((root / "upstream-sha256.json").read_text()) actual_paths = {str(p.relative_to(root)) for p in root.rglob("*.rs")} From 95ee6aa06c7ac41a08325dd001cf8194bde87d4a Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Tue, 10 Nov 2026 21:34:15 +0000 Subject: [PATCH 2/8] test(ts): add ts_fuzz target, nightly ASan pass and stress soak Mirror the Monty coverage for the vendored ZapCode VM: a ts_fuzz target under the metered allocator (nightly fuzz matrix plus CI compile check), an ASan step for the ts unit, threat-model and stress tests, and a 300-round ts-stress-soak job. --- .github/workflows/ci.yml | 1 + .github/workflows/fuzz.yml | 3 +- .github/workflows/nightly.yml | 39 +++ crates/bashkit/fuzz/Cargo.lock | 334 +++++++++++++++++++- crates/bashkit/fuzz/Cargo.toml | 11 + crates/bashkit/fuzz/fuzz_targets/ts_fuzz.rs | 98 ++++++ knowledge/log.md | 1 + knowledge/runtimes/zapcode-runtime.md | 9 + knowledge/security/threat-model.md | 4 +- 9 files changed, 494 insertions(+), 6 deletions(-) create mode 100644 crates/bashkit/fuzz/fuzz_targets/ts_fuzz.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bf7c8f659..0f25a064a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -698,6 +698,7 @@ jobs: cargo +nightly-2026-10-30 fuzz build --features cpython cpython_http_fuzz cargo +nightly-2026-10-30 fuzz build --features python python_fuzz cargo +nightly-2026-10-30 fuzz build --features python,cpython python_diff_fuzz + cargo +nightly-2026-10-30 fuzz build --features typescript ts_fuzz # Gate job for branch protection — name must stay "Check" check: diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index eaf135246..51f8ce3de 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -26,7 +26,7 @@ jobs: strategy: fail-fast: false matrix: - target: [parser_fuzz, lexer_fuzz, analyze_fuzz, arithmetic_fuzz, glob_fuzz, cpython_fuzz, cpython_http_fuzz, python_fuzz, python_diff_fuzz] + target: [parser_fuzz, lexer_fuzz, analyze_fuzz, arithmetic_fuzz, glob_fuzz, cpython_fuzz, cpython_http_fuzz, python_fuzz, python_diff_fuzz, ts_fuzz] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -76,6 +76,7 @@ jobs: python_diff_fuzz) features=(--features python,cpython) ;; cpython_*) features=(--features cpython) ;; python_*) features=(--features python) ;; + ts_fuzz) features=(--features typescript) ;; esac cargo +nightly-2026-10-30 fuzz run "${features[@]}" ${{ matrix.target }} -- \ -max_total_time="$DURATION_INPUT" \ diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index cdd570e30..c5428a3b9 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -194,6 +194,19 @@ jobs: cargo +nightly-2026-10-30 test -Z build-std --target x86_64-unknown-linux-gnu \ -p bashkit --features python --lib --test integration -- --test-threads=1 python + # The vendored ZapCode VM (crates/bashkit/src/zapcode_vendor) is our + # code too, and ts runs under the same metered allocator. The filters + # pick up the unit, threat-model, security and tenant stress tests (a + # bare `ts` would match every `tests` module path). + - name: Run ts (ZapCode) tests with AddressSanitizer + env: + RUSTFLAGS: "-Z sanitizer=address" + ASAN_OPTIONS: "detect_stack_use_after_return=1:detect_leaks=0" + run: | + cargo +nightly-2026-10-30 test -Z build-std --target x86_64-unknown-linux-gnu \ + -p bashkit --features typescript --lib --test integration -- --test-threads=1 \ + typescript threat_ts ts_tenant_stress zapcode + python-stress-soak: name: Python multi-tenant stress soak # PR CI runs python_tenant_stress_tests at 3 rounds. The soak repeats @@ -220,3 +233,29 @@ jobs: run: | cargo test --release -p bashkit --features python --test integration \ -- python_tenant_stress + + ts-stress-soak: + name: TypeScript multi-tenant stress soak + # PR CI runs ts_tenant_stress_tests at 3 rounds. The soak repeats them in + # release mode so rare cross-tenant leaks (meter left on a worker thread, + # charge not released after an abandoned call) show up. + runs-on: ubuntu-latest + timeout-minutes: 45 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install Rust toolchain + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 + + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 + with: + cache-on-failure: true + + - name: Run stress soak + env: + BASHKIT_STRESS_ROUNDS: "300" + run: | + cargo test --release -p bashkit --features typescript --test integration \ + -- ts_tenant_stress diff --git a/crates/bashkit/fuzz/Cargo.lock b/crates/bashkit/fuzz/Cargo.lock index 903b34e74..36cda72a3 100644 --- a/crates/bashkit/fuzz/Cargo.lock +++ b/crates/bashkit/fuzz/Cargo.lock @@ -189,6 +189,12 @@ dependencies = [ "num-bigint", "num-traits", "os_display", + "oxc_allocator", + "oxc_ast", + "oxc_parser", + "oxc_span", + "oxc_syntax", + "postcard", "regex", "regex-automata", "rustls", @@ -531,6 +537,20 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2550f75b8cfac212855f6b1885455df8eaee8fe8e246b647d69146142e016084" +[[package]] +name = "compact_str" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dfdd1c2274d9aa354115b09dc9a901d6c5576818cdf70d14cae2bdb47df00ab" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "rustversion", + "ryu", + "static_assertions", +] + [[package]] name = "compact_str" version = "0.10.0" @@ -556,6 +576,12 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "cow-utils" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417bef24afe1460300965a25ff4a24b8b45ad011948302ec221e8a0a81eb2c79" + [[package]] name = "cpp_demangle" version = "0.5.1" @@ -876,6 +902,12 @@ dependencies = [ "syn 3.0.3", ] +[[package]] +name = "dragonbox_ecma" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd8e701084c37e7ef62d3f9e453b618130cbc0ef3573847785952a3ac3f746bf" + [[package]] name = "drop_bomb" version = "0.1.5" @@ -1074,7 +1106,7 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "050a5d07359ebfac7f0b74916d94cfa30575e45fdc7e9bfbb0f76d5d4203325a" dependencies = [ - "compact_str", + "compact_str 0.10.0", "get-size-derive2", "hashbrown 0.17.1", "ordermap", @@ -1714,6 +1746,12 @@ dependencies = [ "libc", ] +[[package]] +name = "nonmax" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "610a5acd306ec67f907abe5567859a3c693fb9886eb1f012ab8f2a47bef3db51" + [[package]] name = "num-bigint" version = "0.4.8" @@ -1779,6 +1817,212 @@ dependencies = [ "unicode-width", ] +[[package]] +name = "owo-colors" +version = "4.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c45bb4a6ae1280ec0803b1ef9d3455eb50f01efbbe1447ab020f1d54fba9d8" + +[[package]] +name = "oxc-miette" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356a61f2ed4c9b3610245215fbf48970eb277126919f87db9d0efa93a74245c" +dependencies = [ + "cfg-if", + "owo-colors", + "oxc-miette-derive", + "textwrap", + "thiserror", + "unicode-segmentation", + "unicode-width", +] + +[[package]] +name = "oxc-miette-derive" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b237422b014f8f8fff75bb9379e697d13f8d57551a22c88bebb39f073c1bf696" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "oxc_allocator" +version = "0.117.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97b44277218c002c09167474648a478d3d29a29095ef8950ec9f1fac016c62d7" +dependencies = [ + "allocator-api2", + "hashbrown 0.16.1", + "oxc_data_structures", + "rustc-hash", +] + +[[package]] +name = "oxc_ast" +version = "0.117.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4222e4e7a1ab01b2a20420a5a65798377a748ea37ee7ece4d7a6b733f86eb61" +dependencies = [ + "bitflags 2.13.1", + "oxc_allocator", + "oxc_ast_macros", + "oxc_data_structures", + "oxc_diagnostics", + "oxc_estree", + "oxc_regular_expression", + "oxc_span", + "oxc_syntax", +] + +[[package]] +name = "oxc_ast_macros" +version = "0.117.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e65a38ae589e284dd45a85008024f04aa680e9ddf1321c163cf7f187c805e91" +dependencies = [ + "phf 0.13.1", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "oxc_data_structures" +version = "0.117.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f53bed71cad192596aee8f87f6d6bc2a38a4f898255a69b1d41da1968b9b2c6f" + +[[package]] +name = "oxc_diagnostics" +version = "0.117.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a2d2491c0a1ea29a83abe645424f85c64b5c825f60e5304a453e4314a8b6d88" +dependencies = [ + "cow-utils", + "oxc-miette", + "percent-encoding", +] + +[[package]] +name = "oxc_ecmascript" +version = "0.117.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71b23b64fa8c4a84b1406de383c4666366c9f54ffb9cb11a63b8d7433950460a" +dependencies = [ + "cow-utils", + "num-bigint", + "num-traits", + "oxc_allocator", + "oxc_ast", + "oxc_regular_expression", + "oxc_span", + "oxc_syntax", +] + +[[package]] +name = "oxc_estree" +version = "0.117.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a47515ead44bc8beec1ae1514f10ecca63cde043da167c0395dc914f098ea5d2" + +[[package]] +name = "oxc_index" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb3e6120999627ec9703025eab7c9f410ebb7e95557632a8902ca48210416c2b" +dependencies = [ + "nonmax", + "serde", +] + +[[package]] +name = "oxc_parser" +version = "0.117.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3278d4f34d01cdaf85a2391d7b12daba1d95c20c1ff2ac9316d3c28f36353e4e" +dependencies = [ + "bitflags 2.13.1", + "cow-utils", + "memchr", + "num-bigint", + "num-traits", + "oxc_allocator", + "oxc_ast", + "oxc_data_structures", + "oxc_diagnostics", + "oxc_ecmascript", + "oxc_regular_expression", + "oxc_span", + "oxc_syntax", + "rustc-hash", + "seq-macro", +] + +[[package]] +name = "oxc_regular_expression" +version = "0.117.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3d680252672b22c24abbaf6e401eace0be9f53072a03411936204625ff349d0" +dependencies = [ + "bitflags 2.13.1", + "oxc_allocator", + "oxc_ast_macros", + "oxc_diagnostics", + "oxc_span", + "phf 0.13.1", + "rustc-hash", + "unicode-id-start", +] + +[[package]] +name = "oxc_span" +version = "0.117.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6eb1bd62de89fb0c646bfb053b72370750fab43a84ebe09ad97cfa020712314" +dependencies = [ + "compact_str 0.9.1", + "oxc-miette", + "oxc_allocator", + "oxc_ast_macros", + "oxc_estree", + "oxc_str", +] + +[[package]] +name = "oxc_str" +version = "0.117.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e65cbfb06ecbae07e0da931815b6b03ade886d016302c400bda7dc0a2f600d3" +dependencies = [ + "compact_str 0.9.1", + "hashbrown 0.16.1", + "oxc_allocator", + "oxc_estree", +] + +[[package]] +name = "oxc_syntax" +version = "0.117.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0f1617f0aa890517fb61ffa1d2d73a8497aca52e84ef6f027fad1e93250eccc" +dependencies = [ + "bitflags 2.13.1", + "cow-utils", + "dragonbox_ecma", + "nonmax", + "oxc_allocator", + "oxc_ast_macros", + "oxc_estree", + "oxc_index", + "oxc_span", + "phf 0.13.1", + "unicode-id-start", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -1800,11 +2044,22 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "913273894cec178f401a31ec4b656318d95473527be05c0752cc41cdc32be8b7" dependencies = [ - "phf_macros", + "phf_macros 0.12.1", "phf_shared 0.12.1", "serde", ] +[[package]] +name = "phf" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +dependencies = [ + "phf_macros 0.13.1", + "phf_shared 0.13.1", + "serde", +] + [[package]] name = "phf_codegen" version = "0.11.3" @@ -1835,6 +2090,16 @@ dependencies = [ "phf_shared 0.12.1", ] +[[package]] +name = "phf_generator" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" +dependencies = [ + "fastrand", + "phf_shared 0.13.1", +] + [[package]] name = "phf_macros" version = "0.12.1" @@ -1848,6 +2113,19 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "phf_macros" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" +dependencies = [ + "phf_generator 0.13.1", + "phf_shared 0.13.1", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "phf_shared" version = "0.11.3" @@ -1866,6 +2144,15 @@ dependencies = [ "siphasher", ] +[[package]] +name = "phf_shared" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +dependencies = [ + "siphasher", +] + [[package]] name = "pin-project-lite" version = "0.2.17" @@ -2203,7 +2490,7 @@ dependencies = [ "arrayvec", "bitflags 2.13.1", "char_str", - "compact_str", + "compact_str 0.10.0", "get-size2", "is-macro", "memchr", @@ -2409,6 +2696,12 @@ dependencies = [ "serde_core", ] +[[package]] +name = "seq-macro" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc" + [[package]] name = "serde" version = "1.0.229" @@ -2541,6 +2834,12 @@ dependencies = [ "serde", ] +[[package]] +name = "smawk" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8e2fb0f499abb4d162f2bedad68f5ef91a1682b5a03596ddb67efd37768d100" + [[package]] name = "speedate" version = "0.17.0" @@ -2674,6 +2973,17 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "textwrap" +version = "0.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c13547615a44dc9c452a8a534638acdf07120d4b6847c8178705da06306a3057" +dependencies = [ + "smawk", + "unicode-linebreak", + "unicode-width", +] + [[package]] name = "thin-vec" version = "0.2.21" @@ -2782,12 +3092,24 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f" +[[package]] +name = "unicode-id-start" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0825d2e09dcae814a4273c1e1435979d414ede25b2ee235b1545da6682483765" + [[package]] name = "unicode-ident" version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" +[[package]] +name = "unicode-linebreak" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f" + [[package]] name = "unicode-normalization" version = "0.1.26" @@ -2797,6 +3119,12 @@ dependencies = [ "tinyvec", ] +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + [[package]] name = "unicode-width" version = "0.2.2" diff --git a/crates/bashkit/fuzz/Cargo.toml b/crates/bashkit/fuzz/Cargo.toml index edfe05e03..ea8c4b236 100644 --- a/crates/bashkit/fuzz/Cargo.toml +++ b/crates/bashkit/fuzz/Cargo.toml @@ -26,6 +26,9 @@ cpython = ["bashkit/cpython"] # Monty python3 target (bashkit-monty fork). Run with: # cargo +nightly fuzz run python_fuzz --features python python = ["bashkit/python"] +# ZapCode ts target (vendored zapcode_vendor). Run with: +# cargo +nightly fuzz run ts_fuzz --features typescript +typescript = ["bashkit/typescript"] # Prevent this from interfering with workspaces [workspace] @@ -191,3 +194,11 @@ required-features = ["python", "cpython"] test = false doc = false bench = false + +[[bin]] +name = "ts_fuzz" +path = "fuzz_targets/ts_fuzz.rs" +required-features = ["typescript"] +test = false +doc = false +bench = false diff --git a/crates/bashkit/fuzz/fuzz_targets/ts_fuzz.rs b/crates/bashkit/fuzz/fuzz_targets/ts_fuzz.rs new file mode 100644 index 000000000..9ad0038c8 --- /dev/null +++ b/crates/bashkit/fuzz/fuzz_targets/ts_fuzz.rs @@ -0,0 +1,98 @@ +//! Fuzz target for the embedded ZapCode `ts` builtin (vendored zapcode_vendor) +//! +//! Feeds arbitrary programs and command lines to `ts` to find: +//! - Host panics or aborts in the vendored ZapCode parser, compiler or VM +//! - Memory-limit bypasses (TM-TS-026): the metered allocator charges each +//! run; a program that outgrows `max_memory` (32 MiB here) trips libFuzzer's +//! RSS limit or aborts on a failed allocation +//! - Time-limit bypasses: each exec must return near its wall-clock budget +//! - Sandbox escapes: host environment (FUZZ_HOST_CANARY) +//! - Internal Debug shapes leaking into stderr (TM-INF-022) +//! +//! Decision: install `bashkit::MeteredAllocator` as the global allocator, the +//! same way every shipped binding does. Without it `ts` fails closed and the +//! target would only exercise the refusal path. +//! +//! Run with: cargo +nightly fuzz run ts_fuzz --features typescript -- -max_total_time=300 + +#![no_main] + +use libfuzzer_sys::fuzz_target; +use std::time::{Duration, Instant}; + +#[global_allocator] +static ALLOC: bashkit::MeteredAllocator = bashkit::MeteredAllocator; + +/// Wall-clock budget per exec. ts gets 500 ms; the slack covers setup on a +/// loaded fuzz runner. A hang past this is a time-limit bypass. +const EXEC_BUDGET: Duration = Duration::from_secs(5); + +fuzz_target!(|data: &[u8]| { + let Ok(input) = std::str::from_utf8(data) else { + return; + }; + // Keep error messages (which may quote the source) under the stderr cap. + if input.len() > 512 || bashkit::testing::input_echo_would_trip(input) { + return; + } + + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + + rt.block_on(async { + bashkit::testing::fuzz_init(); + let mut bash = bashkit::Bash::builder() + .typescript_with_limits( + bashkit::TypeScriptLimits::default() + .max_duration(Duration::from_millis(500)) + .max_memory(32 * 1024 * 1024) + .max_allocations(200_000), + ) + .limits( + bashkit::ExecutionLimits::new() + .max_commands(50) + .max_stdout_bytes(4096) + .max_stderr_bytes(1024) + .timeout(Duration::from_secs(2)), + ) + .build(); + + let _ = bash + .fs() + .write_file(std::path::Path::new("/fuzz.ts"), input.as_bytes()) + .await; + + let quoted = input.replace('\'', "'\\''"); + let scripts = [ + // Program from a VFS file. + "ts /fuzz.ts".to_string(), + // Program from stdin. + "ts < /fuzz.ts".to_string(), + // Program inline via -c. + format!("ts -c '{quoted}'"), + // Input as a command line (CLI option parsing). + format!("ts '{quoted}' -c 'console.log(1)'"), + ]; + // Once per process: prove ts really runs (allocator installed), so the + // target cannot silently fuzz only the fail-closed path. + static CANARY: std::sync::Once = std::sync::Once::new(); + let mut canary_ok = true; + if !CANARY.is_completed() { + let r = bash.exec("ts -c 'console.log(6*7)'").await.unwrap(); + canary_ok = r.stdout.to_string() == "42\n"; + CANARY.call_once(|| {}); + } + assert!(canary_ok, "[ts_fuzz] ts does not run; check the allocator"); + for script in &scripts { + let start = Instant::now(); + bashkit::testing::fuzz_exec(&mut bash, script, "ts_fuzz", &[]).await; + let elapsed = start.elapsed(); + assert!( + elapsed < EXEC_BUDGET, + "[ts_fuzz] exec took {elapsed:?} (budget {EXEC_BUDGET:?}): {script}" + ); + } + }); +}); diff --git a/knowledge/log.md b/knowledge/log.md index 681d0a217..d8546af08 100644 --- a/knowledge/log.md +++ b/knowledge/log.md @@ -4,6 +4,7 @@ * **TypeScript `max_memory` enforced**: probing ZapCode builtins after the padStart fix found three more ways to abort the host: doubling a string with a template literal, and doubling an array with `concat` or spread. Root cause: ZapCode 1.5.1 never reads `memory_limit_bytes`; it only counts allocations and time. `ts` now runs each script under its own `vm_meter` window (the Monty meter, renamed from `python_meter`), checks live heap at every instruction, and sizes output-amplifying builtins (`join`, `JSON.stringify`, array `toString`, `console.log`, string `concat`, `repeat`, `split`, `replace`) before allocating, since shared strings make `[s, s, s].join()` cost pointers but produce copies. Native `ts` fails closed without `MeteredAllocator`. Fork edits moved to `zapcode_vendor/fork-edits.json`. See [ZapCode Runtime](runtimes/zapcode-runtime.md#memory-limit), TM-TS-026. * **TypeScript wall-clock limit at host calls**: the new `ts_tenant_stress_tests` (modelled on the Monty suite) found `while (true) { await writeFile(...) }` ran 30 s under a 500 ms `max_duration`, because ZapCode restarts its clock at every resume. The host-call loop now checks the run's wall-clock deadline, caps callbacks at the remaining time, and yields. See [ZapCode Runtime](runtimes/zapcode-runtime.md#wall-clock-limit-and-stress), TM-TS-027. +* **ZapCode in fuzzing, nightly ASan and soak**: new `ts_fuzz` target (nightly `fuzz.yml`, CI compile check), a `--features typescript` ASan step, and a `ts-stress-soak` job at 300 rounds, mirroring the Monty coverage added 2026-11-07. See [ZapCode Runtime](runtimes/zapcode-runtime.md#wall-clock-limit-and-stress). * **ZapCode vendored on every target; padStart/padEnd capped**: the pre-release check reproduced security audit F5 on main: `ts -c "'a'.padStart(2**40)"` makes zapcode-core 1.5.1 (latest on crates.io) reserve ~1 TiB, and the failed allocation aborts the process with every tenant. Native builds now use the in-tree ZapCode copy that wasm32-unknown-unknown already used (renamed `zapcode_browser` to `zapcode_vendor`), the registry `zapcode-core` dependency is gone, and the copy carries a `bashkit fork:` edit capping the pad target length at 10,000,000 like upstream `repeat`. `scripts/check_zapcode_vendor.py` now lists fork edits and fails on unlisted markers. A crates.io fork like `bashkit-monty` was not needed since the copy ships inside `bashkit`. See [ZapCode Runtime](runtimes/zapcode-runtime.md#vendored-source), [Threat Model](security/threat-model.md), TM-TS-025. ## 2026-11-09 diff --git a/knowledge/runtimes/zapcode-runtime.md b/knowledge/runtimes/zapcode-runtime.md index 38355f9cf..735f15243 100644 --- a/knowledge/runtimes/zapcode-runtime.md +++ b/knowledge/runtimes/zapcode-runtime.md @@ -247,6 +247,15 @@ must hit only its own limit. It runs 3 rounds on every PR; heap, so a held 8 MiB string costs about 3x that during the call and counts against `max_memory`. +Nightly (`nightly.yml`): an ASan pass over the ts unit, threat-model, security +and stress tests (`--features typescript`, filters `typescript threat_ts +ts_tenant_stress zapcode`), and a `ts-stress-soak` job at 300 rounds in +release. Fuzzing: `fuzz/fuzz_targets/ts_fuzz.rs` runs in the nightly +`fuzz.yml` matrix under the metered allocator with a 32 MiB `max_memory`, so a +memory-limit bypass trips libFuzzer's RSS limit; a canary run asserts `ts` +really executes. Locally: +`cargo +nightly-2026-10-30 fuzz run --features typescript ts_fuzz -- -max_total_time=300`. + ### Vendored source Decision (2026-11-10): every target builds the in-tree copy of ZapCode 1.5.1 in diff --git a/knowledge/security/threat-model.md b/knowledge/security/threat-model.md index bdfb2538c..c42a06ed2 100644 --- a/knowledge/security/threat-model.md +++ b/knowledge/security/threat-model.md @@ -530,7 +530,7 @@ echoes the same text, and the named internal (the arithmetic tokenizer's `Tok` enum, say) is never formatted. Two independent defenses handle this, and a fuzz target that inlines raw bytes needs one of them: either its diagnostic matches a template `strip_real_shell_error_lines` recognizes, or the target -pre-filters with `input_echo_would_trip` as `glob_fuzz`, `cpython_fuzz`, `python_fuzz` and +pre-filters with `input_echo_would_trip` as `glob_fuzz`, `cpython_fuzz`, `python_fuzz`, `ts_fuzz` and `arithmetic_fuzz` do. Arithmetic diagnostics are not one of those templates, so `arithmetic_fuzz` went red in run 271 on `:A>>=::TTA:::Tok::::` until it pre-filtered. Adding a builtin whose errors quote user text means choosing one @@ -2230,7 +2230,7 @@ TypeScript execution requires two explicit opt-in steps, matching the Python bui | TM-TS-023 | Shebang line injection | Low | Shebang stripped safely | `threat_ts_shebang_stripped` | | TM-TS-024 | Deeply nested source overflows the native stack in ZapCode's parser/compiler and aborts the host process | Critical | Conservative nesting estimate rejects depth > 1000 before ZapCode; parse/compile run on a 128 MiB-stack thread (4x debug margin) | `deeply_nested_source_fails_cleanly`, `deep_nesting_at_the_limit_does_not_overflow`, `deep_nesting_past_the_limit_is_rejected` | | TM-TS-025 | `'a'.padStart(2**40)` / `padEnd` asks the allocator for ~1 TiB and aborts the host process (all tenants) | High | Vendored ZapCode `bashkit fork:` edit caps the target length at 10,000,000 (same cap as `repeat`) and fails the run with `AllocationLimitExceeded` | `threat_ts_pad_huge_length_fails_cleanly` | -| TM-TS-026 | Script grows memory past `max_memory` (doubling strings/arrays, or joining/stringifying/printing an array that shares one big string many times) and the failed allocation aborts the host process (all tenants) | Critical | ZapCode 1.5.1 never read `memory_limit_bytes`. Each run gets a per-VM `vm_meter` (charged by `MeteredAllocator`); every instruction stops the run once live heap passes `max_memory`, and amplifying operations (`join`, array `toString`, `JSON.stringify`, `concat`, `console.log`, `repeat`, `split`, `replace`, `padStart`) size their output first and refuse. ts fails closed when `MeteredAllocator` is not the global allocator | `threat_ts_memory_doubling_fails_cleanly`, `threat_ts_shared_string_amplification_fails_cleanly`, `threat_ts_memory_limit_is_per_run`, `ts_tenant_stress_tests::*` | +| TM-TS-026 | Script grows memory past `max_memory` (doubling strings/arrays, or joining/stringifying/printing an array that shares one big string many times) and the failed allocation aborts the host process (all tenants) | Critical | ZapCode 1.5.1 never read `memory_limit_bytes`. Each run gets a per-VM `vm_meter` (charged by `MeteredAllocator`); every instruction stops the run once live heap passes `max_memory`, and amplifying operations (`join`, array `toString`, `JSON.stringify`, `concat`, `console.log`, `repeat`, `split`, `replace`, `padStart`) size their output first and refuse. ts fails closed when `MeteredAllocator` is not the global allocator | `threat_ts_memory_doubling_fails_cleanly`, `threat_ts_shared_string_amplification_fails_cleanly`, `threat_ts_memory_limit_is_per_run`, `ts_tenant_stress_tests::*`, `fuzz/fuzz_targets/ts_fuzz.rs` (nightly, metered allocator, 32 MiB cap under libFuzzer RSS limit) | | TM-TS-027 | Host-call loop outruns the time limit / starves the worker thread | High | ZapCode restarts its clock at every resume, so `max_duration` bounded one VM step and `while (true) { await writeFile(...) }` ran until the shell timeout (30 s under a 500 ms limit). The host-call loop checks the wall-clock deadline at every call, caps each host callback at the remaining time, and yields to the executor there | `ts_tenant_stress_tests::ts_host_call_loops_stop_at_the_wall_clock_limit`, `ts_tenant_stress_tests::ts_abandoned_calls_do_not_poison_the_worker_threads` | ### Blocked Language Features From 5e8d800733425ee25700deb961dec5708c2fbf2a Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Tue, 10 Nov 2026 21:44:18 +0000 Subject: [PATCH 3/8] refactor(ts): pass run time limit and deadline as one RunClock (clippy) --- crates/bashkit/src/builtins/typescript.rs | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/crates/bashkit/src/builtins/typescript.rs b/crates/bashkit/src/builtins/typescript.rs index 5b6b53d44..c6463e2d1 100644 --- a/crates/bashkit/src/builtins/typescript.rs +++ b/crates/bashkit/src/builtins/typescript.rs @@ -950,8 +950,10 @@ async fn run_typescript( cwd, external_fns, execution_budget.as_ref(), - time_limit, - deadline, + RunClock { + limit: time_limit, + deadline, + }, &meter, ) .await @@ -1009,6 +1011,13 @@ fn charge_vm_time(budget: Option<&crate::limits::ExecutionBudget>, started: Inst Ok(()) } +/// Time limit of one `ts` run and its wall-clock deadline (TM-TS-027). +#[derive(Clone, Copy)] +struct RunClock { + limit: std::time::Duration, + deadline: Option, +} + /// Process a VmState, handling suspension for external function calls. async fn process_vm_result( result: RunResult, @@ -1016,10 +1025,13 @@ async fn process_vm_result( cwd: &Path, external_fns: Option<&TypeScriptExternalFns>, execution_budget: Option<&crate::limits::ExecutionBudget>, - time_limit: std::time::Duration, - deadline: Option, + clock: RunClock, meter: &crate::vm_meter::VmMeter, ) -> Result { + let RunClock { + limit: time_limit, + deadline, + } = clock; let stdout = result.stdout; let mut state = result.state; From ac8869a36135db51d67f444c81995b215a6b6f7b Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Tue, 10 Nov 2026 22:00:25 +0000 Subject: [PATCH 4/8] docs(ts): install MeteredAllocator in the TypeScript guide quick start --- crates/bashkit/docs/typescript.md | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/crates/bashkit/docs/typescript.md b/crates/bashkit/docs/typescript.md index f55373675..fdea652f7 100644 --- a/crates/bashkit/docs/typescript.md +++ b/crates/bashkit/docs/typescript.md @@ -1,8 +1,9 @@ # Embedded TypeScript (ZapCode) > **Experimental.** ZapCode is an early-stage TypeScript interpreter that may -> have undiscovered crash or security bugs. Resource limits are enforced by -> ZapCode's VM. The integration should be treated as experimental. +> have undiscovered crash or security bugs. Bashkit enforces the memory and +> wall-clock limits itself (ZapCode only counts allocations and VM time). The +> integration should be treated as experimental. Bashkit embeds the [ZapCode](https://github.com/TheUncharted/zapcode) TypeScript interpreter, a pure-Rust implementation with ~2µs cold start, no V8 dependency, @@ -17,11 +18,16 @@ resource limits and no host access. ## Quick Start -Enable the `typescript` feature and register via builder: +Enable the `typescript` feature, install `bashkit::MeteredAllocator` as the +global allocator (the memory limit reads it; without it `ts` refuses to run), +and register via builder: ```rust use bashkit::Bash; +#[global_allocator] +static ALLOC: bashkit::MeteredAllocator = bashkit::MeteredAllocator; + # #[tokio::main] # async fn main() -> bashkit::Result<()> { let mut bash = Bash::builder().typescript().build(); From 43b1831e02b1bb772a26abcf38a8057d42b0b075 Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Tue, 10 Nov 2026 22:05:51 +0000 Subject: [PATCH 5/8] fix(ts): stop a run over its memory limit before a host call --- crates/bashkit/src/builtins/typescript.rs | 9 +++++++++ crates/bashkit/src/vm_meter.rs | 11 ++++++++--- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/crates/bashkit/src/builtins/typescript.rs b/crates/bashkit/src/builtins/typescript.rs index c6463e2d1..1fd59b2b5 100644 --- a/crates/bashkit/src/builtins/typescript.rs +++ b/crates/bashkit/src/builtins/typescript.rs @@ -1065,6 +1065,15 @@ async fn process_vm_result( if let Some(budget) = execution_budget { budget.consume_work(100)?; } + // A refused reservation is sticky; never hand a host call the + // placeholder it produced (TM-TS-026). + if meter.is_over_limit() { + return Ok(format_error_with_output( + crate::zapcode_guard::limit_error(), + &stdout, + time_limit, + )); + } // Wall-clock bound (TM-TS-027), then yield: the VM never yields // on its own, so without this a caller-side timeout cannot // cancel the call and co-tenants on the worker thread starve. diff --git a/crates/bashkit/src/vm_meter.rs b/crates/bashkit/src/vm_meter.rs index 6f30f9883..2407446ce 100644 --- a/crates/bashkit/src/vm_meter.rs +++ b/crates/bashkit/src/vm_meter.rs @@ -77,6 +77,13 @@ impl VmMeter { } /// Bytes this VM currently holds. + /// True when this meter holds more than its limit or refused a + /// [`reserve`]; usable between steps, outside any window. + #[cfg_attr(not(feature = "typescript"), allow(dead_code))] + pub(crate) fn is_over_limit(&self) -> bool { + self.limit > 0 && (self.exceeded.load(Ordering::Relaxed) || self.live() > self.limit) + } + pub(crate) fn live(&self) -> usize { self.live.load(Ordering::Relaxed) } @@ -260,9 +267,7 @@ pub(crate) fn allocator_installed() -> bool { #[cfg_attr(not(feature = "typescript"), allow(dead_code))] pub(crate) fn over_limit() -> bool { let mut over = false; - with_current(|m| { - over = m.limit > 0 && (m.exceeded.load(Ordering::Relaxed) || m.live() > m.limit); - }); + with_current(|m| over = m.is_over_limit()); over } From ec09005c7cf2a2b17c72f859af3998cfdc6ea22d Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Tue, 10 Nov 2026 22:06:07 +0000 Subject: [PATCH 6/8] chore(knowledge): note the wasm32 ts metering residual risk --- knowledge/runtimes/zapcode-runtime.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/knowledge/runtimes/zapcode-runtime.md b/knowledge/runtimes/zapcode-runtime.md index 735f15243..2f9edff8d 100644 --- a/knowledge/runtimes/zapcode-runtime.md +++ b/knowledge/runtimes/zapcode-runtime.md @@ -223,8 +223,11 @@ tenant. Bashkit enforces `max_memory` itself with the meter Monty uses - Without `MeteredAllocator` as the global allocator the meter would read zero, so native `ts` fails closed with an error naming the allocator. Every bashkit binary, binding, example and test harness that enables - `typescript` installs it. On wasm32 the check is skipped (no probe), and - bashkit-wasm installs the allocator for its `typescript` feature. + `typescript` installs it. On wasm32 the check is skipped, and + bashkit-wasm installs the allocator for its `typescript` feature. Residual + risk: a third-party wasm32 embedder that enables `typescript` without the + allocator gets only the per-operation size checks, not the cumulative + limit (a tab or isolate OOM, not a shared host abort). Not metered: memory allocated by the host between steps (VFS bridging, the external-function callbacks), which is bounded by Bashkit's own limits. From f9cc8b93e43885c2186a1ade06226f21daace236 Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Tue, 10 Nov 2026 20:53:02 +0000 Subject: [PATCH 7/8] fix(deps): pick up fetchkit 0.7.2 linear readable extraction fetchkit 0.7.2 makes readable/agent content focus linear on hostile nesting (TM-DOS-009, security audit F8); 0.7.1 spent ~57 s CPU on a 2.16 MB crafted page inside the fetchkit builtin. --- Cargo.lock | 8 ++++---- crates/bashkit/Cargo.toml | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e395ad441..7265d93ff 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2169,9 +2169,9 @@ checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" [[package]] name = "fetchkit" -version = "0.7.1" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8256b05aa0fc9f4b989f17665578917c580103f36a2af81b20e4b9c2f195d281" +checksum = "44dad6aca1684b78cd1c27e4d5d767b636a05ba0c7b113503db150c01f1ef970" dependencies = [ "async-trait", "bytes", @@ -2195,9 +2195,9 @@ dependencies = [ [[package]] name = "fetchkit-cli" -version = "0.7.1" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c4073e4fa53582027dd32b32f045e33508960fa3bb6b24d97de817ec560815b" +checksum = "7825c9cf5fbf9e4fe0e0c645c573cb28ecdb4efb71ba0fc0068d9ff7f462b284" dependencies = [ "async-trait", "clap", diff --git a/crates/bashkit/Cargo.toml b/crates/bashkit/Cargo.toml index 6247c2988..d0dbaed16 100644 --- a/crates/bashkit/Cargo.toml +++ b/crates/bashkit/Cargo.toml @@ -442,8 +442,8 @@ markkit-cli = { version = "0.3.1", default-features = false, features = ["all_fo markkit = { version = "0.3.1", default-features = false, features = ["all_formats"], optional = true } # fetchkit builtin (native only). No `reqwest-tls`: all traffic goes through # bashkit's HttpClient, so fetchkit adds no TLS stack. -fetchkit-cli = { version = "0.7.1", default-features = false, features = ["docs-pdf", "docs-markkit"], optional = true } -fetchkit = { version = "0.7.1", default-features = false, features = ["docs-pdf", "docs-markkit"], optional = true } +fetchkit-cli = { version = "0.7.2", default-features = false, features = ["docs-pdf", "docs-markkit"], optional = true } +fetchkit = { version = "0.7.2", default-features = false, features = ["docs-pdf", "docs-markkit"], optional = true } # std::time::{Instant,SystemTime} panic on wasm32-unknown-unknown; see # time_compat/mod.rs. Only pulled in for wasm32 — everywhere else time_compat From 6c00569534dcfc15de0a178f6af7c62b3e227252 Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Tue, 10 Nov 2026 21:36:55 +0000 Subject: [PATCH 8/8] chore(supply-chain): exempt fetchkit 0.7.2 --- supply-chain/config.toml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/supply-chain/config.toml b/supply-chain/config.toml index 57ffdf250..525a6d122 100644 --- a/supply-chain/config.toml +++ b/supply-chain/config.toml @@ -277,7 +277,7 @@ criteria = "safe-to-deploy" [[exemptions.brotli-decompressor]] version = "5.0.3" criteria = "safe-to-deploy" -notes = "New transitive dep of lopdf 0.45 via fetchkit 0.7.1 (fetchkit feature only, off by default). Widely used decompressor from the brotli crate family." +notes = "New transitive dep of lopdf 0.45 via fetchkit 0.7.x (fetchkit feature only, off by default). Widely used decompressor from the brotli crate family." [[exemptions.bstr]] version = "1.13.1" @@ -738,11 +738,11 @@ version = "2.5.0" criteria = "safe-to-deploy" [[exemptions.fetchkit]] -version = "0.7.1" +version = "0.7.2" criteria = "safe-to-deploy" [[exemptions.fetchkit-cli]] -version = "0.7.1" +version = "0.7.2" criteria = "safe-to-deploy" [[exemptions.ff]] @@ -1517,7 +1517,7 @@ criteria = "safe-to-deploy" [[exemptions.pdf-inspector]] version = "1.25.2" criteria = "safe-to-deploy" -notes = "Major jump from 0.1.8, pulled in by fetchkit 0.7.1 (the version fetchkit ships and tests with). Parses untrusted PDFs only behind the off-by-default `fetchkit` feature; bashkit's fetchkit builtin tests and markkit_fetchkit example pass on it." +notes = "Major jump from 0.1.8, pulled in by fetchkit 0.7.x (the version fetchkit ships and tests with). Parses untrusted PDFs only behind the off-by-default `fetchkit` feature; bashkit's fetchkit builtin tests and markkit_fetchkit example pass on it." [[exemptions.pem-rfc7468]] version = "1.0.0"