From 0e1836b02dfa1ff07773643c7c1e96c568f98b36 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Mon, 23 Nov 2026 20:23:03 +0000 Subject: [PATCH 01/20] test(agent): cover per-command shell failure budgets Refused shell commands are now budgeted per command rather than per run, so tests assert that distinct commands keep the turn alive while a repeated command or a second block on another tool still halts it. A new scope test also checks that shell failure scopes fingerprint the command without persisting its text. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../middleware_classified_failure_tests.rs | 16 +++++ .../middleware_failure_policy_class_tests.rs | 65 +++++++++++++++++-- 2 files changed, 74 insertions(+), 7 deletions(-) diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_classified_failure_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_classified_failure_tests.rs index 45dcf42b3d1..cd9f95d1579 100644 --- a/crates/openhuman-core/src/agent/tinyagents/middleware_classified_failure_tests.rs +++ b/crates/openhuman-core/src/agent/tinyagents/middleware_classified_failure_tests.rs @@ -463,6 +463,22 @@ fn failure_scope_keeps_resource_and_permission_context_but_ignores_query() { ); } +#[test] +fn a_shell_failure_scope_names_the_command_but_not_its_text() { + let scope = |command: &str| { + super::super::repeated_failure::failure_scope( + "shell", + &serde_json::json!({"command": command, "timeout_secs": 30}), + ) + }; + assert_eq!(scope("cat /etc/os-release"), scope(" cat /etc/os-release\n")); + assert_ne!(scope("cat /etc/os-release"), scope("cd .. && ls")); + assert!(scope("cat /etc/os-release").starts_with("shell:command=")); + // A fingerprint, never the command itself: the scope is persisted with a + // halt cause and a command can carry a token. + assert!(!scope("cat /etc/os-release").contains("os-release")); +} + #[tokio::test] async fn legitimate_wait_polling_does_not_consume_transient_budget() { let handle = SteeringHandle::allow_all(); 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..e0ba32b77ac 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 is budgeted per command (see + // `refused_shell_commands_are_budgeted_per_command`), with a few retries. + assert_eq!( + recovery_policy("shell", SHELL_BLOCK, false), + Some(("blocked_by_policy", 3)) + ); // 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,45 @@ 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(); + for attempt in 1..=4 { + run_call( + &mw, + &mut context, + &format!("scan-{attempt}"), + "shell", + serde_json::json!({"command": "find / -name x"}), + Err(SHELL_BLOCK), + ) + .await; + } + assert_eq!(drain_pause_count(&handle), 1); + let summary = slot.lock().unwrap().clone().unwrap(); + assert!(summary.contains("blocked_by_policy"), "{summary}"); +} + +#[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}"); From 63fa57ed48fb2b2add58242782219e02b2ba3298 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Mon, 23 Nov 2026 20:24:14 +0000 Subject: [PATCH 02/20] feat(security): expose protected-path command class from policy Add a `protected_class` hook to `CommandGateway` and a `protected_command_class` helper on `SecurityPolicy` that reports the command class when the only refusal came from the protected-path floor. This lets callers distinguish floor-only refusals from other denials without changing existing refusal behaviour. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../openhuman-core/src/security/policy/mod.rs | 3 + .../src/security/policy/native_commands.rs | 57 +++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/crates/openhuman-core/src/security/policy/mod.rs b/crates/openhuman-core/src/security/policy/mod.rs index f2967870a1b..ec90e97d03b 100644 --- a/crates/openhuman-core/src/security/policy/mod.rs +++ b/crates/openhuman-core/src/security/policy/mod.rs @@ -13,9 +13,12 @@ mod workspace_scope; pub use module_gate::{host_action_class, PathKind}; #[cfg(test)] pub(crate) use native_commands::Sealed; +pub use jailed_commands::JailedVerdict; pub use native_commands::{ CommandFlow, CommandGateway, CommandQuery, CommandStage, CommandVerdict, Refusal, }; +#[cfg(test)] +pub(crate) use jailed_commands::test_support::FloorGateway; pub use enforcement::validate_path_within_root; pub use enforcement::{ensure_openhuman_scratch_dir, openhuman_scratch_dir}; 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() { From 8fb2f5870a1deba4d9f8dfbf07d611f23a28542a Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Mon, 23 Nov 2026 20:24:45 +0000 Subject: [PATCH 03/20] feat(security): add jailed command policy module Introduce a jailed_commands module under the security policy with test support exposing a floor policy and gateway, and wire it into the policy module so tests can exercise command jailing behaviour. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/security/policy/jailed_commands.rs | 130 ++++++++++++++++++ .../policy/jailed_commands/test_support.rs | 86 ++++++++++++ .../openhuman-core/src/security/policy/mod.rs | 3 +- 3 files changed, 218 insertions(+), 1 deletion(-) create mode 100644 crates/openhuman-core/src/security/policy/jailed_commands.rs create mode 100644 crates/openhuman-core/src/security/policy/jailed_commands/test_support.rs 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/mod.rs b/crates/openhuman-core/src/security/policy/mod.rs index ec90e97d03b..b6cd21d017f 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; @@ -18,7 +19,7 @@ pub use native_commands::{ CommandFlow, CommandGateway, CommandQuery, CommandStage, CommandVerdict, Refusal, }; #[cfg(test)] -pub(crate) use jailed_commands::test_support::FloorGateway; +pub(crate) use jailed_commands::test_support::{floor_policy, FloorGateway}; pub use enforcement::validate_path_within_root; pub use enforcement::{ensure_openhuman_scratch_dir, openhuman_scratch_dir}; From 14ac2f3554f94daf9ea7190dab9b782ae101dcaf Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Mon, 23 Nov 2026 20:25:10 +0000 Subject: [PATCH 04/20] test(security): add tests for jailed command policy Adds unit tests covering the jailed command policy so its allow and deny behaviour is verified. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../security/policy/jailed_commands_tests.rs | 144 ++++++++++++++++++ 1 file changed, 144 insertions(+) create mode 100644 crates/openhuman-core/src/security/policy/jailed_commands_tests.rs 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..70218249cc8 --- /dev/null +++ b/crates/openhuman-core/src/security/policy/jailed_commands_tests.rs @@ -0,0 +1,144 @@ +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) + ); +} From e7138eeb6b1d343cbe45a35f1d6439c1e1c5f768 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Mon, 23 Nov 2026 20:25:30 +0000 Subject: [PATCH 05/20] feat(security): waive protected-path floor for sandboxed shell runs The security gate now knows whether a run's shell is jailed and, when it is, authorizes commands through check_jailed_command so only the lexical protected-path floor is waived while every other refusal still applies. The shell re-checks at execution and refuses if the command would land on the host. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/agent/tinyagents/host/bundle.rs | 6 +++- .../agent/tinyagents/host/security_gate.rs | 14 ++++++++++ .../host/security_gate/authorize.rs | 28 +++++++++++++------ .../src/agent/tinyagents/turn_exec/drive.rs | 6 +++- 4 files changed, 43 insertions(+), 11 deletions(-) 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/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())); } From 636c4f355dfbccca6621f84438489ce02997581e Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Mon, 23 Nov 2026 20:25:42 +0000 Subject: [PATCH 06/20] test(security): cover protected-path floor for sandboxed shells Add tests asserting that a shell running in the kernel jail is allowed to name protected paths such as `..` or `/etc/os-release`, while an unsandboxed shell still hits the protected-path floor and a read-only autonomy level still refuses writes. This pins the behaviour that motivated the fix. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tinyagents/host/security_gate_tests.rs | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) 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..e28768a7785 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,50 @@ 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); } + +// -- a jailed shell and TinySecurity's protected-path floor ------------------- + +#[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:?}"); +} From 9137d5e226b0c75df2be54eb03225b90c48831c3 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Mon, 23 Nov 2026 20:26:08 +0000 Subject: [PATCH 07/20] fix(shell): refuse waived-floor commands that resolve to the host A command admitted only because it would run in the jail now gets refused when it resolves to the host backend, since the protected-path floor is the only boundary left there. Added a helper for the check and tests covering the refusal and the backends it does not apply to. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/tools/impl/system/shell_run.rs | 22 ++++++++++ .../src/tools/impl/system/shell_run_tests.rs | 40 +++++++++++++++++++ 2 files changed, 62 insertions(+) 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..4b7f270ee48 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,24 @@ 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(), + )) +} + /// 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..68e80e15022 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,41 @@ 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 it resolves to the host instead. +#[tokio::test] +async fn a_jailed_command_that_resolves_to_the_host_keeps_the_floor() { + let _storage = crate::storage::test_support::install_backend_for_test( + crate::storage::test_support::memory_backend(), + ); + let (allowed, result) = run_in_policy( + &crate::core::runtime::DispatchCtx::unbound(), + unsandboxed_policy(), + "cd .. && ls", + None, + YieldRequest { + allowed: false, + requested: None, + }, + &jail_workdir(), + None, + None, + &Mutex::new(None), + true, + ) + .await; + assert!(!allowed); + assert!(result.is_error); + assert!(result.output().contains("protected path"), "{}", result.output()); +} + +#[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()); +} From 4846a4ffe25ce1001ed48006e017c784f1557ac0 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Mon, 23 Nov 2026 20:26:31 +0000 Subject: [PATCH 08/20] fix(shell): keep jailed commands off the host and apply local jail grants Execution-stage admission now distinguishes jailed commands from host ones, so a command admitted for the sandbox no longer answers to the lexical protected-path floor and is refused outright if it would fall through to the host. The sandbox path also resolves the operator's `[runtime.local_jail]` grants before planning, falling back to the workspace-only jail if they are unavailable. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/tools/impl/system/shell.rs | 110 ++++++++++++++---- 1 file changed, 89 insertions(+), 21 deletions(-) diff --git a/crates/openhuman-core/src/tools/impl/system/shell.rs b/crates/openhuman-core/src/tools/impl/system/shell.rs index 63ff25c2dd2..ba4c8700c8f 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,70 @@ impl ShellTool { if policy.filesystem_only { tracing::debug!("[shell] the agent opted into a files-only sandbox"); } + // The operator's `[runtime.local_jail]` grants (extra read-write and + // read-only folders, toolchain homes, /proc). The plan still admits + // each one: a grant on the protected floor, the credential deny list + // or the core's own workspace is refused there, not here. + let policy = match crate::sandbox::local_grants::with_resolved_grants(&config, &policy) + .await + { + Ok(granted) => granted, + Err(error) => { + tracing::warn!(%error, "[shell] local jail grants unavailable; the jail keeps its workspace only"); + policy + } + }; 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 From a910b579c2293bfb1f4132afcb2827d2104c079e Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Mon, 23 Nov 2026 20:26:47 +0000 Subject: [PATCH 09/20] fix(shell): resolve local jail grants only for the local sandbox backend The shell tool now resolves local jail grants only when the sandbox backend is the native local jail, leaving container and box policies untouched. This avoids applying local-only grant resolution to backends that manage their own boundaries, with tests covering the protected-path floor at execution. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/tools/impl/system/shell.rs | 17 ++++--- .../shell_tests_runtime_and_sandbox_tests.rs | 51 +++++++++++++++++++ 2 files changed, 61 insertions(+), 7 deletions(-) diff --git a/crates/openhuman-core/src/tools/impl/system/shell.rs b/crates/openhuman-core/src/tools/impl/system/shell.rs index ba4c8700c8f..2fef18ade55 100644 --- a/crates/openhuman-core/src/tools/impl/system/shell.rs +++ b/crates/openhuman-core/src/tools/impl/system/shell.rs @@ -615,14 +615,17 @@ impl ShellTool { // read-only folders, toolchain homes, /proc). The plan still admits // each one: a grant on the protected floor, the credential deny list // or the core's own workspace is refused there, not here. - let policy = match crate::sandbox::local_grants::with_resolved_grants(&config, &policy) - .await - { - Ok(granted) => granted, - Err(error) => { - tracing::warn!(%error, "[shell] local jail grants unavailable; the jail keeps its workspace only"); - policy + // Only the native jail reads them; a container or a box keeps its own. + let policy = if policy.backend == crate::sandbox::SandboxBackendKind::Local { + match crate::sandbox::local_grants::with_resolved_grants(&config, &policy).await { + Ok(granted) => granted, + Err(error) => { + tracing::warn!(%error, "[shell] local jail grants unavailable; the jail keeps its workspace only"); + policy + } } + } else { + policy }; let timeout = requested_timeout; run_in_policy( 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..fe4dd8070ed 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,54 @@ 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()); +} From 09207965f8ae84dd7d437e2d7260fdbeedcc366e Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Mon, 23 Nov 2026 20:27:21 +0000 Subject: [PATCH 10/20] refactor(shell): extract local jail grant resolution into shell_run Moved the `[runtime.local_jail]` grant resolution out of the shell tool into a `with_jail_grants` helper in `shell_run`, so the logic sits with the rest of the spawn-plan handling and can be tested directly. Added a test covering extra read-only and read-write grants reaching a jailed shell and floor grants being dropped. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/tools/impl/system/shell.rs | 19 ++----- .../src/tools/impl/system/shell_run.rs | 32 ++++++++++++ .../src/tools/impl/system/shell_run_tests.rs | 52 +++++++++++++++++++ 3 files changed, 87 insertions(+), 16 deletions(-) diff --git a/crates/openhuman-core/src/tools/impl/system/shell.rs b/crates/openhuman-core/src/tools/impl/system/shell.rs index 2fef18ade55..596d11a1411 100644 --- a/crates/openhuman-core/src/tools/impl/system/shell.rs +++ b/crates/openhuman-core/src/tools/impl/system/shell.rs @@ -611,22 +611,9 @@ impl ShellTool { if policy.filesystem_only { tracing::debug!("[shell] the agent opted into a files-only sandbox"); } - // The operator's `[runtime.local_jail]` grants (extra read-write and - // read-only folders, toolchain homes, /proc). The plan still admits - // each one: a grant on the protected floor, the credential deny list - // or the core's own workspace is refused there, not here. - // Only the native jail reads them; a container or a box keeps its own. - let policy = if policy.backend == crate::sandbox::SandboxBackendKind::Local { - match crate::sandbox::local_grants::with_resolved_grants(&config, &policy).await { - Ok(granted) => granted, - Err(error) => { - tracing::warn!(%error, "[shell] local jail grants unavailable; the jail keeps its workspace only"); - policy - } - } - } else { - policy - }; + // 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, 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 4b7f270ee48..65676dc0bef 100644 --- a/crates/openhuman-core/src/tools/impl/system/shell_run.rs +++ b/crates/openhuman-core/src/tools/impl/system/shell_run.rs @@ -290,6 +290,38 @@ pub(super) fn unjailed_floor_refusal( )) } +/// `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 68e80e15022..4f84504b598 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 @@ -234,3 +234,55 @@ fn only_a_host_run_of_a_waived_command_is_refused() { } 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); +} From b9619a374d9fb022064d3851596d6fad15bfea48 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Mon, 23 Nov 2026 20:28:06 +0000 Subject: [PATCH 11/20] docs(security): document jailed shell command checks and local jail grants The security policy README now explains how shell commands running inside the kernel sandbox are checked with the protected-path floor waived while every other refusal is kept, and the sandbox and cron READMEs describe how local jail grants are resolved and admitted. The approval-gate page was corrected to match. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/cron/README.md | 4 +++- crates/openhuman-core/src/sandbox/README.md | 10 ++++++++++ .../src/security/policy/README.md | 18 ++++++++++++++++++ docs/gitbooks/en/features/approval-gate.md | 2 +- 4 files changed, 32 insertions(+), 2 deletions(-) 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/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. From 6b50ed2c4f39cf7282e2efb251cbda9001a10124 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Mon, 23 Nov 2026 20:43:23 +0000 Subject: [PATCH 12/20] chore(security): drop unused test re-export of FloorGateway Removed the unused `FloorGateway` re-export from the policy module's test-only imports, leaving only `floor_policy`. This trims a stale import that no longer has any consumers. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/security/policy/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/openhuman-core/src/security/policy/mod.rs b/crates/openhuman-core/src/security/policy/mod.rs index b6cd21d017f..9a6bd21e3c1 100644 --- a/crates/openhuman-core/src/security/policy/mod.rs +++ b/crates/openhuman-core/src/security/policy/mod.rs @@ -19,7 +19,7 @@ pub use native_commands::{ CommandFlow, CommandGateway, CommandQuery, CommandStage, CommandVerdict, Refusal, }; #[cfg(test)] -pub(crate) use jailed_commands::test_support::{floor_policy, FloorGateway}; +pub(crate) use jailed_commands::test_support::floor_policy; pub use enforcement::validate_path_within_root; pub use enforcement::{ensure_openhuman_scratch_dir, openhuman_scratch_dir}; From b5189356a84e3a6c859b99cd3222deb162676c71 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Mon, 23 Nov 2026 20:49:42 +0000 Subject: [PATCH 13/20] fix(agent): scope shell failures per command and allow retries Shell failures now use a fingerprint of the command as their failure scope, so a refusal of one command no longer shares a budget with an unrelated one. Blocked shell commands also get a few retries before the turn stops, since previously any two refused commands in a run ended it. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../agent/tinyagents/middleware/failure_policy.rs | 6 ++++++ .../agent/tinyagents/middleware/repeated_failure.rs | 13 +++++++++++++ 2 files changed, 19 insertions(+) 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..161106912b5 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,12 @@ 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. + // + // A shell failure is scoped by its command (`failure_scope`), so a + // different command is a fresh attempt, not a retry; the same refused + // command gets a few retries before the turn stops. Before that, any + // two refused commands in a run ended it (Nov 2026, scheduled agents). + Class::BlockedByPolicy if tool == "shell" => ("blocked_by_policy", 3), Class::BlockedByPolicy => ("blocked_by_policy", 1), // The user said no, or never answered. Asking again only re-prompts. Class::Denied | Class::ApprovalExpired => ("policy", 0), 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..ec53dae2a44 100644 --- a/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs +++ b/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs @@ -208,8 +208,21 @@ fn args_fingerprint(arguments: &serde_json::Value) -> String { /// tool it reaches, and by that inner call's resource fields: every /// `use_skill` failure used to share one budget, so a timeout in one skill's /// sub-tool and a refusal in another's halted the turn together. +/// +/// A `shell` call is scoped by a fingerprint of its command (never the text, +/// which can carry a token): two different commands are two operations. Every +/// shell failure used to share the scope `shell`, so a policy refusal of one +/// command and of an unrelated one ended the run together. pub(super) fn failure_scope(tool: &str, arguments: &serde_json::Value) -> String { let mut scope = tool.to_owned(); + if tool == "shell" { + if let Some(command) = arguments.get("command").and_then(|c| c.as_str()) { + scope.push_str(":command="); + scope.push_str(&args_fingerprint(&serde_json::Value::String( + command.trim().to_owned(), + ))); + } + } let mut resource_args = arguments; if let Some(target) = dispatch_target(tool, arguments) { if let Some(skill) = target.skill { From 1e91edcaa3b32bf9fe54105f3b65ecaee7ac7749 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Mon, 23 Nov 2026 20:57:03 +0000 Subject: [PATCH 14/20] fix(tinyagents): widen shell refusal budget and stop on repeated command Shell policy refusals now share a wider class budget that a successful command resets, so unrelated refused commands no longer end the run together. The same command refused unchanged three times still stops the turn, tracked per run by command fingerprint. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tinyagents/middleware/failure_policy.rs | 13 ++-- .../tinyagents/middleware/repeated_failure.rs | 61 +++++++++++++++---- .../middleware_classified_failure_tests.rs | 16 ----- .../middleware_failure_policy_class_tests.rs | 31 ++++++++-- 4 files changed, 82 insertions(+), 39 deletions(-) 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 161106912b5..6f683ae59b4 100644 --- a/crates/openhuman-core/src/agent/tinyagents/middleware/failure_policy.rs +++ b/crates/openhuman-core/src/agent/tinyagents/middleware/failure_policy.rs @@ -229,11 +229,14 @@ pub(super) fn classified_recovery_policy( // the user's denial, and a second refusal on the same operation and // scope still stops. // - // A shell failure is scoped by its command (`failure_scope`), so a - // different command is a fresh attempt, not a retry; the same refused - // command gets a few retries before the turn stops. Before that, any - // two refused commands in a run ended it (Nov 2026, scheduled agents). - Class::BlockedByPolicy if tool == "shell" => ("blocked_by_policy", 3), + // 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`). + Class::BlockedByPolicy if tool == "shell" => ("blocked_by_policy", 8), Class::BlockedByPolicy => ("blocked_by_policy", 1), // The user said no, or never answered. Asking again only re-prompts. Class::Denied | Class::ApprovalExpired => ("policy", 0), 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 ec53dae2a44..5ce19d42693 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 = 3; + 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 } } } @@ -208,21 +247,8 @@ fn args_fingerprint(arguments: &serde_json::Value) -> String { /// tool it reaches, and by that inner call's resource fields: every /// `use_skill` failure used to share one budget, so a timeout in one skill's /// sub-tool and a refusal in another's halted the turn together. -/// -/// A `shell` call is scoped by a fingerprint of its command (never the text, -/// which can carry a token): two different commands are two operations. Every -/// shell failure used to share the scope `shell`, so a policy refusal of one -/// command and of an unrelated one ended the run together. pub(super) fn failure_scope(tool: &str, arguments: &serde_json::Value) -> String { let mut scope = tool.to_owned(); - if tool == "shell" { - if let Some(command) = arguments.get("command").and_then(|c| c.as_str()) { - scope.push_str(":command="); - scope.push_str(&args_fingerprint(&serde_json::Value::String( - command.trim().to_owned(), - ))); - } - } let mut resource_args = arguments; if let Some(target) = dispatch_target(tool, arguments) { if let Some(skill) = target.skill { @@ -396,6 +422,11 @@ 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, @@ -572,6 +603,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_classified_failure_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_classified_failure_tests.rs index cd9f95d1579..45dcf42b3d1 100644 --- a/crates/openhuman-core/src/agent/tinyagents/middleware_classified_failure_tests.rs +++ b/crates/openhuman-core/src/agent/tinyagents/middleware_classified_failure_tests.rs @@ -463,22 +463,6 @@ fn failure_scope_keeps_resource_and_permission_context_but_ignores_query() { ); } -#[test] -fn a_shell_failure_scope_names_the_command_but_not_its_text() { - let scope = |command: &str| { - super::super::repeated_failure::failure_scope( - "shell", - &serde_json::json!({"command": command, "timeout_secs": 30}), - ) - }; - assert_eq!(scope("cat /etc/os-release"), scope(" cat /etc/os-release\n")); - assert_ne!(scope("cat /etc/os-release"), scope("cd .. && ls")); - assert!(scope("cat /etc/os-release").starts_with("shell:command=")); - // A fingerprint, never the command itself: the scope is persisted with a - // halt cause and a command can carry a token. - assert!(!scope("cat /etc/os-release").contains("os-release")); -} - #[tokio::test] async fn legitimate_wait_polling_does_not_consume_transient_budget() { let handle = SteeringHandle::allow_all(); 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 e0ba32b77ac..174a21d6d85 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 @@ -65,11 +65,11 @@ fn a_policy_block_allows_one_alternative_but_a_user_denial_does_not() { "{tool}" ); } - // A refused shell command is budgeted per command (see - // `refused_shell_commands_are_budgeted_per_command`), with a few retries. + // 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", 3)) + Some(("blocked_by_policy", 8)) ); // The user said no, or never answered: asking again only re-prompts them. assert_eq!( @@ -167,7 +167,8 @@ async fn refused_shell_commands_are_budgeted_per_command() { async fn the_same_refused_shell_command_retried_still_stops_the_turn() { let (mw, handle, slot) = breaker(); let mut context = ctx(); - for attempt in 1..=4 { + for attempt in 1..=3 { + assert_eq!(drain_pause_count(&handle), 0, "attempt {attempt}"); run_call( &mw, &mut context, @@ -178,11 +179,31 @@ async fn the_same_refused_shell_command_retried_still_stops_the_turn() { ) .await; } - assert_eq!(drain_pause_count(&handle), 1); + assert_eq!(drain_pause_count(&handle), 1, "the third identical refusal 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(); From 5ae5c96494a987d3d1814023ff1d42e011281c3a Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Mon, 23 Nov 2026 20:57:10 +0000 Subject: [PATCH 15/20] refactor(agent): use run context in host failure policy assess The assess implementation now takes the run context instead of ignoring it, so the refused command budget can be computed from the instance id. This removes the unused parameter and lets the policy apply per-instance budget logic. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/agent/tinyagents/middleware/repeated_failure.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 5ce19d42693..d2b80c9161f 100644 --- a/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs +++ b/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs @@ -341,7 +341,7 @@ impl FailureScopePolicy for HostFailurePolicy { fn assess( &self, - _ctx: &RunContext, + ctx: &RunContext, _invocation: &ToolInvocationIdentity, call: &TaToolCall, _scope: &FailureScope, @@ -423,7 +423,7 @@ impl FailureScopePolicy for HostFailurePolicy { 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) + self.refused_command_budget(ctx.instance_id(), call, budget) } else { budget }; From c582f8d412d9f8487bd1b006ef4f7462f4cdbaa5 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Mon, 23 Nov 2026 21:04:02 +0000 Subject: [PATCH 16/20] fix(agent): tighten shell refusal retry budget and nudge Read-only refusals now get a single retry instead of the wider shell budget, since every acting command is refused alike in that mode. The same refused command now stops the turn on its second refusal, and a dedicated nudge tells the model to try a different permitted command rather than resending the same one. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tinyagents/middleware/failure_policy.rs | 28 +++++++++++- .../tinyagents/middleware/repeated_failure.rs | 9 +++- .../middleware_failure_policy_class_tests.rs | 43 +++++++++++++------ 3 files changed, 64 insertions(+), 16 deletions(-) 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 6f683ae59b4..1d718b4dfaf 100644 --- a/crates/openhuman-core/src/agent/tinyagents/middleware/failure_policy.rs +++ b/crates/openhuman-core/src/agent/tinyagents/middleware/failure_policy.rs @@ -235,8 +235,11 @@ pub(super) fn classified_recovery_policy( // 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`). - Class::BlockedByPolicy if tool == "shell" => ("blocked_by_policy", 8), + // `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), @@ -303,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, 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 d2b80c9161f..dee7aa00b29 100644 --- a/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs +++ b/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs @@ -149,7 +149,7 @@ struct HostFailurePolicy { /// 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 = 3; +const SAME_REFUSED_COMMAND_LIMIT: u32 = 2; impl HostFailurePolicy { fn new( @@ -432,6 +432,13 @@ impl FailureScopePolicy for HostFailurePolicy { &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 }; 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 174a21d6d85..603aca462c5 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 @@ -167,19 +167,36 @@ async fn refused_shell_commands_are_budgeted_per_command() { async fn the_same_refused_shell_command_retried_still_stops_the_turn() { let (mw, handle, slot) = breaker(); let mut context = ctx(); - for attempt in 1..=3 { - assert_eq!(drain_pause_count(&handle), 0, "attempt {attempt}"); - run_call( - &mw, - &mut context, - &format!("scan-{attempt}"), - "shell", - serde_json::json!({"command": "find / -name x"}), - Err(SHELL_BLOCK), - ) - .await; - } - assert_eq!(drain_pause_count(&handle), 1, "the third identical refusal stops"); + 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}"); } From c749a964cee11a37373f10c7e27489385d463191 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Mon, 23 Nov 2026 21:04:10 +0000 Subject: [PATCH 17/20] fix(agent): clarify shell refusal nudge wording Reworded the shell refusal nudge to tell the model to try a different, narrower, permitted command, making the guidance clearer when a command is blocked by policy. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/agent/tinyagents/middleware/failure_policy.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 1d718b4dfaf..67e230893c3 100644 --- a/crates/openhuman-core/src/agent/tinyagents/middleware/failure_policy.rs +++ b/crates/openhuman-core/src/agent/tinyagents/middleware/failure_policy.rs @@ -322,7 +322,7 @@ fn is_read_only_refusal(error: &str) -> bool { 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, permitted command (a scoped path, a bounded command, a read instead of 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." ) From 4fbf95c8decbe4815792513ca5890414dbb6f28c Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Mon, 23 Nov 2026 21:13:47 +0000 Subject: [PATCH 18/20] test(shell): add failure output to jail assertion Include the command output in the assertion message so a failing jail check shows what the command actually returned, making the failure easier to diagnose. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/tools/impl/system/shell_run_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 4f84504b598..f84049924b1 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 @@ -220,7 +220,7 @@ async fn a_jailed_command_that_resolves_to_the_host_keeps_the_floor() { true, ) .await; - assert!(!allowed); + assert!(!allowed, "{}", result.output()); assert!(result.is_error); assert!(result.output().contains("protected path"), "{}", result.output()); } From 32d1278aa883347f981a4e11df222993d7e1bdbc Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Mon, 23 Nov 2026 21:17:11 +0000 Subject: [PATCH 19/20] chore(security): reformat policy tests and reorder re-exports Reformatted several security policy test files to satisfy rustfmt line-length rules and reordered the re-exports in the policy module so the jailed-commands items sit together. No behaviour changed. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tinyagents/host/security_gate_tests.rs | 11 ++++- .../middleware_failure_policy_class_tests.rs | 11 ++++- .../security/policy/jailed_commands_tests.rs | 15 +++++-- .../openhuman-core/src/security/policy/mod.rs | 6 +-- .../src/tools/impl/system/shell_run_tests.rs | 41 ++++++------------- .../shell_tests_runtime_and_sandbox_tests.rs | 29 ++++++++++--- 6 files changed, 69 insertions(+), 44 deletions(-) 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 e28768a7785..b50622f031d 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 @@ -732,7 +732,11 @@ async fn floor_decision( #[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"] { + 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}"); } @@ -754,5 +758,8 @@ async fn an_unsandboxed_shell_keeps_the_protected_path_floor() { 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:?}"); + assert!( + format!("{decision:?}").contains("read-only"), + "{decision:?}" + ); } 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 603aca462c5..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 @@ -196,7 +196,11 @@ async fn the_same_refused_shell_command_retried_still_stops_the_turn() { Err(SHELL_BLOCK), ) .await; - assert_eq!(drain_pause_count(&handle), 1, "the same command refused again stops"); + 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}"); } @@ -225,7 +229,10 @@ async fn refused_shell_commands_with_nothing_running_still_stop_the_turn() { 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")] { + for (id, url) in [ + ("f-1", "https://blocked.test/a"), + ("f-2", "https://blocked.test/a"), + ] { run_call( &mw, &mut context, diff --git a/crates/openhuman-core/src/security/policy/jailed_commands_tests.rs b/crates/openhuman-core/src/security/policy/jailed_commands_tests.rs index 70218249cc8..03496d2958a 100644 --- a/crates/openhuman-core/src/security/policy/jailed_commands_tests.rs +++ b/crates/openhuman-core/src/security/policy/jailed_commands_tests.rs @@ -31,7 +31,11 @@ fn neutral_text_replaces_path_words_and_keeps_shell_syntax() { #[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"] { + 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)) @@ -58,7 +62,9 @@ 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, + policy + .check_jailed_command(harness("rm -rf ../build")) + .await, Err(Refusal::ReadOnly) ); // The hidden-execution defence. @@ -103,7 +109,10 @@ 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), + 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. diff --git a/crates/openhuman-core/src/security/policy/mod.rs b/crates/openhuman-core/src/security/policy/mod.rs index 9a6bd21e3c1..ad18d0529b1 100644 --- a/crates/openhuman-core/src/security/policy/mod.rs +++ b/crates/openhuman-core/src/security/policy/mod.rs @@ -11,15 +11,15 @@ 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; -pub use jailed_commands::JailedVerdict; pub use native_commands::{ CommandFlow, CommandGateway, CommandQuery, CommandStage, CommandVerdict, Refusal, }; -#[cfg(test)] -pub(crate) use jailed_commands::test_support::floor_policy; pub use enforcement::validate_path_within_root; pub use enforcement::{ensure_openhuman_scratch_dir, openhuman_scratch_dir}; 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 f84049924b1..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 @@ -198,39 +198,22 @@ async fn without_a_turn_a_sandboxed_command_runs_to_its_end() { } /// A command admitted only because it would run in the jail (the protected-path -/// floor waived) is refused when it resolves to the host instead. -#[tokio::test] -async fn a_jailed_command_that_resolves_to_the_host_keeps_the_floor() { - let _storage = crate::storage::test_support::install_backend_for_test( - crate::storage::test_support::memory_backend(), - ); - let (allowed, result) = run_in_policy( - &crate::core::runtime::DispatchCtx::unbound(), - unsandboxed_policy(), - "cd .. && ls", - None, - YieldRequest { - allowed: false, - requested: None, - }, - &jail_workdir(), - None, - None, - &Mutex::new(None), - true, - ) - .await; - assert!(!allowed, "{}", result.output()); - assert!(result.is_error); - assert!(result.output().contains("protected path"), "{}", result.output()); -} - +/// 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:?}"); + 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()); } 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 fe4dd8070ed..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 @@ -62,7 +62,11 @@ fn floor_shell(autonomy: AutonomyLevel) -> ShellTool { #[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"] { + for command in [ + "cd .. && ls", + "sed 's/../X/' notes.txt", + "cat /etc/os-release", + ] { let answer = tool .check_for_execution(command, true) .await @@ -79,11 +83,22 @@ async fn a_command_outside_the_jail_keeps_the_protected_path_floor() { .check_for_execution("cd .. && ls", false) .await .expect_err("the floor refuses a host command"); - assert!(refusal.output().contains("protected path"), "{}", refusal.output()); + 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(); + let result = tool + .execute(json!({"command": "cd .. && ls"})) + .await + .unwrap(); assert!(result.is_error); - assert!(result.output().contains("protected path"), "{}", result.output()); + assert!( + result.output().contains("protected path"), + "{}", + result.output() + ); } #[cfg(feature = "security-module")] @@ -94,5 +109,9 @@ async fn a_jailed_command_keeps_the_read_only_refusal_at_execution() { .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()); + assert!( + refusal.output().contains("read-only"), + "{}", + refusal.output() + ); } From 434f80f4dc83f6168d64a816c9abdca4e8c3d35d Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Mon, 23 Nov 2026 21:17:26 +0000 Subject: [PATCH 20/20] test(security-gate): move jailed shell tests into their own module The protected-path floor tests for jailed shells were extracted from the main security gate test file into a dedicated module, keeping the growing test suite organised without changing what the tests cover. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../host/security_gate_jailed_shell_tests.rs | 55 +++++++++++++++++++ .../tinyagents/host/security_gate_tests.rs | 54 +----------------- 2 files changed, 57 insertions(+), 52 deletions(-) create mode 100644 crates/openhuman-core/src/agent/tinyagents/host/security_gate_jailed_shell_tests.rs 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 b50622f031d..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 @@ -710,56 +710,6 @@ async fn security_configured_off_keeps_local_only_for_the_shell_tool() { assert_eq!(local, GateDecision::Allow); } -// -- a jailed shell and TinySecurity's protected-path floor ------------------- -#[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:?}" - ); -} +#[path = "security_gate_jailed_shell_tests.rs"] +mod jailed_shell;