diff --git a/crates/bashkit/docs/threat-model.md b/crates/bashkit/docs/threat-model.md index 7614b2217..c65727812 100644 --- a/crates/bashkit/docs/threat-model.md +++ b/crates/bashkit/docs/threat-model.md @@ -738,6 +738,7 @@ Python `pathlib.Path` and `open()` operations are bridged to Bashkit's virtual f | ReDoS via `re` (TM-PY-033) | Catastrophic backtracking pattern | Linear-time engine for plain patterns, backtrack cap (`re.PatternError`) for fancy ones, time limit for match loops | MITIGATED | | Uninterruptible VM loop (TM-PY-034) | Tight loop ignores cancellation or shared budget | Forked checkpoint hook runs the request `ExecutionBudget` check inside the VM | MITIGATED | | Shared-graph expansion in host conversion (TM-PY-035) | `x = [x, x]` repeated, then returned to the host | Every converter walks Monty values with a node cap | MITIGATED | +| 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 | **Architecture:** diff --git a/crates/bashkit/src/builtins/python.rs b/crates/bashkit/src/builtins/python.rs index f9827c2c8..0819a7790 100644 --- a/crates/bashkit/src/builtins/python.rs +++ b/crates/bashkit/src/builtins/python.rs @@ -569,6 +569,22 @@ async fn run_python( if let Some(budget) = &execution_budget { budget.consume_work(1)?; } + // Important security decision: Monty's clock pauses while the VM is + // suspended on the host, so `max_duration` alone bounds VM time only and + // a loop of cheap host calls (file writes) ran ~10x past it. Bound wall + // clock at every host call too, and yield to the executor there: the VM + // never yields on its own, so without this a caller-side timeout cannot + // cancel the call and co-tenants on the same worker thread starve. + if !matches!(progress, RunProgress::Complete(_)) { + if python_deadline.is_some_and(|deadline| Instant::now() >= deadline) { + return Ok(format_exception_with_output( + MontyException::new(ExcType::TimeoutError, None), + &buf, + Some(time_limit), + )); + } + tokio::task::yield_now().await; + } match progress { RunProgress::OsCall(os_call) => { let function_call = os_call.function_call.clone(); diff --git a/crates/bashkit/tests/integration/main.rs b/crates/bashkit/tests/integration/main.rs index f3b2b7d1b..e6e6cc442 100644 --- a/crates/bashkit/tests/integration/main.rs +++ b/crates/bashkit/tests/integration/main.rs @@ -142,6 +142,7 @@ pub mod proptest_differential; pub mod python_integration_tests; pub mod python_security_tests; pub mod python_tenant_isolation_tests; +pub mod python_tenant_stress_tests; pub mod redirect_error_tests; pub mod regex_limit_tests; pub mod release_profile_tests; diff --git a/crates/bashkit/tests/integration/python_tenant_stress_tests.rs b/crates/bashkit/tests/integration/python_tenant_stress_tests.rs new file mode 100644 index 000000000..12b923df2 --- /dev/null +++ b/crates/bashkit/tests/integration/python_tenant_stress_tests.rs @@ -0,0 +1,243 @@ +//! Multi-tenant stress for the forked Monty `python3` (TM-PY-032, TM-PY-034). +//! +//! Many tenants share one process and a few worker threads. Hostile ones +//! (memory bombs, 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 = "python")] + +use bashkit::{Bash, PythonLimits}; +use std::time::Duration; + +fn rounds() -> usize { + std::env::var("BASHKIT_STRESS_ROUNDS") + .ok() + .map(|v| { + v.parse::() + .ok() + .filter(|n| (1..=1000).contains(n)) + .unwrap_or_else(|| panic!("BASHKIT_STRESS_ROUNDS must be 1..=1000, got {v:?}")) + }) + .unwrap_or(3) +} + +fn tenant(limit_mib: usize, max_ms: u64) -> Bash { + Bash::builder() + .python_with_limits( + PythonLimits::default() + .max_memory(limit_mib * 1024 * 1024) + .max_duration(Duration::from_millis(max_ms)) + .max_recursion(200), + ) + .env("BASHKIT_ALLOW_INPROCESS_PYTHON", "1") + .build() +} + +#[derive(Clone, Copy, Debug)] +enum Load { + /// Computes and prints a known value. + Good, + /// One big up-front allocation over the limit. + BigAlloc, + /// Growth through many small objects over the limit. + ManySmall, + /// Never terminates on its own. + Spin, + /// Unbounded recursion. + Recurse, +} + +const LOADS: [Load; 5] = [ + Load::Good, + Load::BigAlloc, + Load::ManySmall, + Load::Spin, + Load::Recurse, +]; + +fn script(load: Load) -> &'static str { + match load { + Load::Good => "python3 -c \"print(sum(i * i for i in range(20000)))\"", + Load::BigAlloc => "python3 -c \"x = 'a' * (64 * 1024 * 1024)\"", + Load::ManySmall => "python3 -c \"x = [str(i) for i in range(3000000)]\"", + Load::Spin => "python3 -c \"while True:\n pass\"", + Load::Recurse => "python3 -c \"def f(n):\n return f(n + 1)\nf(0)\"", + } +} + +async fn run(load: Load) { + // Only the runaway loop should end on time; the rest must end on their + // own limit (memory, recursion) 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 = bash.exec(script(load)).await.unwrap(); + match load { + Load::Good => { + assert_eq!(r.exit_code, 0, "{load:?} stderr: {}", r.stderr); + assert_eq!(r.stdout, "2666466670000\n", "{load:?}"); + } + Load::BigAlloc | Load::ManySmall => { + assert_ne!(r.exit_code, 0, "{load:?} stdout: {}", r.stdout); + assert!( + r.stderr.contains("MemoryError"), + "{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("RecursionError"), + "{load:?} stderr: {}", + r.stderr + ); + } + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn 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 { + let load = LOADS[i % LOADS.len()]; + handles.push(tokio::spawn(run(load))); + } + for h in handles { + h.await.unwrap(); + } + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn abandoned_calls_do_not_poison_the_worker_threads() { + // Drop python3 calls while they are suspended between VM steps (caller-side + // timeout). The VM only yields at host calls, so the script loops on file + // writes while holding 8 MiB. Dropping it frees that memory outside any + // metering window. If that corrupted the per-thread meter, or charged a + // dead budget, later VMs on the same threads (and the same session) would + // fail or pass wrongly. + const HOLD_AND_YIELD: &str = "python3 -c \"from pathlib import Path\nx = 'a' * (8 * 1024 * 1024)\np = Path('/tmp/spin')\nwhile True:\n p.write_text('x')\""; + 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 dropped = + tokio::time::timeout(Duration::from_millis(50), bash.exec(HOLD_AND_YIELD)) + .await + .is_err(); + assert!(dropped, "call finished instead of being abandoned"); + // Same session right after: its full budget must be available. + let r = bash + .exec("python3 -c \"x = 'a' * (10 * 1024 * 1024)\nprint(len(x) // 1048576)\"") + .await + .unwrap(); + assert_eq!(r.exit_code, 0, "after abandon stderr: {}", r.stderr); + assert_eq!(r.stdout, "10\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::BigAlloc + }; + after.push(tokio::spawn(run(load))); + } + for h in after { + h.await.unwrap(); + } + } +} + +#[tokio::test] +async fn one_session_reuses_its_budget_across_many_calls() { + // A tenant that keeps 10 of its 16 MiB live per call, many times over. If + // memory charged in one call were not released at its end, later calls in + // the same session would trip MemoryError. + let mut bash = tenant(16, 2000); + for i in 0..(10 * rounds()) { + let r = bash + .exec("python3 -c \"x = 'a' * (10 * 1024 * 1024)\nprint(len(x) // 1048576)\"") + .await + .unwrap(); + assert_eq!(r.exit_code, 0, "call {i} stderr: {}", r.stderr); + assert_eq!(r.stdout, "10\n", "call {i}"); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn huge_single_allocations_are_refused_up_front() { + // A request bigger than the machine has would make the global allocator + // fail, and Rust aborts the whole process (every tenant) on allocation + // failure. Monty must refuse these by size before allocating; run them + // concurrently next to a well-behaved tenant to show the process survives. + let bombs = [ + "x = 'a' * (10**12)", + "x = b'a' * (10**12)", + "x = [0] * (10**11)", + "x = (1,) * (10**11)", + "x = 'ab' * (2**62)", + "x = 'x'.ljust(10**12)", + "x = 'x'.zfill(10**12)", + "x = 'a'.center(10**12)", + "x = ' '.join(['a'] * 10**10)", + "x = 10 ** (10**8)", + "x = 2 << (10**10)", + "x = list(range(10**11))", + "x = '{:>1000000000000}'.format(1)", + ]; + let mut handles = Vec::new(); + for code in bombs { + handles.push(tokio::spawn(async move { + let mut bash = tenant(64, 10_000); + let r = bash.exec(&format!("python3 -c \"{code}\"")).await.unwrap(); + assert_ne!(r.exit_code, 0, "{code}: stdout {}", r.stdout); + assert!( + r.stderr.contains("MemoryError"), + "{code}: stderr {}", + r.stderr + ); + })); + } + handles.push(tokio::spawn(run(Load::Good))); + for h in handles { + h.await.unwrap(); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn host_call_loops_stop_at_the_wall_clock_limit() { + // Monty's clock pauses while the VM waits on the host, so a loop of cheap + // file writes used to run ~10x past max_duration and never yield the + // worker thread. The limit must bound wall-clock time. + let mut bash = tenant(16, 500); + let started = std::time::Instant::now(); + let r = bash + .exec("python3 -c \"from pathlib import Path\np = Path('/tmp/spin')\nwhile True:\n p.write_text('x')\"") + .await + .unwrap(); + 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 455b8994d..b8d30a0b3 100644 --- a/knowledge/log.md +++ b/knowledge/log.md @@ -2,6 +2,8 @@ ## 2026-11-06 +* **Python wall-clock limit**: Monty 1.x pauses its clock while the VM waits on the host, so `PythonLimits::max_duration` bounded VM time only. A `while True: p.write_text('x')` loop under a 500 ms limit ran 6 s, never yielding its worker thread, so caller-side timeouts could not cancel it and co-tenants on that thread stalled. The host-call loop now enforces the wall-clock deadline (exit 124) and yields at every host call. Found by the multi-tenant stress suite. See [Python Builtin](runtimes/python-builtin.md), TM-PY-036. +* **Monty multi-tenant stress**: `python_tenant_stress_tests` mixes hostile and well-behaved `python3` tenants on shared worker threads, abandons calls mid-run, and reuses one session's memory budget many times; each tenant must hit only its own limit. 20-round soak passed locally (80 s). See [Python Builtin](runtimes/python-builtin.md), TM-PY-032. * **Dependabot config parse fix**: #2852 set `versioning-strategy: increase` on a cargo entry, which cargo rejects, so Dependabot refused the whole `dependabot.yml` (red check on `main`). Replaced by committing the two random-fs fixture lockfiles, which also puts them in the advisory scan; a test pins cargo strategies to `auto`/`lockfile-only`. See [Dependencies](operations/dependencies.md). * **Monty fuzz target**: `python_fuzz` fuzzes the forked Monty `python3` with the metered allocator installed (file, stdin, `-c`, CLI args; 32 MiB / 500 ms limits, per-exec wall-clock assertion, leak checks). Nightly in `fuzz.yml`, build-checked in `fuzz-check`. First local run: 282k execs in 8 min, 0 crashes. See [Python Builtin](runtimes/python-builtin.md), TM-PY-032. * **Dependabot jobs green again**: the weekly cargo "/" job failed since 2026-10-19 because `turso_core = "0.8.0-pre.1"` (lock at 0.8.3) made Dependabot try 0.9.0-pre.2 as an in-range lockfile update, which cargo rejects; the requirement is now the stable `0.8.3`. The example/fixture job failed since 2026-10-13 because Dependabot follows the `crates/bashkit` path dep into the root workspace and tries to bump bashkit's own (root-owned, partly optional) deps; that entry now `allow`s only each manifest's own deps and uses `versioning-strategy: increase` for the lockfile-less fixtures. Crates only the Monty forks declare are ignored in the "/" entry so they move with upstream (#2848 had bumped them and broke the build). All three are pinned by `scripts/tests/test_dependabot_coverage.py`. See [Dependencies](operations/dependencies.md). diff --git a/knowledge/runtimes/python-builtin.md b/knowledge/runtimes/python-builtin.md index a5f1d160c..c1b83cb18 100644 --- a/knowledge/runtimes/python-builtin.md +++ b/knowledge/runtimes/python-builtin.md @@ -86,6 +86,14 @@ metering" below), so it is stricter than the 0.0.19 estimate: a dict of ~500k short strings reaches the 64 MiB default. It also caps the host-side buffer that collects `print` output. There is no allocation-count knob. +`max_duration` bounds wall-clock time. Monty 1.x pauses its own clock while +the VM waits on the host (VFS calls, external functions), so Monty alone +bounds VM time only: a loop of cheap file writes ran ~12x past the limit and +never yielded the worker thread. Bashkit checks the wall-clock deadline at +every host call (exit 124 like any time limit) and yields to the executor +there, so a caller-side timeout can cancel the call and co-tenants on the +same worker thread are scheduled (TM-PY-036). + Each Python entry also consumes the request-scoped `ExecutionBudget`: source bytes are charged as aggregate input, Monty heap growth past the run's high-water mark is charged as work (one unit per 64 bytes), and every 64 VM @@ -303,3 +311,9 @@ is where inherited interpreter bugs show up. ```bash cargo +nightly-2026-10-30 fuzz run --features python python_fuzz -- -max_total_time=300 ``` + +Stress: `tests/integration/python_tenant_stress_tests.rs` runs 20 tenants on 4 +worker threads per round, mixing memory bombs, runaway loops, unbounded +recursion and well-behaved scripts; it also drops calls mid-run and then checks +that the worker threads still meter correctly, and reuses one session's budget +across many calls. 3 rounds per PR; `BASHKIT_STRESS_ROUNDS=N` for a soak. diff --git a/knowledge/security/threat-model.md b/knowledge/security/threat-model.md index 6504a7582..8d9a64708 100644 --- a/knowledge/security/threat-model.md +++ b/knowledge/security/threat-model.md @@ -2007,10 +2007,11 @@ yield `OsCall` events that Bashkit intercepts and dispatches to the VFS. | TM-PY-010 | Error text leaks into pipeline data | Medium | Pipeline consumers receive stdout only; tracebacks stay on stderr | `threat_python_pipeline_error_handling` | | TM-PY-011 | Command substitution captures stderr diagnostics | Medium | `$(python ...)` captures stdout only | `threat_python_subst_captures_stdout` | | TM-PY-012 | Shell escape via Python `eval`/`exec` | Critical | Monty has no `os.system`/`subprocess`; `exec`/`eval` (Monty 1.x) run inside the same VM, limits and OS-call bridge | `threat_python_no_shell_exec` | -| TM-PY-032 | Cross-tenant memory accounting / process abort | Critical | Upstream Monty 1.x reads a process-wide allocator counter and `monty-alloc` aborts the process. Forked `monty_types::set_memory_probe` reads a per-VM `VmMeter` fed by `bashkit::MeteredAllocator` (thread-local, exact sync VM windows); allocator never aborts; `python3` fails closed when the allocator is not installed | `python_tenant_isolation_tests::*`, `fuzz/fuzz_targets/python_fuzz.rs` (nightly, metered allocator, 32 MiB cap under libFuzzer RSS limit) | +| TM-PY-032 | Cross-tenant memory accounting / process abort | Critical | Upstream Monty 1.x reads a process-wide allocator counter and `monty-alloc` aborts the process. Forked `monty_types::set_memory_probe` reads a per-VM `VmMeter` fed by `bashkit::MeteredAllocator` (thread-local, exact sync VM windows); allocator never aborts; `python3` fails closed when the allocator is not installed | `python_tenant_isolation_tests::*`, `python_tenant_stress_tests::*`, `fuzz/fuzz_targets/python_fuzz.rs` (nightly, metered allocator, 32 MiB cap under libFuzzer RSS limit) | | TM-PY-033 | ReDoS via `re` | High | `re` enabled since 2026-11-05: plain patterns run on the linear-time `regex` engine, backreference/lookaround patterns on `fancy-regex` with a backtrack cap (`re.PatternError`), match loops stopped by the time limit | `python_security_tests::regex_redos_patterns_are_bounded`, `regex_loop_is_stopped_by_time_limit`, `regex_huge_pattern_is_rejected_or_bounded` | -| TM-PY-034 | Uninterruptible VM loop ignores cancellation / shared budget | High | Forked `monty_types::set_checkpoint_hook` runs the request `ExecutionBudget` check at every VM time checkpoint; `Err` stops the run uncatchably | `python_security_tests::whitebox_resource_limits::*`, budget tests in `builtins::python` | +| TM-PY-034 | Uninterruptible VM loop ignores cancellation / shared budget | High | Forked `monty_types::set_checkpoint_hook` runs the request `ExecutionBudget` check at every VM time checkpoint; `Err` stops the run uncatchably | `python_security_tests::whitebox_resource_limits::*`, budget tests in `builtins::python`, `python_tenant_stress_tests::*` (spin, abandoned calls, budget reuse) | | TM-PY-035 | Shared object graph expands exponentially in host conversion | High | Monty 1.x `MontyObject` graphs can share children; every host converter (runtime values, scripted-tool JSON, Python binding) walks with a node cap (100k / 1M) | `runtime_value` and `tool_registry` unit tests | +| 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-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` |