From 7507b70934100e3cfece4b38714485a44aea6038 Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Fri, 6 Nov 2026 23:48:24 +0000 Subject: [PATCH 1/2] fix(python): preflight json.dumps indent and separator writes `json.dumps([1], indent=10**12)`, or a huge string indent/separator over deep or long data, allocated past the python3 memory limit unchecked; the metered allocator cannot refuse, so one tenant aborted the process. The Monty fork now preflights the indent repeat and each separator/indent write, raising MemoryError (TM-PY-038). --- crates/bashkit-monty/src/modules/json/dump.rs | 88 +++++++++++++------ crates/bashkit/docs/threat-model.md | 1 + .../python_tenant_isolation_tests.rs | 52 +++++++++++ knowledge/log.md | 1 + knowledge/security/threat-model.md | 1 + 5 files changed, 116 insertions(+), 27 deletions(-) diff --git a/crates/bashkit-monty/src/modules/json/dump.rs b/crates/bashkit-monty/src/modules/json/dump.rs index 46e6816be..b24bc8352 100644 --- a/crates/bashkit-monty/src/modules/json/dump.rs +++ b/crates/bashkit-monty/src/modules/json/dump.rs @@ -15,6 +15,8 @@ use crate::{ exception_private::{ExcType, ExcTypeExt, RunError, RunResult}, heap::{ContainsHeap, DropGuard, DropWithContext, Heap, HeapData, HeapId, HeapRead}, py_value::PyValue, + // bashkit fork: preflight helper for the indent string. + resource_checks::check_repeat_size, sorting::{apply_permutation, sort_indices}, types::{Dict, PyTrait, Type, str::allocate_string}, value::Value, @@ -339,23 +341,31 @@ fn apply_bool_flag(flags: u8, bit: u8, value: &Value, vm: &mut VM<'_>) -> RunRes fn parse_indent_value(value: &Value, vm: &mut VM<'_>) -> RunResult> { match value.py_value(vm) { PyValue::None => Ok(None), - PyValue::Bool(value) => spaces_from_indent_count(i64::from(value)), + // bashkit fork: preflight the indent size (see `spaces_from_indent_count`). + PyValue::Bool(value) => spaces_from_indent_count(i64::from(value), vm), PyValue::Int(integer) => { - spaces_from_indent_count(integer.to_i64(vm).ok_or_else(ExcType::overflow_index_sized_int)?) + // bashkit fork: preflight the indent size (see `spaces_from_indent_count`). + let count = integer.to_i64(vm).ok_or_else(ExcType::overflow_index_sized_int)?; + spaces_from_indent_count(count, vm) } PyValue::Str(value) => Ok(Some(value.as_str(vm).to_owned())), _ => Err(ExcType::type_error_sequence_repeat(value.py_type_name(vm))), } } +/// bashkit fork: takes the VM to preflight the repeat size. /// Builds the `' ' * count` indent string. -fn spaces_from_indent_count(count: i64) -> RunResult> { +fn spaces_from_indent_count(count: i64, vm: &VM<'_>) -> RunResult> { // CPython repeats a negative count to the empty string. let count = if count < 0 { 0 } else { usize::try_from(count).map_err(|_| ExcType::overflow_index_sized_int())? }; + // bashkit fork: preflight the repeat like `' ' * n`. Upstream allocated + // `indent=10**12` unchecked, and the metered allocator cannot refuse an + // allocation, so one tenant aborted the shared process. + check_repeat_size(1, count, &vm.heap.tracker)?; Ok(Some(" ".repeat(count))) } @@ -579,7 +589,9 @@ impl<'h> Encoder<'_, 'h> { mut write_next: impl FnMut(&mut Self, usize) -> RunResult, ) -> RunResult<()> { self.out.push('['); - let pretty = self.config.indent.is_some(); + // bashkit fork: preflighted separator/indent write (see `push_checked`). + let config = self.config; + let pretty = config.indent.is_some(); let mut wrote_any = false; loop { // Write the separator + indent BEFORE we know whether the next @@ -587,11 +599,12 @@ impl<'h> Encoder<'_, 'h> { // cursor back. let prefix_start = self.out.len(); if wrote_any { - self.out.push_str(&self.config.item_separator); + // bashkit fork: preflighted separator/indent write (see `push_checked`). + self.push_checked(&config.item_separator)?; } if pretty { - self.out.push('\n'); - write_indent(self.out, self.config, depth + 1); + // bashkit fork: preflighted separator/indent write (see `push_checked`). + self.write_newline_indent(depth + 1)?; } let body_start = self.out.len(); if !write_next(self, depth + 1)? { @@ -605,8 +618,8 @@ impl<'h> Encoder<'_, 'h> { wrote_any = true; } if pretty && wrote_any { - self.out.push('\n'); - write_indent(self.out, self.config, depth); + // bashkit fork: preflighted separator/indent write (see `push_checked`). + self.write_newline_indent(depth)?; } self.out.push(']'); Ok(()) @@ -643,27 +656,57 @@ impl<'h> Encoder<'_, 'h> { self.out.push('{'); - let pretty = self.config.indent.is_some(); + // bashkit fork: preflighted separator/indent write (see `push_checked`). + let config = self.config; + let pretty = config.indent.is_some(); for (index, (key, value)) in entries.iter().enumerate() { if index != 0 { - self.out.push_str(&self.config.item_separator); + // bashkit fork: preflighted separator/indent write (see `push_checked`). + self.push_checked(&config.item_separator)?; } if pretty { - self.out.push('\n'); - write_indent(self.out, self.config, depth + 1); + // bashkit fork: preflighted separator/indent write (see `push_checked`). + self.write_newline_indent(depth + 1)?; } write_json_key(key, self.out, self.config, self.vm)?; - self.out.push_str(&self.config.key_separator); + // bashkit fork: preflighted separator/indent write (see `push_checked`). + self.push_checked(&config.key_separator)?; self.serialize_value(value, depth + 1)?; } if pretty && !entries.is_empty() { - self.out.push('\n'); - write_indent(self.out, self.config, depth); + // bashkit fork: preflighted separator/indent write (see `push_checked`). + self.write_newline_indent(depth)?; } self.out.push('}'); Ok(()) } + /// bashkit fork: separators and indentation are user strings written once + /// per item (and indentation once per depth level), so each write is + /// preflighted like a value. Upstream pushed them unchecked, which let + /// `json.dumps([[...]], indent=big)` grow the output past the memory + /// limit; the metered allocator cannot refuse, so the process aborted. + fn push_checked(&mut self, text: &str) -> RunResult<()> { + self.check_output_growth(text.len())?; + self.out.push_str(text); + Ok(()) + } + + /// bashkit fork: writes a newline plus `depth` copies of the indent + /// string, preflighted as one block (see [`Self::push_checked`]). + fn write_newline_indent(&mut self, depth: usize) -> RunResult<()> { + let config = self.config; + let Some(indent) = &config.indent else { + return Ok(()); + }; + self.check_output_growth(indent.len().saturating_mul(depth).saturating_add(1))?; + self.out.push('\n'); + for _ in 0..depth { + self.out.push_str(indent); + } + Ok(()) + } + /// Preflights the output buffer's next doubling before writing a value of /// about `value_len` bytes, so serializing a large document raises /// `MemoryError` instead of reallocating past the limit's headroom. @@ -877,17 +920,8 @@ fn write_json_float_text(value: f64, out: &mut String) { } } -/// Writes indentation for pretty-printed JSON output. -/// -/// The `indent` string is repeated once for each nesting level, matching -/// CPython's behavior for both numeric and string indentation. -fn write_indent(out: &mut String, config: &JsonDumpsConfig, depth: usize) { - if let Some(indent) = &config.indent { - for _ in 0..depth { - out.push_str(indent); - } - } -} +// bashkit fork: upstream `write_indent` lives on as the preflighted +// `Encoder::write_newline_indent`. /// Writes a Rust string as a JSON string token. /// diff --git a/crates/bashkit/docs/threat-model.md b/crates/bashkit/docs/threat-model.md index 53d90f85f..20dfaba3f 100644 --- a/crates/bashkit/docs/threat-model.md +++ b/crates/bashkit/docs/threat-model.md @@ -740,6 +740,7 @@ Python `pathlib.Path` and `open()` operations are bridged to Bashkit's virtual f | 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 | | 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 | **Architecture:** diff --git a/crates/bashkit/tests/integration/python_tenant_isolation_tests.rs b/crates/bashkit/tests/integration/python_tenant_isolation_tests.rs index 3ee2d8620..1229d928b 100644 --- a/crates/bashkit/tests/integration/python_tenant_isolation_tests.rs +++ b/crates/bashkit/tests/integration/python_tenant_isolation_tests.rs @@ -89,3 +89,55 @@ async fn str_join_respects_memory_limit() { .unwrap(); assert_ne!(r.exit_code, 0, "stdout: {}", r.stdout); } + +/// Runs `script` as a `python3` file under a 32 MiB limit. +async fn run_py(script: &str) -> bashkit::ExecResult { + let mut bash = tenant(32); + bash.fs() + .write_file(std::path::Path::new("/t.py"), script.as_bytes()) + .await + .unwrap(); + bash.exec("python3 /t.py").await.unwrap() +} + +// THREAT[TM-PY-038]: `json.dumps` indent and separators are preflighted. +// Upstream Monty built `' ' * indent` and wrote separators unchecked; the +// metered allocator cannot refuse, so these aborted the whole process. +#[tokio::test] +async fn json_dumps_huge_indent_is_memory_error() { + let r = run_py("import json\njson.dumps([1], indent=10**12)\n").await; + assert_ne!(r.exit_code, 0, "stdout: {}", r.stdout); + assert!(r.stderr.contains("MemoryError"), "stderr: {}", r.stderr); +} + +#[tokio::test] +async fn json_dumps_deep_string_indent_is_memory_error() { + // 1 MB indent written depth times per line, 40 levels deep: ~1.6 GB. + let r = run_py( + "import json\nx = 1\nfor _ in range(40):\n x = [x]\njson.dumps(x, indent='x' * 1000000)\n", + ) + .await; + assert_ne!(r.exit_code, 0, "stdout: {}", r.stdout); + assert!(r.stderr.contains("MemoryError"), "stderr: {}", r.stderr); +} + +#[tokio::test] +async fn json_dumps_huge_separator_is_memory_error() { + // 10 KB separator between 100k items: ~1 GB. + let r = run_py("import json\njson.dumps([0] * 100000, separators=('x' * 10000, ':'))\n").await; + assert_ne!(r.exit_code, 0, "stdout: {}", r.stdout); + assert!(r.stderr.contains("MemoryError"), "stderr: {}", r.stderr); +} + +#[tokio::test] +async fn json_dumps_pretty_output_unchanged() { + let r = run_py( + "import json\nprint(json.dumps({'a': [1, 2], 'b': {}}, indent=2))\nprint(json.dumps([1, {'k': 'v'}], indent='\\t', separators=(';', '=')))\n", + ) + .await; + assert_eq!(r.exit_code, 0, "stderr: {}", r.stderr); + assert_eq!( + r.stdout, + "{\n \"a\": [\n 1,\n 2\n ],\n \"b\": {}\n}\n[\n\t1;\n\t{\n\t\t\"k\"=\"v\"\n\t}\n]\n" + ); +} diff --git a/knowledge/log.md b/knowledge/log.md index 757a1b428..be5839de8 100644 --- a/knowledge/log.md +++ b/knowledge/log.md @@ -2,6 +2,7 @@ ## 2026-11-06 +* **`json.dumps` indent preflight**: a security audit found `json.dumps([1], indent=10**12)` (and huge string indents or separators on deep or long data) allocated past the Python memory limit unchecked; the metered allocator cannot refuse, so one tenant aborted the process. The Monty fork now preflights the indent repeat and every separator/indent write, raising `MemoryError`. See [Threat Model](security/threat-model.md), TM-PY-038. * **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 fork drift markers completed**: the drift check landed (#2861) from a branch cut before the shared-graph fix (#2857), so `main` went red on 12 unmarked regions the moment both were in. Eleven were real #2857 edits (seven `repr_check_time(..)?` call sites, the `ResourceError` import, a doc sentence, the `tick` initializer) and are now marked. The twelfth was a checker blind spot: its fixed three-line window read the tail of a multi-line fork note and missed the marker on the note's first line, which is how the forks are written (`repr_check_time`'s note is eleven lines). The window now covers the whole comment/attribute block attached to the changed item, stopping at the first line of code so one item's note cannot mark the next item's drift. See [Dependencies](operations/dependencies.md#monty-forks). * **Monty fork drift check**: `scripts/check_monty_fork.py` compares both forks with the SHA-256-pinned upstream 1.4.0 crates and fails on unmarked edits (it found one unmarked import, now marked); runs in CI lint and `just check`. Re-sync checklist for upstream security fixes added. See [Dependencies](operations/dependencies.md#monty-forks). diff --git a/knowledge/security/threat-model.md b/knowledge/security/threat-model.md index f4f34aa54..3d1d127ea 100644 --- a/knowledge/security/threat-model.md +++ b/knowledge/security/threat-model.md @@ -2013,6 +2013,7 @@ yield `OsCall` events that Bashkit intercepts and dispatches to the VFS. | 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-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-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` | From b7808b5a1386d995c191aa22134a0c93ae6206bc Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Sat, 7 Nov 2026 00:40:45 +0000 Subject: [PATCH 2/2] fix(python): preflight json.dumps str dict keys Str keys now go through the same output-growth check as str values. --- crates/bashkit-monty/src/modules/json/dump.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/bashkit-monty/src/modules/json/dump.rs b/crates/bashkit-monty/src/modules/json/dump.rs index b24bc8352..774aae126 100644 --- a/crates/bashkit-monty/src/modules/json/dump.rs +++ b/crates/bashkit-monty/src/modules/json/dump.rs @@ -668,6 +668,12 @@ impl<'h> Encoder<'_, 'h> { // bashkit fork: preflighted separator/indent write (see `push_checked`). self.write_newline_indent(depth + 1)?; } + // bashkit fork: str keys are preflighted like str values. + let key_len = match key.py_value(self.vm) { + PyValue::Str(key) => key.as_str(self.vm).len(), + _ => 0, + }; + self.check_output_growth(key_len)?; write_json_key(key, self.out, self.config, self.vm)?; // bashkit fork: preflighted separator/indent write (see `push_checked`). self.push_checked(&config.key_separator)?;