diff --git a/crates/bashkit/docs/threat-model.md b/crates/bashkit/docs/threat-model.md index 085dc830d..f5979bcd5 100644 --- a/crates/bashkit/docs/threat-model.md +++ b/crates/bashkit/docs/threat-model.md @@ -60,6 +60,7 @@ through configurable limits. | Unicode path attacks (TM-DOS-015) | RTL override in filename | `validate_path()` rejects control/bidi chars | MITIGATED | | TOCTOU append (TM-DOS-034) | Concurrent appends bypass limits | Single write lock | **FIXED** | | OverlayFs upper-only check (TM-DOS-035) | `check_write_limits()` ignores lower layer | Combined limit accounting | **MITIGATED** | +| DEBUG trap recursive amplification (TM-DOS-145) | Commands in a DEBUG/ERR trap recursively trigger traps | Suppress trap re-entry with the per-interpreter `in_trap` guard | **FIXED** | | OverlayFs double-count (TM-DOS-036) | `compute_usage()` counts overwritten files | Subtract overrides | **MITIGATED** | | OverlayFs chmod CoW bypass (TM-DOS-037) | chmod writes to unlimited upper | Route through `check_write_limits()` | **MITIGATED** | | OverlayFs incomplete whiteout (TM-DOS-038) | `rm -r` misses lower children | Check ancestor whiteouts | **MITIGATED** | @@ -204,6 +205,7 @@ handling, including discarded output. Stdout cached text shares that budget | jq unbounded generator (TM-DOS-093) | `jq -n 'repeat(1)'` / `range(0;1e18)` | Cap output at `max_stdout_bytes`; poll deadline every 4096 values | FIXED | | Persistent history memory DoS (TM-DOS-094) | Unbounded command history in long-lived instances | `ExecutionLimits` caps history entries/bytes/output | FIXED | | Multi-component glob amplification (TM-DOS-095) | `/*/*/*/*` multiplies the candidate set at each component | Reject patterns deeper than `max_path_depth`; cap live candidates at `max_file_count` | FIXED | +| CLI host-stdin memory ingestion (TM-DOS-146) | An unbounded producer grows one-shot CLI stdin before execution | Read at most `MAX_STDIN_BYTES + 1`; reject over-cap input; `--no-stdin` opts out | FIXED | | Aggregate budget refresh (TM-DOS-096) | Nest/mix parsers, pipelines, traversal, runtimes, archives, and callbacks to restart local ceilings | One poisoned request-scoped `ExecutionBudget` meters aggregate work/input/live bytes without replacing subsystem caps | MITIGATED | | Tilde expansion amplification (TM-DOS-134) | Large `HOME`/`PWD`/`OLDPWD` repeated after assignment colons | Borrowed directories, checked pre-allocation live-byte reservations, byte-proportional work/deadline checks, and leases retained through assignment/field consumption; failures abort expansion | MITIGATED | | Contradictory execution-profile limits (TM-DOS-097) | Host config silently requests ineffective or impossible limits | Validate profile cross-field invariants before `BashBuilder` accepts it | MITIGATED | @@ -420,6 +422,7 @@ Network access is disabled by default. When enabled, strict controls apply. | Embedded CLI egress bypass (TM-NET-030) | `fetchkit fetch`/`markkit extract URL` follow a redirect off the allowlist or read host proxy env | Both builtins send every hop through the sandbox HTTP client (allowlist re-checked per hop); no own TLS stack; `--allow-env-proxy` refused | MITIGATED | | Host header steers credentials (TM-NET-031) | `curl -H 'Host: other'` to an approved IP | Caller Host/framing/proxy headers are dropped before credential injection | MITIGATED | | Encoded slash escapes path rule (TM-NET-032) | `/v1/..%2Fadmin` against a `/v1/` rule | Path-scoped rules refuse `%2F`/`%5C` | MITIGATED | +| Host proxy leakage (TM-NET-033) | `HTTP_PROXY` routes sandbox traffic through host infrastructure | The built-in client uses `.no_proxy()` and ignores host proxy variables | MITIGATED | **Credential Injection (TM-NET-024–027):** @@ -552,7 +555,7 @@ echo $user_input |--------|---------------|------------|--------| | Shared filesystem (TM-ISO-001) | Access other tenant files | Separate Bash instances | MITIGATED | | Shared memory (TM-ISO-002) | Read other tenant data | Rust memory safety | MITIGATED | -| Resource starvation (TM-ISO-003) | One tenant exhausts limits | Per-instance limits | MITIGATED | +| Aggregate resource starvation (TM-ISO-003) | Concurrent tenants exhaust shared workers, VM threads, CPU, or memory | TypeScript has process-wide asynchronous admission (TM-TS-028); per-instance limits contain each request. CPU-bound Python still holds one shared worker (TM-PY-039), and same-process CPU/memory are not hard-isolated | PARTIAL | | Cross-tenant jq env (TM-ISO-004) | `std::env::set_var()` in jq | Custom jaq context variable | **FIXED** | | Cumulative counter bypass (TM-ISO-005) | Repeated `exec()` resets counters | Session-level counters | **MITIGATED** | | Memory budget exhaustion (TM-ISO-006) | Unbounded variable/array growth | Per-instance MemoryLimits | **MITIGATED** | @@ -747,7 +750,7 @@ Python `pathlib.Path` and `open()` operations are bridged to Bashkit's virtual f | Host-call loop outruns the time limit (TM-PY-036) | `while True:` around a cheap file write; Monty's clock pauses on host calls and the VM never yields the thread | Wall-clock deadline and an executor yield at every host call | MITIGATED | | Shared-graph walk outlives time limit (TM-PY-037) | `x = [x, x]` repeated, then `repr` or `==` inside Python | Forked tracker counts every amortized check on one tick, so recursive walks still check time | MITIGATED | | Huge `json.dumps` indent (TM-PY-038) | `json.dumps(x, indent=10**12)` or a huge separator inside Python | Indent size and every separator/indent write are checked against the memory limit (`MemoryError`) | MITIGATED | -| CPU-bound run holds a shared worker thread (TM-PY-039) | `while True: pass` or `for (;;) {}` with no host calls; the run yields only at host calls | Per-run cap (profile 30 s, Hardened 10 s; Python bindings: `timeout_seconds`) plus the execution deadline. Hosts that raise `timeout_seconds` accept a longer hold | ACCEPTED | +| CPU-bound Python run holds a shared worker thread (TM-PY-039) | `while True: pass` with no host calls; the run yields only at host calls | Per-run cap (profile 30 s, Hardened 10 s; Python bindings: `timeout_seconds`) plus the execution deadline. Hosts that raise `timeout_seconds` accept a longer hold. TypeScript uses separate native admission (TM-TS-028) | ACCEPTED | **Architecture:** @@ -895,9 +898,10 @@ access is bridged through Bashkit's VFS, never the host filesystem. | 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 | +| CPU-only VM step starves async workers (TM-TS-028) | Concurrent `while (true) {}` steps synchronously join dedicated 128 MiB-stack threads from Tokio workers | Run and join on the blocking pool; process-wide active-VM semaphore (default at most 4, configurable before first use); queue wait consumes the caller deadline and abandoned work retains its permit | 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-027), including error-isolation and +Per-threat coverage (TM-TS-001 … TM-TS-028), 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/docs/typescript.md b/crates/bashkit/docs/typescript.md index fdea652f7..75084d930 100644 --- a/crates/bashkit/docs/typescript.md +++ b/crates/bashkit/docs/typescript.md @@ -186,6 +186,25 @@ When the duration limit fires, the command exits with status 124 and prints `ts: execution timed out after Ns` on stderr, like coreutils `timeout` and `python3`. Any other error (including a script's own `throw`) exits 1. +Native VM steps use dedicated 128 MiB-stack threads so accepted parser depth +cannot overflow the host stack. A process-wide admission limit bounds active +VM threads across every `Bash` instance and keeps their joins off Tokio async +workers. The default is available CPU parallelism capped at four. Configure it +once, before the first TypeScript execution: + +```rust +use bashkit::configure_typescript_vm_concurrency; + +configure_typescript_vm_concurrency(2)?; +# Ok::<(), bashkit::TypeScriptVmConcurrencyError>(()) +``` + +Excess calls wait asynchronously, and that queue time consumes each call's +own duration limit. If an admitted VM step outlives the caller deadline it may +finish in the background, but it retains its slot until it stops, so abandoned +work cannot exceed the configured cap. wasm32 has no native threads; VM steps +there still run synchronously on the JavaScript event loop. + ## Configuration Use `TypeScriptConfig` for full control over aliases and hint behavior: diff --git a/crates/bashkit/src/builtins/mod.rs b/crates/bashkit/src/builtins/mod.rs index 4e6d3d66b..4c92967b0 100644 --- a/crates/bashkit/src/builtins/mod.rs +++ b/crates/bashkit/src/builtins/mod.rs @@ -316,7 +316,7 @@ pub use python::{Python, PythonExternalFnHandler, PythonExternalFns, PythonLimit #[cfg(feature = "typescript")] pub use typescript::{ TypeScriptConfig, TypeScriptExtension, TypeScriptExternalFnHandler, TypeScriptExternalFns, - TypeScriptLimits, + TypeScriptLimits, TypeScriptVmConcurrencyError, configure_typescript_vm_concurrency, }; #[cfg(feature = "sqlite")] diff --git a/crates/bashkit/src/builtins/typescript.rs b/crates/bashkit/src/builtins/typescript.rs index 371acada2..68409e5e2 100644 --- a/crates/bashkit/src/builtins/typescript.rs +++ b/crates/bashkit/src/builtins/typescript.rs @@ -22,6 +22,8 @@ use std::future::Future; use std::path::{Path, PathBuf}; use std::pin::Pin; use std::sync::Arc; +#[cfg(not(target_arch = "wasm32"))] +use std::sync::OnceLock; use std::time::Duration; use zapcode_core::{ResourceLimits, RunResult, Value, VmState, ZapcodeRun}; @@ -52,6 +54,118 @@ const TS_CALL_WORK_UNITS: u64 = 4096; #[cfg(not(target_arch = "wasm32"))] const TS_VM_STACK_BYTES: usize = 128 * 1024 * 1024; +/// Upper bound used when the host does not configure TypeScript VM admission. +/// Four active 128 MiB stack reservations are a deliberate process-wide cap, +/// while smaller hosts default to their available CPU parallelism. +#[cfg(not(target_arch = "wasm32"))] +const DEFAULT_MAX_ACTIVE_TS_VMS: usize = 4; + +/// Error returned by [`configure_typescript_vm_concurrency`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TypeScriptVmConcurrencyError { + /// At least one VM slot is required. + Zero, + /// Tokio cannot represent this many semaphore permits. + TooLarge { requested: usize, maximum: usize }, + /// TypeScript has already initialized the process-wide admission limit. + AlreadyInitialized { active_limit: usize }, +} + +impl std::fmt::Display for TypeScriptVmConcurrencyError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Zero => f.write_str("TypeScript VM concurrency must be at least 1"), + Self::TooLarge { requested, maximum } => write!( + f, + "TypeScript VM concurrency {requested} exceeds the maximum {maximum}" + ), + Self::AlreadyInitialized { active_limit } => write!( + f, + "TypeScript VM concurrency is already initialized at {active_limit}" + ), + } + } +} + +impl std::error::Error for TypeScriptVmConcurrencyError {} + +/// Configure the process-wide number of active native TypeScript VM steps. +/// +/// Call this once, before the first TypeScript execution. Excess steps wait +/// asynchronously and their wait time consumes their own runtime deadline. +/// The default is the host's available parallelism, capped at four. The cap +/// bounds simultaneous 128 MiB native stack reservations across all `Bash` +/// instances in the process. +/// +/// wasm32 has no native VM threads; a positive value is accepted as a no-op. +pub fn configure_typescript_vm_concurrency( + max_active: usize, +) -> std::result::Result<(), TypeScriptVmConcurrencyError> { + if max_active == 0 { + return Err(TypeScriptVmConcurrencyError::Zero); + } + if max_active > tokio::sync::Semaphore::MAX_PERMITS { + return Err(TypeScriptVmConcurrencyError::TooLarge { + requested: max_active, + maximum: tokio::sync::Semaphore::MAX_PERMITS, + }); + } + #[cfg(not(target_arch = "wasm32"))] + { + TS_VM_ADMISSION + .set(VmAdmission::new(max_active)) + .map_err(|_| TypeScriptVmConcurrencyError::AlreadyInitialized { + active_limit: vm_admission().limit, + })?; + } + Ok(()) +} + +#[cfg(not(target_arch = "wasm32"))] +#[derive(Clone)] +struct VmAdmission { + semaphore: Arc, + limit: usize, +} + +#[cfg(not(target_arch = "wasm32"))] +impl VmAdmission { + fn new(limit: usize) -> Self { + Self { + semaphore: Arc::new(tokio::sync::Semaphore::new(limit)), + limit, + } + } + + async fn acquire( + &self, + deadline: Option, + ) -> Option { + let acquire = Arc::clone(&self.semaphore).acquire_owned(); + match deadline { + Some(deadline) => { + let remaining = deadline.checked_duration_since(Instant::now())?; + crate::time_compat::timeout(remaining, acquire) + .await + .ok()? + .ok() + } + None => acquire.await.ok(), + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +static TS_VM_ADMISSION: OnceLock = OnceLock::new(); + +#[cfg(not(target_arch = "wasm32"))] +fn vm_admission() -> &'static VmAdmission { + TS_VM_ADMISSION.get_or_init(|| { + let parallelism = std::thread::available_parallelism().map_or(1, usize::from); + VmAdmission::new(parallelism.min(DEFAULT_MAX_ACTIVE_TS_VMS)) + }) +} + /// Resource limits for the embedded TypeScript (ZapCode) interpreter. /// /// Use the builder pattern to customize, or `Default` for the standard limits: @@ -914,7 +1028,9 @@ async fn run_typescript( 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 meter = Arc::new(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 @@ -935,12 +1051,23 @@ async fn run_typescript( } }; - let result = on_vm_stack(&meter, || runner.run(Vec::new())); + let result = run_vm_step(Arc::clone(&meter), deadline, move || runner.run(Vec::new())).await; charge_vm_time(execution_budget.as_ref(), started)?; let result = match result { - Some(Ok(r)) => r, - Some(Err(e)) => return Ok(format_error_with_output(e, "", time_limit)), - None => return Ok(ExecResult::err(VM_THREAD_ERROR.to_string(), 1)), + VmStepResult::Complete(Ok(r)) => r, + VmStepResult::Complete(Err(e)) => { + return Ok(format_error_with_output(e, "", time_limit)); + } + VmStepResult::TimedOut => { + return Ok(format_error_with_output( + zapcode_core::ZapcodeError::TimeLimitExceeded, + "", + time_limit, + )); + } + VmStepResult::ThreadUnavailable => { + return Ok(ExecResult::err(VM_THREAD_ERROR.to_string(), 1)); + } }; // Process the result through the suspend/resume loop for VFS bridging @@ -967,15 +1094,77 @@ const VM_THREAD_ERROR: &str = "ts: cannot start execution thread\n"; const METER_MISSING_ERROR: &str = "ts: TypeScript memory limits need bashkit::MeteredAllocator as the global allocator\n"; +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +enum VmStepResult { + Complete(T), + TimedOut, + ThreadUnavailable, +} + +/// Run one synchronous ZapCode step without blocking a Tokio worker. +/// +/// Native callers first wait asynchronously for the process-wide admission +/// slot, then move the blocking thread creation/join onto Tokio's managed +/// blocking pool. The permit lives inside that blocking task, so a caller +/// whose deadline expires cannot release the slot while its abandoned VM +/// thread is still winding down. +#[cfg(not(target_arch = "wasm32"))] +async fn run_vm_step( + meter: Arc, + deadline: Option, + step: impl FnOnce() -> T + Send + 'static, +) -> VmStepResult { + run_vm_step_with_admission(vm_admission().clone(), meter, deadline, step).await +} + +#[cfg(not(target_arch = "wasm32"))] +async fn run_vm_step_with_admission( + admission: VmAdmission, + meter: Arc, + deadline: Option, + step: impl FnOnce() -> T + Send + 'static, +) -> VmStepResult { + let Some(permit) = admission.acquire(deadline).await else { + return VmStepResult::TimedOut; + }; + let task = tokio::task::spawn_blocking(move || { + let _permit = permit; + // The blocking pool has its own queue after semaphore admission. Do + // not start a stale VM if that queue consumed the caller's deadline. + if deadline.is_some_and(|deadline| Instant::now() >= deadline) { + return VmStepResult::TimedOut; + } + match on_vm_stack(&meter, step) { + Some(result) => VmStepResult::Complete(result), + None => VmStepResult::ThreadUnavailable, + } + }); + let joined = match deadline { + Some(deadline) => { + let Some(remaining) = deadline.checked_duration_since(Instant::now()) else { + return VmStepResult::TimedOut; + }; + match crate::time_compat::timeout(remaining, task).await { + Ok(joined) => joined, + Err(_) => return VmStepResult::TimedOut, + } + } + None => task.await, + }; + match joined { + Ok(result) => result, + Err(error) if error.is_panic() => std::panic::resume_unwind(error.into_panic()), + Err(_) => VmStepResult::ThreadUnavailable, + } +} + /// 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. +/// `meter`'s window on a dedicated [`TS_VM_STACK_BYTES`] stack. `None` means +/// no thread could be started. #[cfg(not(target_arch = "wasm32"))] -fn on_vm_stack( +fn on_vm_stack( meter: &crate::vm_meter::VmMeter, - step: impl FnOnce() -> T + Send, + step: impl FnOnce() -> T + Send + 'static, ) -> Option { std::thread::scope(|scope| { let handle = std::thread::Builder::new() @@ -996,9 +1185,13 @@ fn on_vm_stack( /// 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(meter: &crate::vm_meter::VmMeter, step: impl FnOnce() -> T) -> Option { - let _window = crate::vm_meter::VmWindow::enter(meter); - Some(step()) +async fn run_vm_step( + meter: Arc, + _deadline: Option, + step: impl FnOnce() -> T, +) -> VmStepResult { + let _window = crate::vm_meter::VmWindow::enter(&meter); + VmStepResult::Complete(step()) } /// Charge the wall-clock time a synchronous VM step ran to the shared work @@ -1026,7 +1219,7 @@ async fn process_vm_result( external_fns: Option<&TypeScriptExternalFns>, execution_budget: Option<&crate::limits::ExecutionBudget>, clock: RunClock, - meter: &crate::vm_meter::VmMeter, + meter: &Arc, ) -> Result { let RunClock { limit: time_limit, @@ -1108,14 +1301,24 @@ async fn process_vm_result( }; let started = Instant::now(); - let resumed = on_vm_stack(meter, move || snapshot.resume(return_value)); + let resumed = run_vm_step(Arc::clone(meter), deadline, move || { + snapshot.resume(return_value) + }) + .await; charge_vm_time(execution_budget, started)?; state = match resumed { - Some(Ok(s)) => s, - Some(Err(e)) => { + VmStepResult::Complete(Ok(s)) => s, + VmStepResult::Complete(Err(e)) => { return Ok(format_error_with_output(e, &stdout, time_limit)); } - None => { + VmStepResult::TimedOut => { + return Ok(format_error_with_output( + zapcode_core::ZapcodeError::TimeLimitExceeded, + &stdout, + time_limit, + )); + } + VmStepResult::ThreadUnavailable => { let mut result = ExecResult::err(VM_THREAD_ERROR.to_string(), 1); result.stdout = stdout.into(); return Ok(result); @@ -1704,6 +1907,57 @@ mod tests { assert_eq!(config.limits.common.max_duration, Duration::from_secs(5)); } + #[test] + fn vm_concurrency_rejects_zero() { + assert_eq!( + configure_typescript_vm_concurrency(0), + Err(TypeScriptVmConcurrencyError::Zero) + ); + assert!(matches!( + configure_typescript_vm_concurrency(usize::MAX), + Err(TypeScriptVmConcurrencyError::TooLarge { .. }) + )); + } + + #[cfg(not(target_arch = "wasm32"))] + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn vm_admission_caps_active_threads_and_times_out_queued_steps() { + use std::sync::atomic::{AtomicUsize, Ordering}; + + let admission = VmAdmission::new(2); + let active = Arc::new(AtomicUsize::new(0)); + let maximum = Arc::new(AtomicUsize::new(0)); + let started = Arc::new(AtomicUsize::new(0)); + let mut calls = Vec::new(); + + for _ in 0..8 { + let admission = admission.clone(); + let active = Arc::clone(&active); + let maximum = Arc::clone(&maximum); + let started = Arc::clone(&started); + calls.push(tokio::spawn(async move { + let meter = Arc::new(crate::vm_meter::VmMeter::with_limit(1024)); + let deadline = Instant::now().checked_add(Duration::from_millis(100)); + run_vm_step_with_admission(admission, meter, deadline, move || { + started.fetch_add(1, Ordering::SeqCst); + let now = active.fetch_add(1, Ordering::SeqCst) + 1; + maximum.fetch_max(now, Ordering::SeqCst); + std::thread::sleep(Duration::from_millis(200)); + active.fetch_sub(1, Ordering::SeqCst); + }) + .await + })); + } + + for call in calls { + assert!(matches!(call.await.unwrap(), VmStepResult::TimedOut)); + } + tokio::time::sleep(Duration::from_millis(150)).await; + assert_eq!(started.load(Ordering::SeqCst), 2); + assert_eq!(maximum.load(Ordering::SeqCst), 2); + assert_eq!(active.load(Ordering::SeqCst), 0); + } + // --- Unsupported mode hint tests --- #[tokio::test] diff --git a/crates/bashkit/src/interpreter/mod.rs b/crates/bashkit/src/interpreter/mod.rs index 867098f76..f0a61a254 100644 --- a/crates/bashkit/src/interpreter/mod.rs +++ b/crates/bashkit/src/interpreter/mod.rs @@ -1971,7 +1971,7 @@ pub struct Interpreter { /// Interceptor hooks registry (shared with Bash callers). hooks: Arc, /// True while executing a trap handler. Suppresses recursive DEBUG trap - /// invocation to prevent amplification attacks (TM-DOS-035). + /// invocation to prevent amplification attacks (TM-DOS-145). in_trap: bool, /// Nesting level of `run_trap_command` entries (TM-DOS-020). trap_nesting: usize, @@ -3162,7 +3162,7 @@ impl Interpreter { self.nofork_now = false; self.traps_mut().clear(); self.last_exit_code = 0; - // THREAT[TM-DOS-035/057]: A timeout can drop execution while a trap + // THREAT[TM-DOS-145/057]: A timeout can drop execution while a trap // handler is awaited; clear the re-entrancy guard before each exec so // one cancelled script cannot suppress traps in the next script. self.in_trap = false; @@ -14883,7 +14883,7 @@ impl Interpreter { } /// The DEBUG handler to run before the next command, if any: not - /// inside another trap handler (TM-DOS-035), nor in a `( )` / `$( )` + /// inside another trap handler (TM-DOS-145), nor in a `( )` / `$( )` /// subshell or function body that does not inherit it. fn has_debug_trap(&self) -> bool { !self.in_trap && !self.debug_trap_dormant && self.scoped.traps.contains_key("DEBUG") @@ -15107,7 +15107,7 @@ impl Interpreter { stdout: &mut crate::StreamData, stderr: &mut crate::StreamData, ) { - // THREAT[TM-DOS-035]: Suppress ERR trap re-entrancy while executing trap + // THREAT[TM-DOS-145]: Suppress ERR trap re-entrancy while executing trap // handlers to prevent recursive ERR -> ERR amplification. if self.in_trap { return; @@ -18150,7 +18150,7 @@ echo "count=$COUNT" #[tokio::test] async fn test_debug_trap_no_recursive_amplification() { - // THREAT[TM-DOS-035]: Commands inside the DEBUG trap handler must NOT + // THREAT[TM-DOS-145]: Commands inside the DEBUG trap handler must NOT // trigger further DEBUG trap invocations (prevents N*M amplification). let result = run_script( r#"trap_count=0; trap '((trap_count++))' DEBUG; echo a; echo b; echo c; trap - DEBUG; echo $trap_count"#, diff --git a/crates/bashkit/src/lib.rs b/crates/bashkit/src/lib.rs index b96b55443..a7c7b7022 100644 --- a/crates/bashkit/src/lib.rs +++ b/crates/bashkit/src/lib.rs @@ -613,7 +613,7 @@ pub use monty_types::{ExcType, ExtFunctionResult, MontyException, MontyObject, O #[cfg(feature = "typescript")] pub use builtins::{ TypeScriptConfig, TypeScriptExtension, TypeScriptExternalFnHandler, TypeScriptExternalFns, - TypeScriptLimits, + TypeScriptLimits, TypeScriptVmConcurrencyError, configure_typescript_vm_concurrency, }; // Re-export ZapCode types needed by external handler consumers. #[cfg(feature = "typescript")] diff --git a/crates/bashkit/src/network/client.rs b/crates/bashkit/src/network/client.rs index cba2b37cd..1866e0ae1 100644 --- a/crates/bashkit/src/network/client.rs +++ b/crates/bashkit/src/network/client.rs @@ -14,7 +14,7 @@ //! - **TM-NET-012**: Chunked encoding bomb → streaming size check //! - **TM-NET-013**: Gzip/compression bomb → auto-decompression disabled //! - **TM-NET-014**: DNS rebind via redirect → manual redirect requires allowlist check -//! - **TM-NET-015**: Host proxy leakage → `.no_proxy()` ignores host `HTTP_PROXY`/`HTTPS_PROXY` +//! - **TM-NET-033**: Host proxy leakage → `.no_proxy()` ignores host `HTTP_PROXY`/`HTTPS_PROXY` //! - **TM-NET-002 (TOCTOU)**: DNS rebinding between pre-resolve check and actual connect → //! private-IP filtering installed as reqwest's DNS resolver, so the connection path itself //! refuses to dial any private/reserved IP, even if DNS answers diverge between checks. @@ -808,7 +808,7 @@ fn build_client( .no_gzip() .no_brotli() .no_deflate() - // THREAT[TM-NET-015]: Ignore host proxy env vars (HTTP_PROXY, HTTPS_PROXY, ALL_PROXY) + // THREAT[TM-NET-033]: Ignore host proxy env vars (HTTP_PROXY, HTTPS_PROXY, ALL_PROXY) // to prevent sandboxed HTTP traffic from being redirected through a host proxy .no_proxy(); @@ -1001,7 +1001,7 @@ mod tests { #[test] fn test_build_client_uses_no_proxy() { // Verify build_client succeeds — the .no_proxy() call ensures - // host HTTP_PROXY/HTTPS_PROXY env vars are ignored (TM-NET-015). + // host HTTP_PROXY/HTTPS_PROXY env vars are ignored (TM-NET-033). let client = build_client(Duration::from_secs(30), None, true); assert!(client.is_ok(), "build_client should succeed with no_proxy"); } diff --git a/crates/bashkit/tests/integration/threat_model_doc_tests.rs b/crates/bashkit/tests/integration/threat_model_doc_tests.rs index 5efe5af37..20983d74d 100644 --- a/crates/bashkit/tests/integration/threat_model_doc_tests.rs +++ b/crates/bashkit/tests/integration/threat_model_doc_tests.rs @@ -68,6 +68,43 @@ fn walk_rs_files(root: &Path, out: &mut Vec) { } } +#[test] +fn threat_definition_ids_are_unique_within_each_section() { + let manifest = Path::new(env!("CARGO_MANIFEST_DIR")); + let doc_path = manifest.join("../../knowledge/security/threat-model.md"); + let doc = std::fs::read_to_string(&doc_path) + .unwrap_or_else(|e| panic!("read {}: {e}", doc_path.display())); + let mut section = "preamble"; + let mut definitions = BTreeMap::::new(); + let mut duplicates = Vec::new(); + + for (index, line) in doc.lines().enumerate() { + let line_number = index + 1; + if line.starts_with("### ") { + section = line; + definitions.clear(); + } + let Some(rest) = line.strip_prefix("| TM-") else { + continue; + }; + let Some((suffix, _)) = rest.split_once(" |") else { + continue; + }; + let id = format!("TM-{suffix}"); + if let Some(first_line) = definitions.insert(id.clone(), line_number) { + duplicates.push(format!( + "{id} in {section}: lines {first_line} and {line_number}" + )); + } + } + + assert!( + duplicates.is_empty(), + "duplicate canonical threat definitions:\n{}", + duplicates.join("\n") + ); +} + #[test] fn threat_ids_cited_in_code_exist_in_threat_model_doc() { let manifest = Path::new(env!("CARGO_MANIFEST_DIR")); diff --git a/crates/bashkit/tests/integration/ts_tenant_stress_tests.rs b/crates/bashkit/tests/integration/ts_tenant_stress_tests.rs index d021549ec..065aef9b2 100644 --- a/crates/bashkit/tests/integration/ts_tenant_stress_tests.rs +++ b/crates/bashkit/tests/integration/ts_tenant_stress_tests.rs @@ -63,6 +63,17 @@ async fn exec_ts(bash: &mut Bash, script: &str) -> bashkit::ExecResult { .unwrap() } +fn spin_tenant(max_ms: u64) -> Bash { + Bash::builder() + .typescript_with_limits( + TypeScriptLimits::default() + .max_memory(16 * 1024 * 1024) + .max_duration(Duration::from_millis(max_ms)) + .max_allocations(SPIN_ALLOCATIONS), + ) + .build() +} + #[derive(Clone, Copy, Debug)] enum Load { /// Computes and prints a known value. @@ -280,6 +291,54 @@ async fn ts_host_call_loops_stop_at_the_wall_clock_limit() { ); } +/// A synchronous VM join must not hold the only Tokio worker for the whole +/// attacker deadline (EVE-1351). +#[tokio::test(flavor = "current_thread")] +async fn ts_cpu_loop_does_not_starve_current_thread_timer() { + let started = std::time::Instant::now(); + let attacker = tokio::spawn(async { + let mut bash = spin_tenant(300); + exec_ts(&mut bash, script(Load::Spin)).await + }); + + tokio::time::sleep(Duration::from_millis(20)).await; + let timer_elapsed = started.elapsed(); + assert!( + timer_elapsed < Duration::from_millis(200), + "20 ms timer was starved for {timer_elapsed:?}" + ); + + let result = attacker.await.unwrap(); + assert_eq!(result.exit_code, 124, "stderr: {}", result.stderr); +} + +/// Filling every Tokio worker with hostile VMs must not stop an unrelated +/// tenant's timer (EVE-1351). +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn ts_cpu_loops_do_not_starve_all_multi_thread_workers() { + let started = std::time::Instant::now(); + let attackers: Vec<_> = (0..2) + .map(|_| { + tokio::spawn(async { + let mut bash = spin_tenant(300); + exec_ts(&mut bash, script(Load::Spin)).await + }) + }) + .collect(); + + tokio::time::sleep(Duration::from_millis(20)).await; + let timer_elapsed = started.elapsed(); + assert!( + timer_elapsed < Duration::from_millis(200), + "20 ms timer was starved for {timer_elapsed:?}" + ); + + for attacker in attackers { + let result = attacker.await.unwrap(); + assert_eq!(result.exit_code, 124, "stderr: {}", result.stderr); + } +} + /// A pure runaway loop, with no host calls to carry the deadline check, stops /// on `max_duration` once its allocation budget is not what binds (TM-TS-027). #[tokio::test] diff --git a/knowledge/log.md b/knowledge/log.md index 5c8e4419c..96570fec3 100644 --- a/knowledge/log.md +++ b/knowledge/log.md @@ -18,6 +18,7 @@ ## 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 worker isolation and admission**: pure CPU ZapCode steps and their dedicated-thread joins now run off Tokio workers, behind a host-configurable process-wide semaphore (default available parallelism, capped at four). Queue and completion waits consume the request deadline; an abandoned step keeps its permit until it ends. Current-thread, saturated multi-thread, and high-concurrency regressions cover the contract. See [ZapCode Runtime](runtimes/zapcode-runtime.md#wall-clock-limit-and-stress), TM-TS-028. * **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. diff --git a/knowledge/runtimes/markkit-fetchkit-builtins.md b/knowledge/runtimes/markkit-fetchkit-builtins.md index e936053d8..dbf25a26f 100644 --- a/knowledge/runtimes/markkit-fetchkit-builtins.md +++ b/knowledge/runtimes/markkit-fetchkit-builtins.md @@ -79,7 +79,7 @@ is sent. Hosts refuse unknown future host features too (fail closed). | Flag | Why | |---|---| | markkit `--ocr` (+ `--ocr-*`) | runs a host Tesseract binary, reads host model files | -| fetchkit `--allow-env-proxy` | host proxy env (TM-NET-015) | +| fetchkit `--allow-env-proxy` | host proxy env (TM-NET-033) | | fetchkit `--render-rakers` | embedded QuickJS engine; decided never in the sandbox | | fetchkit `--bot-auth-key` / `--bot-auth-agent` | bashkit signs in `HttpClient`; a key in argv double-signs and lands in history | | fetchkit `--allow-remote-conversion` | uploads documents to a third party | diff --git a/knowledge/runtimes/zapcode-runtime.md b/knowledge/runtimes/zapcode-runtime.md index dc6099d94..db17d3823 100644 --- a/knowledge/runtimes/zapcode-runtime.md +++ b/knowledge/runtimes/zapcode-runtime.md @@ -66,6 +66,11 @@ Configurable via `TypeScriptLimits`: | Max stack depth | 512 | `.max_stack_depth(n)` | Prevent stack overflow | | Max allocations | 1,000,000 | `.max_allocations(n)` | Bound VM allocation count | +Native process-wide VM concurrency defaults to available CPU parallelism +capped at four. `configure_typescript_vm_concurrency(n)` changes it once before +the first run; this is aggregate host admission, separate from per-run +`TypeScriptLimits`. + `max_allocations` counts VM stack pushes and array/object creations, and the counter never decreases within a run (`zapcode_vendor/sandbox.rs`, `track_allocation`), so it is a per-run budget of operations rather than a live @@ -245,9 +250,26 @@ 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. +time, and yields to the executor. + +Decision (2026-11-19, TM-TS-028): every native VM step runs on a dedicated +128 MiB-stack thread, but thread creation and join run inside Tokio's managed +blocking pool rather than on an async worker. A process-wide semaphore admits +at most the host's available parallelism, capped at four by default. Hosts can +call `configure_typescript_vm_concurrency` once before the first TypeScript +execution to choose a different cap. Admission is asynchronous and its wait +consumes the run's wall-clock deadline; a request that cannot enter before its +deadline exits 124 without starting another VM thread. The caller also stops +waiting at the same deadline if an admitted step is still running. That +abandoned native step retains its semaphore permit until its ZapCode limit +ends it, so simultaneous CPU work and 128 MiB stack reservations stay capped. + +This removes TypeScript VM work and joins from shared Tokio workers: unrelated +timers and tenants keep being polled during a pure `while (true) {}` step on +both current-thread and saturated multi-thread runtimes. It does not hard- +partition CPU; admitted VM threads can consume their configured cores until +their per-run limits fire. wasm32 has no threads or blocking pool and still +runs a VM step synchronously on the caller's JavaScript event loop. `tests/integration/ts_tenant_stress_tests.rs` mixes hostile `ts` tenants (memory doubling, shared-string amplification, spin, recursion, abandoned @@ -257,6 +279,12 @@ 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`. +The same suite proves 20 ms unrelated timers progress while pure CPU loops +fill a current-thread or every multi-thread Tokio worker. The unit admission +fixture starts eight blocking steps against a two-slot controller and proves +only two native threads start while all queued callers expire within their +own deadlines. + Decision (2026-11-11): the spin tenant asserts only that it stopped on one of its own limits, because `max_allocations` and `max_duration` race and the winner depends on build speed. A release build burns the 1M push budget in a diff --git a/knowledge/security/http-transport.md b/knowledge/security/http-transport.md index 351544c85..106de534a 100644 --- a/knowledge/security/http-transport.md +++ b/knowledge/security/http-transport.md @@ -18,7 +18,7 @@ Implemented ## Problem -Embedding hosts (reference consumer: [everruns](https://github.com/everruns/everruns), `specs/egress.md` there) must route *all* outbound traffic through a host-owned egress boundary, for network policy, audit, signing, and airgapped deployments. bashkit's built-in reqwest connectivity dials the network directly and deliberately ignores host proxy env vars (TM-NET-015), so without an injection point an embedder cannot centralize sandbox HTTP. The legacy `HttpHandler` hook was too weak for this: loose `(method, url, body, headers)` args, no timeouts, no SSRF precheck result, stringly-typed errors that could not distinguish a host policy denial from a connect failure. +Embedding hosts (reference consumer: [everruns](https://github.com/everruns/everruns), `specs/egress.md` there) must route *all* outbound traffic through a host-owned egress boundary, for network policy, audit, signing, and airgapped deployments. bashkit's built-in reqwest connectivity dials the network directly and deliberately ignores host proxy env vars (TM-NET-033), so without an injection point an embedder cannot centralize sandbox HTTP. The legacy `HttpHandler` hook was too weak for this: loose `(method, url, body, headers)` args, no timeouts, no SSRF precheck result, stringly-typed errors that could not distinguish a host policy denial from a connect failure. ## Design Decisions @@ -78,5 +78,5 @@ handling without live network dependencies. - [Request Signing](request-signing.md), signing pipeline the transport inherits - [Credential Injection](credential-injection.md), header injection ahead of dispatch -- [Threat Model](threat-model.md), TM-NET-023 (SSRF responsibility of custom transports), TM-NET-015 (host proxy isolation on the built-in path) +- [Threat Model](threat-model.md), TM-NET-023 (SSRF responsibility of custom transports), TM-NET-033 (host proxy isolation on the built-in path) - [Tool Contract](../integrations/tool-contract.md), LLM tool surface this feeds diff --git a/knowledge/security/threat-model.md b/knowledge/security/threat-model.md index 597d8a712..b47f898f9 100644 --- a/knowledge/security/threat-model.md +++ b/knowledge/security/threat-model.md @@ -266,7 +266,7 @@ on default 2 MiB test threads (TM-DOS-044). | TM-DOS-043 | Arithmetic side-effect overflow/panic | `((x+=1))` or `$((x++))` at the `i64` boundaries | Compound assignment and prefix/postfix increment/decrement use wrapping arithmetic in both evaluator paths | **MITIGATED** | | TM-DOS-030 | Parser limit bypass via eval/source/trap | `eval`, `source`, trap handlers now use `Parser::with_limits()` |, | **FIXED** (2026-03 audit verified) | | TM-DOS-031 | Glob/ExtGlob exponential blowup | `+(a\|aa)` against long string causes O(n!) recursion in `glob_match_impl`; a run of plain `*` (consecutive `****…` or separated `*a*b*…`) previously recursed per value position and blew up (a 33-`*` pattern timed out `glob_fuzz`) | Plain `*` now matches via a single backtracking restore point (the classic linear wildcard algorithm), worst case O(value·pattern), no per-position recursion; `glob_match_impl` still carries a recursion-depth cap for extglob nesting and bails on excessive depth, and every recursive glob/extglob step spends from a `MAX_GLOB_STEPS` (100,000) budget shared by one match or one removal/substitution scan, failing the match once spent. `[[ == ]]` understands extglob without `shopt` (bash 5.2), so this budget is what bounds it (`test_cond_extglob_backtracking_is_bounded`); aliases that expand to huge brace ranges go through the same parser-budget check (`interpreter/mod.rs:4216`) | **MITIGATED** | -| TM-DOS-035 | DEBUG trap recursive amplification | `trap 'a=1;b=2;...' DEBUG` amplifies N commands to N*M | Suppress DEBUG trap inside trap handlers (`in_trap` guard) | **FIXED** | +| TM-DOS-145 | DEBUG trap recursive amplification | `trap 'a=1;b=2;...' DEBUG` amplifies N commands to N*M | Suppress DEBUG trap inside trap handlers (`in_trap` guard) | **FIXED** | | TM-DOS-032 | Tokio runtime exhaustion (Python) | Rapid `execute_sync()` calls each create new tokio runtime, exhausting OS threads | `PyBash` and `BashTool` create one `Arc` per instance in `__new__` via `make_runtime()` and reuse it for every `execute_sync` call; no per-call runtime construction | **MITIGATED** | | TM-DOS-033 | AWK unbounded loops | `BEGIN { while(1){} }` or deep user-function recursion | Every awk loop form (`while`, `do`, `for`, `for-in`) honours `ExecutionLimits::max_loop_iterations`; user-function recursion is capped at `AWK_MAX_CALL_DEPTH`; both abort the program with a fatal error (TM-DOS-109); 30s timeout backstop | **MITIGATED** | | TM-DOS-051 | Removed custom YAML parser recursion | The former `yaml` helper recursively parsed attacker-controlled indentation | The helper and parser were removed when `yq` replaced them; TM-DOS-101 covers the production parser boundary | **REMOVED** | @@ -883,7 +883,7 @@ matches literal host strings exactly, never resolved IPs; no DNS lookup. | TM-NET-012 | Chunked encoding bomb | Infinite chunked response | Response size limit (streaming) | **MITIGATED** | | TM-NET-013 | Gzip bomb / Zip bomb | 10KB gzip → 10GB decompressed | Auto-decompression disabled | **MITIGATED** | | TM-NET-014 | DNS rebind via redirect | Redirect to rebinded IP | Manual redirect requires allowlist check | **MITIGATED** | -| TM-NET-015 | Host proxy leakage | `HTTP_PROXY`/`HTTPS_PROXY` env vars route sandboxed traffic through host proxy | `.no_proxy()` on reqwest builder | **MITIGATED** | +| TM-NET-033 | Host proxy leakage | `HTTP_PROXY`/`HTTPS_PROXY` env vars route sandboxed traffic through host proxy | `.no_proxy()` on reqwest builder | **MITIGATED** | | TM-NET-018 | JSON body injection | `http POST url name='x","admin":true'` via unescaped string formatting | Use `serde_json` for JSON construction | **MITIGATED** | | TM-NET-019 | Query param injection | `http GET url q=='foo&admin=true'` injects extra params | URL-encode via local x-www-form-urlencoded encoder | **MITIGATED** | | TM-NET-020 | Form body injection | `http --form POST url user='x&role=admin'` injects extra fields | URL-encode via local x-www-form-urlencoded encoder | **MITIGATED** | @@ -930,7 +930,7 @@ redacted everywhere they could surface. **Implementation**: `network/client.rs`, `DEFAULT_MAX_RESPONSE_BYTES` 10MB, timeouts default 30s / connect 10s, clamped to [1s, 10min] (TM-NET-008/009/010); `redirect(Policy::none())` (TM-NET-011/014); `.no_gzip().no_brotli().no_deflate()` (TM-NET-013); `.no_proxy()` -(TM-NET-015); `read_body_with_limit()` streams and checks size per chunk (TM-NET-008/012). +(TM-NET-033); `read_body_with_limit()` streams and checks size per chunk (TM-NET-008/012). #### 5.4 HTTP Client Mitigations @@ -1042,8 +1042,8 @@ Only exact domain matches are allowed (TM-NET-017). |----|--------|--------------|------------|--------| | TM-ISO-001 | Shared filesystem | Access other session's files | Separate Bash instances with separate FS | **MITIGATED** | | TM-ISO-002 | Shared memory | Read other session's data | Rust memory safety, per-instance state | **MITIGATED** | -| TM-ISO-003 | Resource starvation | One session exhausts limits | Per-instance limits | **MITIGATED** | -| TM-ISO-004 | Cross-session env pollution via jq | `std::env::set_var()` in jq | Custom jaq global variable (`$__bashkit_env__`) | **MITIGATED** | +| TM-ISO-003 | Aggregate same-process resource starvation | Concurrent sessions exhaust shared workers, VM threads, CPU, or memory despite per-instance limits | TypeScript steps use asynchronous process-wide admission (TM-TS-028); per-instance limits contain each request. Residual: CPU-bound Python still holds one Tokio worker (TM-PY-039), and same-process CPU/memory are not hard-isolated | **PARTIAL** | +| TM-ISO-004 | Cross-session env pollution via jq | `std::env::set_var()` in jq modifies process-wide env, visible to concurrent sessions | Custom `$__bashkit_env__` jaq context variable replaces `std::env` access | **FIXED** | | TM-ISO-007 | Alias leakage | Aliases defined in session A visible in session B | Per-instance alias HashMap | **MITIGATED** | | TM-ISO-008 | Trap handler leakage | Trap from session A fires in session B | Per-instance trap HashMap | **MITIGATED** | | TM-ISO-009 | Shell option leakage | `set -e` in session A affects session B | Per-instance SHOPT_* variables | **MITIGATED** | @@ -1059,7 +1059,6 @@ Only exact domain matches are allowed (TM-NET-017). | TM-ISO-019 | jq cross-session env | `jq 'env.X'` sees other session's vars | jaq reads from injected global, not `std::env` | **MITIGATED** | | TM-ISO-020 | Subshell mutation leakage | Subshell vars leak to parent or sibling sessions | Snapshot/restore in subshell + per-instance state | **MITIGATED** | -| TM-ISO-004 | Cross-session env pollution via jq | `std::env::set_var()` in jq modifies process-wide env, visible to concurrent sessions | Custom `$__bashkit_env__` jaq context variable replaces `std::env` access | **FIXED** | | TM-ISO-005 | Session-level cumulative counter bypass | Repeated `exec()` calls each reset `ExecutionCounters`, giving unbounded aggregate resources | `SessionLimits` (`limits.rs`) caps cumulative commands and `exec()` call count across the lifetime of a `Bash` instance; counters are preserved across `reset_transient_state()` | **MITIGATED** | | TM-ISO-006 | No per-instance variable/memory budget | Unbounded `HashMap` growth in variables, arrays, functions or their definition filenames exhausts process memory | `MemoryLimits` (`limits.rs`) caps `max_variable_count`, `max_total_variable_bytes`, `max_array_entries`, `max_function_count`, and `max_function_body_bytes` per instance. The function byte cap includes definition filenames and metadata keys, conservatively charged per function before insertion; source frames/definitions share `Arc` filename storage. Filename maps live in `ScopedState`, so forks and subshell rollback follow function state. Redefinition replaces the old charge; unset drops metadata and refunds bytes/count. Functions and admitted metadata persist across exec calls; shell-state restore replaces functions and discards old filenames (not serialized). Byte admission failure returns a resource-limit error; the established function-count silent skip remains. Regressions: `function_metadata_security_tests`, `function_metadata_shares_storage_and_drops_with_functions` | **MITIGATED** | | TM-ISO-021 | EXIT trap leaks across `exec()` calls | EXIT trap set in one `exec()` fires in subsequent `exec()` calls on same Bash instance | `reset_transient_state()` clears `traps` at the start of every `exec()` | **MITIGATED** | @@ -1086,7 +1085,9 @@ counter leaked cross-session ordering). Now `/dev/fd/N` (N >= 3) is answered per `ProcSubFs` (`fs/proc_sub_fds.rs`), which wraps that shell's VFS view and never forwards such a path to the shared filesystem. -**Current Risk**: MEDIUM - cumulative resource bypass (TM-ISO-005) and memory exhaustion (TM-ISO-006) +**Current Risk**: MEDIUM - aggregate same-process availability remains partial (TM-ISO-003), +including the accepted Python worker hold (TM-PY-039). TypeScript VM admission +prevents unbounded native VM threads and Tokio-worker starvation (TM-TS-028). **Implementation**: each session is a separate `Bash::builder()` instance with its own `Arc` and limits, no shared mutable state (TM-ISO-001 through TM-ISO-020). @@ -1479,7 +1480,7 @@ This section maps former vulnerability IDs to the new threat ID scheme and track | TM-DOS-091 | SQLite `.dump` cumulative output bypass | `.dump` built the full schema+rows string before checking `max_output_bytes`; an attacker controlling many tables/rows could cause memory to grow far beyond the configured output cap | `bounded_append()` helper enforces the cap after each schema line and each INSERT row; `dispatch()` receives the *remaining* budget (`max_output_bytes - stdout.len()`) from `run_statements`, **FIXED** via #1869 | | TM-DOS-092 | Subshell snapshot amplification | Deeply nested `( ... )` keeps CoW state snapshots and call-stack clones alive | `max_subshell_depth` counter (default 32) bounds live explicit subshell snapshots | **MITIGATED** | | TM-DOS-093 | jq unbounded generator OOM/hang | `jq -n 'repeat(1)'` / `range(0;1e18)`, the jaq result loop appended every value to an in-memory string with no byte/value/deadline cap; jaq's iterator is synchronous so the async execution timeout cannot preempt it. jq is a core builtin (no opt-in gate) | Cap accumulated output at the caller's `max_stdout_bytes` and poll `ExecutionDeadline::is_expired()` every 4096 values, aborting with a clean error (`builtins/jq/mod.rs`), **FIXED** | -| TM-DOS-095 | CLI host-stdin memory ingestion unbounded | One-shot `bashkit -c` reads the host's stdin into memory before execution; an unbounded producer (`yes \| bashkit -c …`) would grow the buffer without limit | Read through `Take` at `MAX_STDIN_BYTES` + 1 and reject over-cap input with a clear error; skipped entirely when stdin is a terminal; `--no-stdin` opts out (`crates/bashkit-cli/src/main.rs`), **FIXED** | +| TM-DOS-146 | CLI host-stdin memory ingestion unbounded | One-shot `bashkit -c` reads the host's stdin into memory before execution; an unbounded producer (`yes \| bashkit -c …`) would grow the buffer without limit | Read through `Take` at `MAX_STDIN_BYTES` + 1 and reject over-cap input with a clear error; skipped entirely when stdin is a terminal; `--no-stdin` opts out (`crates/bashkit-cli/src/main.rs`), **FIXED** | | TM-DOS-094 | Persistent command history memory DoS | Long-lived Bash instances can retain, serialize, and list unbounded command history across many `exec()` calls | `ExecutionLimits` caps history entries, retained history bytes, and history output bytes; persisted saves append deltas unless compaction is required, **FIXED** | | TM-DOS-095 | Multi-component glob cross-product amplification | Per-component pathname expansion walks a candidate set that multiplies at every glob component, so a wide tree plus a pattern like `/*/*/*/*` can materialize far more candidates than the tree has leaves | `expand_glob` rejects patterns deeper than `FsLimits::max_path_depth` and truncates the live candidate set to `FsLimits::max_file_count` after each component (`interpreter/glob.rs`), **FIXED** | | TM-DOS-096 | Aggregate execution-budget refresh | Nested substitutions, pipelines, traversal, builtin/runtime interpreters, archive expansion, and host callbacks each relied on independent ceilings, letting mixed workloads repeatedly restart resource accounting inside one request | `ExecutionBudget` is created once per host `exec_with_options`, cloned into parser/interpreter descendants and execution extensions, and monotonically meters aggregate work, aggregate input, and live intermediate leases. Any ceiling, deadline, or cancellation poisons the shared request while existing subsystem limits remain enforced. `cd` borrows CDPATH entries, searches one candidate at a time, reserves path/normalization workspace before allocation, charges candidate-length work, yields every 64 candidates, and gates filesystem awaits on cancellation/deadlines; bounded `cdpath_*` regressions cover the former eager candidate amplification, **MITIGATED** | @@ -1579,7 +1580,7 @@ storage; a custom backend's reported read size remains a trusted contract. | HTTP connect timeout | TM-NET-009 | `network/client.rs` | Yes | | HTTP read timeout | TM-NET-010 | `network/client.rs` | Yes | | No auto-redirect | TM-NET-011, TM-NET-014 | `network/client.rs` | Yes | -| No host proxy | TM-NET-015 | `network/client.rs` | Yes | +| No host proxy | TM-NET-033 | `network/client.rs` | Yes | | Log value redaction | TM-LOG-001 to TM-LOG-004 | `logging.rs` | Yes | | Log injection prevention | TM-LOG-005, TM-LOG-006 | `logging.rs` | Yes | | Log value truncation | TM-LOG-007, TM-LOG-008 | `logging.rs` | Yes | @@ -2034,7 +2035,7 @@ yield `OsCall` events that Bashkit intercepts and dispatches to the VFS. | TM-PY-036 | Host-call loop outruns the time limit / starves the worker thread | High | Monty 1.x pauses its clock while suspended on the host, so `max_duration` counted VM time only. The host-call loop checks the wall-clock deadline at every OS/external call and yields to the executor there | `python_tenant_stress_tests::host_call_loops_stop_at_the_wall_clock_limit`, `python_tenant_stress_tests::abandoned_calls_do_not_poison_the_worker_threads` | | TM-PY-037 | Shared-graph walk outlives the time limit | Critical | Upstream amortized checks key on the per-loop index, so recursive `repr`/compare over `x = [x, x]` never checks time and blocks the thread past every limit. Fork counts all `*_every` calls on one tracker-wide tick; `repr` errors on a time hit | `python_security_tests::whitebox_resource_limits::shared_graph_walks_respect_time_limit` | | TM-PY-038 | `json.dumps` indent/separators bypass memory preflight | Critical | Upstream built `' ' * indent` and wrote `indent`/`separators` strings per item and per depth level without a size check; `MeteredAllocator` cannot refuse, so `json.dumps([1], indent=10**12)` aborted the whole process. Fork preflights the indent repeat (`check_repeat_size`) and every separator/indent write through the output-growth check, raising `MemoryError` | `python_tenant_isolation_tests::json_dumps_*` | **MITIGATED** | -| TM-PY-039 | CPU-bound run holds a shared worker thread for its whole time limit | Medium | A VM loop with no host calls (`while True: pass`, `for (;;) {}`) runs inline on the async worker and yields only at host calls (TM-PY-036), so co-tenants on that thread wait until `max_duration` or the execution deadline stops it. The profile caps each `python3`/`ts` run (30 s, Hardened 10 s). Python `Bash`/`BashTool(timeout_seconds=...)` sets that cap too, so a host that raises `timeout_seconds` accepts a longer worst-case hold; multi-tenant hosts keep `timeout_seconds` short or give each tenant its own runtime/thread. `ts` runs also stop at the `max_work_units` budget | `test_tool_runtimes.py::test_timeout_seconds_raises_runtime_time_limit` | +| TM-PY-039 | CPU-bound Python run holds a shared worker thread for its whole time limit | Medium | A VM loop with no host calls (`while True: pass`) runs inline on the async worker and yields only at host calls (TM-PY-036), so co-tenants on that thread wait until `max_duration` or the execution deadline stops it. The profile caps each `python3` run (30 s, Hardened 10 s). Python `Bash`/`BashTool(timeout_seconds=...)` sets that cap too, so a host that raises `timeout_seconds` accepts a longer worst-case hold; multi-tenant hosts keep `timeout_seconds` short or give each tenant its own runtime/thread. TypeScript is covered separately by TM-TS-028 | `test_tool_runtimes.py::test_timeout_seconds_raises_runtime_time_limit` | | TM-PY-013 | Unknown CLI options smuggle behavior | Low | Unknown `python` options rejected with exit 2 | `threat_python_unknown_options` | | TM-PY-014 | Python escapes Bashkit resource limits | High | Bashkit `ExecutionLimits` apply to the `python` command like any builtin | `threat_python_respects_bash_limits` | | TM-PY-015 | Real filesystem read via pathlib | Critical | VFS bridge reads only from Bashkit VFS, not host | `threat_python_vfs_no_real_fs` | @@ -2246,6 +2247,7 @@ TypeScript execution requires two explicit opt-in steps, matching the Python bui | 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::*`, `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` | +| TM-TS-028 | CPU-only VM steps starve Tokio workers and create unbounded 128 MiB-stack threads | High | Native VM execution and the dedicated-thread join run on Tokio's blocking pool, never an async worker. A process-wide semaphore caps active VM threads (default: available parallelism, at most 4; host-configurable before first use); admission wait and blocking completion share the run deadline. A timed-out blocking step may finish in the background, but retains its permit, so abandoned work and stack reservations remain bounded | `ts_tenant_stress_tests::ts_cpu_loop_does_not_starve_current_thread_timer`, `ts_cpu_loops_do_not_starve_all_multi_thread_workers`, `builtins::typescript::tests::vm_admission_caps_active_threads_and_times_out_queued_steps` | ### Blocked Language Features