diff --git a/AGENTS.md b/AGENTS.md index 0714ea17beb..45c0184ae2b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -271,10 +271,14 @@ With the policy **disabled** (the default): The floor is TinySecurity's. With **security disabled** (`security/switch.rs`: a build without `security-module`, or `[security] mode -= "off"`) no TinySecurity check runs: paths resolve on the host with no floor -(the `..` and null-byte preflight stays), and tool calls are not classified. -`[privacy] mode = "local_only"` and approvals a channel or flow demands still -apply. += "off"`) there is no path policy at all: paths resolve on the host with no +floor, so file tools reach `~/.ssh` like any other path. Refusing `..` and null +bytes stays, as input validation of a malformed argument, not as policy. Tool +calls are not classified. `[privacy] mode = "local_only"` is its own network +setting and stays enforced: egress descriptors are refused, and shell commands +that may reach the network are refused by the host's conservative classifier +(`security/policy/local_only_commands.rs`). Approvals a channel or flow demands +still apply. With `[autonomy] enabled = true`: diff --git a/crates/openhuman-core/src/agent/harness/artifact_offload/policy_tests.rs b/crates/openhuman-core/src/agent/harness/artifact_offload/policy_tests.rs index 73495527c11..18a3a7ea9e8 100644 --- a/crates/openhuman-core/src/agent/harness/artifact_offload/policy_tests.rs +++ b/crates/openhuman-core/src/agent/harness/artifact_offload/policy_tests.rs @@ -25,3 +25,29 @@ fn redactor_reports_a_rewritten_body_as_changed() { assert_eq!(out.text, with_secret); } } + +/// With security disabled nothing is reserved: even a credential store under a +/// home directory may be materialized into. +async fn assert_materialization_is_unchecked() { + let dir = tempfile::tempdir().unwrap(); + let policy = SecurityPolicy { + workspace_dir: dir.path().join("workspace"), + action_dir: dir.path().join("action"), + ..SecurityPolicy::default() + }; + assert!(materialization_allowed(&policy, &dir.path().join("home/.ssh/id_rsa")).await); + assert!(materialization_allowed(&policy, &dir.path().join("workspace/memory.db")).await); +} + +#[cfg(not(feature = "security-module"))] +#[tokio::test] +async fn a_build_without_the_module_materializes_anywhere() { + assert_materialization_is_unchecked().await; +} + +#[cfg(feature = "security-module")] +#[tokio::test] +async fn security_configured_off_materializes_anywhere() { + let _off = crate::security::switch::off_for_this_thread(); + assert_materialization_is_unchecked().await; +} 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 4f8a7933f8d..c0ef77bdbe7 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 @@ -391,3 +391,46 @@ async fn an_enforcing_gate_denies_a_tool_the_module_cannot_classify() { "{write:?}" ); } + +/// Local-only privacy mode still refuses a shell command that may reach the +/// network when security is disabled; a local command still runs. +async fn local_only_shell_decisions() -> (GateDecision, GateDecision) { + let _mode = + crate::security::live_policy::test_privacy_scope(crate::config::PrivacyMode::LocalOnly); + let gate = gate(AutonomyLevel::Full); + let network = gate + .authorize_tool(&req( + SHELL_TOOL, + json!({ "command": "curl https://example.com" }), + )) + .await + .unwrap(); + let local = gate + .authorize_tool(&req(SHELL_TOOL, json!({ "command": "ls -la" }))) + .await + .unwrap(); + (network, local) +} + +#[cfg(not(feature = "security-module"))] +#[tokio::test] +async fn a_build_without_the_module_keeps_local_only_for_the_shell_tool() { + let (network, local) = local_only_shell_decisions().await; + assert!(!network.is_allowed()); + assert!(network + .denial_reason() + .is_some_and(|reason| reason.contains("Local-only privacy mode"))); + assert_eq!(local, GateDecision::Allow); +} + +#[cfg(feature = "security-module")] +#[tokio::test] +async fn security_configured_off_keeps_local_only_for_the_shell_tool() { + let _off = crate::security::switch::off_for_this_thread(); + let (network, local) = local_only_shell_decisions().await; + assert!(!network.is_allowed()); + assert!(network + .denial_reason() + .is_some_and(|reason| reason.contains("Local-only privacy mode"))); + assert_eq!(local, GateDecision::Allow); +} diff --git a/crates/openhuman-core/src/attachments/mod_tests.rs b/crates/openhuman-core/src/attachments/mod_tests.rs index 8e4b82a08e7..cc90a9cb99f 100644 --- a/crates/openhuman-core/src/attachments/mod_tests.rs +++ b/crates/openhuman-core/src/attachments/mod_tests.rs @@ -190,6 +190,9 @@ fn config(root: &Path) -> Config { } } +// Refusing the unrelated file is enforced security: a build without the +// security module has security disabled (`crate::security::switch`). +#[cfg(feature = "security-module")] #[tokio::test] async fn ready_media_artifact_in_files_folder_can_be_attached() { let temp = tempfile::tempdir().unwrap(); diff --git a/crates/openhuman-core/src/media/generation/artifact_tool_tests.rs b/crates/openhuman-core/src/media/generation/artifact_tool_tests.rs index 6aa04f26a67..3825598f211 100644 --- a/crates/openhuman-core/src/media/generation/artifact_tool_tests.rs +++ b/crates/openhuman-core/src/media/generation/artifact_tool_tests.rs @@ -571,3 +571,28 @@ async fn per_call_observer_reports_each_calls_own_job_state() { assert_eq!(ma, vec!["Generating video — 15s elapsed (job pending)"]); assert_eq!(mb, vec!["Generating video — 15s elapsed (job in_progress)"]); } + +/// With security disabled the media reference floor checks nothing: a +/// reference inside a credential store is admitted. +async fn assert_references_are_unchecked() { + let dir = tempfile::tempdir().unwrap(); + let key = dir.path().join("home/.ssh/id_rsa"); + let args = json!({ + "references": [key.to_string_lossy()], + "first_frame": key.to_string_lossy(), + }); + assert_eq!(super::check_media_reference_floor(&args).await, Ok(())); +} + +#[cfg(not(feature = "security-module"))] +#[tokio::test] +async fn a_build_without_the_module_admits_any_media_reference() { + assert_references_are_unchecked().await; +} + +#[cfg(feature = "security-module")] +#[tokio::test] +async fn security_configured_off_admits_any_media_reference() { + let _off = crate::security::switch::off_for_this_thread(); + assert_references_are_unchecked().await; +} diff --git a/crates/openhuman-core/src/security/README.md b/crates/openhuman-core/src/security/README.md index 1540a79b3eb..2e846976c36 100644 --- a/crates/openhuman-core/src/security/README.md +++ b/crates/openhuman-core/src/security/README.md @@ -16,8 +16,11 @@ decisions: build without the `security-module` feature, or when the booted config says `[security] mode = "off"` (`RuntimeBuilder::security` for an embedder). The checks are then permissive: the prompt screen, tool classification and - approvals, path checks, the action budget and the audit trail allow, egress - is permitted unless `[privacy] mode = "local_only"`, and redaction passes tool + approvals, path checks (no path policy at all, protected floor included), + the action budget and the audit trail allow, egress and network shell + commands are permitted unless `[privacy] mode = "local_only"` + (`policy/local_only_commands.rs` classifies shell commands then), and + redaction passes tool output, diagnostics and log URLs through unredacted. The approval gate is unchanged: approvals a channel, flow or origin demands still need a person (and an engine), while the module's own approval prompts are skipped. The diff --git a/crates/openhuman-core/src/security/policy/README.md b/crates/openhuman-core/src/security/policy/README.md index 40c6b5bb423..d7480f1ce10 100644 --- a/crates/openhuman-core/src/security/policy/README.md +++ b/crates/openhuman-core/src/security/policy/README.md @@ -47,6 +47,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 | +| [`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 | | [`enforcement.rs`](./enforcement.rs) | Host tool admission, budget snapshots, and scratch-directory mechanics | diff --git a/crates/openhuman-core/src/security/policy/local_only_commands.rs b/crates/openhuman-core/src/security/policy/local_only_commands.rs new file mode 100644 index 00000000000..5185c804893 --- /dev/null +++ b/crates/openhuman-core/src/security/policy/local_only_commands.rs @@ -0,0 +1,407 @@ +//! Shell commands under local-only privacy mode while security is disabled. +//! +//! With security enforced, TinySecurity classifies every command, including +//! whether it reaches the network. With security disabled +//! (`crate::security::switch`) nothing is classified and commands are allowed, +//! except under `[privacy] mode = "local_only"`. That mode is the user's own +//! network setting, not a module check, so it stays enforced: the host refuses +//! a command that may reach the network. +//! +//! The classification here is deliberately conservative and narrow. It reads +//! the program of every command in a pipeline or list and refuses: +//! +//! - a known network client (`curl`, `wget`, `nc`, `ssh`, `scp`, `ftp`, ...); +//! - a network subcommand of a local tool (`git clone/fetch/pull/push`, +//! `npm install`, `pip install`, `cargo install`, `docker pull`, ...), and +//! `rsync` with a remote endpoint; +//! - anything it cannot read with confidence: command or process +//! substitution, parameter expansion, unbalanced quotes, inline code passed +//! to a shell or an interpreter (`sh -c`, `python -c`, `eval`), and runners +//! whose program is built from input (`xargs`). +//! +//! Scripts and build tools (`make`, `cargo build`, `python app.py`) are not +//! opened: their own network use is outside what a command line shows. + +use super::native_commands::{CommandQuery, CommandVerdict, Refusal}; +use super::types::{CommandClass, GateDecision, SecurityPolicy}; +use crate::config::PrivacyMode; + +impl SecurityPolicy { + /// The verdict for a command TinySecurity is not asked about (security + /// disabled): allowed, unless local-only privacy mode is active and the + /// command may reach the network. + pub(super) fn unchecked_command_verdict( + &self, + query: &CommandQuery<'_>, + ) -> Result { + let network = may_reach_network(query.command); + if network && self.local_only() { + tracing::debug!( + "[privacy][local-only] refused a shell command that may reach the network" + ); + return Err(Refusal::LocalOnly); + } + Ok(CommandVerdict { + class: unchecked_class(query, network), + gate: GateDecision::Allow, + }) + } + + /// Whether local-only privacy mode is active: on this policy, or on the live + /// session policy the egress chokepoints read. + fn local_only(&self) -> bool { + self.privacy_mode() == PrivacyMode::LocalOnly + || crate::security::live_policy::current_privacy_mode() == PrivacyMode::LocalOnly + } +} + +/// The class of a command nobody classified: what the model declared, else +/// `Network` for a command that may reach the network and `Write` otherwise. +/// Informational only, since a disabled scope allows every class. +pub(super) fn unchecked_class(query: &CommandQuery<'_>, network: bool) -> CommandClass { + query.declared.unwrap_or(if network { + CommandClass::Network + } else { + CommandClass::Write + }) +} + +/// Programs whose purpose is to talk to the network. +const NETWORK_CLIENTS: &[&str] = &[ + "curl", + "wget", + "nc", + "ncat", + "netcat", + "socat", + "ssh", + "scp", + "sftp", + "ftp", + "lftp", + "telnet", + "http", + "https", + "httpie", + "xh", + "aria2c", + "ping", + "ping6", + "dig", + "nslookup", + "host", + "whois", + "traceroute", + "tracepath", + "mosh", + "rclone", + "gsutil", + "aws", + "gcloud", + "az", + "kubectl", + "helm", +]; + +/// Shells and interpreters that run inline code given with one of these flags. +const INLINE_CODE: &[(&str, &[&str])] = &[ + ("sh", &["-c"]), + ("bash", &["-c"]), + ("zsh", &["-c"]), + ("dash", &["-c"]), + ("ksh", &["-c"]), + ("fish", &["-c"]), + ("python", &["-c"]), + ("python3", &["-c"]), + ("python2", &["-c"]), + ("node", &["-e", "--eval", "-p", "--print"]), + ("deno", &["eval"]), + ("bun", &["-e", "--eval"]), + ("perl", &["-e", "-E"]), + ("ruby", &["-e"]), + ("php", &["-r"]), + ("osascript", &["-e"]), + ("powershell", &["-c", "-command"]), + ("pwsh", &["-c", "-command"]), +]; + +/// Programs that run text they are given, or a program built from input. +const OPAQUE: &[&str] = &["eval", "source", ".", "xargs", "parallel", "watch"]; + +/// Programs that run the rest of the line as a command, after their options. +const WRAPPERS: &[&str] = &[ + "sudo", "doas", "env", "nohup", "time", "nice", "ionice", "timeout", "command", "exec", + "stdbuf", "builtin", "chrt", "setsid", "unbuffer", +]; + +/// Subcommands of local tools that fetch from, or send to, the network. +const NETWORK_SUBCOMMANDS: &[(&str, &[&str])] = &[ + ( + "git", + &[ + "clone", + "fetch", + "pull", + "push", + "ls-remote", + "remote", + "submodule", + "archive", + ], + ), + ( + "npm", + &[ + "install", "i", "ci", "add", "update", "publish", "view", "exec", + ], + ), + ("npx", &[""]), + ("pnpm", &["install", "i", "add", "update", "dlx", "publish"]), + ("yarn", &["install", "add", "upgrade", "dlx", "publish"]), + ("bunx", &[""]), + ("pip", &["install", "download"]), + ("pip3", &["install", "download"]), + ("pipx", &["install", "run"]), + ("uv", &["pip", "add", "sync", "tool"]), + ("uvx", &[""]), + ("poetry", &["install", "add", "update", "publish"]), + ( + "cargo", + &["install", "fetch", "update", "publish", "add", "search"], + ), + ("go", &["get", "install", "mod"]), + ("gem", &["install", "update", "fetch"]), + ("bundle", &["install", "update"]), + ("composer", &["install", "require", "update"]), + ("apt", &["install", "update", "upgrade", "download"]), + ("apt-get", &["install", "update", "upgrade", "download"]), + ("dnf", &["install", "update", "upgrade", "download"]), + ("yum", &["install", "update", "upgrade"]), + ("apk", &["add", "update", "upgrade", "fetch"]), + ("pacman", &["-S", "-Sy", "-Syu"]), + ("brew", &["install", "update", "upgrade", "fetch", "tap"]), + ("docker", &["pull", "push", "login", "search"]), + ("podman", &["pull", "push", "login", "search"]), +]; + +/// Whether `command` may reach the network, or cannot be read with confidence. +pub(crate) fn may_reach_network(command: &str) -> bool { + if ["`", "$(", "<(", ">(", "${"] + .iter() + .any(|construct| command.contains(construct)) + { + return true; + } + let Some(segments) = segments(command) else { + return true; + }; + segments + .iter() + .any(|words| segment_may_reach_network(words)) +} + +/// The words of every simple command in `command`, split at `;`, `&`, `|`, +/// newlines and parentheses. `None` when quoting is unbalanced. +fn segments(command: &str) -> Option>> { + let mut segments = Vec::new(); + let mut words: Vec = Vec::new(); + let mut word = String::new(); + let mut in_word = false; + let mut chars = command.chars(); + while let Some(c) = chars.next() { + match c { + '\'' => { + in_word = true; + loop { + match chars.next()? { + '\'' => break, + other => word.push(other), + } + } + } + '"' => { + in_word = true; + loop { + match chars.next()? { + '"' => break, + '\\' => word.push(chars.next()?), + other => word.push(other), + } + } + } + '\\' => { + in_word = true; + if let Some(next) = chars.next() { + if next != '\n' { + word.push(next); + } + } + } + ';' | '&' | '|' | '\n' | '(' | ')' => { + if in_word { + words.push(std::mem::take(&mut word)); + in_word = false; + } + if !words.is_empty() { + segments.push(std::mem::take(&mut words)); + } + } + c if c.is_whitespace() => { + if in_word { + words.push(std::mem::take(&mut word)); + in_word = false; + } + } + other => { + in_word = true; + word.push(other); + } + } + } + if in_word { + words.push(word); + } + if !words.is_empty() { + segments.push(words); + } + Some(segments) +} + +/// Whether one simple command may reach the network. +fn segment_may_reach_network(words: &[String]) -> bool { + let words = strip_prefix(words); + let Some((program, args)) = words.split_first() else { + return false; + }; + let program = program_name(program); + if NETWORK_CLIENTS.contains(&program) || OPAQUE.contains(&program) { + return true; + } + if let Some((_, flags)) = INLINE_CODE + .iter() + .find(|(name, _)| program_matches(name, program)) + { + if args.iter().any(|arg| { + let arg = arg.to_ascii_lowercase(); + flags.iter().any(|flag| arg == *flag) + }) { + return true; + } + } + if program == "rsync" { + return args.iter().any(|arg| remote_endpoint(arg)); + } + if program == "find" { + return args + .iter() + .position(|arg| matches!(arg.as_str(), "-exec" | "-execdir" | "-ok" | "-okdir")) + .is_some_and(|at| segment_may_reach_network(&args[at + 1..])); + } + if let Some((_, subcommands)) = NETWORK_SUBCOMMANDS + .iter() + .find(|(name, _)| *name == program) + { + if subcommands == &[""] { + return true; + } + let Some(subcommand) = first_subcommand(program, args) else { + return false; + }; + return subcommands.contains(&subcommand); + } + false +} + +/// Drop leading variable assignments and wrapper programs with their options, +/// leaving the program that actually runs. +fn strip_prefix(mut words: &[String]) -> &[String] { + loop { + let Some((first, rest)) = words.split_first() else { + return words; + }; + if is_assignment(first) { + words = rest; + continue; + } + let name = program_name(first); + if !WRAPPERS.contains(&name) { + return words; + } + words = rest; + // Options of the wrapper, and the duration `timeout` takes. + while let Some((next, rest)) = words.split_first() { + if next.starts_with('-') || is_assignment(next) { + let takes_value = matches!(next.as_str(), "-n" | "-u" | "-g" | "-s" | "-k" | "-C"); + words = rest; + if takes_value { + words = words.split_first().map_or(words, |(_, rest)| rest); + } + } else if name == "timeout" && next.chars().next().is_some_and(|c| c.is_ascii_digit()) { + words = rest; + } else { + break; + } + } + } +} + +/// The first subcommand of `program`, skipping its global options (and the +/// values `git -C ` and `git -c ` take). +fn first_subcommand<'a>(program: &str, args: &'a [String]) -> Option<&'a str> { + let mut args = args.iter(); + while let Some(arg) = args.next() { + if program == "pacman" && arg.starts_with("-S") { + return Some(if arg.as_str() == "-S" { "-S" } else { "-Sy" }); + } + if arg.starts_with('-') { + if program == "git" && matches!(arg.as_str(), "-C" | "-c" | "--git-dir" | "--work-tree") + { + args.next(); + } + continue; + } + return Some(arg.as_str()); + } + None +} + +/// The program's file name, so `/usr/bin/curl` reads as `curl`. +fn program_name(word: &str) -> &str { + word.rsplit(['/', '\\']).next().unwrap_or(word) +} + +/// Whether `program` is `name` or a versioned form of it (`python3.12`). +fn program_matches(name: &str, program: &str) -> bool { + program == name + || program + .strip_prefix(name) + .is_some_and(|rest| rest.chars().all(|c| c.is_ascii_digit() || c == '.')) +} + +/// `NAME=value` before a command. +fn is_assignment(word: &str) -> bool { + word.split_once('=').is_some_and(|(name, _)| { + !name.is_empty() + && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') + && !name.starts_with(|c: char| c.is_ascii_digit()) + }) +} + +/// An rsync endpoint on another host: `host:path`, `user@host:path` or an +/// `rsync://` URL. A local path with a colon after a slash is not remote. +fn remote_endpoint(arg: &str) -> bool { + if arg.starts_with('-') { + return false; + } + if arg.contains("://") { + return true; + } + match arg.find(':') { + Some(colon) => !arg[..colon].contains('/'), + None => false, + } +} + +#[cfg(test)] +#[path = "local_only_commands_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/security/policy/local_only_commands_tests.rs b/crates/openhuman-core/src/security/policy/local_only_commands_tests.rs new file mode 100644 index 00000000000..531a40b7a7b --- /dev/null +++ b/crates/openhuman-core/src/security/policy/local_only_commands_tests.rs @@ -0,0 +1,159 @@ +//! Local-only shell classification while security is disabled. + +use super::*; +use crate::security::policy::{CommandFlow, CommandStage}; + +#[test] +fn local_commands_do_not_reach_the_network() { + for command in [ + "ls -la", + "cat README.md | grep -n security", + "cargo test -p openhuman", + "git status && git diff --stat", + "git -C crates log --oneline", + "make build", + "python3 app.py", + "npm run build", + "rsync -a src/ backup/", + "rsync -a ./a:b/ dst/", + "FOO=1 BAR=2 echo hi", + "find . -name '*.rs' -exec wc -l {} ;", + "sudo -u builder cargo build", + "timeout 30 cargo check", + "echo \"it's fine\" > notes.txt", + ] { + assert!(!may_reach_network(command), "{command} is local"); + } +} + +#[test] +fn network_clients_and_network_subcommands_may_reach_the_network() { + for command in [ + "curl https://example.com", + "/usr/bin/wget -q https://example.com", + "ls; curl example.com", + "echo hi | nc example.com 80", + "ncat example.com 443", + "ssh user@example.com", + "scp file host:/tmp", + "sudo -u builder curl example.com", + "env A=1 wget example.com", + "timeout 5 ssh example.com", + "nohup aria2c url &", + "git clone https://example.com/repo.git", + "git -C repo fetch origin", + "git pull", + "git push origin main", + "git ls-remote origin", + "npm install left-pad", + "npx create-something", + "pip install requests", + "pip3 download requests", + "cargo install ripgrep", + "docker pull alpine", + "apt-get update", + "brew install jq", + "rsync -a src/ host:dst/", + "rsync -a rsync://example.com/mod/ .", + "telnet example.com 23", + "http GET example.com", + "find . -name x -exec curl -T {} example.com ;", + ] { + assert!( + may_reach_network(command), + "{command} may reach the network" + ); + } +} + +#[test] +fn commands_that_cannot_be_read_with_confidence_are_treated_as_network() { + for command in [ + "sh -c 'ls'", + "bash -c ls", + "python3 -c 'print(1)'", + "python3.12 -c 'import urllib'", + "node -e 'fetch(1)'", + "perl -e 1", + "eval ls", + "source ./setup.sh", + "echo $(whoami)", + "echo `whoami`", + "cat <(ls)", + "echo ${HOME}", + "echo 'unbalanced", + "echo \"unbalanced", + "ls | xargs cat", + ] { + assert!(may_reach_network(command), "{command} cannot be read"); + } +} + +fn query(command: &str) -> CommandQuery<'_> { + CommandQuery { + command, + declared: None, + flow: CommandFlow::Harness, + stage: CommandStage::Authorize, + } +} + +/// With security disabled, local-only privacy mode refuses network commands +/// and allows local ones; Standard and Sensitive allow both. +async fn assert_local_only_refuses_network_commands() { + use crate::security::live_policy::test_privacy_scope; + let policy = SecurityPolicy::default(); + + { + let _mode = test_privacy_scope(PrivacyMode::LocalOnly); + assert_eq!( + policy + .check_command(query("curl https://example.com")) + .await, + Err(Refusal::LocalOnly) + ); + assert_eq!( + policy + .classify_native_command(query("git fetch origin")) + .await, + Err(Refusal::LocalOnly) + ); + let local = policy.check_command(query("ls -la")).await.unwrap(); + assert_eq!(local.gate, GateDecision::Allow); + assert!(Refusal::LocalOnly + .to_string() + .contains("Local-only privacy mode is active")); + } + + // The policy's own mode is honoured too, not only the live session's. + let local_only_policy = SecurityPolicy::default().with_privacy_mode(PrivacyMode::LocalOnly); + assert_eq!( + local_only_policy + .check_command(query("wget example.com")) + .await, + Err(Refusal::LocalOnly) + ); + + for mode in [PrivacyMode::Standard, PrivacyMode::Sensitive] { + let _mode = test_privacy_scope(mode); + let verdict = policy + .check_command(query("curl https://example.com")) + .await + .unwrap(); + assert_eq!(verdict.gate, GateDecision::Allow, "{mode:?}"); + assert_eq!(verdict.class, CommandClass::Network); + } +} + +#[cfg(not(feature = "security-module"))] +#[tokio::test] +async fn a_build_without_the_module_keeps_local_only_for_shell_commands() { + assert_local_only_refuses_network_commands().await; +} + +#[cfg(feature = "security-module")] +#[tokio::test] +async fn security_configured_off_keeps_local_only_for_shell_commands() { + let _off = crate::security::switch::off_for_this_thread(); + assert_local_only_refuses_network_commands().await; +} diff --git a/crates/openhuman-core/src/security/policy/mod.rs b/crates/openhuman-core/src/security/policy/mod.rs index 1672a229b70..d56a3c9f220 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 local_only_commands; mod module_gate; mod native_commands; mod native_paths; diff --git a/crates/openhuman-core/src/security/policy/native_commands.rs b/crates/openhuman-core/src/security/policy/native_commands.rs index bd4ea2dba40..7e7d380ed5d 100644 --- a/crates/openhuman-core/src/security/policy/native_commands.rs +++ b/crates/openhuman-core/src/security/policy/native_commands.rs @@ -102,7 +102,9 @@ impl SecurityPolicy { query: CommandQuery<'_>, ) -> Result { if crate::security::switch::disabled().is_some() { - return Ok(unchecked_class(&query)); + return self + .unchecked_command_verdict(&query) + .map(|verdict| verdict.class); } #[cfg(feature = "security-module")] { @@ -129,13 +131,11 @@ impl SecurityPolicy { /// Asked even when autonomy is disabled: a disabled scope allows every /// command except those naming TinySecurity's protected paths. With security /// disabled (`crate::security::switch`) nothing is asked and every command - /// is allowed without approval. + /// is allowed without approval, except one that may reach the network under + /// local-only privacy mode (`local_only_commands`). pub async fn check_command(&self, query: CommandQuery<'_>) -> Result { if crate::security::switch::disabled().is_some() { - return Ok(CommandVerdict { - class: unchecked_class(&query), - gate: GateDecision::Allow, - }); + return self.unchecked_command_verdict(&query); } match &self.command_gateway { Some(gateway) => gateway.decide(self, &query).await, @@ -193,13 +193,6 @@ impl SecurityPolicy { } } -/// The class of a command nobody classified (security disabled): what the model -/// declared, or `Write` when it declared nothing. Informational only, since a -/// disabled scope allows every class. -fn unchecked_class(query: &CommandQuery<'_>) -> CommandClass { - query.declared.unwrap_or(CommandClass::Write) -} - /// A class-only question: the gate for a command of `class`, with no command /// text to classify. fn class_query(class: CommandClass) -> CommandQuery<'static> { @@ -260,6 +253,11 @@ pub(crate) fn refusal_message(denial: Refusal) -> String { Refusal::Unavailable => format!( "{POLICY_BLOCKED_MARKER} TinySecurity command authorization unavailable; command denied" ), + Refusal::LocalOnly => format!( + "{POLICY_BLOCKED_MARKER} Local-only privacy mode is active: this command may reach \ + the network. Do not retry it; use a local alternative, or disable local-only mode \ + in Settings to allow it." + ), } } @@ -276,6 +274,9 @@ pub enum Refusal { Category, /// The module could not answer: missing, untrusted, faulted or too slow. Unavailable, + /// Local-only privacy mode is active and the command may reach the network + /// (security disabled, so the host decided; see `local_only_commands`). + LocalOnly, } impl std::fmt::Display for Refusal { diff --git a/crates/openhuman-core/src/security/policy/path_checks.rs b/crates/openhuman-core/src/security/policy/path_checks.rs index e4e8f4008c7..3973df7c66c 100644 --- a/crates/openhuman-core/src/security/policy/path_checks.rs +++ b/crates/openhuman-core/src/security/policy/path_checks.rs @@ -11,6 +11,11 @@ impl SecurityPolicy { /// Synchronous lexical preflight only. TinySecurity performs authorization, /// protected-floor and reservation decisions in the async validators. + /// + /// This is input validation, not policy: an empty path, a NUL byte or a + /// parent traversal (`..`, including its percent-encoded forms) is a + /// malformed tool argument, refused whether security is enforced or + /// disabled. With security disabled it is the only check a path gets. pub fn is_path_string_allowed(&self, path: &str) -> bool { !path.is_empty() && !path.contains('\0') diff --git a/crates/openhuman-core/src/security/policy/policy_tests.rs b/crates/openhuman-core/src/security/policy/policy_tests.rs index 4113792063f..74c50bd5eba 100644 --- a/crates/openhuman-core/src/security/policy/policy_tests.rs +++ b/crates/openhuman-core/src/security/policy/policy_tests.rs @@ -129,6 +129,29 @@ pub(super) async fn assert_every_policy_gate_allows() { vec![true] ); + // No protected floor: a credential store under a home directory is a + // path like any other. + let home = root.join("home"); + fs::create_dir_all(home.join(".ssh")).unwrap(); + fs::write(home.join(".ssh/id_rsa"), "key").unwrap(); + let key = home.join(".ssh/id_rsa"); + assert!(!SecurityPolicy::is_always_forbidden_async(&key).await); + assert_eq!( + policy.validate_path(&key.to_string_lossy()).await.unwrap(), + key + ); + assert_eq!( + policy + .validate_parent_path(&home.join(".ssh/new_key").to_string_lossy()) + .await + .unwrap(), + home.join(".ssh/new_key") + ); + assert!(!policy.is_internal(&key).await); + // Input validation, not policy: a parent traversal or a NUL is malformed. + assert!(policy.validate_path("../notes.md").await.is_err()); + assert!(policy.validate_path("notes\0.md").await.is_err()); + // Tier and budget. policy.spend_action("file_write").await.unwrap(); assert_eq!( @@ -202,6 +225,28 @@ async fn an_enforcing_policy_without_the_module_still_refuses() { }; assert!(crate::security::switch::disabled().is_none()); assert!(!policy.can_act(), "no module answer, no acting tier"); + + // A credential store is refused when the module cannot be asked. + let key = dir.path().join("home/.ssh/id_rsa"); + fs::create_dir_all(key.parent().unwrap()).unwrap(); + fs::write(&key, "key").unwrap(); + let temp = tempfile::tempdir().unwrap(); + let mut config = crate::credentials::test_support::plaintext_fixture_config(temp.path()); + config.modules.enabled = false; + let context = crate::core::runtime::CoreContext::for_test_with_config( + crate::core::runtime::DomainSet::full(), + config, + ); + let refused = crate::core::runtime::CoreContext::scope(context, async { + policy.validate_path(&key.to_string_lossy()).await + }) + .await; + assert!( + refused + .as_ref() + .is_err_and(|error| error.contains("[policy-blocked]")), + "{refused:?}" + ); assert!(policy.is_rate_limited()); assert_eq!( policy.gate_decision(CommandClass::Write), diff --git a/crates/openhuman-core/src/security/switch.rs b/crates/openhuman-core/src/security/switch.rs index 04c5cd2f84d..f908c1bab5d 100644 --- a/crates/openhuman-core/src/security/switch.rs +++ b/crates/openhuman-core/src/security/switch.rs @@ -21,7 +21,8 @@ //! [`disabled_for`], which also honours that configuration's own `[security]`. //! //! Some things stay on when security is disabled, because they are not module -//! checks: `[privacy] mode = "local_only"` still refuses external egress; the +//! checks: `[privacy] mode = "local_only"` still refuses external egress and +//! shell commands that may reach the network; the //! approval gate is unchanged, so a call a channel, flow or origin requires a //! person to approve still waits for one (and is refused where no approval //! engine exists), although the module-driven approval prompts are skipped diff --git a/crates/openhuman-core/src/util/redact_tests.rs b/crates/openhuman-core/src/util/redact_tests.rs index 5ff6b152489..103fd50d776 100644 --- a/crates/openhuman-core/src/util/redact_tests.rs +++ b/crates/openhuman-core/src/util/redact_tests.rs @@ -28,3 +28,24 @@ fn security_configured_off_logs_the_endpoint_unredacted() { CREDENTIALED_URL ); } + +/// With security disabled a token in the query string is logged as given. +fn assert_token_query_is_logged_unchanged() { + let url = "https://api.example.test/v1/items?token=sk-live-123&page=2"; + let logged = redact_url_for_log(url); + assert_eq!(logged, url); + assert!(logged.contains("token=sk-live-123")); +} + +#[cfg(not(feature = "security-module"))] +#[test] +fn a_build_without_the_module_logs_a_token_query_param_unchanged() { + assert_token_query_is_logged_unchanged(); +} + +#[cfg(feature = "security-module")] +#[test] +fn security_configured_off_logs_a_token_query_param_unchanged() { + let _off = crate::security::switch::off_for_this_thread(); + assert_token_query_is_logged_unchanged(); +}