From 82120c7af7a7cec8983a5dbc4f66f6f80c6a13aa Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Thu, 19 Nov 2026 18:35:09 +0000 Subject: [PATCH 1/4] fix: session limits in bindings, rm preserve-root, analyze uploads - Python/Node: max_exec_calls / max_session_commands (maxExecCalls / maxSessionCommands) raise or lower the per-instance session caps without switching profiles; kept across reset() - Session limit errors say the host can raise the limit; document defaults, snapshot carry-over and reset() in configuration docs - rm -r / refuses like GNU --preserve-root (exit 1) instead of a silent success; --no-preserve-root opts out - analyze(): uploads / ScriptAnalysis::file_uploads() lists local files curl, wget and scp would send - docs: sudo runs as the one sandbox user --- crates/bashkit-js/README.md | 3 + crates/bashkit-js/__test__/analyze.spec.ts | 22 ++ .../__test__/cwd-env-options.spec.ts | 61 +++ crates/bashkit-js/src/lib.rs | 64 ++++ crates/bashkit-js/wrapper.ts | 27 +- crates/bashkit-python/README.md | 7 + crates/bashkit-python/bashkit/__init__.py | 2 + crates/bashkit-python/bashkit/_bashkit.pyi | 47 +++ crates/bashkit-python/src/lib.rs | 145 ++++++++ crates/bashkit-python/tests/test_analyze.py | 23 ++ .../tests/test_execution_profiles.py | 53 +++ crates/bashkit-wasm/js/index.d.ts | 12 + crates/bashkit-wasm/src/lib.rs | 13 + crates/bashkit/docs/compatibility.md | 2 + crates/bashkit/src/analysis.rs | 352 ++++++++++++++++++ crates/bashkit/src/builtins/fileops.rs | 19 +- crates/bashkit/src/lib.rs | 3 +- crates/bashkit/src/limits.rs | 11 +- crates/bashkit/tests/integration/main.rs | 1 + .../integration/rm_preserve_root_tests.rs | 68 ++++ docs/configuration.md | 36 ++ docs/script-analysis.md | 24 ++ docs/security.md | 8 + knowledge/integrations/script-analysis.md | 25 ++ knowledge/log.md | 4 + 25 files changed, 1026 insertions(+), 6 deletions(-) create mode 100644 crates/bashkit/tests/integration/rm_preserve_root_tests.rs diff --git a/crates/bashkit-js/README.md b/crates/bashkit-js/README.md index 9bf017939..e1ac20dfe 100644 --- a/crates/bashkit-js/README.md +++ b/crates/bashkit-js/README.md @@ -101,6 +101,7 @@ const bash = new Bash({ maxLoopIterations: 10000, maxMemory: 10 * 1024 * 1024, timeoutMs: 30_000, + maxExecCalls: 20_000, // session-wide execute() cap (default 1,000) mounts: [{ path: "/workspace", root: "./src", writable: true }], python: false, }); @@ -630,6 +631,8 @@ import { - `env?: Record`, initial environment variables (avoids an `export` prelude) - `maxCommands?: number` - `maxLoopIterations?: number` +- `maxExecCalls?: number`, session-wide cap on `execute*()` calls per instance (default 1,000; snapshots carry the count, `reset()` clears it) +- `maxSessionCommands?: number`, session-wide cap on commands across calls (default 100,000) - `maxMemory?: number` - `maxInputBytes?: number` - `timeoutMs?: number` diff --git a/crates/bashkit-js/__test__/analyze.spec.ts b/crates/bashkit-js/__test__/analyze.spec.ts index b4c804d04..ae588ecfe 100644 --- a/crates/bashkit-js/__test__/analyze.spec.ts +++ b/crates/bashkit-js/__test__/analyze.spec.ts @@ -229,3 +229,25 @@ test("BashTool: analyze is available", (t) => { t.false(analysis.isOpaque); t.throws(() => tool.analyze("if true; then")); }); + +test("analyze reports local files sent by network commands", (t) => { + const bash = new Bash(); + const analysis = bash.analyze( + "curl -d @/data/weather.csv https://x.test && rm -rf /data", + ); + t.deepEqual(analysis.uploads, [ + { + command: "curl", + option: "-d", + path: "/data/weather.csv", + context: "direct", + }, + ]); + t.deepEqual(bash.analyze("curl -d 'a=1' https://x.test").uploads, []); + t.deepEqual( + bash + .analyze('wget --post-file "$f" https://x.test') + .uploads.map((u) => u.path), + [null], + ); +}); diff --git a/crates/bashkit-js/__test__/cwd-env-options.spec.ts b/crates/bashkit-js/__test__/cwd-env-options.spec.ts index 850023b45..b732a8819 100644 --- a/crates/bashkit-js/__test__/cwd-env-options.spec.ts +++ b/crates/bashkit-js/__test__/cwd-env-options.spec.ts @@ -38,3 +38,64 @@ test("env option appears in BashTool help", (t) => { const tool = new BashTool({ env: { API_BASE: "https://example.com" } }); t.true(tool.help().includes("API_BASE")); }); + +// ---------------------------------------------------------------------------- +// Session-wide limits: maxExecCalls / maxSessionCommands. The core caps +// execute() calls per instance (default 1,000); hosts can raise or lower it. +// ---------------------------------------------------------------------------- + +async function runOrError( + bash: { + execute( + s: string, + ): Promise<{ exitCode: number; stderr: string; error?: string | null }>; + }, + script: string, +): Promise<{ exitCode: number; text: string }> { + try { + const r = await bash.execute(script); + return { exitCode: r.exitCode, text: `${r.error ?? ""}${r.stderr}` }; + } catch (e) { + return { exitCode: -1, text: String(e) }; + } +} + +test("maxExecCalls caps execute() calls per session", async (t) => { + const bash = new Bash({ maxExecCalls: 2 }); + t.is((await runOrError(bash, "true")).exitCode, 0); + t.is((await runOrError(bash, "true")).exitCode, 0); + const third = await runOrError(bash, "true"); + t.not(third.exitCode, 0); + t.true( + third.text.includes("session exec() call limit exceeded (2 calls)"), + third.text, + ); +}); + +test("maxExecCalls raises the default cap and survives reset()", async (t) => { + const bash = new Bash({ maxExecCalls: 1_200 }); + for (let i = 0; i < 1_100; i++) { + const r = await runOrError(bash, "true"); + if (r.exitCode !== 0) t.fail(r.text); + } + const small = new Bash({ maxExecCalls: 1 }); + t.is((await runOrError(small, "true")).exitCode, 0); + t.not((await runOrError(small, "true")).exitCode, 0); + small.reset(); + t.is((await runOrError(small, "true")).exitCode, 0); + t.pass(); +}); + +test("maxSessionCommands caps commands across calls", async (t) => { + const bash = new Bash({ maxSessionCommands: 3 }); + t.is((await runOrError(bash, "true; true")).exitCode, 0); + const second = await runOrError(bash, "true; true"); + t.not(second.exitCode, 0); + t.true(second.text.includes("session command limit exceeded"), second.text); +}); + +test("BashTool accepts maxExecCalls", async (t) => { + const tool = new BashTool({ maxExecCalls: 1 }); + t.is((await runOrError(tool, "true")).exitCode, 0); + t.not((await runOrError(tool, "true")).exitCode, 0); +}); diff --git a/crates/bashkit-js/src/lib.rs b/crates/bashkit-js/src/lib.rs index 3e8eae902..dbeb82a69 100644 --- a/crates/bashkit-js/src/lib.rs +++ b/crates/bashkit-js/src/lib.rs @@ -1317,6 +1317,11 @@ pub struct BashOptions { pub max_parser_operations: Option, pub max_stdout_bytes: Option, pub max_stderr_bytes: Option, + /// Session-wide cap on `execute*()` calls for this instance (default 1,000). + /// Counts across calls and survives snapshots; `reset()` clears it. + pub max_exec_calls: Option, + /// Session-wide cap on commands across all calls (default 100,000). + pub max_session_commands: Option, /// Maximum interpreter memory in bytes (variables, arrays, functions). /// /// Caps `max_total_variable_bytes` and clamps `max_function_body_bytes`. @@ -1409,6 +1414,22 @@ pub struct JsAnalyzedRedirect { pub is_write: bool, } +/// A local file that `curl`, `wget`, or `scp` would send, found by `analyze()`. +#[napi(object, js_name = "AnalyzedUpload")] +pub struct JsAnalyzedUpload { + /// `"curl"`, `"wget"`, or `"scp"`. + pub command: String, + /// Option naming the file (`"-d"`, `"-F"`, `"--post-file"`, ...), or + /// `null` for an `scp` source operand. + #[napi(ts_type = "string | null")] + pub option: Option>, + /// Local path, or `null` when the argument is not fully literal. + #[napi(ts_type = "string | null")] + pub path: Option>, + /// `"direct"`, `"substitution"`, or `"function_body"`. + pub context: String, +} + /// Result of `analyze()` — what a script statically refers to. /// /// **Advisory only.** Static analysis cannot see through dynamic dispatch, @@ -1420,6 +1441,8 @@ pub struct JsScriptAnalysis { pub commands: Vec, /// Every file redirect target, in source order. pub redirects: Vec, + /// Local files that `curl`, `wget`, or `scp` would send, in source order. + pub uploads: Vec, /// Function names the script defines. pub functions: Vec, /// Distinct statically known command names, in first-seen order. @@ -1446,6 +1469,16 @@ fn analysis_to_js(analysis: bashkit::ScriptAnalysis) -> JsScriptAnalysis { .map(str::to_owned) .collect(), is_opaque: analysis.is_opaque(), + uploads: analysis + .file_uploads() + .into_iter() + .map(|u| JsAnalyzedUpload { + command: u.command, + option: Some(u.option), + path: Some(u.path), + context: u.context.as_str().to_owned(), + }) + .collect(), commands: analysis .commands .iter() @@ -1499,6 +1532,8 @@ fn default_opts() -> BashOptions { max_parser_operations: None, max_stdout_bytes: None, max_stderr_bytes: None, + max_exec_calls: None, + max_session_commands: None, max_memory: None, capture_final_env: None, files: None, @@ -1575,6 +1610,8 @@ struct SharedState { max_parser_operations: Option, max_stdout_bytes: Option, max_stderr_bytes: Option, + max_exec_calls: Option, + max_session_commands: Option, max_memory: Option, capture_final_env: Option, /// Constructor-provided VFS seed restored by `reset()`; runtime-created @@ -3888,6 +3925,28 @@ impl ScriptedTool { // Helpers // ============================================================================ +/// Apply `maxExecCalls` / `maxSessionCommands` over the profile's session limits. +/// +/// THREAT[TM-DOS-059]: the caps stay on by default so a tenant cannot dodge +/// per-call limits by splitting work across calls; hosts running long agent +/// sessions raise them explicitly here instead of switching profiles. +fn apply_session_limits( + builder: bashkit::BashBuilder, + state: &SharedState, +) -> bashkit::BashBuilder { + if state.max_exec_calls.is_none() && state.max_session_commands.is_none() { + return builder; + } + let mut session = core_profile(state).session_limits().clone(); + if let Some(v) = state.max_exec_calls { + session = session.max_exec_calls(u64::from(v)); + } + if let Some(v) = state.max_session_commands { + session = session.max_total_commands(u64::from(v)); + } + builder.session_limits(session) +} + /// Build `ExecutionLimits` from the limit fields stored in `SharedState`. fn build_limits(state: &SharedState) -> ExecutionLimits { let mut limits = core_profile(state).execution_limits().clone(); @@ -3973,6 +4032,7 @@ fn build_bash_from_state(state: &SharedState) -> RustBash { } builder = builder.limits(build_limits(state)); + builder = apply_session_limits(builder, state); if let Some(max_mem) = state.max_memory { builder = builder.max_memory(max_mem as usize); @@ -4168,6 +4228,8 @@ fn shared_state_from_opts(opts: BashOptions) -> napi::Result { max_parser_operations: opts.max_parser_operations, max_stdout_bytes: opts.max_stdout_bytes, max_stderr_bytes: opts.max_stderr_bytes, + max_exec_calls: opts.max_exec_calls, + max_session_commands: opts.max_session_commands, max_memory: opts.max_memory, capture_final_env: opts.capture_final_env, files: opts.files.clone(), @@ -4227,6 +4289,8 @@ fn shared_state_from_opts(opts: BashOptions) -> napi::Result { max_parser_operations: opts.max_parser_operations, max_stdout_bytes: opts.max_stdout_bytes, max_stderr_bytes: opts.max_stderr_bytes, + max_exec_calls: opts.max_exec_calls, + max_session_commands: opts.max_session_commands, max_memory: opts.max_memory, capture_final_env: opts.capture_final_env, files: opts.files, diff --git a/crates/bashkit-js/wrapper.ts b/crates/bashkit-js/wrapper.ts index c357275b8..9b73548db 100644 --- a/crates/bashkit-js/wrapper.ts +++ b/crates/bashkit-js/wrapper.ts @@ -30,6 +30,7 @@ import type { ScriptAnalysis, AnalyzedCommand, AnalyzedRedirect, + AnalyzedUpload, ExecutionProfileName as NativeExecutionProfileName, Terminal as NativeTerminalType, TerminalOptions, @@ -44,7 +45,12 @@ import { queueAsyncExecute, } from "./internal.js"; -export type { ScriptAnalysis, AnalyzedCommand, AnalyzedRedirect }; +export type { + ScriptAnalysis, + AnalyzedCommand, + AnalyzedRedirect, + AnalyzedUpload, +}; export { BashError }; export type { TerminalOptions, TerminalCommandRecord, TerminalActivityInfo }; @@ -249,6 +255,23 @@ export interface BashOptions extends RuntimeFunctionOptions { maxCommands?: number; maxLoopIterations?: number; maxTotalLoopIterations?: number; + /** + * Session-wide cap on `execute*()` calls for this instance (default 1,000). + * + * Unlike `maxCommands`, this counts across calls so a tenant cannot dodge + * per-call limits by splitting work. Snapshots carry the count; `reset()` + * clears it. Raise it for long agent sessions. + * + * @example + * ```typescript + * const bash = new Bash({ maxExecCalls: 50_000 }); + * ``` + */ + maxExecCalls?: number; + /** + * Session-wide cap on commands across all calls (default 100,000). + */ + maxSessionCommands?: number; /** * Maximum script input size in UTF-8 bytes. * @@ -585,6 +608,8 @@ function toNativeOptions( maxCommands: options?.maxCommands, maxLoopIterations: options?.maxLoopIterations, maxTotalLoopIterations: options?.maxTotalLoopIterations, + maxExecCalls: options?.maxExecCalls, + maxSessionCommands: options?.maxSessionCommands, maxMemory: options?.maxMemory, maxInputBytes: options?.maxInputBytes, timeoutMs: options?.timeoutMs, diff --git a/crates/bashkit-python/README.md b/crates/bashkit-python/README.md index 74e8d804c..05fe0801a 100644 --- a/crates/bashkit-python/README.md +++ b/crates/bashkit-python/README.md @@ -91,10 +91,17 @@ bash = Bash( max_loop_iterations=10000, max_memory=10 * 1024 * 1024, timeout_seconds=30, + max_exec_calls=20_000, # session-wide execute() cap (default 1,000) python=False, ) ``` +`max_commands` and the other limits apply per `execute()` call. Each `Bash` +instance also has session-wide caps that count across calls: 1,000 `execute()` +calls (`max_exec_calls`) and 100,000 commands (`max_session_commands`). Raise +them for long agent sessions; snapshots carry the counts and `reset()` clears +them. + ### Embedded Python and TypeScript Native wheels include both runtimes, disabled by default. Enable only those diff --git a/crates/bashkit-python/bashkit/__init__.py b/crates/bashkit-python/bashkit/__init__.py index 0ce8deb3f..4cf33b852 100644 --- a/crates/bashkit-python/bashkit/__init__.py +++ b/crates/bashkit-python/bashkit/__init__.py @@ -46,6 +46,7 @@ from bashkit._bashkit import ( AnalyzedCommand, AnalyzedRedirect, + AnalyzedUpload, Bash, BashError, BashTool, @@ -75,6 +76,7 @@ __all__ = [ "AnalyzedCommand", "AnalyzedRedirect", + "AnalyzedUpload", "Bash", "BashError", "ExecutionProfile", diff --git a/crates/bashkit-python/bashkit/_bashkit.pyi b/crates/bashkit-python/bashkit/_bashkit.pyi index c5c8af369..d0ec9359d 100644 --- a/crates/bashkit-python/bashkit/_bashkit.pyi +++ b/crates/bashkit-python/bashkit/_bashkit.pyi @@ -527,6 +527,8 @@ class Bash: custom_builtins: Mapping[str, BuiltinCallback] | None = None, network: NetworkConfig | None = None, profile: ExecutionProfile = ExecutionProfile.Standard, + max_exec_calls: int | None = None, + max_session_commands: int | None = None, ) -> None: """Create a new Bash interpreter. @@ -572,6 +574,12 @@ class Bash: callbacks run on the caller's active asyncio loop for ``await execute()`` and on a private loop for ``execute_sync()``. + max_exec_calls: Session-wide cap on ``execute()`` calls (default + 1,000). Counts across calls, so a tenant cannot dodge per-call + limits by splitting work; snapshots carry the count and + ``reset()`` clears it. Raise it for long agent sessions. + max_session_commands: Session-wide cap on commands across all + calls (default 100,000). network: Optional outbound HTTP / network configuration. Pass ``{"allow": [...]}`` for an explicit allowlist or ``{"allow_all": True}`` to allow every URL (mirrors @@ -878,6 +886,8 @@ class Bash: custom_builtins: Mapping[str, BuiltinCallback] | None = None, network: NetworkConfig | None = None, profile: ExecutionProfile = ExecutionProfile.Standard, + max_exec_calls: int | None = None, + max_session_commands: int | None = None, ) -> Bash: """Create a new ``Bash`` from snapshot bytes and optional constructor kwargs.""" ... @@ -905,6 +915,8 @@ class Bash: custom_builtins: Mapping[str, BuiltinCallback] | None = None, network: NetworkConfig | None = None, profile: ExecutionProfile = ExecutionProfile.Standard, + max_exec_calls: int | None = None, + max_session_commands: int | None = None, ) -> Bash: """Create a new ``Bash`` from HMAC-protected snapshot bytes.""" ... @@ -1071,6 +1083,27 @@ class AnalyzedRedirect: """Return the redirect as a plain dictionary.""" ... +class AnalyzedUpload: + """A local file that ``curl``, ``wget``, or ``scp`` would send. + + Covers ``curl -d @f`` / ``--data-binary @f`` / ``--json @f`` / + ``--data-urlencode name@f`` / ``-F k=@f`` / ``-T f``, ``wget + --post-file`` / ``--body-file``, and ``scp`` sources to a remote target. + Advisory: the network allowlist is what actually stops an upload. + """ + + command: str + option: str | None + """Option naming the file, or ``None`` for an ``scp`` source operand.""" + path: str | None + """Local path, or ``None`` when the argument is not fully literal.""" + context: str + """``"direct"``, ``"substitution"``, or ``"function_body"``.""" + + def to_dict(self) -> dict[str, Any]: + """Return the upload as a plain dictionary.""" + ... + class ScriptAnalysis: """Result of :meth:`Bash.analyze` — what a script statically refers to. @@ -1090,6 +1123,8 @@ class ScriptAnalysis: commands: list[AnalyzedCommand] redirects: list[AnalyzedRedirect] + uploads: list[AnalyzedUpload] + """Local files that ``curl``, ``wget``, or ``scp`` would send.""" functions: list[str] command_names: list[str] has_dynamic_commands: bool @@ -1194,6 +1229,8 @@ class BashTool: external_handler: ExternalHandler | None = None, typescript_external_functions: list[str] | None = None, typescript_external_handler: TypeScriptExternalHandler | None = None, + max_exec_calls: int | None = None, + max_session_commands: int | None = None, ) -> None: """Create a new BashTool. @@ -1225,6 +1262,12 @@ class BashTool: either. Async callbacks run on the caller's active asyncio loop for ``await execute()`` and on a private loop for ``execute_sync()``. + max_exec_calls: Session-wide cap on ``execute()`` calls (default + 1,000). Counts across calls, so a tenant cannot dodge per-call + limits by splitting work; snapshots carry the count and + ``reset()`` clears it. Raise it for long agent sessions. + max_session_commands: Session-wide cap on commands across all + calls (default 100,000). network: Optional outbound HTTP / network configuration. See ``Bash.__init__`` for accepted keys. Preserved across ``reset()`` and ``from_snapshot()``. @@ -1553,6 +1596,8 @@ class BashTool: external_handler: ExternalHandler | None = None, typescript_external_functions: list[str] | None = None, typescript_external_handler: TypeScriptExternalHandler | None = None, + max_exec_calls: int | None = None, + max_session_commands: int | None = None, ) -> BashTool: """Create a new ``BashTool`` from snapshot bytes and optional constructor kwargs.""" ... @@ -1582,6 +1627,8 @@ class BashTool: external_handler: ExternalHandler | None = None, typescript_external_functions: list[str] | None = None, typescript_external_handler: TypeScriptExternalHandler | None = None, + max_exec_calls: int | None = None, + max_session_commands: int | None = None, ) -> BashTool: """Create a new ``BashTool`` from HMAC-protected snapshot bytes.""" ... diff --git a/crates/bashkit-python/src/lib.rs b/crates/bashkit-python/src/lib.rs index 64b7afe0b..16c629d96 100644 --- a/crates/bashkit-python/src/lib.rs +++ b/crates/bashkit-python/src/lib.rs @@ -2679,6 +2679,47 @@ impl AnalyzedRedirect { } } +/// A local file a network command would send, found by `analyze()`. +#[pyclass(from_py_object)] +#[derive(Clone)] +pub struct AnalyzedUpload { + /// `"curl"`, `"wget"`, or `"scp"`. + #[pyo3(get)] + pub command: String, + /// Option naming the file (`"-d"`, `"-F"`, `"--post-file"`, ...), or + /// `None` for an `scp` source operand. + #[pyo3(get)] + pub option: Option, + /// Local path, or `None` when the argument is not fully literal. + #[pyo3(get)] + pub path: Option, + /// `"direct"`, `"substitution"`, or `"function_body"`. + #[pyo3(get)] + pub context: String, +} + +#[pymethods] +impl AnalyzedUpload { + fn __repr__(&self) -> String { + format!( + "AnalyzedUpload(command={:?}, option={:?}, path={:?}, context={:?})", + self.command, self.option, self.path, self.context + ) + } + + /// Return the upload as a plain dictionary. + fn to_dict(&self) -> PyResult> { + Python::attach(|py| { + let dict = PyDict::new(py); + dict.set_item("command", &self.command)?; + dict.set_item("option", &self.option)?; + dict.set_item("path", &self.path)?; + dict.set_item("context", &self.context)?; + Ok(dict.into()) + }) + } +} + /// Result of `analyze()` — what a script statically refers to. /// /// **Advisory only.** Static analysis cannot see through dynamic dispatch, @@ -2693,6 +2734,9 @@ pub struct ScriptAnalysis { /// Every file redirect target, in source order. #[pyo3(get)] pub redirects: Vec, + /// Local files that `curl`, `wget`, or `scp` would send, in source order. + #[pyo3(get)] + pub uploads: Vec, /// Function names the script defines. #[pyo3(get)] pub functions: Vec, @@ -2753,6 +2797,11 @@ impl ScriptAnalysis { redirects.append(redirect.to_dict()?)?; } dict.set_item("redirects", redirects)?; + let uploads = pyo3::types::PyList::empty(py); + for upload in &self.uploads { + uploads.append(upload.to_dict()?)?; + } + dict.set_item("uploads", uploads)?; dict.set_item("functions", &self.functions)?; dict.set_item("command_names", &self.command_names)?; dict.set_item("has_dynamic_commands", self.has_dynamic_commands)?; @@ -2774,6 +2823,16 @@ impl From for ScriptAnalysis { .map(str::to_owned) .collect(), is_opaque: analysis.is_opaque(), + uploads: analysis + .file_uploads() + .into_iter() + .map(|u| AnalyzedUpload { + command: u.command, + option: u.option, + path: u.path, + context: u.context.as_str().to_owned(), + }) + .collect(), commands: analysis .commands .iter() @@ -4827,6 +4886,31 @@ fn prepare_runtime_external_handler( .map(Some) } +/// Apply `max_exec_calls` / `max_session_commands` over the profile's +/// session limits. +/// +/// THREAT[TM-DOS-059]: the caps stay on by default so a tenant cannot dodge +/// per-call limits by splitting work across calls; hosts running long agent +/// sessions raise them explicitly here instead of switching profiles. +fn apply_session_limits( + builder: bashkit::BashBuilder, + profile: &bashkit::ExecutionProfile, + max_exec_calls: Option, + max_session_commands: Option, +) -> bashkit::BashBuilder { + if max_exec_calls.is_none() && max_session_commands.is_none() { + return builder; + } + let mut session = profile.session_limits().clone(); + if let Some(calls) = max_exec_calls { + session = session.max_exec_calls(calls); + } + if let Some(commands) = max_session_commands { + session = session.max_total_commands(commands); + } + builder.session_limits(session) +} + /// Embedded Python limits from the profile, with `timeout` as each run's cap. /// /// Decision: `timeout_seconds` also sets the runtimes' own time limit, see @@ -5020,6 +5104,10 @@ pub struct PyBash { /// `None` means the interpreter is built without a `NetworkAllowlist`, /// matching the current "network disabled" default. network: Option, + /// Session cap on `execute()` calls; `None` keeps the profile default. + max_exec_calls: Option, + /// Session cap on total commands across calls; `None` keeps the profile default. + max_session_commands: Option, } // THREAT[TM-PY-030]: see the equivalent Drop on ScriptedTool. @@ -5075,6 +5163,12 @@ impl PyBash { limits = limits.timeout(timeout); } builder = builder.limits(limits); + builder = apply_session_limits( + builder, + &profile, + self.max_exec_calls, + self.max_session_commands, + ); if let Some(max_memory) = self.max_memory { builder = builder.max_memory(usize::try_from(max_memory).unwrap_or(usize::MAX)); @@ -5138,6 +5232,8 @@ impl PyBash { custom_builtins=None, network=None, profile=PyExecutionProfile::Standard, + max_exec_calls=None, + max_session_commands=None, ))] #[allow(clippy::too_many_arguments)] fn new( @@ -5161,6 +5257,8 @@ impl PyBash { custom_builtins: Option<&Bound<'_, PyDict>>, network: Option<&Bound<'_, PyDict>>, profile: PyExecutionProfile, + max_exec_calls: Option, + max_session_commands: Option, ) -> PyResult { let core_profile = profile.core(); let mut builder = Bash::builder().profile(core_profile.clone()); @@ -5192,6 +5290,8 @@ impl PyBash { limits = limits.timeout(timeout); } builder = builder.limits(limits); + builder = + apply_session_limits(builder, &core_profile, max_exec_calls, max_session_commands); if let Some(mm) = max_memory { builder = builder.max_memory(usize::try_from(mm).unwrap_or(usize::MAX)); @@ -5278,6 +5378,8 @@ impl PyBash { max_memory, timeout_seconds, network, + max_exec_calls, + max_session_commands, }) } @@ -5774,6 +5876,8 @@ impl PyBash { custom_builtins=None, network=None, profile=PyExecutionProfile::Standard, + max_exec_calls=None, + max_session_commands=None, ))] #[allow(clippy::too_many_arguments)] fn from_snapshot( @@ -5798,6 +5902,8 @@ impl PyBash { custom_builtins: Option<&Bound<'_, PyDict>>, network: Option<&Bound<'_, PyDict>>, profile: PyExecutionProfile, + max_exec_calls: Option, + max_session_commands: Option, ) -> PyResult { let bash = Self::new( py, @@ -5820,6 +5926,8 @@ impl PyBash { custom_builtins, network, profile, + max_exec_calls, + max_session_commands, )?; bash.restore_snapshot(py, data)?; Ok(bash) @@ -5849,6 +5957,8 @@ impl PyBash { custom_builtins=None, network=None, profile=PyExecutionProfile::Standard, + max_exec_calls=None, + max_session_commands=None, ))] #[allow(clippy::too_many_arguments)] fn from_snapshot_keyed( @@ -5874,6 +5984,8 @@ impl PyBash { custom_builtins: Option<&Bound<'_, PyDict>>, network: Option<&Bound<'_, PyDict>>, profile: PyExecutionProfile, + max_exec_calls: Option, + max_session_commands: Option, ) -> PyResult { let bash = Self::new( py, @@ -5896,6 +6008,8 @@ impl PyBash { custom_builtins, network, profile, + max_exec_calls, + max_session_commands, )?; bash.restore_snapshot_keyed(py, data, key)?; Ok(bash) @@ -6182,6 +6296,10 @@ pub struct BashTool { timeout_seconds: Option, /// Outbound network config preserved across `reset()` and snapshots. network: Option, + /// Session cap on `execute()` calls; `None` keeps the profile default. + max_exec_calls: Option, + /// Session cap on total commands across calls; `None` keeps the profile default. + max_session_commands: Option, } // THREAT[TM-PY-030]: see the equivalent Drop on ScriptedTool. @@ -6276,6 +6394,12 @@ impl BashTool { limits = limits.timeout(timeout); } builder = builder.limits(limits); + builder = apply_session_limits( + builder, + &profile, + self.max_exec_calls, + self.max_session_commands, + ); if let Some(max_memory) = self.max_memory { builder = builder.max_memory(usize::try_from(max_memory).unwrap_or(usize::MAX)); @@ -6381,6 +6505,8 @@ impl BashTool { external_handler=None, typescript_external_functions=None, typescript_external_handler=None, + max_exec_calls=None, + max_session_commands=None, ))] fn new( py: Python<'_>, @@ -6405,6 +6531,8 @@ impl BashTool { external_handler: Option>, typescript_external_functions: Option>, typescript_external_handler: Option>, + max_exec_calls: Option, + max_session_commands: Option, ) -> PyResult { let core_profile = profile.core(); let mut builder = Bash::builder().profile(core_profile.clone()); @@ -6482,6 +6610,8 @@ impl BashTool { limits = limits.timeout(timeout); } builder = builder.limits(limits); + builder = + apply_session_limits(builder, &core_profile, max_exec_calls, max_session_commands); if let Some(mm) = max_memory { builder = builder.max_memory(usize::try_from(mm).unwrap_or(usize::MAX)); @@ -6544,6 +6674,8 @@ impl BashTool { max_memory, timeout_seconds, network, + max_exec_calls, + max_session_commands, }) } @@ -6941,6 +7073,8 @@ impl BashTool { external_handler=None, typescript_external_functions=None, typescript_external_handler=None, + max_exec_calls=None, + max_session_commands=None, ))] #[allow(clippy::too_many_arguments)] fn from_snapshot( @@ -6967,6 +7101,8 @@ impl BashTool { external_handler: Option>, typescript_external_functions: Option>, typescript_external_handler: Option>, + max_exec_calls: Option, + max_session_commands: Option, ) -> PyResult { let tool = Self::new( py, @@ -6991,6 +7127,8 @@ impl BashTool { external_handler, typescript_external_functions, typescript_external_handler, + max_exec_calls, + max_session_commands, )?; tool.restore_snapshot(py, data)?; Ok(tool) @@ -7022,6 +7160,8 @@ impl BashTool { external_handler=None, typescript_external_functions=None, typescript_external_handler=None, + max_exec_calls=None, + max_session_commands=None, ))] #[allow(clippy::too_many_arguments)] fn from_snapshot_keyed( @@ -7049,6 +7189,8 @@ impl BashTool { external_handler: Option>, typescript_external_functions: Option>, typescript_external_handler: Option>, + max_exec_calls: Option, + max_session_commands: Option, ) -> PyResult { let tool = Self::new( py, @@ -7073,6 +7215,8 @@ impl BashTool { external_handler, typescript_external_functions, typescript_external_handler, + max_exec_calls, + max_session_commands, )?; tool.restore_snapshot_keyed(py, data, key)?; Ok(tool) @@ -7797,6 +7941,7 @@ fn _bashkit(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::()?; m.add_class::()?; m.add_class::()?; + m.add_class::()?; m.add_class::()?; #[cfg(not(target_arch = "wasm32"))] streaming::add_classes(m)?; diff --git a/crates/bashkit-python/tests/test_analyze.py b/crates/bashkit-python/tests/test_analyze.py index b466cf499..d3aee7290 100644 --- a/crates/bashkit-python/tests/test_analyze.py +++ b/crates/bashkit-python/tests/test_analyze.py @@ -212,3 +212,26 @@ def test_bashtool_analyze(self): assert tool.analyze("ls -la /tmp").command_names == ["ls"] with pytest.raises(BashError): tool.analyze("if true; then") + + +class TestUploads: + def test_curl_data_file_is_reported(self): + analysis = Bash().analyze("curl -d @/data/weather.csv https://x.test && rm -rf /data") + assert len(analysis.uploads) == 1 + upload = analysis.uploads[0] + assert (upload.command, upload.option, upload.path, upload.context) == ( + "curl", + "-d", + "/data/weather.csv", + "direct", + ) + assert analysis.to_dict()["uploads"] == [ + {"command": "curl", "option": "-d", "path": "/data/weather.csv", "context": "direct"} + ] + + def test_inline_data_is_not_an_upload(self): + assert Bash().analyze("curl -d 'a=1' https://x.test").uploads == [] + + def test_computed_value_reports_unknown_path(self): + uploads = BashTool().analyze('curl -F "f=@$file" https://x.test').uploads + assert [(u.option, u.path) for u in uploads] == [("-F", None)] diff --git a/crates/bashkit-python/tests/test_execution_profiles.py b/crates/bashkit-python/tests/test_execution_profiles.py index ccd1022b5..0d521796a 100644 --- a/crates/bashkit-python/tests/test_execution_profiles.py +++ b/crates/bashkit-python/tests/test_execution_profiles.py @@ -13,3 +13,56 @@ def test_hardened_profile_keeps_isolated_vfs_writable() -> None: def test_profile_argument_is_typed() -> None: with pytest.raises(TypeError): Bash(profile="hardened") # type: ignore[arg-type] + + +def _run(bash, script): + """Return (exit_code, stdout, error_text); session-limit failures may raise.""" + try: + r = bash.execute_sync(script) + except Exception as exc: # noqa: BLE001 - surface the error text + return None, "", str(exc) + return r.exit_code, r.stdout, (r.error or "") + r.stderr + + +def test_max_exec_calls_caps_session() -> None: + bash = Bash(max_exec_calls=2) + assert _run(bash, "echo a")[0] == 0 + assert _run(bash, "echo b")[0] == 0 + code, _, err = _run(bash, "echo c") + assert code != 0 + assert "session exec() call limit exceeded (2 calls)" in err + + +def test_max_exec_calls_raises_default_cap() -> None: + # Default is 1,000 calls; a host running long agent sessions can raise it. + bash = Bash(max_exec_calls=1_200) + for _ in range(1_100): + code, _, err = _run(bash, "true") + assert code == 0, err + + +def test_max_exec_calls_survives_reset_config() -> None: + bash = Bash(max_exec_calls=1) + assert _run(bash, "true")[0] == 0 + assert _run(bash, "true")[0] != 0 + bash.reset() + assert _run(bash, "true")[0] == 0 + assert _run(bash, "true")[0] != 0 + + +def test_max_session_commands_caps_session() -> None: + bash = Bash(max_session_commands=3) + assert _run(bash, "true; true")[0] == 0 + code, _, err = _run(bash, "true; true") + assert code != 0 + assert "session command limit exceeded" in err + + +def test_bash_tool_accepts_session_limits() -> None: + from bashkit import BashTool + + tool = BashTool(max_exec_calls=1) + assert _run(tool, "echo a")[0] == 0 + code, _, err = _run(tool, "echo b") + assert code != 0 + assert "session exec() call limit exceeded (1 calls)" in err diff --git a/crates/bashkit-wasm/js/index.d.ts b/crates/bashkit-wasm/js/index.d.ts index 2fcb02c6b..916c975ef 100644 --- a/crates/bashkit-wasm/js/index.d.ts +++ b/crates/bashkit-wasm/js/index.d.ts @@ -231,9 +231,21 @@ export interface AnalyzedRedirect { readonly isWrite: boolean; } +/** A local file that `curl`, `wget`, or `scp` would send. */ +export interface AnalyzedUpload { + readonly command: "curl" | "wget" | "scp"; + /** Option naming the file, or `null` for an `scp` source operand. */ + readonly option: string | null; + /** Local path, or `null` when the argument is not fully literal. */ + readonly path: string | null; + readonly context: "direct" | "substitution" | "function_body"; +} + export interface ScriptAnalysis { readonly commands: AnalyzedCommand[]; readonly redirects: AnalyzedRedirect[]; + /** Local files that `curl`, `wget`, or `scp` would send, in source order. */ + readonly uploads: AnalyzedUpload[]; readonly functions: string[]; readonly commandNames: string[]; readonly hasDynamicCommands: boolean; diff --git a/crates/bashkit-wasm/src/lib.rs b/crates/bashkit-wasm/src/lib.rs index f894ff41f..12de543d5 100644 --- a/crates/bashkit-wasm/src/lib.rs +++ b/crates/bashkit-wasm/src/lib.rs @@ -621,9 +621,22 @@ impl Bash { }) }) .collect::>(); + let uploads = analysis + .file_uploads() + .into_iter() + .map(|upload| { + serde_json::json!({ + "command": upload.command, + "option": upload.option, + "path": upload.path, + "context": upload.context.as_str(), + }) + }) + .collect::>(); let value = serde_json::json!({ "commands": commands, "redirects": redirects, + "uploads": uploads, "functions": analysis.functions, "commandNames": analysis.command_names(), "hasDynamicCommands": analysis.has_dynamic_commands, diff --git a/crates/bashkit/docs/compatibility.md b/crates/bashkit/docs/compatibility.md index 9998842a1..8c92492f4 100644 --- a/crates/bashkit/docs/compatibility.md +++ b/crates/bashkit/docs/compatibility.md @@ -418,6 +418,8 @@ Default limits (configurable): | Parser operations | 100,000 | Fuel-based limit | | Input size | 10MB | Max script size | | AST depth | 100 | Nesting limit | +| `exec()` calls | 1,000 | Per `Bash` instance (session), see [session limits](../../../docs/configuration.md#session-limits) | +| Total commands | 100,000 | Per `Bash` instance (session) | --- diff --git a/crates/bashkit/src/analysis.rs b/crates/bashkit/src/analysis.rs index 9e17fcdf9..effd62dfb 100644 --- a/crates/bashkit/src/analysis.rs +++ b/crates/bashkit/src/analysis.rs @@ -589,6 +589,264 @@ impl Walker { } } +/// A local file a network command would send, found by +/// [`ScriptAnalysis::file_uploads`]. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct AnalyzedUpload { + /// Network command that sends the file (`curl`, `wget`, `scp`). + pub command: String, + /// Option that names the file (`-d`, `--data-binary`, `-F`, `-T`, + /// `--post-file`), or `None` for an `scp` source operand. + pub option: Option, + /// Local path, or `None` when the argument is not fully literal. + pub path: Option, + /// Where the command sits. + pub context: CommandPlacement, +} + +impl ScriptAnalysis { + /// Local files that `curl`, `wget`, or `scp` would read and send, in + /// source order. + /// + /// Decision: a derived view over [`commands`](Self::commands), not a + /// stored field, so the serialized shape stays stable. It covers the + /// flags that read a file into the request body (`curl -d @f`, + /// `--data-binary @f`, `--data-urlencode name@f`, `--json @f`, + /// `-F k=@f`/`k= Vec { + let mut out = Vec::new(); + for cmd in &self.commands { + let Some(name) = cmd.name.as_deref() else { + continue; + }; + let (name, args) = match unwrap_network_command(name, &cmd.args) { + Some(found) => found, + None => continue, + }; + let mut push = |option: Option<&str>, path: Option| { + out.push(AnalyzedUpload { + command: name.to_owned(), + option: option.map(str::to_owned), + path, + context: cmd.context, + }); + }; + match name { + "curl" => curl_uploads(args, &mut push), + "wget" => wget_uploads(args, &mut push), + "scp" => scp_uploads(args, &mut push), + _ => {} + } + } + out + } +} + +const NETWORK_UPLOADERS: &[&str] = &["curl", "wget", "scp"]; + +/// The network command and its arguments, looking through wrappers such as +/// `sudo` or `env FOO=1` to the first argument that names one. +fn unwrap_network_command<'a>( + name: &'a str, + args: &'a [Option], +) -> Option<(&'a str, &'a [Option])> { + if NETWORK_UPLOADERS.contains(&name) { + return Some((name, args)); + } + if !is_command_wrapper(name) { + return None; + } + args.iter().enumerate().find_map(|(i, arg)| { + let arg = arg.as_deref()?; + NETWORK_UPLOADERS + .iter() + .find(|n| **n == arg) + .map(|n| (*n, &args[i + 1..])) + }) +} + +/// Short curl options that take a value; the rest are boolean. +const CURL_SHORT_WITH_VALUE: &str = "AbcCdDeEFHKmoPQrtTuUwxXyYz"; + +/// Long curl options whose value is a file sent in the request. +fn curl_long_upload(option: &str) -> Option Option<&str>> { + match option { + "data" | "data-binary" | "data-ascii" | "json" => Some(at_file), + "data-urlencode" => Some(urlencode_file), + "form" => Some(form_file), + "upload-file" => Some(plain_file), + _ => None, + } +} + +fn curl_short_upload(flag: char) -> Option Option<&str>> { + match flag { + 'd' => Some(at_file), + 'F' => Some(form_file), + 'T' => Some(plain_file), + _ => None, + } +} + +/// `@file` (curl `-d`, `--data-binary`, `--json`). `--data-raw` sends `@` +/// literally, so it is not listed. +fn at_file(value: &str) -> Option<&str> { + value + .strip_prefix('@') + .filter(|p| !p.is_empty() && *p != "-") +} + +/// `--data-urlencode`: `@file` or `name@file`, unless an `=` comes first. +fn urlencode_file(value: &str) -> Option<&str> { + let at = value.find('@')?; + if value[..at].contains('=') { + return None; + } + Some(&value[at + 1..]).filter(|p| !p.is_empty() && *p != "-") +} + +/// `-F name=@file[;type=…]` or `name= Option<&str> { + let (_, rest) = value.split_once('=')?; + let path = rest.strip_prefix('@').or_else(|| rest.strip_prefix('<'))?; + let path = path.split(';').next().unwrap_or(path); + Some(path).filter(|p| !p.is_empty() && *p != "-") +} + +fn plain_file(value: &str) -> Option<&str> { + Some(value).filter(|p| !p.is_empty() && *p != "-" && *p != ".") +} + +/// Record one upload. A non-literal value is reported with `path: None` +/// because it could name any file. +fn record( + push: &mut impl FnMut(Option<&str>, Option), + option: &str, + value: Option<&str>, + extract: fn(&str) -> Option<&str>, +) { + match value { + None => push(Some(option), None), + Some(v) => { + if let Some(path) = extract(v) { + push(Some(option), Some(path.to_owned())); + } + } + } +} + +fn curl_uploads(args: &[Option], push: &mut impl FnMut(Option<&str>, Option)) { + let mut i = 0; + while i < args.len() { + let Some(arg) = args[i].as_deref() else { + i += 1; + continue; + }; + i += 1; + if arg == "--" { + break; + } + if let Some(long) = arg.strip_prefix("--") { + if let Some(extract) = curl_long_upload(long) { + let value = args.get(i).map(|v| v.as_deref()); + i += 1; + if let Some(value) = value { + record(push, arg, value, extract); + } + } + continue; + } + let Some(flags) = arg.strip_prefix('-').filter(|f| !f.is_empty()) else { + continue; + }; + // Bundled short options: booleans first, then at most one that takes + // a value (attached `-d@f` or the next argument). + for (pos, flag) in flags.char_indices() { + if !CURL_SHORT_WITH_VALUE.contains(flag) { + continue; + } + let attached = &flags[pos + flag.len_utf8()..]; + let value = if attached.is_empty() { + let v = args.get(i).map(|v| v.as_deref()); + i += 1; + v + } else { + Some(Some(attached)) + }; + if let (Some(extract), Some(value)) = (curl_short_upload(flag), value) { + record(push, &format!("-{flag}"), value, extract); + } + break; + } + } +} + +fn wget_uploads(args: &[Option], push: &mut impl FnMut(Option<&str>, Option)) { + let mut i = 0; + while i < args.len() { + let arg = args[i].as_deref(); + i += 1; + let Some(arg) = arg else { continue }; + for option in ["--post-file", "--body-file"] { + if arg == option { + let value = args.get(i).map(|v| v.as_deref()); + i += 1; + if let Some(value) = value { + record(push, option, value, plain_file); + } + } else if let Some(value) = arg + .strip_prefix(option) + .and_then(|rest| rest.strip_prefix('=')) + { + record(push, option, Some(value), plain_file); + } + } + } +} + +/// Short `scp` options that take a value. +const SCP_SHORT_WITH_VALUE: &str = "cDFiJlloPSX"; + +fn scp_uploads(args: &[Option], push: &mut impl FnMut(Option<&str>, Option)) { + let mut operands: Vec> = Vec::new(); + let mut i = 0; + let mut opts_done = false; + while i < args.len() { + let arg = args[i].as_deref(); + i += 1; + match arg { + Some("--") if !opts_done => opts_done = true, + Some(a) if !opts_done && a.starts_with('-') && a.len() > 1 => { + let flags = &a[1..]; + if let Some(pos) = flags.find(|c| SCP_SHORT_WITH_VALUE.contains(c)) + && pos + 1 == flags.len() + { + i += 1; + } + } + other => operands.push(other), + } + } + let Some((target, sources)) = operands.split_last() else { + return; + }; + // Only a remote target (`host:path`) sends local files out. + if !target.is_some_and(|t| t.contains(':')) { + return; + } + for source in sources { + match source { + None => push(None, None), + Some(s) if !s.contains(':') => push(None, Some((*s).to_owned())), + Some(_) => {} + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -605,6 +863,100 @@ mod tests { .collect() } + fn uploads(script: &str) -> Vec<(String, Option, Option)> { + analyze(script) + .unwrap() + .file_uploads() + .into_iter() + .map(|u| (u.command, u.option, u.path)) + .collect() + } + + fn up( + cmd: &str, + opt: Option<&str>, + path: Option<&str>, + ) -> (String, Option, Option) { + (cmd.into(), opt.map(Into::into), path.map(Into::into)) + } + + #[test] + fn curl_data_file_is_an_upload() { + assert_eq!( + uploads("curl -d @/data/weather.csv https://x.test && rm -rf /data"), + vec![up("curl", Some("-d"), Some("/data/weather.csv"))] + ); + assert_eq!( + uploads("curl -sSd@/etc/passwd https://x.test"), + vec![up("curl", Some("-d"), Some("/etc/passwd"))] + ); + assert_eq!( + uploads("curl --data-binary @a --json @b --data-urlencode q@c https://x.test"), + vec![ + up("curl", Some("--data-binary"), Some("a")), + up("curl", Some("--json"), Some("b")), + up("curl", Some("--data-urlencode"), Some("c")), + ] + ); + } + + #[test] + fn curl_form_and_upload_file() { + assert_eq!( + uploads("curl -F 'f=@/tmp/a.txt;type=text/plain' -F 'g= = Vec::new(); let mut opts_done = false; for arg in ctx.args { @@ -153,8 +154,9 @@ impl Builtin for Rm { match long.split('=').next().unwrap_or("") { "recursive" => recursive = true, "force" => force = true, - "dir" | "interactive" | "verbose" | "one-file-system" | "no-preserve-root" - | "preserve-root" => {} + "no-preserve-root" => preserve_root = false, + "preserve-root" => preserve_root = true, + "dir" | "interactive" | "verbose" | "one-file-system" => {} _ => return Ok(super::invalid_option("rm", arg, 1)), } } else if arg.starts_with('-') && arg.len() > 1 { @@ -185,6 +187,19 @@ impl Builtin for Rm { for file in files { let path = resolve_path(ctx.cwd, file); + // Decision: GNU rm's --preserve-root failsafe (on by default). + // `rm -rf /` used to exit 0 and silently do nothing, which reads + // as success to an agent. Refuse like GNU, even with -f; the + // check is on the resolved path, so `/tmp/..` counts too. + if recursive && preserve_root && path == Path::new("/") { + stderr.push_str(&format!( + "rm: it is dangerous to operate recursively on '{}'\n\ + rm: use --no-preserve-root to override this failsafe\n", + file + )); + continue; + } + // lstat: rm acts on a link itself (dangling links included). let metadata = ctx.fs.lstat(&path).await; let Ok(meta) = metadata else { diff --git a/crates/bashkit/src/lib.rs b/crates/bashkit/src/lib.rs index 1c4305655..47d7bd31c 100644 --- a/crates/bashkit/src/lib.rs +++ b/crates/bashkit/src/lib.rs @@ -499,7 +499,8 @@ pub use execution::Execution; pub use stream::StreamData; pub use analysis::{ - AnalyzedCommand, AnalyzedRedirect, CommandPlacement, RedirectMode, ScriptAnalysis, + AnalyzedCommand, AnalyzedRedirect, AnalyzedUpload, CommandPlacement, RedirectMode, + ScriptAnalysis, }; pub use async_trait::async_trait; pub use builtins::git::GitConfig; diff --git a/crates/bashkit/src/limits.rs b/crates/bashkit/src/limits.rs index 9bcc6dcbb..a8f2e4939 100644 --- a/crates/bashkit/src/limits.rs +++ b/crates/bashkit/src/limits.rs @@ -765,10 +765,17 @@ pub enum LimitExceeded { #[error("parser fuel exhausted ({0} operations, max {1})")] ParserExhausted(usize, usize), - #[error("session command limit exceeded ({0} total commands)")] + // Decision: name the host knob in the message. The cap spans the whole + // Bash instance, so only the embedding host can lift it (new instance, + // reset, or a higher `SessionLimits`); the script cannot. + #[error( + "session command limit exceeded ({0} total commands); raise the session limit (host setting) or start a new session" + )] SessionMaxCommands(u64), - #[error("session exec() call limit exceeded ({0} calls)")] + #[error( + "session exec() call limit exceeded ({0} calls); raise the session limit (host setting) or start a new session" + )] SessionMaxExecCalls(u64), #[error("memory limit exceeded: {0}")] diff --git a/crates/bashkit/tests/integration/main.rs b/crates/bashkit/tests/integration/main.rs index 038ac8ca2..5576f4d1e 100644 --- a/crates/bashkit/tests/integration/main.rs +++ b/crates/bashkit/tests/integration/main.rs @@ -154,6 +154,7 @@ pub mod regex_limit_tests; pub mod release_profile_tests; pub mod remote_fs_round_trip_tests; pub mod request_lifecycle_contract_tests; +pub mod rm_preserve_root_tests; pub mod runtime_env_tests; pub mod script_analysis; pub mod script_execution_tests; diff --git a/crates/bashkit/tests/integration/rm_preserve_root_tests.rs b/crates/bashkit/tests/integration/rm_preserve_root_tests.rs new file mode 100644 index 000000000..3fab8e8ab --- /dev/null +++ b/crates/bashkit/tests/integration/rm_preserve_root_tests.rs @@ -0,0 +1,68 @@ +//! `rm -r /` refuses like GNU rm's default `--preserve-root` failsafe. +//! +//! No real-bash oracle here on purpose: running these against the host shell +//! is exactly what the failsafe exists to prevent. +use bashkit::Bash; + +const REFUSAL: &str = "rm: it is dangerous to operate recursively on '/'\n\ + rm: use --no-preserve-root to override this failsafe\n"; + +#[tokio::test] +async fn rm_rf_root_refuses_and_keeps_files() { + let mut bash = Bash::new(); + let r = bash + .exec("echo keep > /tmp/f; rm -rf /; echo \"rc=$?\"; cat /tmp/f") + .await + .unwrap(); + assert_eq!(r.stdout, "rc=1\nkeep\n"); + assert_eq!(r.stderr, REFUSAL); +} + +#[tokio::test] +async fn rm_r_root_spellings_resolve_to_root() { + for spelling in ["//", "/tmp/..", "/./"] { + let mut bash = Bash::new(); + let r = bash + .exec(&format!( + "rm -r {spelling}; echo \"rc=$?\"; [ -d /tmp ] && echo ok" + )) + .await + .unwrap(); + assert_eq!(r.stdout, "rc=1\nok\n", "{spelling}: {}", r.stderr); + assert!( + r.stderr.contains("dangerous to operate recursively"), + "{spelling}: {}", + r.stderr + ); + } +} + +#[tokio::test] +async fn rm_root_failsafe_does_not_stop_other_operands() { + let mut bash = Bash::new(); + let r = bash + .exec("mkdir -p /tmp/gone; rm -rf / /tmp/gone; echo \"rc=$?\"; [ -e /tmp/gone ] || echo removed") + .await + .unwrap(); + assert_eq!(r.stdout, "rc=1\nremoved\n"); +} + +#[tokio::test] +async fn rm_without_recursive_on_root_is_a_directory_error() { + let mut bash = Bash::new(); + let r = bash.exec("rm /; echo \"rc=$?\"").await.unwrap(); + assert_eq!(r.stdout, "rc=1\n"); + assert_eq!(r.stderr, "rm: cannot remove '/': Is a directory\n"); +} + +#[tokio::test] +async fn rm_rf_glob_under_root_still_empties_the_sandbox() { + // Matches real bash: `/*` expands to the top-level entries, which are not + // `/` itself, so the failsafe does not apply. + let mut bash = Bash::new(); + let r = bash + .exec("echo x > /tmp/f; rm -rf /*; echo \"rc=$?\"; [ -e /tmp/f ] || echo gone") + .await + .unwrap(); + assert_eq!(r.stdout, "rc=0\ngone\n"); +} diff --git a/docs/configuration.md b/docs/configuration.md index c7a565da9..935387116 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -54,6 +54,42 @@ let limits = ExecutionLimits::new() let mut bash = Bash::builder().limits(limits).build(); ``` +## Session limits + +`ExecutionLimits` reset on every `exec()` call. Session limits count across all +calls on one `Bash` instance, so a tenant cannot dodge the per-call caps by +splitting work into many small calls: + +| Limit | Default | Rust | Python | Node | +|-------|---------|------|--------|------| +| `exec()` calls | 1,000 | `SessionLimits::max_exec_calls` | `max_exec_calls=` | `maxExecCalls` | +| Total commands | 100,000 | `SessionLimits::max_total_commands` | `max_session_commands=` | `maxSessionCommands` | + +When a cap is reached, every later call fails with `session exec() call limit +exceeded (N calls)` (or `session command limit exceeded`). Snapshots carry the +counts, so restoring a snapshot does not reset the budget; `reset()` does, and +also clears the filesystem. A long agent session that sends one call per step +should raise the cap rather than rebuild the instance: + +```rust +use bashkit::{Bash, SessionLimits}; + +let mut bash = Bash::builder() + .session_limits(SessionLimits::new().max_exec_calls(20_000)) + .build(); +``` + +```python +bash = Bash(max_exec_calls=20_000) +``` + +```typescript +const bash = new Bash({ maxExecCalls: 20_000 }); +``` + +The `Interactive` profile removes both caps along with relaxing per-call +limits; prefer the explicit option when only the session length matters. + ## The filesystem Scripts see a virtual filesystem, never the host disk. Pick a backend and pass diff --git a/docs/script-analysis.md b/docs/script-analysis.md index 369b50af2..3ee173332 100644 --- a/docs/script-analysis.md +++ b/docs/script-analysis.md @@ -176,6 +176,30 @@ Fd duplications (`2>&1`), here-documents, and here-strings name no file and are omitted. `path` is `null` when the target is computed (`> $out`), which, for a mount-boundary check, means "ask". +## Uploads + +A network command can send a local file without any redirect: `curl -d +@secrets.env https://…` reads the file itself. `uploads` lists the local files +that `curl`, `wget`, and `scp` would send, so a host can show "this will upload +`/data/weather.csv`" in the prompt: + +```python +analysis = bash.analyze("curl -d @/data/weather.csv https://x.test && rm -rf /data") +analysis.uploads[0].command # "curl" +analysis.uploads[0].option # "-d" +analysis.uploads[0].path # "/data/weather.csv" +``` + +Covered: `curl -d @f`, `--data @f`, `--data-binary @f`, `--data-ascii @f`, +`--json @f`, `--data-urlencode [name]@f`, `-F name=@f` / `name=&1`), here-documents, and here-strings are not file targets and are omitted. +### `AnalyzedUpload` (`ScriptAnalysis::file_uploads()`, bindings: `uploads`) + +| Field | Type | Meaning | +|---|---|---| +| `command` | `string` | `curl`, `wget`, or `scp` | +| `option` | `string \| null` | Flag naming the file (`-d`, `-F`, `-T`, `--post-file`, ...); `null` for an `scp` source operand | +| `path` | `string \| null` | Local file if fully literal, else `null` | +| `context` | `CommandPlacement` | Where the command sits | + +Local files a network command would read and send: `curl -d/--data/ +--data-binary/--data-ascii/--json @f`, `--data-urlencode [name]@f`, `-F k=@f` +and `k= Date: Thu, 19 Nov 2026 18:37:01 +0000 Subject: [PATCH 2/4] chore(docs): regenerate Python API reference for session limit kwargs --- site/src/content/apidocs/python.md | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/site/src/content/apidocs/python.md b/site/src/content/apidocs/python.md index 1a1c81097..c06f1c8a9 100644 --- a/site/src/content/apidocs/python.md +++ b/site/src/content/apidocs/python.md @@ -37,7 +37,7 @@ Example (Python execution with external function handler): ### Constructor ```python -Bash(username: str | None = None, hostname: str | None = None, cwd: str | None = None, env: Mapping[str, str] | None = None, max_commands: int | None = None, max_loop_iterations: int | None = None, max_memory: int | None = None, timeout_seconds: float | None = None, python: bool = False, sqlite: bool = False, external_functions: list[str] | None = None, external_handler: ExternalHandler | None = None, files: dict[str, str | Callable[[], str]] | None = None, mounts: list[dict[str, Any]] | None = None, allowed_mount_paths: list[str] | None = None, readonly_filesystem: bool = False, custom_builtins: Mapping[str, BuiltinCallback] | None = None, network: NetworkConfig | None = None, profile: ExecutionProfile = ExecutionProfile.Standard) -> None +Bash(username: str | None = None, hostname: str | None = None, cwd: str | None = None, env: Mapping[str, str] | None = None, max_commands: int | None = None, max_loop_iterations: int | None = None, max_memory: int | None = None, timeout_seconds: float | None = None, python: bool = False, sqlite: bool = False, external_functions: list[str] | None = None, external_handler: ExternalHandler | None = None, files: dict[str, str | Callable[[], str]] | None = None, mounts: list[dict[str, Any]] | None = None, allowed_mount_paths: list[str] | None = None, readonly_filesystem: bool = False, custom_builtins: Mapping[str, BuiltinCallback] | None = None, network: NetworkConfig | None = None, profile: ExecutionProfile = ExecutionProfile.Standard, max_exec_calls: int | None = None, max_session_commands: int | None = None) -> None ``` Create a new Bash interpreter. @@ -61,6 +61,8 @@ Create a new Bash interpreter. - **`allowed_mount_paths`** — Host path prefixes allowed for real filesystem mounts. Required when mounting sensitive host locations such as paths under a user home directory. - **`readonly_filesystem`** — Deny all filesystem mutations after configured files and mounts are applied. - **`custom_builtins`** — Constructor-time Python callbacks exposed as bash builtins. Each callback receives a ``BuiltinContext`` with raw ``argv`` tokens, optional pipeline ``stdin``, and a live ``fs`` handle to the virtual filesystem, and must return a stdout string, a ``BuiltinResult``, or await either. Async callbacks run on the caller's active asyncio loop for ``await execute()`` and on a private loop for ``execute_sync()``. +- **`max_exec_calls`** — Session-wide cap on ``execute()`` calls (default 1,000). Counts across calls, so a tenant cannot dodge per-call limits by splitting work; snapshots carry the count and ``reset()`` clears it. Raise it for long agent sessions. +- **`max_session_commands`** — Session-wide cap on commands across all calls (default 100,000). - **`network`** — Optional outbound HTTP / network configuration. Pass ``{"allow": [...]}`` for an explicit allowlist or ``{"allow_all": True}`` to allow every URL (mirrors ``NetworkAllowlist::allow_all()`` in the Rust core). Set ``"block_private_ips": False`` to relax the SSRF guard. Add ``"credentials": [...]`` to inject headers transparently for matching URLs and ``"credential_placeholders": [...]`` to expose opaque placeholder env vars that are replaced with the real secret on the wire. When omitted, network access is disabled (current default). Preserved across ``reset()`` and ``from_snapshot()`` — placeholder env vars are regenerated on each rebuild. Example: @@ -362,7 +364,7 @@ Restore interpreter state from bytes produced by ``snapshot_keyed()``. ### `from_snapshot` ```python -Bash.from_snapshot(data: bytes, username: str | None = None, hostname: str | None = None, cwd: str | None = None, env: Mapping[str, str] | None = None, max_commands: int | None = None, max_loop_iterations: int | None = None, max_memory: int | None = None, timeout_seconds: float | None = None, python: bool = False, sqlite: bool = False, external_functions: list[str] | None = None, external_handler: ExternalHandler | None = None, files: dict[str, str] | None = None, mounts: list[dict[str, Any]] | None = None, allowed_mount_paths: list[str] | None = None, readonly_filesystem: bool = False, custom_builtins: Mapping[str, BuiltinCallback] | None = None, network: NetworkConfig | None = None, profile: ExecutionProfile = ExecutionProfile.Standard) -> Bash +Bash.from_snapshot(data: bytes, username: str | None = None, hostname: str | None = None, cwd: str | None = None, env: Mapping[str, str] | None = None, max_commands: int | None = None, max_loop_iterations: int | None = None, max_memory: int | None = None, timeout_seconds: float | None = None, python: bool = False, sqlite: bool = False, external_functions: list[str] | None = None, external_handler: ExternalHandler | None = None, files: dict[str, str] | None = None, mounts: list[dict[str, Any]] | None = None, allowed_mount_paths: list[str] | None = None, readonly_filesystem: bool = False, custom_builtins: Mapping[str, BuiltinCallback] | None = None, network: NetworkConfig | None = None, profile: ExecutionProfile = ExecutionProfile.Standard, max_exec_calls: int | None = None, max_session_commands: int | None = None) -> Bash ``` Create a new ``Bash`` from snapshot bytes and optional constructor kwargs. @@ -370,7 +372,7 @@ Create a new ``Bash`` from snapshot bytes and optional constructor kwargs. ### `from_snapshot_keyed` ```python -Bash.from_snapshot_keyed(data: bytes, key: bytes, username: str | None = None, hostname: str | None = None, cwd: str | None = None, env: Mapping[str, str] | None = None, max_commands: int | None = None, max_loop_iterations: int | None = None, max_memory: int | None = None, timeout_seconds: float | None = None, python: bool = False, sqlite: bool = False, external_functions: list[str] | None = None, external_handler: ExternalHandler | None = None, files: dict[str, str] | None = None, mounts: list[dict[str, Any]] | None = None, allowed_mount_paths: list[str] | None = None, readonly_filesystem: bool = False, custom_builtins: Mapping[str, BuiltinCallback] | None = None, network: NetworkConfig | None = None, profile: ExecutionProfile = ExecutionProfile.Standard) -> Bash +Bash.from_snapshot_keyed(data: bytes, key: bytes, username: str | None = None, hostname: str | None = None, cwd: str | None = None, env: Mapping[str, str] | None = None, max_commands: int | None = None, max_loop_iterations: int | None = None, max_memory: int | None = None, timeout_seconds: float | None = None, python: bool = False, sqlite: bool = False, external_functions: list[str] | None = None, external_handler: ExternalHandler | None = None, files: dict[str, str] | None = None, mounts: list[dict[str, Any]] | None = None, allowed_mount_paths: list[str] | None = None, readonly_filesystem: bool = False, custom_builtins: Mapping[str, BuiltinCallback] | None = None, network: NetworkConfig | None = None, profile: ExecutionProfile = ExecutionProfile.Standard, max_exec_calls: int | None = None, max_session_commands: int | None = None) -> Bash ``` Create a new ``Bash`` from HMAC-protected snapshot bytes. @@ -600,7 +602,7 @@ Adds LLM-facing contract metadata (``description``, ``system_prompt``, ### Constructor ```python -BashTool(username: str | None = None, hostname: str | None = None, cwd: str | None = None, env: Mapping[str, str] | None = None, max_commands: int | None = None, max_loop_iterations: int | None = None, max_memory: int | None = None, timeout_seconds: float | None = None, files: dict[str, str | Callable[[], str]] | None = None, mounts: list[dict[str, Any]] | None = None, allowed_mount_paths: list[str] | None = None, readonly_filesystem: bool = False, custom_builtins: Mapping[str, BuiltinCallback] | None = None, network: NetworkConfig | None = None, profile: ExecutionProfile = ExecutionProfile.Standard, python: bool = False, typescript: bool = False, external_functions: list[str] | None = None, external_handler: ExternalHandler | None = None, typescript_external_functions: list[str] | None = None, typescript_external_handler: TypeScriptExternalHandler | None = None) -> None +BashTool(username: str | None = None, hostname: str | None = None, cwd: str | None = None, env: Mapping[str, str] | None = None, max_commands: int | None = None, max_loop_iterations: int | None = None, max_memory: int | None = None, timeout_seconds: float | None = None, files: dict[str, str | Callable[[], str]] | None = None, mounts: list[dict[str, Any]] | None = None, allowed_mount_paths: list[str] | None = None, readonly_filesystem: bool = False, custom_builtins: Mapping[str, BuiltinCallback] | None = None, network: NetworkConfig | None = None, profile: ExecutionProfile = ExecutionProfile.Standard, python: bool = False, typescript: bool = False, external_functions: list[str] | None = None, external_handler: ExternalHandler | None = None, typescript_external_functions: list[str] | None = None, typescript_external_handler: TypeScriptExternalHandler | None = None, max_exec_calls: int | None = None, max_session_commands: int | None = None) -> None ``` Create a new BashTool. @@ -620,6 +622,8 @@ Create a new BashTool. - **`allowed_mount_paths`** — Host path prefixes allowed for real filesystem mounts. Required when mounting sensitive host locations such as paths under a user home directory. - **`readonly_filesystem`** — Deny all filesystem mutations after configured files and mounts are applied. - **`custom_builtins`** — Constructor-time Python callbacks exposed as bash builtins. Each callback receives a ``BuiltinContext`` (including a live ``fs`` handle to the virtual filesystem) and must return a stdout string, a ``BuiltinResult``, or await either. Async callbacks run on the caller's active asyncio loop for ``await execute()`` and on a private loop for ``execute_sync()``. +- **`max_exec_calls`** — Session-wide cap on ``execute()`` calls (default 1,000). Counts across calls, so a tenant cannot dodge per-call limits by splitting work; snapshots carry the count and ``reset()`` clears it. Raise it for long agent sessions. +- **`max_session_commands`** — Session-wide cap on commands across all calls (default 100,000). - **`network`** — Optional outbound HTTP / network configuration. See ``Bash.__init__`` for accepted keys. Preserved across ``reset()`` and ``from_snapshot()``. - **`profile`** — Execution profile (Standard or Compatibility). - **`python`** — Register sandboxed Monty Python (default ``False``). @@ -982,7 +986,7 @@ Restore interpreter state from bytes produced by ``snapshot_keyed()``. ### `from_snapshot` ```python -BashTool.from_snapshot(data: bytes, username: str | None = None, hostname: str | None = None, cwd: str | None = None, env: Mapping[str, str] | None = None, max_commands: int | None = None, max_loop_iterations: int | None = None, max_memory: int | None = None, timeout_seconds: float | None = None, files: dict[str, str] | None = None, mounts: list[dict[str, Any]] | None = None, allowed_mount_paths: list[str] | None = None, readonly_filesystem: bool = False, custom_builtins: Mapping[str, BuiltinCallback] | None = None, network: NetworkConfig | None = None, profile: ExecutionProfile = ExecutionProfile.Standard, python: bool = False, typescript: bool = False, external_functions: list[str] | None = None, external_handler: ExternalHandler | None = None, typescript_external_functions: list[str] | None = None, typescript_external_handler: TypeScriptExternalHandler | None = None) -> BashTool +BashTool.from_snapshot(data: bytes, username: str | None = None, hostname: str | None = None, cwd: str | None = None, env: Mapping[str, str] | None = None, max_commands: int | None = None, max_loop_iterations: int | None = None, max_memory: int | None = None, timeout_seconds: float | None = None, files: dict[str, str] | None = None, mounts: list[dict[str, Any]] | None = None, allowed_mount_paths: list[str] | None = None, readonly_filesystem: bool = False, custom_builtins: Mapping[str, BuiltinCallback] | None = None, network: NetworkConfig | None = None, profile: ExecutionProfile = ExecutionProfile.Standard, python: bool = False, typescript: bool = False, external_functions: list[str] | None = None, external_handler: ExternalHandler | None = None, typescript_external_functions: list[str] | None = None, typescript_external_handler: TypeScriptExternalHandler | None = None, max_exec_calls: int | None = None, max_session_commands: int | None = None) -> BashTool ``` Create a new ``BashTool`` from snapshot bytes and optional constructor kwargs. @@ -990,7 +994,7 @@ Create a new ``BashTool`` from snapshot bytes and optional constructor kwargs. ### `from_snapshot_keyed` ```python -BashTool.from_snapshot_keyed(data: bytes, key: bytes, username: str | None = None, hostname: str | None = None, cwd: str | None = None, env: Mapping[str, str] | None = None, max_commands: int | None = None, max_loop_iterations: int | None = None, max_memory: int | None = None, timeout_seconds: float | None = None, files: dict[str, str] | None = None, mounts: list[dict[str, Any]] | None = None, allowed_mount_paths: list[str] | None = None, readonly_filesystem: bool = False, custom_builtins: Mapping[str, BuiltinCallback] | None = None, network: NetworkConfig | None = None, profile: ExecutionProfile = ExecutionProfile.Standard, python: bool = False, typescript: bool = False, external_functions: list[str] | None = None, external_handler: ExternalHandler | None = None, typescript_external_functions: list[str] | None = None, typescript_external_handler: TypeScriptExternalHandler | None = None) -> BashTool +BashTool.from_snapshot_keyed(data: bytes, key: bytes, username: str | None = None, hostname: str | None = None, cwd: str | None = None, env: Mapping[str, str] | None = None, max_commands: int | None = None, max_loop_iterations: int | None = None, max_memory: int | None = None, timeout_seconds: float | None = None, files: dict[str, str] | None = None, mounts: list[dict[str, Any]] | None = None, allowed_mount_paths: list[str] | None = None, readonly_filesystem: bool = False, custom_builtins: Mapping[str, BuiltinCallback] | None = None, network: NetworkConfig | None = None, profile: ExecutionProfile = ExecutionProfile.Standard, python: bool = False, typescript: bool = False, external_functions: list[str] | None = None, external_handler: ExternalHandler | None = None, typescript_external_functions: list[str] | None = None, typescript_external_handler: TypeScriptExternalHandler | None = None, max_exec_calls: int | None = None, max_session_commands: int | None = None) -> BashTool ``` Create a new ``BashTool`` from HMAC-protected snapshot bytes. From 1bc101a0a26ed6eabf8d3a7db627cbabf0dbc460 Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Thu, 19 Nov 2026 19:24:35 +0000 Subject: [PATCH 3/4] fix(analysis): detect curl --opt=value uploads; list preserve-root in rm --help --- crates/bashkit/src/analysis.rs | 35 +++++++++++++++++++++++--- crates/bashkit/src/builtins/fileops.rs | 2 +- 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/crates/bashkit/src/analysis.rs b/crates/bashkit/src/analysis.rs index effd62dfb..faf3d45b1 100644 --- a/crates/bashkit/src/analysis.rs +++ b/crates/bashkit/src/analysis.rs @@ -751,11 +751,24 @@ fn curl_uploads(args: &[Option], push: &mut impl FnMut(Option<&str>, Opt break; } if let Some(long) = arg.strip_prefix("--") { - if let Some(extract) = curl_long_upload(long) { - let value = args.get(i).map(|v| v.as_deref()); - i += 1; + // Bashkit's curl also takes `--data=value` (real curl does not), so + // analysis follows the builtin: an `=value` is the inline value. + let (name, inline) = match long.split_once('=') { + Some((name, value)) => (name, Some(value)), + None => (long, None), + }; + if let Some(extract) = curl_long_upload(name) { + let option = format!("--{name}"); + let value = match inline { + Some(v) => Some(Some(v)), + None => { + let v = args.get(i).map(|v| v.as_deref()); + i += 1; + v + } + }; if let Some(value) = value { - record(push, arg, value, extract); + record(push, &option, value, extract); } } continue; @@ -900,6 +913,20 @@ mod tests { ); } + #[test] + fn curl_long_equals_value_is_an_upload() { + assert_eq!( + uploads("curl --data-binary=@/f --form=x=@/g --upload-file=/h https://x.test"), + vec![ + up("curl", Some("--data-binary"), Some("/f")), + up("curl", Some("--form"), Some("/g")), + up("curl", Some("--upload-file"), Some("/h")), + ] + ); + // The inline value does not swallow the next argument. + assert!(uploads("curl --data=a=1 @/not-data https://x.test").is_empty()); + } + #[test] fn curl_form_and_upload_file() { assert_eq!( diff --git a/crates/bashkit/src/builtins/fileops.rs b/crates/bashkit/src/builtins/fileops.rs index e854cc6ab..2b6e6599d 100644 --- a/crates/bashkit/src/builtins/fileops.rs +++ b/crates/bashkit/src/builtins/fileops.rs @@ -128,7 +128,7 @@ impl Builtin for Rm { async fn execute(&self, ctx: Context<'_>) -> Result { if let Some(r) = super::check_help_version( ctx.args, - "Usage: rm [OPTION]... [FILE]...\nRemove (unlink) the FILE(s).\n\n -f\t\tignore nonexistent files and arguments, never prompt\n -r, -R\tremove directories and their contents recursively\n --help\tdisplay this help and exit\n --version\toutput version information and exit\n", + "Usage: rm [OPTION]... [FILE]...\nRemove (unlink) the FILE(s).\n\n -f\t\tignore nonexistent files and arguments, never prompt\n -r, -R\tremove directories and their contents recursively\n --no-preserve-root\tdo not treat '/' specially\n --preserve-root\tdo not remove '/' (default)\n --help\tdisplay this help and exit\n --version\toutput version information and exit\n", Some("rm (bashkit) 0.1"), ) { return Ok(r); From e1a786f3d5046c5b20fc3b24909f410dc7c0dd78 Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Thu, 19 Nov 2026 19:35:43 +0000 Subject: [PATCH 4/4] test(remote-fs): ignore ls -l mtimes when comparing bulk and plain walks The two filesystems are seeded at different moments, so 'ls -lR' output differs when the seeding straddles a minute boundary (seen on CI). --- .../integration/remote_fs_round_trip_tests.rs | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/crates/bashkit/tests/integration/remote_fs_round_trip_tests.rs b/crates/bashkit/tests/integration/remote_fs_round_trip_tests.rs index d6f178088..779328309 100644 --- a/crates/bashkit/tests/integration/remote_fs_round_trip_tests.rs +++ b/crates/bashkit/tests/integration/remote_fs_round_trip_tests.rs @@ -69,6 +69,26 @@ async fn run(fs: &CountingFs, bash: &mut Bash, script: &str) -> (CallCounts, Str (counts, r.stdout.to_string()) } +/// Blank the `YYYY-MM-DD HH:MM` columns of `ls -l` lines. +fn without_ls_times(out: &str) -> String { + out.lines() + .map(|line| { + let fields: Vec<&str> = line.split_whitespace().collect(); + let is_long = fields.len() >= 5 + && fields[2].len() == 10 + && fields[2].as_bytes()[4] == b'-' + && fields[3].len() == 5 + && fields[3].as_bytes()[2] == b':'; + if is_long { + format!("{} {} - - {}", fields[0], fields[1], fields[4..].join(" ")) + } else { + line.to_string() + } + }) + .collect::>() + .join("\n") +} + fn line_count(out: &str) -> u64 { out.lines().count() as u64 } @@ -475,6 +495,9 @@ async fn ls_recursive_and_tree_output_is_the_same_with_bulk_walk() { ] { let (_, expected) = run(&plain, &mut plain_bash, script).await; let (c, got) = run(&bulk, &mut bulk_bash, script).await; + // The two trees are seeded at slightly different times, so `ls -l` + // mtimes can straddle a minute boundary; compare everything else. + let (got, expected) = (without_ls_times(&got), without_ls_times(&expected)); assert_eq!(got, expected, "{script}"); assert!(!expected.is_empty(), "{script}: vacuous"); assert!(