Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions crates/bashkit-python/bashkit/_bashkit.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -540,7 +540,10 @@ class Bash:
max_commands: Limit total commands executed.
max_loop_iterations: Limit iterations per loop.
max_memory: Memory limit in bytes for the VFS.
timeout_seconds: Abort execution after this duration.
timeout_seconds: Abort execution after this duration. Also the time
limit of each embedded ``python3`` run (profile default: 30 s,
Hardened 10 s). A CPU-bound run holds its worker thread up to
this limit, so keep it short when tenants share threads.
python: Enable embedded Python (``python3`` builtin).
sqlite: Enable embedded SQLite (``sqlite``/``sqlite3`` builtin).
Defaults to ``False``. When ``True``, the Turso-backed engine
Expand Down Expand Up @@ -1204,7 +1207,10 @@ class BashTool:
max_commands: Limit total commands executed.
max_loop_iterations: Limit iterations per loop.
max_memory: Memory limit in bytes for the VFS.
timeout_seconds: Abort execution after this duration.
timeout_seconds: Abort execution after this duration. Also the time
limit of each embedded ``python3``/``ts`` run (profile default:
30 s, Hardened 10 s). A CPU-bound run holds its worker thread up
to this limit, so keep it short when tenants share threads.
files: Dict mapping VFS paths to file contents or lazy callables.
mounts: List of real host directory mount configs.
allowed_mount_paths: Host path prefixes allowed for real filesystem
Expand Down
74 changes: 56 additions & 18 deletions crates/bashkit-python/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4748,6 +4748,30 @@ fn prepare_runtime_external_handler(
.map(Some)
}

/// Embedded Python limits from the profile, with `timeout` as each run's cap.
///
/// Decision: `timeout_seconds` also sets the runtimes' own time limit, see
/// knowledge/runtimes/python-package.md#embedded-tool-runtimes.
fn python_limits(profile: &bashkit::ExecutionProfile, timeout: Option<Duration>) -> PythonLimits {
let limits = profile.python_limits().clone();
match timeout {
Some(timeout) => limits.max_duration(timeout),
None => limits,
}
}

/// Embedded TypeScript limits; see [`python_limits`].
fn typescript_limits(
profile: &bashkit::ExecutionProfile,
timeout: Option<Duration>,
) -> bashkit::TypeScriptLimits {
let limits = profile.typescript_limits().clone();
match timeout {
Some(timeout) => limits.max_duration(timeout),
None => limits,
}
}

/// Apply python/external_handler configuration to a `BashBuilder`.
///
/// Centralises the logic shared between `new()` and `reset()`.
Expand Down Expand Up @@ -4956,6 +4980,10 @@ impl PyBash {
}
}

let timeout = self
.timeout_seconds
.map(parse_timeout_seconds)
.transpose()?;
let mut limits = profile.execution_limits().clone();
if let Some(max_commands) = self.max_commands {
limits = limits.max_commands(usize::try_from(max_commands).unwrap_or(usize::MAX));
Expand All @@ -4964,8 +4992,8 @@ impl PyBash {
limits = limits
.max_loop_iterations(usize::try_from(max_loop_iterations).unwrap_or(usize::MAX));
}
if let Some(timeout_seconds) = self.timeout_seconds {
limits = limits.timeout(parse_timeout_seconds(timeout_seconds)?);
if let Some(timeout) = timeout {
limits = limits.timeout(timeout);
}
builder = builder.limits(limits);

Expand All @@ -4977,7 +5005,7 @@ impl PyBash {
builder = apply_python_config(
builder,
self.python,
profile.python_limits().clone(),
python_limits(&profile, timeout),
self.external_functions.clone(),
handler_clone,
);
Expand Down Expand Up @@ -5073,15 +5101,16 @@ impl PyBash {
}
}

let timeout = timeout_seconds.map(parse_timeout_seconds).transpose()?;
let mut limits = core_profile.execution_limits().clone();
if let Some(mc) = max_commands {
limits = limits.max_commands(usize::try_from(mc).unwrap_or(usize::MAX));
}
if let Some(mli) = max_loop_iterations {
limits = limits.max_loop_iterations(usize::try_from(mli).unwrap_or(usize::MAX));
}
if let Some(ts) = timeout_seconds {
limits = limits.timeout(parse_timeout_seconds(ts)?);
if let Some(timeout) = timeout {
limits = limits.timeout(timeout);
}
builder = builder.limits(limits);

Expand All @@ -5108,7 +5137,7 @@ impl PyBash {
builder = apply_python_config(
builder,
python,
core_profile.python_limits().clone(),
python_limits(&core_profile, timeout),
fn_names,
handler_for_build,
);
Expand Down Expand Up @@ -6112,26 +6141,32 @@ impl BashTool {
fn build_live_builder(&self, py: Python<'_>) -> PyResult<bashkit::BashBuilder> {
let profile = self.profile.core();
let mut builder = Bash::builder().profile(profile.clone());
let timeout = self
.timeout_seconds
.map(parse_timeout_seconds)
.transpose()?;
if self.python {
let limits = python_limits(&profile, timeout);
if let Some(handler) = &self.external_handler {
builder = builder.python_with_external_handler(
profile.python_limits().clone(),
limits,
self.external_functions.clone(),
make_external_handler_native(py, handler),
);
} else {
builder = builder.python();
builder = builder.python_with_limits(limits);
}
}
if self.typescript {
let limits = typescript_limits(&profile, timeout);
if let Some(handler) = &self.typescript_external_handler {
builder = builder.typescript_with_external_handler(
profile.typescript_limits().clone(),
limits,
self.typescript_external_functions.clone(),
make_typescript_external_handler_native(py, handler),
);
} else {
builder = builder.typescript();
builder = builder.typescript_with_limits(limits);
}
}

Expand All @@ -6158,8 +6193,8 @@ impl BashTool {
limits = limits
.max_loop_iterations(usize::try_from(max_loop_iterations).unwrap_or(usize::MAX));
}
if let Some(timeout_seconds) = self.timeout_seconds {
limits = limits.timeout(parse_timeout_seconds(timeout_seconds)?);
if let Some(timeout) = timeout {
limits = limits.timeout(timeout);
}
builder = builder.limits(limits);

Expand Down Expand Up @@ -6294,6 +6329,7 @@ impl BashTool {
) -> PyResult<Self> {
let core_profile = profile.core();
let mut builder = Bash::builder().profile(core_profile.clone());
let timeout = timeout_seconds.map(parse_timeout_seconds).transpose()?;
let fn_names = external_functions.unwrap_or_default();
let external_handler_reentry_guard = ExternalHandlerReentryGuard::new(
py,
Expand All @@ -6307,14 +6343,15 @@ impl BashTool {
&external_handler_reentry_guard,
)?;
if python {
let limits = python_limits(&core_profile, timeout);
if let Some(handler) = &external_handler {
builder = builder.python_with_external_handler(
core_profile.python_limits().clone(),
limits,
fn_names.clone(),
make_external_handler_native(py, handler),
);
} else {
builder = builder.python();
builder = builder.python_with_limits(limits);
}
}
let ts_fn_names = typescript_external_functions.unwrap_or_default();
Expand All @@ -6328,14 +6365,15 @@ impl BashTool {
"typescript_external",
)?;
if typescript {
let limits = typescript_limits(&core_profile, timeout);
if let Some(handler) = &typescript_external_handler {
builder = builder.typescript_with_external_handler(
core_profile.typescript_limits().clone(),
limits,
ts_fn_names.clone(),
make_typescript_external_handler_native(py, handler),
);
} else {
builder = builder.typescript();
builder = builder.typescript_with_limits(limits);
}
}

Expand All @@ -6361,8 +6399,8 @@ impl BashTool {
if let Some(mli) = max_loop_iterations {
limits = limits.max_loop_iterations(usize::try_from(mli).unwrap_or(usize::MAX));
}
if let Some(ts) = timeout_seconds {
limits = limits.timeout(parse_timeout_seconds(ts)?);
if let Some(timeout) = timeout {
limits = limits.timeout(timeout);
}
builder = builder.limits(limits);

Expand Down
24 changes: 22 additions & 2 deletions crates/bashkit-python/tests/test_tool_runtimes.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
"""Opt-in tool runtimes share the VFS and survive interpreter rebuilds."""
"""Opt-in tool runtimes share the VFS, survive interpreter rebuilds, and honor timeout_seconds."""

import importlib.util
import time

import pytest

from bashkit import BashTool
from bashkit import Bash, BashTool, ExecutionProfile

PYTHON_ENV = {"BASHKIT_ALLOW_INPROCESS_PYTHON": "1"}

Expand Down Expand Up @@ -124,3 +125,22 @@ def test_invalid_runtime_program_reports_failure(runtime, script):
assert result.exit_code != 0
assert result.stdout == ""
assert result.stderr


@pytest.mark.parametrize(
("cls", "runtime", "script"),
[
(Bash, "python", "python3 -c 'while True: pass'"),
(BashTool, "typescript", "ts -c 'for (;;) {}'"),
],
)
def test_timeout_seconds_raises_runtime_time_limit(cls, runtime, script):
# Hardened caps each runtime call at 10 s; timeout_seconds must lift it too.
tool = cls(profile=ExecutionProfile.Hardened, timeout_seconds=11, env=PYTHON_ENV, **{runtime: True})
start = time.monotonic()
result = tool.execute_sync(script)
elapsed = time.monotonic() - start
assert result.exit_code == 124, result.stderr
assert "timed out" in result.stderr
# Past the Hardened 10 s cap, but still stopped by the 11 s deadline.
assert 10.5 < elapsed < 20
1 change: 1 addition & 0 deletions crates/bashkit/docs/threat-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -747,6 +747,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 |

**Architecture:**

Expand Down
1 change: 1 addition & 0 deletions knowledge/log.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## 2026-11-06

* **Python package runtime timeout**: `Bash(timeout_seconds=...)` and `BashTool(timeout_seconds=...)` raised the shell timeout but left embedded Python and TypeScript at the profile's `max_duration` per run (30 s, Hardened 10 s), so `timeout_seconds=120` still stopped `python3` at 30 s. `timeout_seconds` now also sets that limit, as `Bash` already did for SQLite. A longer cap also lengthens how long a CPU-bound run can hold a shared worker thread; recorded as TM-PY-039. See [Python Package](runtimes/python-package.md#embedded-tool-runtimes), [Threat Model](security/threat-model.md).
* **markkit/fetchkit honor the exec deadline**: a security audit found `markkit extract` on a large document ran synchronously on the tenant's async worker, so a 300 ms `exec` timeout returned after 7+ s and co-tenants on that worker stalled. Both builtins now run on tokio's blocking pool, and their timeouts are capped at the remaining `exec` budget (302 ms in the regression test). See [markkit/fetchkit builtins](runtimes/markkit-fetchkit-builtins.md), TM-DOS-143.
* **`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.
* **Re-entry depth and on-demand stack growth**: a security audit found three ways one tenant could overflow the native stack and abort the shared process: `f(){ eval f; }` and `compgen -C` (plus `fc` and PROMPT_COMMAND) re-entered the interpreter with no depth count; `./s.sh` running itself skipped the `sh s.sh` child-shell guard; and the product of capped nesting kinds (compounds x functions x eval) still exceeded a 2 MiB release worker stack. Re-entry now counts against `max_function_depth` and `MAX_REENTRY_DEPTH` (8), path-invoked scripts take the child-shell guard, and `execute_command` grows the stack on the heap through `stacker` (already in the graph via Monty; not on wasm32). See [Threat Model](security/threat-model.md), TM-DOS-125, TM-DOS-141, TM-DOS-142.
Expand Down
13 changes: 12 additions & 1 deletion knowledge/runtimes/python-package.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,16 @@ captures this grant at construction, so an agent's `export` cannot enable it.
Do not infer permission from untrusted script contents. See
[Python Builtin](python-builtin.md) and [ZapCode Runtime](zapcode-runtime.md).

`timeout_seconds` on `Bash` and `BashTool` also sets the embedded runtimes'
`max_duration` (the limit of each `python3`/`ts` run, profile default 30 s,
Hardened 10 s), as `Bash` does for SQLite. Each run stays clamped to the
remaining execution deadline. `ts` VM time also draws on the execution work
budget at one unit per microsecond, so a `ts` run past about 100 s (Hardened
25 s) still fails on `max_work_units`.
A CPU-bound run yields its worker thread only at host calls, so raising
`timeout_seconds` also raises the longest time one tenant can hold a shared
worker thread (TM-PY-039 in the [Threat Model](../security/threat-model.md)).

LangChain's `BashkitTool` / `create_bash_tool`, deepagents' `BashkitMiddleware` /
`create_bash_middleware`, and `BashkitBackend` forward `python`, `typescript`,
and `env` to their native tool. Backend-created middleware shares the configured
Expand All @@ -192,7 +202,8 @@ reset retain the host's runtime selection.
Regression evidence: `crates/bashkit-python/tests/test_tool_runtimes.py` covers
defaults, independent runtime selection, metadata, sync/async execution, shared
VFS, reset, keyed/unkeyed snapshot factories, framework forwarding, invalid
programs, and rejection of script-only Python opt-in.
programs, rejection of script-only Python opt-in, and `timeout_seconds` raising
the runtime time limit.

### Embedded runtime host functions

Expand Down
3 changes: 2 additions & 1 deletion knowledge/security/threat-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -2001,7 +2001,7 @@ yield `OsCall` events that Bashkit intercepts and dispatches to the VFS.

| ID | Threat | Severity | Mitigation | Test |
|----|--------|----------|------------|------|
| TM-PY-001 | Infinite loop via `while True` | High | Monty time limit (30s) | `threat_python_infinite_loop` |
| TM-PY-001 | Infinite loop via `while True` | High | Monty time limit (30s; Python bindings: `timeout_seconds`, see TM-PY-039) | `threat_python_infinite_loop` |
| TM-PY-002 | Memory exhaustion via large allocation | High | Monty max_memory (64MB) read from bashkit's per-VM allocator meter (TM-PY-032), which also caps collected `print` output | `threat_python_memory_exhaustion` |
| TM-PY-003 | Stack overflow via deep recursion | High | Monty max_recursion (200) + parser depth limit (200, since 0.0.4) | `threat_python_recursion_bomb` |
| TM-PY-004 | Shell escape via os.system/subprocess | Critical | Monty has no os.system/subprocess implementation | `threat_python_no_os_operations` |
Expand All @@ -2020,6 +2020,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-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` |
Expand Down
Loading
Loading