diff --git a/crates/openhuman-core/src/agent/tinyagents/host/bundle.rs b/crates/openhuman-core/src/agent/tinyagents/host/bundle.rs index 5920727abe1..f152e3637fb 100644 --- a/crates/openhuman-core/src/agent/tinyagents/host/bundle.rs +++ b/crates/openhuman-core/src/agent/tinyagents/host/bundle.rs @@ -164,7 +164,11 @@ impl OpenHumanHostBundleFactory { .with_approval(turn.approval.clone()) .with_dispatch(turn.dispatch_ctx()) .with_headless_descendant_settlement(turn.headless_descendant_settlement) - .with_scheduled_actions(turn.scheduled_actions); + .with_scheduled_actions(turn.scheduled_actions) + .with_sandboxed_shell(matches!( + turn.sandbox_mode, + Some(tinyagents_definition::SandboxMode::Sandboxed) + )); if let Some(policy) = inputs.tool_policy { security = security.with_tool_policy(policy); } diff --git a/crates/openhuman-core/src/agent/tinyagents/host/security_gate.rs b/crates/openhuman-core/src/agent/tinyagents/host/security_gate.rs index 83cc5f2c10a..134f6ab3174 100644 --- a/crates/openhuman-core/src/agent/tinyagents/host/security_gate.rs +++ b/crates/openhuman-core/src/agent/tinyagents/host/security_gate.rs @@ -158,6 +158,12 @@ pub struct OpenHumanSecurityGate { /// `TrustedAutomationSource::CronActions` origin and a run depth of 0 or 1 /// it lifts the read-only Cron stage; every later stage still applies. scheduled_actions: bool, + /// The run's sandbox mode is `Sandboxed`, so its shell commands run inside + /// the kernel jail and TinySecurity's lexical protected-path floor is + /// waived for them (`SecurityPolicy::check_jailed_command`). The shell + /// re-checks at execution and refuses again if the command would land on + /// the host after all. + sandboxed_shell: bool, } impl OpenHumanSecurityGate { @@ -180,9 +186,17 @@ impl OpenHumanSecurityGate { screening_config: None, headless_descendant_settlement: false, scheduled_actions: false, + sandboxed_shell: false, } } + /// Marks the gate as a run whose shell is jailed (its definition's sandbox + /// mode is `Sandboxed`). + pub(crate) fn with_sandboxed_shell(mut self, enabled: bool) -> Self { + self.sandboxed_shell = enabled; + self + } + /// Marks the gate as the root session of an opted-in scheduled-actions /// cron run (`cron::origin::scheduled_actions_enabled`), or as a direct /// child granted it (`agent::subagent_host::ops::scheduled_actions_grant`). diff --git a/crates/openhuman-core/src/agent/tinyagents/host/security_gate/authorize.rs b/crates/openhuman-core/src/agent/tinyagents/host/security_gate/authorize.rs index b763ac73401..ea92628e53a 100644 --- a/crates/openhuman-core/src/agent/tinyagents/host/security_gate/authorize.rs +++ b/crates/openhuman-core/src/agent/tinyagents/host/security_gate/authorize.rs @@ -200,15 +200,25 @@ impl OpenHumanSecurityGate { tinytools::status::POLICY_BLOCKED_MARKER ))); }; - let verdict = match policy - .check_command(crate::security::policy::CommandQuery { - command, - declared: None, - flow: crate::security::policy::CommandFlow::Harness, - stage: crate::security::policy::CommandStage::Authorize, - }) - .await - { + let query = crate::security::policy::CommandQuery { + command, + declared: None, + flow: crate::security::policy::CommandFlow::Harness, + stage: crate::security::policy::CommandStage::Authorize, + }; + // A jailed shell leaves paths to the jail: only TinySecurity's + // lexical protected-path floor is waived, every other refusal + // stays, and the shell refuses again at execution should the + // command land on the host. + let checked = if self.sandboxed_shell { + policy + .check_jailed_command(query) + .await + .map(|answer| answer.verdict) + } else { + policy.check_command(query).await + }; + let verdict = match checked { Ok(verdict) => verdict, Err(reason) => return Ok(GateDecision::deny(reason.to_string())), }; diff --git a/crates/openhuman-core/src/agent/tinyagents/host/security_gate_jailed_shell_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/security_gate_jailed_shell_tests.rs new file mode 100644 index 00000000000..5f8d69dd4dd --- /dev/null +++ b/crates/openhuman-core/src/agent/tinyagents/host/security_gate_jailed_shell_tests.rs @@ -0,0 +1,55 @@ +//! A jailed shell and TinySecurity's protected-path floor. + +use super::*; + +#[cfg(feature = "security-module")] +async fn floor_decision( + autonomy: AutonomyLevel, + sandboxed_shell: bool, + command: &str, +) -> GateDecision { + let (policy, _) = crate::security::policy::floor_policy(autonomy); + OpenHumanSecurityGate::new(Arc::new(policy), registry()) + .with_sandboxed_shell(sandboxed_shell) + .authorize_tool(&req(SHELL_TOOL, json!({ "command": command }))) + .await + .expect("authorization") +} + +/// Production (Nov 2026): a scheduled agent whose shell runs in the kernel +/// jail had `cd ..`, `sed 's/../X/'` and `cat /etc/os-release` refused for +/// naming a protected path, a lexical check the jail makes redundant. +#[cfg(feature = "security-module")] +#[tokio::test] +async fn a_sandboxed_shell_is_not_refused_for_naming_a_protected_path() { + for command in [ + "cd .. && ls", + "sed 's/../X/' notes.txt", + "cat /etc/os-release", + ] { + let decision = floor_decision(AutonomyLevel::Full, true, command).await; + assert_eq!(decision, GateDecision::Allow, "{command}"); + } +} + +#[cfg(feature = "security-module")] +#[tokio::test] +async fn an_unsandboxed_shell_keeps_the_protected_path_floor() { + let decision = floor_decision(AutonomyLevel::Full, false, "cd .. && ls").await; + assert!(!decision.is_allowed(), "{decision:?}"); + assert!( + format!("{decision:?}").contains("protected path"), + "{decision:?}" + ); +} + +#[cfg(feature = "security-module")] +#[tokio::test] +async fn a_sandboxed_shell_keeps_the_read_only_refusal() { + let decision = floor_decision(AutonomyLevel::ReadOnly, true, "rm -rf ../build").await; + assert!(!decision.is_allowed(), "{decision:?}"); + assert!( + format!("{decision:?}").contains("read-only"), + "{decision:?}" + ); +} diff --git a/crates/openhuman-core/src/agent/tinyagents/host/security_gate_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/security_gate_tests.rs index e487cd7ca6a..8288231e69e 100644 --- a/crates/openhuman-core/src/agent/tinyagents/host/security_gate_tests.rs +++ b/crates/openhuman-core/src/agent/tinyagents/host/security_gate_tests.rs @@ -709,3 +709,7 @@ async fn security_configured_off_keeps_local_only_for_the_shell_tool() { .is_some_and(|reason| reason.contains("Local-only privacy mode"))); assert_eq!(local, GateDecision::Allow); } + + +#[path = "security_gate_jailed_shell_tests.rs"] +mod jailed_shell; diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/failure_policy.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/failure_policy.rs index d1dd5031956..67e230893c3 100644 --- a/crates/openhuman-core/src/agent/tinyagents/middleware/failure_policy.rs +++ b/crates/openhuman-core/src/agent/tinyagents/middleware/failure_policy.rs @@ -228,6 +228,18 @@ pub(super) fn classified_recovery_policy( // attempt. Its own class, so a refusal does not share a budget with // the user's denial, and a second refusal on the same operation and // scope still stops. + // + // Every shell failure shares the scope `shell`, so with one retry any + // two refused commands in a row ended the run, however unrelated + // (Nov 2026, scheduled agents in the kernel sandbox). A different + // command is a fresh attempt, so a shell refusal gets a wider budget, + // reset by any command that runs; the same command refused again + // unchanged still stops the run (`repeated_failure`, + // `SAME_REFUSED_COMMAND_LIMIT`). Read-only mode refuses every acting + // command alike, so another command cannot help there: one retry. + Class::BlockedByPolicy if tool == "shell" && !is_read_only_refusal(error) => { + ("blocked_by_policy", SHELL_REFUSAL_BUDGET) + } Class::BlockedByPolicy => ("blocked_by_policy", 1), // The user said no, or never answered. Asking again only re-prompts. Class::Denied | Class::ApprovalExpired => ("policy", 0), @@ -294,3 +306,24 @@ pub(super) fn classified_recovery_policy( Class::Unknown => return None, }) } + +/// Refusals of different shell commands a run may collect with no command +/// running in between (a command that runs resets it). +pub(super) const SHELL_REFUSAL_BUDGET: usize = 8; + +/// The autonomy tier's read-only refusal (`security::policy::refusal_message`). +fn is_read_only_refusal(error: &str) -> bool { + error.to_ascii_lowercase().contains("read-only mode") +} + +/// The corrective after a refused shell command. The harness's own copy for +/// `blocked_by_policy` says another refusal ends the turn, which holds for the +/// other tools but not for a different shell command. +pub(super) fn shell_refusal_nudge(failure_line: &str) -> String { + format!( + "The `shell` command was blocked by policy and did not run ({failure_line}). Try a \ + different, narrower, permitted command (a scoped path, a bounded command, a read instead of a \ + write) or continue with other tools. Do not resend the same command: refused again, \ + it ends the turn." + ) +} diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs index aecf9aa09b8..dee7aa00b29 100644 --- a/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs +++ b/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs @@ -140,8 +140,17 @@ struct HostFailurePolicy { stop: StopLatch, tool_facts: Mutex>, last_exit_report: Mutex>, + /// Per run: how often each shell command (by fingerprint) was refused by + /// the security policy. See [`SAME_REFUSED_COMMAND_LIMIT`]. + refused_commands: Mutex>>, } +/// The refusal of one shell command that stops the run when the same command +/// is sent again unchanged. Refusals of different commands share the class's +/// own budget (`failure_policy`, `blocked_by_policy` for `shell`), which a +/// successful command resets. +const SAME_REFUSED_COMMAND_LIMIT: u32 = 2; + impl HostFailurePolicy { fn new( handle: SteeringHandle, @@ -151,6 +160,36 @@ impl HostFailurePolicy { stop: StopLatch::new(handle, halt_summary), tool_facts: Mutex::default(), last_exit_report: Mutex::default(), + refused_commands: Mutex::default(), + } + } + + /// The budget for a shell command the policy refused: the class budget, + /// or none once this exact command has been refused + /// [`SAME_REFUSED_COMMAND_LIMIT`] times in the run. + fn refused_command_budget(&self, instance: u64, call: &TaToolCall, budget: usize) -> usize { + let Some(command) = call.arguments.get("command").and_then(|c| c.as_str()) else { + return budget; + }; + let fingerprint = args_fingerprint(&serde_json::Value::String(command.trim().to_owned())); + let mut runs = self + .refused_commands + .lock() + .unwrap_or_else(|p| p.into_inner()); + let count = runs + .entry(instance) + .or_default() + .entry(fingerprint) + .or_default(); + *count += 1; + if *count >= SAME_REFUSED_COMMAND_LIMIT { + tracing::debug!( + refusals = *count, + "[tinyagents::failure] the same refused shell command was sent again; stopping" + ); + 0 + } else { + budget } } } @@ -302,7 +341,7 @@ impl FailureScopePolicy for HostFailurePolicy { fn assess( &self, - _ctx: &RunContext, + ctx: &RunContext, _invocation: &ToolInvocationIdentity, call: &TaToolCall, _scope: &FailureScope, @@ -383,11 +422,23 @@ impl FailureScopePolicy for HostFailurePolicy { if let Some((class, budget)) = recovery_policy_with_effect(&call.name, &content, body_failure, effect) { + let budget = if class == "blocked_by_policy" && call.name == "shell" { + self.refused_command_budget(ctx.instance_id(), call, budget) + } else { + budget + }; let nudge = if class == "missing_app" && call.name == "shell" { Some(missing_program_nudge( &call.name, &first_error_line(&failure_text), )) + } else if class == "blocked_by_policy" + && call.name == "shell" + && budget == super::failure_policy::SHELL_REFUSAL_BUDGET + { + Some(super::failure_policy::shell_refusal_nudge( + &first_error_line(&failure_text), + )) } else { None }; @@ -559,6 +610,10 @@ impl FailureScopePolicy for HostFailurePolicy { .lock() .unwrap_or_else(|p| p.into_inner()) .remove(&ctx.instance_id()); + self.refused_commands + .lock() + .unwrap_or_else(|p| p.into_inner()) + .remove(&ctx.instance_id()); } } diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_failure_policy_class_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_failure_policy_class_tests.rs index 54a051d72dc..eef83e271b7 100644 --- a/crates/openhuman-core/src/agent/tinyagents/middleware_failure_policy_class_tests.rs +++ b/crates/openhuman-core/src/agent/tinyagents/middleware_failure_policy_class_tests.rs @@ -58,17 +58,19 @@ fn breaker() -> ( #[test] fn a_policy_block_allows_one_alternative_but_a_user_denial_does_not() { - for (tool, error) in [ - ("shell", SHELL_BLOCK), - ("web_fetch", FETCH_BLOCK), - ("file_read", FILE_BLOCK), - ] { + for (tool, error) in [("web_fetch", FETCH_BLOCK), ("file_read", FILE_BLOCK)] { assert_eq!( recovery_policy(tool, error, false), Some(("blocked_by_policy", 1)), "{tool}" ); } + // A refused shell command gets a wider budget: a different command is a + // fresh attempt (see `refused_shell_commands_are_budgeted_per_command`). + assert_eq!( + recovery_policy("shell", SHELL_BLOCK, false), + Some(("blocked_by_policy", 8)) + ); // The user said no, or never answered: asking again only re-prompts them. assert_eq!( recovery_policy( @@ -132,11 +134,21 @@ async fn a_blocked_shell_command_lets_the_model_try_a_narrower_one() { assert!(slot.lock().unwrap().is_none()); } +/// Production (Nov 2026): a scheduled agent's second refused shell command of +/// a run, whatever the two commands were, ended the run with "a step this +/// needs is blocked by your security settings". Two different commands are +/// two different attempts, not a retry of one blocked step. #[tokio::test] -async fn a_second_consecutive_policy_block_stops_the_turn() { +async fn refused_shell_commands_are_budgeted_per_command() { let (mw, handle, slot) = breaker(); let mut context = ctx(); - for (id, command) in [("scan-1", "find / -name x"), ("scan-2", "ls -R /")] { + for (id, command) in [ + ("scan-1", "find / -name x"), + ("scan-2", "ls -R /"), + ("scan-3", "cat /etc/os-release"), + ("scan-4", "cd .. && ls"), + ("scan-5", "du -sh /"), + ] { run_call( &mw, &mut context, @@ -147,6 +159,90 @@ async fn a_second_consecutive_policy_block_stops_the_turn() { ) .await; } + assert_eq!(drain_pause_count(&handle), 0); + assert!(slot.lock().unwrap().is_none()); +} + +#[tokio::test] +async fn the_same_refused_shell_command_retried_still_stops_the_turn() { + let (mw, handle, slot) = breaker(); + let mut context = ctx(); + run_call( + &mw, + &mut context, + "scan-1", + "shell", + serde_json::json!({"command": "ls /blocked"}), + Err(SHELL_BLOCK), + ) + .await; + // A different command in between does not reset the first one's count. + run_call( + &mw, + &mut context, + "scan-2", + "shell", + serde_json::json!({"command": "find / -name x"}), + Err(SHELL_BLOCK), + ) + .await; + assert_eq!(drain_pause_count(&handle), 0); + run_call( + &mw, + &mut context, + "scan-3", + "shell", + serde_json::json!({"command": " find / -name x ", "timeout_secs": 30}), + Err(SHELL_BLOCK), + ) + .await; + assert_eq!( + drain_pause_count(&handle), + 1, + "the same command refused again stops" + ); + let summary = slot.lock().unwrap().clone().unwrap(); + assert!(summary.contains("blocked_by_policy"), "{summary}"); +} + +#[tokio::test] +async fn refused_shell_commands_with_nothing_running_still_stop_the_turn() { + let (mw, handle, slot) = breaker(); + let mut context = ctx(); + for attempt in 1..=9 { + assert_eq!(drain_pause_count(&handle), 0, "attempt {attempt}"); + run_call( + &mw, + &mut context, + &format!("scan-{attempt}"), + "shell", + serde_json::json!({"command": format!("ls /blocked-{attempt}")}), + Err(SHELL_BLOCK), + ) + .await; + } + assert_eq!(drain_pause_count(&handle), 1); + assert!(slot.lock().unwrap().is_some()); +} + +#[tokio::test] +async fn a_second_policy_block_on_another_tool_still_stops_the_turn() { + let (mw, handle, slot) = breaker(); + let mut context = ctx(); + for (id, url) in [ + ("f-1", "https://blocked.test/a"), + ("f-2", "https://blocked.test/a"), + ] { + run_call( + &mw, + &mut context, + id, + "web_fetch", + serde_json::json!({"url": url}), + Err(FETCH_BLOCK), + ) + .await; + } assert_eq!(drain_pause_count(&handle), 1); let summary = slot.lock().unwrap().clone().unwrap(); assert!(summary.contains("blocked_by_policy"), "{summary}"); diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_exec/drive.rs b/crates/openhuman-core/src/agent/tinyagents/turn_exec/drive.rs index 47cc5ada82a..7eb8e50adb0 100644 --- a/crates/openhuman-core/src/agent/tinyagents/turn_exec/drive.rs +++ b/crates/openhuman-core/src/agent/tinyagents/turn_exec/drive.rs @@ -58,7 +58,11 @@ pub(super) async fn drive_turn( .with_headless_descendant_settlement(run_context.headless_descendant_settlement) // Only a child the sub-agent runner granted scheduled actions // carries the mark (`subagent_host::ops::scheduled_actions_grant`). - .with_scheduled_actions(run_context.scheduled_actions); + .with_scheduled_actions(run_context.scheduled_actions) + .with_sandboxed_shell(matches!( + run_context.sandbox_mode, + Some(tinyagents_definition::SandboxMode::Sandboxed) + )); if let Some(policy) = tool_policy.as_ref() { gate = gate.with_tool_policy(Arc::new(policy.session.clone())); } diff --git a/crates/openhuman-core/src/cron/README.md b/crates/openhuman-core/src/cron/README.md index acd384df3e8..f7eccec02d7 100644 --- a/crates/openhuman-core/src/cron/README.md +++ b/crates/openhuman-core/src/cron/README.md @@ -230,7 +230,9 @@ Nothing else is lifted: the channel boundary, the autonomy tier (`[autonomy]`, including `workspace_only` when enabled), TinySecurity's command analysis and protected-path floor, the agent's `sandbox_mode`, the browser's allowed-websites list and its forced checkpoint before payment all still -apply. A job created from a channel conversation keeps running as that +apply. (An agent whose `sandbox_mode = "sandboxed"` runs its shell in the +kernel jail, where the lexical protected-path floor on command text is waived +and the jail's grants are the boundary; see `security/policy/README.md`.) A job created from a channel conversation keeps running as that channel's `ExternalChannel` turn, opted-in agent or not. The browser's `[browser] unattended_actions` list is reachable from every cron diff --git a/crates/openhuman-core/src/sandbox/README.md b/crates/openhuman-core/src/sandbox/README.md index f1f59fcfcb1..eff93848048 100644 --- a/crates/openhuman-core/src/sandbox/README.md +++ b/crates/openhuman-core/src/sandbox/README.md @@ -11,6 +11,16 @@ consumption denies execution. OpenHuman maps the module results to the existing `None`, `Local`, `Docker`, `OpenShell` or `Agent37` routing and status contracts; it does not duplicate the protected-path or credential-root policy. +`[runtime.local_jail]` grants (`extra_read_only`, `extra_read_write`, +`toolchain_homes`, `allow_proc`) are resolved by TinyBox +(`local_grants::with_resolved_grants`) and added to a native-jail policy before +it is planned: for the agent shell's sandboxed path +(`tools/impl/system/shell_run.rs::with_jail_grants`), for the MCP stdio +sandbox, and with security disabled. The plan still admits each grant: one on +TinySecurity's floor or overlapping the core's `workspace_dir` is refused, and +the core's credential files (secrets file, auth profiles, config) stay on the +jail's deny list. + `[security.sandbox] backend = "openshell"` routes a command to the tenant's own long-lived box on an NVIDIA OpenShell gateway ([`openshell/`](./openshell/mod.rs)), declared to TinySecurity as the `tinybox-openshell` container executor. Nothing diff --git a/crates/openhuman-core/src/security/policy/README.md b/crates/openhuman-core/src/security/policy/README.md index 53c93c33813..dab5334176d 100644 --- a/crates/openhuman-core/src/security/policy/README.md +++ b/crates/openhuman-core/src/security/policy/README.md @@ -20,6 +20,23 @@ TinySecurity's command check directly so read-only shell commands can remain available. Flow nodes use the same module gate before HTTP, code, and connector operations. A missing module answer refuses the operation. +A shell command that will run inside the kernel sandbox (the run's sandbox +mode is `Sandboxed`) is checked with `check_jailed_command` +([`jailed_commands.rs`](./jailed_commands.rs)). TinySecurity's protected-path +floor is lexical: any word naming `..`, `/etc`, `/proc`, a credential store and +so on refuses the command, so `cd ..` or `cat /etc/os-release` were refused +although the jail grants only the agent's own folders. For a jailed command +that one refusal is waived. Because the module answers the floor before the +rest of its admission, the host asks again with the path words neutralized and +the original class declared, so the tier's class gate, the hidden-execution +defence, approval and the hourly budget still apply, and a command whose path +words cannot be neutralized stays refused. The security gate +(`OpenHumanSecurityGate::with_sandboxed_shell`) and the shell tool's execution +check both use it; when the spawn plan resolves such a command to the host +after all (sandbox turned off), the shell refuses it with the floor's message +(`shell_run::unjailed_floor_refusal`). Commands outside the jail, scheduled +shell jobs and every other tool keep the floor. + ## Path authorization `native_paths.rs` translates OpenHuman's configuration and scoped trusted roots @@ -54,6 +71,7 @@ controls whether OpenHuman asks the module to apply the enabled tier policy. | --- | --- | | [`types.rs`](./types.rs) | Host configuration/context types, autonomy tier, stable gate/error types, and trusted roots | | [`native_commands.rs`](./native_commands.rs) | TinySecurity command gateway and adaptation to host approval outcomes | +| [`jailed_commands.rs`](./jailed_commands.rs) | The command check for a shell command that runs in the kernel sandbox: the protected-path floor waived, every other refusal kept | | [`local_only_commands.rs`](./local_only_commands.rs) | With security disabled: the host's conservative classifier that refuses shell commands which may reach the network under `[privacy] mode = "local_only"` | | [`native_paths.rs`](./native_paths.rs) | Host path context translated to TinySecurity's path-policy contract | | [`module_gate.rs`](./module_gate.rs) | Batched path checks and cached module answers for sync-only host traits | diff --git a/crates/openhuman-core/src/security/policy/jailed_commands.rs b/crates/openhuman-core/src/security/policy/jailed_commands.rs new file mode 100644 index 00000000000..ffa42580ef6 --- /dev/null +++ b/crates/openhuman-core/src/security/policy/jailed_commands.rs @@ -0,0 +1,130 @@ +//! Shell commands that will run inside the kernel sandbox. +//! +//! TinySecurity's protected-path floor is lexical: it refuses a command when +//! any word of its text names a parent folder (`..`), a critical root (`/etc`, +//! `/proc`, ...) or a credential store, whatever the command does with it. +//! `cd ..`, `sed 's/../X/'` and `cat /etc/os-release` are all refused. For a +//! command that runs on the host that floor is the only thing between the +//! model and those paths. A command that runs inside the jail (Landlock / +//! bubblewrap through TinyBox, or a container) can reach only what its plan +//! grants, and the plan keeps the floor, the credential deny list and the +//! core's own state out of every grant (`sandbox::spawn_plan`). There the +//! words in the command text add nothing, so the floor is waived. +//! +//! Only that one refusal is waived. The module answers the floor before the +//! rest of its admission (the tier's class gate, the hidden-execution +//! defence, the hourly budget), so a floor refusal says nothing about those. +//! [`SecurityPolicy::check_jailed_command`] asks again with the path words +//! replaced by a neutral word and the original class declared, so every other +//! refusal still applies and the class can only go up. A command whose +//! protected words cannot be neutralized stays refused. +//! +//! The waiver holds only while the command really runs in the jail: a caller +//! that ends up on the host after all must refuse it ([`JailedVerdict`]). + +use super::native_commands::{CommandFlow, CommandQuery, CommandVerdict, Refusal}; +use super::types::SecurityPolicy; + +/// The answer for a command that will run inside the kernel sandbox. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct JailedVerdict { + pub verdict: CommandVerdict, + /// TinySecurity refused the command only for naming a protected path, and + /// this answer was taken without that floor. The caller must run the + /// command inside the jail, or refuse it with [`Refusal::Protected`]. + pub floor_waived: bool, +} + +impl JailedVerdict { + /// An answer that waived nothing. + pub fn checked(verdict: CommandVerdict) -> Self { + Self { + verdict, + floor_waived: false, + } + } +} + +impl SecurityPolicy { + /// [`Self::check_command`] for a command that will run inside the kernel + /// sandbox: the protected-path floor is waived, every other refusal stays. + /// Only the harness flow is considered; scheduled and legacy execution keep + /// the floor. + pub async fn check_jailed_command( + &self, + query: CommandQuery<'_>, + ) -> Result { + match self.check_command(query).await { + Err(Refusal::Protected) if query.flow == CommandFlow::Harness => {} + other => return other.map(JailedVerdict::checked), + } + let Some(class) = self.protected_command_class(&query).await else { + return Err(Refusal::Protected); + }; + let neutral = neutral_command_text(query.command); + if neutral == query.command { + return Err(Refusal::Protected); + } + let declared = Some(query.declared.map_or(class, |declared| declared.max(class))); + let verdict = self + .check_command(CommandQuery { + command: &neutral, + declared, + ..query + }) + .await?; + log::debug!( + "[security][command] protected-path floor waived for a jailed command \ + class={class:?} stage={:?} gate={:?}", + query.stage, + verdict.gate + ); + Ok(JailedVerdict { + verdict, + floor_waived: true, + }) + } +} + +/// `command` with every path-like word replaced by `x`, for asking the module +/// about everything but the protected-path floor. A path-like word is a run of +/// word characters holding `.`, `/` or `~`. Quotes, `$`, backticks, +/// parentheses, redirections and separators are kept as they are, so the +/// module still sees any hidden execution. The result is only ever classified, +/// never run. +pub(crate) fn neutral_command_text(command: &str) -> String { + fn word_char(c: char) -> bool { + c.is_alphanumeric() + || matches!( + c, + '.' | '/' | '~' | '-' | '_' | '+' | '@' | '%' | ':' | ',' | '=' + ) + } + fn flush(word: &mut String, out: &mut String) { + if word.contains(['.', '/', '~']) { + out.push('x'); + } else { + out.push_str(word); + } + word.clear(); + } + let mut out = String::with_capacity(command.len()); + let mut word = String::new(); + for c in command.chars() { + if word_char(c) { + word.push(c); + } else { + flush(&mut word, &mut out); + out.push(c); + } + } + flush(&mut word, &mut out); + out +} + +#[cfg(test)] +pub(crate) mod test_support; + +#[cfg(test)] +#[path = "jailed_commands_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/security/policy/jailed_commands/test_support.rs b/crates/openhuman-core/src/security/policy/jailed_commands/test_support.rs new file mode 100644 index 00000000000..b5835ade283 --- /dev/null +++ b/crates/openhuman-core/src/security/policy/jailed_commands/test_support.rs @@ -0,0 +1,86 @@ +//! A scripted TinySecurity command gateway with a lexical protected-path +//! floor, for tests of what callers do with a floor refusal. + +use std::sync::Mutex; + +use async_trait::async_trait; + +use crate::security::policy::{ + AutonomyLevel, CommandClass, CommandGateway, CommandQuery, CommandStage, CommandVerdict, + GateDecision, Refusal, SecurityPolicy, +}; + +/// Answers like the module, in miniature: the floor first (`..`, `/etc`, +/// `.ssh`), then the hidden-execution defence and the tier's class gate. +/// `rm` is destructive, `touch` a write, anything else a read. +#[derive(Debug, Default)] +pub(crate) struct FloorGateway { + pub queries: Mutex, CommandStage)>>, +} + +impl FloorGateway { + fn protected(command: &str) -> bool { + command.contains("..") || command.contains("/etc") || command.contains(".ssh") + } + + fn class(query: &CommandQuery<'_>) -> CommandClass { + let own = match query.command.split_whitespace().next() { + Some("rm") => CommandClass::Destructive, + Some("touch") => CommandClass::Write, + _ => CommandClass::Read, + }; + query.declared.map_or(own, |declared| declared.max(own)) + } +} + +impl crate::security::policy::Sealed for FloorGateway {} + +#[async_trait] +impl CommandGateway for FloorGateway { + async fn decide( + &self, + policy: &SecurityPolicy, + query: &CommandQuery<'_>, + ) -> Result { + self.queries + .lock() + .unwrap() + .push((query.command.to_owned(), query.declared, query.stage)); + if Self::protected(query.command) { + return Err(Refusal::Protected); + } + if policy.autonomy != AutonomyLevel::Full && query.command.contains("$(") { + return Err(Refusal::Hidden); + } + let class = Self::class(query); + let gate = match (policy.autonomy, class) { + (_, CommandClass::Read) => GateDecision::Allow, + (AutonomyLevel::ReadOnly, _) => return Err(Refusal::ReadOnly), + (AutonomyLevel::Supervised, _) => GateDecision::Prompt, + (AutonomyLevel::Full, CommandClass::Write) => GateDecision::Allow, + (AutonomyLevel::Full, _) => GateDecision::Prompt, + }; + Ok(CommandVerdict { class, gate }) + } + + async fn protected_class( + &self, + _policy: &SecurityPolicy, + query: &CommandQuery<'_>, + ) -> Option { + Self::protected(query.command).then(|| Self::class(query)) + } +} + +/// A policy at `autonomy` that asks [`FloorGateway`]. +pub(crate) fn floor_policy( + autonomy: AutonomyLevel, +) -> (SecurityPolicy, std::sync::Arc) { + let gateway = std::sync::Arc::new(FloorGateway::default()); + let mut policy = SecurityPolicy { + autonomy, + ..SecurityPolicy::default() + }; + policy.command_gateway = Some(gateway.clone()); + (policy, gateway) +} diff --git a/crates/openhuman-core/src/security/policy/jailed_commands_tests.rs b/crates/openhuman-core/src/security/policy/jailed_commands_tests.rs new file mode 100644 index 00000000000..03496d2958a --- /dev/null +++ b/crates/openhuman-core/src/security/policy/jailed_commands_tests.rs @@ -0,0 +1,153 @@ +use super::*; +use crate::security::policy::{ + floor_policy, AutonomyLevel, CommandClass, CommandStage, GateDecision, +}; + +fn harness(command: &str) -> CommandQuery<'_> { + CommandQuery { + command, + declared: None, + flow: CommandFlow::Harness, + stage: CommandStage::Authorize, + } +} + +#[test] +fn neutral_text_replaces_path_words_and_keeps_shell_syntax() { + assert_eq!(neutral_command_text("cd .. && ls"), "cd x && ls"); + assert_eq!(neutral_command_text("sed 's/../X/' f"), "sed 'x' f"); + assert_eq!(neutral_command_text("cat /etc/os-release"), "cat x"); + assert_eq!(neutral_command_text("cat $HOME/.ssh/id"), "cat $x"); + assert_eq!( + neutral_command_text("cat $(echo ../x) `ls ../y` 2>&1"), + "cat $(echo x) `ls x` 2>&1" + ); + assert_eq!(neutral_command_text("ls -la | wc -l"), "ls -la | wc -l"); +} + +// Every test below asks a scripted gateway; without the module security is +// disabled (`crate::security::switch`) and nothing is asked at all. + +#[cfg(feature = "security-module")] +#[tokio::test] +async fn a_jailed_command_naming_a_protected_path_is_not_refused_for_it() { + for command in [ + "cd .. && ls", + "sed 's/../X/' notes.txt", + "cat /etc/os-release", + ] { + let (policy, _) = floor_policy(AutonomyLevel::Full); + let answer = policy + .check_jailed_command(harness(command)) + .await + .unwrap_or_else(|refusal| panic!("{command}: {refusal}")); + assert!(answer.floor_waived, "{command}"); + assert_eq!(answer.verdict.gate, GateDecision::Allow, "{command}"); + } +} + +#[cfg(feature = "security-module")] +#[tokio::test] +async fn the_floor_still_refuses_a_command_that_is_not_jailed() { + let (policy, _) = floor_policy(AutonomyLevel::Full); + assert_eq!( + policy.check_command(harness("cd .. && ls")).await, + Err(Refusal::Protected) + ); +} + +#[cfg(feature = "security-module")] +#[tokio::test] +async fn a_jailed_command_keeps_every_other_refusal() { + // The tier's class gate: read-only mode refuses a destructive command. + let (policy, _) = floor_policy(AutonomyLevel::ReadOnly); + assert_eq!( + policy + .check_jailed_command(harness("rm -rf ../build")) + .await, + Err(Refusal::ReadOnly) + ); + // The hidden-execution defence. + let (policy, _) = floor_policy(AutonomyLevel::Supervised); + assert_eq!( + policy + .check_jailed_command(harness("cat $(echo ../secret)")) + .await, + Err(Refusal::Hidden) + ); +} + +#[cfg(feature = "security-module")] +#[tokio::test] +async fn a_jailed_command_keeps_its_class_and_its_approval() { + let (policy, gateway) = floor_policy(AutonomyLevel::Supervised); + let answer = policy + .check_jailed_command(CommandQuery { + stage: CommandStage::Execute, + ..harness("rm -rf ../build") + }) + .await + .expect("a jailed destructive command is asked about, not refused"); + assert_eq!(answer.verdict.class, CommandClass::Destructive); + assert_eq!(answer.verdict.gate, GateDecision::Prompt); + // The second question carries the original class and the caller's stage, + // so the module's budget is spent once, at execution. + let queries = gateway.queries.lock().unwrap(); + assert_eq!( + queries.last().unwrap(), + &( + "rm -rf x".to_owned(), + Some(CommandClass::Destructive), + CommandStage::Execute + ) + ); +} + +#[cfg(feature = "security-module")] +#[tokio::test] +async fn a_floor_refusal_without_a_known_class_stays_refused() { + // No path word to neutralize: the floor cannot be asked around. + let (policy, _) = floor_policy(AutonomyLevel::Full); + assert_eq!( + policy + .check_jailed_command(harness("ls ..")) + .await + .map(|a| a.floor_waived), + Ok(true) + ); + // A gateway that cannot name the class (the default) keeps the refusal. + #[derive(Debug)] + struct Classless; + impl crate::security::policy::Sealed for Classless {} + #[async_trait::async_trait] + impl crate::security::policy::CommandGateway for Classless { + async fn decide( + &self, + _policy: &SecurityPolicy, + _query: &CommandQuery<'_>, + ) -> Result { + Err(Refusal::Protected) + } + } + let mut policy = SecurityPolicy::default(); + policy.command_gateway = Some(std::sync::Arc::new(Classless)); + assert_eq!( + policy.check_jailed_command(harness("cd ..")).await, + Err(Refusal::Protected) + ); +} + +#[cfg(feature = "security-module")] +#[tokio::test] +async fn scheduled_commands_keep_the_floor() { + let (policy, _) = floor_policy(AutonomyLevel::Full); + assert_eq!( + policy + .check_jailed_command(CommandQuery { + flow: CommandFlow::Scheduled, + ..harness("cd .. && ls") + }) + .await, + Err(Refusal::Protected) + ); +} diff --git a/crates/openhuman-core/src/security/policy/mod.rs b/crates/openhuman-core/src/security/policy/mod.rs index f2967870a1b..ad18d0529b1 100644 --- a/crates/openhuman-core/src/security/policy/mod.rs +++ b/crates/openhuman-core/src/security/policy/mod.rs @@ -1,6 +1,7 @@ //! Host context and adapters for TinySecurity policy operations. mod enforcement; +mod jailed_commands; mod local_only_commands; mod module_gate; mod native_commands; @@ -10,6 +11,9 @@ mod path_checks; mod types; mod workspace_scope; +#[cfg(test)] +pub(crate) use jailed_commands::test_support::floor_policy; +pub use jailed_commands::JailedVerdict; pub use module_gate::{host_action_class, PathKind}; #[cfg(test)] pub(crate) use native_commands::Sealed; diff --git a/crates/openhuman-core/src/security/policy/native_commands.rs b/crates/openhuman-core/src/security/policy/native_commands.rs index 7e7d380ed5d..6a67773f6ef 100644 --- a/crates/openhuman-core/src/security/policy/native_commands.rs +++ b/crates/openhuman-core/src/security/policy/native_commands.rs @@ -88,6 +88,17 @@ pub trait CommandGateway: sealed::Sealed + std::fmt::Debug + Send + Sync { policy: &SecurityPolicy, query: &CommandQuery<'_>, ) -> Result; + + /// The class of a command refused only by the protected-path floor, or + /// `None` when it was not refused for that reason or the class is unknown + /// (see [`SecurityPolicy::check_jailed_command`]). `None` keeps the refusal. + async fn protected_class( + &self, + _policy: &SecurityPolicy, + _query: &CommandQuery<'_>, + ) -> Option { + None + } } /// A shared gateway handle, as stored on the policy. @@ -406,6 +417,52 @@ impl SecurityPolicy { } } +impl SecurityPolicy { + /// The class TinySecurity gave `query.command` when its only refusal was + /// the protected-path floor. The floor answers before the rest of the + /// module's admission, so its class is all a refusal carries. `None` when + /// the module refused for another reason, allowed it, or cannot answer. + pub(super) async fn protected_command_class( + &self, + query: &CommandQuery<'_>, + ) -> Option { + if crate::security::switch::disabled().is_some() { + return None; + } + if let Some(gateway) = &self.command_gateway { + return gateway.protected_class(self, query).await; + } + self.native_protected_class(query).await + } + + #[cfg(feature = "security-module")] + async fn native_protected_class(&self, query: &CommandQuery<'_>) -> Option { + use crate::modules::security::command::{command_decision, CommandOp}; + + // Classification never spends the budget, so the authorize-stage + // policy (already registered with the module) serves either stage. + let policy = self + .native_command_policy(query.flow, CommandStage::Authorize) + .ok()?; + let decision = command_decision( + &self.workspace_dir, + policy, + query.command, + query.declared.map(to_bus_class), + CommandOp::Classify, + ) + .await + .ok()?; + (decision.denial == Some(tinysecurity_bus::CommandDenial::Protected)) + .then(|| from_bus_class(decision.class)) + } + + #[cfg(not(feature = "security-module"))] + async fn native_protected_class(&self, _query: &CommandQuery<'_>) -> Option { + None + } +} + #[cfg(feature = "security-module")] fn absolute(path: &std::path::Path) -> Result { if path.is_absolute() { diff --git a/crates/openhuman-core/src/tools/impl/system/shell.rs b/crates/openhuman-core/src/tools/impl/system/shell.rs index 63ff25c2dd2..596d11a1411 100644 --- a/crates/openhuman-core/src/tools/impl/system/shell.rs +++ b/crates/openhuman-core/src/tools/impl/system/shell.rs @@ -305,26 +305,17 @@ impl ShellTool { // TinySecurity owns command classification and admission. Re-check at // execution time so a command approved earlier cannot bypass a policy // reload or a newly exhausted budget. - let verdict = match self - .security - .check_command(crate::security::policy::CommandQuery { - command, - declared: None, - flow: crate::security::policy::CommandFlow::Harness, - stage: crate::security::policy::CommandStage::Execute, - }) - .await - { - Ok(verdict) if verdict.gate != crate::security::policy::GateDecision::Block => verdict, - Ok(_) => { - return ( - false, - ToolResult::error("[policy-blocked] Security policy blocked this command."), - ); - } - Err(reason) => return (false, ToolResult::error(reason.to_string())), + // A run whose sandbox mode is `Sandboxed` always takes the sandbox + // path below (`should_plan_command`), so its command is jailed unless + // the plan resolves it to the host; `run_in_policy` refuses that case. + let jailed = matches!( + crate::agent::tinyagents::host::run_context::sandbox_mode_for_tool(context), + Some(tinyagents_definition::SandboxMode::Sandboxed) + ); + let floor_waived = match self.check_for_execution(command, jailed).await { + Ok(answer) => answer.floor_waived, + Err(refusal) => return (false, refusal), }; - let _ = verdict; let _cwd = self.effective_action_dir_for_context(context); @@ -344,7 +335,16 @@ impl ShellTool { Ok(policy) => { let (timeout, dir) = (requested_timeout, &action_dir); run_in_policy( - ctx, policy, command, timeout, come_back, dir, context, meter, audit, + ctx, + policy, + command, + timeout, + come_back, + dir, + context, + meter, + audit, + floor_waived, ) .await } @@ -385,9 +385,18 @@ impl ShellTool { context, meter, audit, + floor_waived, ) .await; } + // Unreachable while a `Sandboxed` run always plans; should that change, + // a command admitted for the jail must not run on the host. + if floor_waived { + return ( + false, + ToolResult::error(crate::security::policy::Refusal::Protected.to_string()), + ); + } // Clear the environment to prevent leaking API keys and other secrets // (CWE-200), then re-add only safe, functional variables. @@ -576,6 +585,7 @@ impl ShellTool { context: Option<&dyn ToolRunContext>, meter: Option, audit: &AuditOnce, + floor_waived: bool, ) -> (bool, ToolResult) { let config = match ctx.load_config().await { Ok(config) => config, @@ -601,12 +611,60 @@ impl ShellTool { if policy.filesystem_only { tracing::debug!("[shell] the agent opted into a files-only sandbox"); } + // The operator's `[runtime.local_jail]` grants; the plan still admits + // each one (`shell_run::with_jail_grants`). + let policy = super::shell_run::with_jail_grants(&config, policy).await; let timeout = requested_timeout; run_in_policy( - ctx, policy, command, timeout, come_back, action_dir, context, meter, audit, + ctx, + policy, + command, + timeout, + come_back, + action_dir, + context, + meter, + audit, + floor_waived, ) .await } + + /// The execution-stage admission. TinySecurity owns classification and + /// admission; this re-check at execution means a command approved earlier + /// cannot bypass a policy reload or a newly exhausted budget. A `jailed` + /// command does not answer to the lexical protected-path floor + /// (`SecurityPolicy::check_jailed_command`); the caller must then keep it + /// in the jail. + async fn check_for_execution( + &self, + command: &str, + jailed: bool, + ) -> Result { + let query = crate::security::policy::CommandQuery { + command, + declared: None, + flow: crate::security::policy::CommandFlow::Harness, + stage: crate::security::policy::CommandStage::Execute, + }; + let checked = if jailed { + self.security.check_jailed_command(query).await + } else { + self.security + .check_command(query) + .await + .map(crate::security::policy::JailedVerdict::checked) + }; + match checked { + Ok(answer) if answer.verdict.gate != crate::security::policy::GateDecision::Block => { + Ok(answer) + } + Ok(_) => Err(ToolResult::error( + "[policy-blocked] Security policy blocked this command.", + )), + Err(reason) => Err(ToolResult::error(reason.to_string())), + } + } } /// Emit a single `CommandExecution` audit event. A write failure is logged as diff --git a/crates/openhuman-core/src/tools/impl/system/shell_run.rs b/crates/openhuman-core/src/tools/impl/system/shell_run.rs index 67786894fd1..65676dc0bef 100644 --- a/crates/openhuman-core/src/tools/impl/system/shell_run.rs +++ b/crates/openhuman-core/src/tools/impl/system/shell_run.rs @@ -175,6 +175,7 @@ pub(super) async fn run_in_policy( context: Option<&dyn ToolRunContext>, meter: Option, audit: &AuditOnce, + floor_waived: bool, ) -> (bool, ToolResult) { tracing::debug!( backend = ?policy.backend, @@ -230,6 +231,9 @@ pub(super) async fn run_in_policy( return (true, result); } }; + if let Some(refusal) = unjailed_floor_refusal(floor_waived, resolved.backend()) { + return (false, refusal); + } let (slot, yield_after, effective) = come_back(request, context, command, effective, resolved.can_yield()); @@ -268,6 +272,56 @@ pub(super) async fn run_in_policy( (true, result) } +/// The refusal for a command admitted only because it would run in the jail +/// (TinySecurity's protected-path floor waived, see +/// `SecurityPolicy::check_jailed_command`) that resolved to the host instead: +/// the operator turned the sandbox off, or the plan chose no sandbox. There the +/// floor is the only boundary, so the command is refused as it always was. +pub(super) fn unjailed_floor_refusal( + floor_waived: bool, + backend: crate::sandbox::SandboxBackendKind, +) -> Option { + if !floor_waived || backend != crate::sandbox::SandboxBackendKind::None { + return None; + } + tracing::debug!("[shell] a jailed command resolved to the host; protected-path floor applies"); + Some(ToolResult::error( + crate::security::policy::Refusal::Protected.to_string(), + )) +} + +/// `policy` with the operator's `[runtime.local_jail]` grants added: the extra +/// read-write and read-only folders, the toolchain homes and `/proc` when +/// allowed. Only the native jail reads them; a container or a box keeps its +/// own. Nothing is decided here: TinyBox drops a grant on TinySecurity's floor +/// while resolving them, and the spawn plan then admits each remaining one, +/// refusing any that overlaps the core's workspace or sits on the floor, and +/// keeps the core's credential files on the jail's deny list +/// (`sandbox::spawn_plan`). Grants that cannot be resolved leave the policy as +/// it was. +pub(super) async fn with_jail_grants( + config: &crate::config::Config, + policy: crate::sandbox::SandboxPolicy, +) -> crate::sandbox::SandboxPolicy { + if policy.backend != crate::sandbox::SandboxBackendKind::Local { + return policy; + } + match crate::sandbox::local_grants::with_resolved_grants(config, &policy).await { + Ok(granted) => { + tracing::debug!( + read_only = granted.read_only_mounts.len(), + read_write = granted.read_write_mounts.len(), + "[shell] local jail grants applied" + ); + granted + } + Err(error) => { + tracing::warn!(%error, "[shell] local jail grants unavailable; the jail keeps its workspace only"); + policy + } + } +} + /// The call's audit entry, to be written once by whoever learns the outcome. pub(super) fn audit_once( audit: Arc, diff --git a/crates/openhuman-core/src/tools/impl/system/shell_run_tests.rs b/crates/openhuman-core/src/tools/impl/system/shell_run_tests.rs index d6da4764aff..a75c3b6ee4f 100644 --- a/crates/openhuman-core/src/tools/impl/system/shell_run_tests.rs +++ b/crates/openhuman-core/src/tools/impl/system/shell_run_tests.rs @@ -144,6 +144,7 @@ async fn a_sandboxed_command_yields_and_is_followed_to_its_end() { Some(&call), None, &audit, + false, ) .await; assert!(allowed); @@ -186,6 +187,7 @@ async fn without_a_turn_a_sandboxed_command_runs_to_its_end() { None, None, &Mutex::new(None), + false, ) .await; assert_eq!( @@ -194,3 +196,76 @@ async fn without_a_turn_a_sandboxed_command_runs_to_its_end() { "nothing to follow it with" ); } + +/// A command admitted only because it would run in the jail (the protected-path +/// floor waived) is refused when the plan resolves it to the host instead +/// (`run_in_policy` applies this right after resolving the backend). +#[test] +fn only_a_host_run_of_a_waived_command_is_refused() { + use crate::sandbox::SandboxBackendKind as Backend; + assert!(unjailed_floor_refusal(true, Backend::None).is_some()); + for backend in [ + Backend::Local, + Backend::Docker, + Backend::OpenShell, + Backend::Agent37, + ] { + assert!( + unjailed_floor_refusal(true, backend).is_none(), + "{backend:?}" + ); + } + assert!(unjailed_floor_refusal(false, Backend::None).is_none()); +} + +/// Production (Nov 2026): `[runtime.local_jail] extra_read_write` and +/// `extra_read_only` reached the jail only with security off, so an operator +/// could not give a sandboxed agent's shell a code checkout or a scratch dir. +#[cfg(feature = "modules")] +#[tokio::test] +async fn configured_local_jail_grants_reach_a_jailed_shell() { + let tmp = tempfile::tempdir().unwrap(); + let _port = crate::modules::security::gap::install_path_floor_port( + crate::modules::security::gap::ScriptedPathFloorPort::new( + [std::path::PathBuf::from("/etc")], + vec![], + ), + ); + let code = tmp.path().join("code"); + let scratch = tmp.path().join("scratch"); + std::fs::create_dir_all(&code).unwrap(); + std::fs::create_dir_all(&scratch).unwrap(); + let mut config = crate::config::Config::default(); + config.workspace_dir = tmp.path().join("core"); + config.runtime.local_jail.toolchain_homes = false; + config.runtime.local_jail.extra_read_only = + vec![code.to_string_lossy().into_owned(), "/etc".into()]; + config.runtime.local_jail.extra_read_write = vec![scratch.to_string_lossy().into_owned()]; + + let mut jailed = unsandboxed_policy(); + jailed.backend = crate::sandbox::SandboxBackendKind::Local; + let granted = with_jail_grants(&config, jailed).await; + let real = |path: &std::path::Path| path.canonicalize().unwrap(); + assert!( + granted.read_only_mounts.contains(&real(&code)), + "{:?}", + granted.read_only_mounts + ); + assert!( + granted.read_write_mounts.contains(&real(&scratch)), + "{:?}", + granted.read_write_mounts + ); + // A grant on the protected floor is dropped before it reaches the plan. + assert!(!granted + .read_only_mounts + .iter() + .any(|path| path.starts_with("/etc"))); + + // A container keeps its own mounts. + let mut container = unsandboxed_policy(); + container.backend = crate::sandbox::SandboxBackendKind::Docker; + let kept = with_jail_grants(&config, container.clone()).await; + assert_eq!(kept.read_only_mounts, container.read_only_mounts); + assert_eq!(kept.read_write_mounts, container.read_write_mounts); +} diff --git a/crates/openhuman-core/src/tools/impl/system/shell_tests_runtime_and_sandbox_tests.rs b/crates/openhuman-core/src/tools/impl/system/shell_tests_runtime_and_sandbox_tests.rs index 5fab961374a..8ad2de3c43b 100644 --- a/crates/openhuman-core/src/tools/impl/system/shell_tests_runtime_and_sandbox_tests.rs +++ b/crates/openhuman-core/src/tools/impl/system/shell_tests_runtime_and_sandbox_tests.rs @@ -45,3 +45,73 @@ async fn shell_uses_host_node_and_python_from_path() { ); } } + +// -- the protected-path floor at execution ----------------------------------- + +#[cfg(feature = "security-module")] +fn floor_shell(autonomy: AutonomyLevel) -> ShellTool { + let (mut policy, _) = crate::security::policy::floor_policy(autonomy); + policy.workspace_dir = test_workdir(); + policy.action_dir = test_workdir(); + ShellTool::new(Arc::new(policy), test_runtime(), test_audit()) +} + +/// A sandboxed run's command is admitted at execution even though its text +/// names a protected path; the jail is the boundary. +#[cfg(feature = "security-module")] +#[tokio::test] +async fn a_jailed_command_is_admitted_without_the_protected_path_floor() { + let tool = floor_shell(AutonomyLevel::Full); + for command in [ + "cd .. && ls", + "sed 's/../X/' notes.txt", + "cat /etc/os-release", + ] { + let answer = tool + .check_for_execution(command, true) + .await + .unwrap_or_else(|refusal| panic!("{command}: {}", refusal.output())); + assert!(answer.floor_waived, "{command}"); + } +} + +#[cfg(feature = "security-module")] +#[tokio::test] +async fn a_command_outside_the_jail_keeps_the_protected_path_floor() { + let tool = floor_shell(AutonomyLevel::Full); + let refusal = tool + .check_for_execution("cd .. && ls", false) + .await + .expect_err("the floor refuses a host command"); + assert!( + refusal.output().contains("protected path"), + "{}", + refusal.output() + ); + // And the whole tool, called with no run (no sandbox mode), refuses it too. + let result = tool + .execute(json!({"command": "cd .. && ls"})) + .await + .unwrap(); + assert!(result.is_error); + assert!( + result.output().contains("protected path"), + "{}", + result.output() + ); +} + +#[cfg(feature = "security-module")] +#[tokio::test] +async fn a_jailed_command_keeps_the_read_only_refusal_at_execution() { + let tool = floor_shell(AutonomyLevel::ReadOnly); + let refusal = tool + .check_for_execution("rm -rf ../build", true) + .await + .expect_err("read-only mode refuses a destructive command"); + assert!( + refusal.output().contains("read-only"), + "{}", + refusal.output() + ); +} diff --git a/docs/gitbooks/en/features/approval-gate.md b/docs/gitbooks/en/features/approval-gate.md index 69325c6d4e4..08b8f3098ee 100644 --- a/docs/gitbooks/en/features/approval-gate.md +++ b/docs/gitbooks/en/features/approval-gate.md @@ -152,7 +152,7 @@ A triage dispatch that your own machine started keeps the authority its caller a The browser's consequential actions (click, fill, type, key press, select, check, and a task's `needs_approval` step) are the exception. They use the **forced** gate, which ignores auto-approval and denies every turn that is not a routable WebChat chat, cron included. An operator opts specific action kinds back in for cron, background and approval-free workflow turns with `[browser] unattended_actions`. See [TinyComputer browser on Linux and Docker](../developing/tinycomputer-docker.md#4-unattended-actions). -A scheduled job has nobody to ask, so its turns are read-only. An agent definition can opt its cron jobs into acting with `scheduled_actions = true`, and only when it also names its tools explicitly (`[tools] named = [...]`). Such a job runs as `TrustedAutomation { CronActions }`: its own run may use shell and acting tools without a prompt, while sub-agents it spawns stay read-only. It is also trusted automation for the wallet: it may execute prepared transfers within the `[wallet_policy]` caps (when `automation_enabled` is set) and pay x402 within the per-request budget. A plain cron job can only read (including balances); it can neither execute a transfer nor pay x402. A job created from a channel conversation keeps running as that channel's `ExternalChannel` turn, so `wallet_execute_prepared` transfers and x402 payments are refused for it, opted-in agent or not. The autonomy tier, TinySecurity's command analysis and protected-path floor, the agent's sandbox, the browser's allowed websites and its checkpoint before payment still apply, and SaaS mode ignores the setting. See `crates/openhuman-core/src/cron/README.md`, "Scheduled actions". +A scheduled job has nobody to ask, so its turns are read-only. An agent definition can opt its cron jobs into acting with `scheduled_actions = true`, and only when it also names its tools explicitly (`[tools] named = [...]`). Such a job runs as `TrustedAutomation { CronActions }`: its own run may use shell and acting tools without a prompt, while sub-agents it spawns stay read-only. It is also trusted automation for the wallet: it may execute prepared transfers within the `[wallet_policy]` caps (when `automation_enabled` is set) and pay x402 within the per-request budget. A plain cron job can only read (including balances); it can neither execute a transfer nor pay x402. A job created from a channel conversation keeps running as that channel's `ExternalChannel` turn, so `wallet_execute_prepared` transfers and x402 payments are refused for it, opted-in agent or not. The autonomy tier, TinySecurity's command analysis and protected-path floor (waived for a shell command that runs inside the agent's kernel sandbox, where the jail is the boundary), the agent's sandbox, the browser's allowed websites and its checkpoint before payment still apply, and SaaS mode ignores the setting. See `crates/openhuman-core/src/cron/README.md`, "Scheduled actions". An external channel turn parks because remote input is untrusted. The row is written, and you can still decide on the thread card before the timeout.