Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(security): add policy command module for security checks

Steven Enamakelae1b76b94ae4
diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.toml
index 97644daed9..aa44524157 100644
--- a/crates/openhuman-core/Cargo.toml
+++ b/crates/openhuman-core/Cargo.toml
@@ -148,6 +148,9 @@ tinyagents-harness = { path = "../../vendor/tinyagents/crates/tinyagents-harness
# Per-process directory jail (Landlock / Seatbelt / AppContainer / noop). Owned by
# tinybox; OpenHuman keeps only the policy of when to jail (`sandbox::ops`).
tinybox-jail = { path = "../../vendor/tinybox/crates/tinybox-jail" }
+# Quote-aware shell command-string scanners (`tinybox_core::shell::scan`); the
+# classification policy built on them stays in `security::policy`.
+tinybox-core = { path = "../../vendor/tinybox/crates/tinybox-core" }
tinyagents-definition = { path = "../../vendor/tinyagents/crates/tinyagents-definition" }
tinyagents-graph = { path = "../../vendor/tinyagents/crates/tinyagents-graph", features = [
"sqlite",
@@ -670,9 +673,6 @@ windows-sys = { version = "0.61", features = [
# default. Avoids pulling OpenSSL as a runtime dep on Linux.
tokio-tungstenite = { version = "0.29", default-features = false, features = ["connect", "handshake", "rustls-tls-webpki-roots"] }
-[target.'cfg(target_os = "linux")'.dependencies]
-landlock = { version = "0.4", optional = true }
-
[dev-dependencies]
# Turns on `tinyflows-sqlite`'s `test-fixtures` gate for test builds only: the
# flows test suite stages a terminal run flipped back to `running` and a
@@ -1158,7 +1158,9 @@ crash-reporting = ["dep:sentry"]
# is a compile-surface and architecture win, NOT a dependency win — see the
# measured note above before claiming otherwise.
channels = ["dep:tinychannels", "tinychannels/email", "tinychannels/lark"]
-sandbox-landlock = ["dep:landlock", "tinybox-jail/landlock"]
+sandbox-landlock = ["tinybox-jail/landlock"]
+# Retained so the feature name still forwards through embed/cli/tinyhumans/app;
+# the legacy bwrap `Command` wrapper it gated was removed (unused).
sandbox-bubblewrap = []
landlock = ["sandbox-landlock"]
# The WhatsApp Web provider now lives in tinychannels; forward to its feature.
diff --git a/crates/openhuman-core/src/security/policy/command_checks.rs b/crates/openhuman-core/src/security/policy/command_checks.rs
index 14a4771697..925cd8c66f 100644
--- a/crates/openhuman-core/src/security/policy/command_checks.rs
+++ b/crates/openhuman-core/src/security/policy/command_checks.rs
@@ -1,10 +1,12 @@
use crate::util::floor_char_boundary;
use super::policy_command::{
- classify_segment, command_basename, contains_unquoted_char, contains_unquoted_single_ampersand,
- has_dangerous_env_prefix, has_hidden_execution, has_leading_env_assignment,
- is_command_executor, normalized_command_name, skip_env_assignments, split_unquoted_segments,
- strip_quoted_heredoc_bodies,
+ classify_segment, has_dangerous_env_prefix, has_hidden_execution, is_command_executor,
+};
+use tinybox_core::shell::scan::{
+ command_basename, contains_unquoted_char, contains_unquoted_single_ampersand,
+ has_leading_env_assignment, normalized_command_name, skip_env_assignments,
+ split_unquoted_segments, strip_quoted_heredoc_bodies,
};
use super::types::{
AutonomyLevel, CommandClass, CommandRiskLevel, GateDecision, SecurityPolicy,
diff --git a/crates/openhuman-core/src/security/policy/policy_command/classification.rs b/crates/openhuman-core/src/security/policy/policy_command/classification.rs
index 858c091108..4a102e573a 100644
--- a/crates/openhuman-core/src/security/policy/policy_command/classification.rs
+++ b/crates/openhuman-core/src/security/policy/policy_command/classification.rs
@@ -2,7 +2,7 @@
//! bucket lists, verb-sensitive VCS / package-manager handling, and the
//! structural "hidden execution" guard for the harness-gated command flow.
-use super::quoting::contains_unquoted_background_ampersand;
+use tinybox_core::shell::scan::{contains_unquoted_background_ampersand, strip_quoted_heredoc_bodies};
use crate::security::policy::policy_command::command_name::is_command_executor;
use crate::security::policy::types::CommandClass;
@@ -364,7 +364,7 @@ pub(in crate::security::policy) fn has_hidden_execution(command: &str) -> bool {
// — the life-scenario `meal-plan` write was blocked because four recipe
// titles read "Chicken & Spinach". An *unquoted* delimiter is left in place
// by the helper, because expansion IS live in that body.
- let command = &super::quoting::strip_quoted_heredoc_bodies(command);
+ let command = &strip_quoted_heredoc_bodies(command);
// The backtick check is deliberately NOT quote-aware: any backtick in the
// command string is blocked, even inside a double-quoted literal. Over-
// blocking is the safe direction here. (By contrast the `&` case below is
diff --git a/crates/openhuman-core/src/security/policy/policy_command/command_name.rs b/crates/openhuman-core/src/security/policy/policy_command/command_name.rs
index a02cf7fbd7..6969d24475 100644
--- a/crates/openhuman-core/src/security/policy/policy_command/command_name.rs
+++ b/crates/openhuman-core/src/security/policy/policy_command/command_name.rs
@@ -1,18 +1,8 @@
-//! Normalizing a raw command word down to the basename the classifier keys
-//! off, and detecting bases that execute arbitrary code (interpreters,
-//! shells, `xargs`, Windows LOLBins, …).
+//! Detecting bases that execute arbitrary code (interpreters,
+//! shells, `xargs`, Windows LOLBins, …). Basename normalisation itself is
+//! `tinybox_core::shell::scan`.
-pub(in crate::security::policy) fn command_basename(command: &str) -> &str {
- command.split(['/', '\\']).next_back().unwrap_or(command)
-}
-
-pub(in crate::security::policy) fn normalized_command_name(command: &str) -> String {
- let command = command_basename(command).to_ascii_lowercase();
- command
- .strip_suffix(".exe")
- .unwrap_or(command.as_str())
- .to_string()
-}
+use tinybox_core::shell::scan::normalized_command_name;
fn is_python_command(command: &str) -> bool {
let command = normalized_command_name(command);
diff --git a/crates/openhuman-core/src/security/policy/policy_command/env_guard.rs b/crates/openhuman-core/src/security/policy/policy_command/env_guard.rs
index ac51ca24f0..7da351ff7b 100644
--- a/crates/openhuman-core/src/security/policy/policy_command/env_guard.rs
+++ b/crates/openhuman-core/src/security/policy/policy_command/env_guard.rs
@@ -1,5 +1,4 @@
-//! Detection of leading inline environment-variable assignments on a shell
-//! command, and the "dangerous" subset that can redirect execution of an
+//! The "dangerous" subset of inline environment-variable assignments that can redirect execution of an
//! otherwise-allowed command (pagers, editors, loader overrides, …).
/// Environment variable names that can trigger arbitrary command execution
@@ -57,7 +56,7 @@ const DANGEROUS_ENV_PREFIXES: &[&str] = &[
/// Returns true if `s` starts with one or more inline env assignments and any
/// of the assigned names are in [`DANGEROUS_ENV_PREFIXES`].
///
-/// Now superseded by [`has_leading_env_assignment`] for the
+/// Now superseded by `has_leading_env_assignment` for the
/// allowlist check (which rejects ANY leading env assignment), but kept
/// for callers that specifically want the dangerous-only signal —
/// notably tests that pin the old DANGEROUS_ENV_PREFIXES rejection
@@ -99,64 +98,3 @@ pub(in crate::security::policy) fn has_dangerous_env_prefix(s: &str) -> bool {
rest = rest[word.len()..].trim_start();
}
}
-
-/// Returns true if `s` starts with at least one inline env-var
-/// assignment of the shape `NAME=...`, where `NAME` begins with an ASCII
-/// letter or underscore. Catches the entire `GIT_SSH=…`, `SSH_ASKPASS=…`,
-/// `LD_PRELOAD=…`, `IFS=…` family — including names we haven't enumerated
-/// in [`DANGEROUS_ENV_PREFIXES`] — by treating ANY leading assignment as
-/// suspect. The allowlist already names every command we want to permit;
-/// nothing in that list needs the operator to set an env var at invoke
-/// time, so the broader gate has no false-positive surface on the
-/// approved path.
-///
-/// Used by [`SecurityPolicy::is_command_allowed`] as a structural guard
-/// alongside the existing dangerous-prefix check.
-pub(in crate::security::policy) fn has_leading_env_assignment(s: &str) -> bool {
- let Some(word) = s.split_whitespace().next() else {
- return false;
- };
- let Some((name, _value)) = word.split_once('=') else {
- return false;
- };
- if name.is_empty() {
- return false;
- }
- // Identifier shape: first char letter or `_`, the rest alphanumeric
- // or `_`. Anything else (e.g. `foo[bar]=`) is not a shell assignment.
- let mut chars = name.chars();
- let first = match chars.next() {
- Some(c) => c,
- None => return false,
- };
- if !(first.is_ascii_alphabetic() || first == '_') {
- return false;
- }
- if !chars.all(|c| c.is_ascii_alphanumeric() || c == '_') {
- return false;
- }
- true
-}
-
-/// Skip leading environment variable assignments (e.g. `FOO=bar cmd args`).
-/// Returns the remainder starting at the first non-assignment word.
-pub(in crate::security::policy) fn skip_env_assignments(s: &str) -> &str {
- let mut rest = s;
- loop {
- let Some(word) = rest.split_whitespace().next() else {
- return rest;
- };
- // Environment assignment: contains '=' and starts with a letter or underscore
- if word.contains('=')
- && word
- .chars()
- .next()
- .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
- {
- // Advance past this word
- rest = rest[word.len()..].trim_start();
- } else {
- return rest;
- }
- }
-}
diff --git a/crates/openhuman-core/src/security/policy/policy_command/mod.rs b/crates/openhuman-core/src/security/policy/policy_command/mod.rs
index d499cb3dde..8c822d021d 100644
--- a/crates/openhuman-core/src/security/policy/policy_command/mod.rs
+++ b/crates/openhuman-core/src/security/policy/policy_command/mod.rs
@@ -2,24 +2,19 @@
//! command-risk and allowlist gates.
//!
//! Split by responsibility:
-//! - [`env_guard`]: leading inline env-assignment detection.
-//! - [`command_name`]: basename normalization and "executes arbitrary code" bases.
-//! - [`quoting`]: quote-aware segment splitting, unquoted-character detection,
-//! and the quoted-heredoc body pre-pass.
+//! - [`env_guard`]: the dangerous inline env-assignment names.
+//! - [`command_name`]: the "executes arbitrary code" bases.
+//!
+//! The lexical scanning (quote-aware segment splitting, unquoted-character
+//! detection, quoted-heredoc blanking, basename and env-assignment parsing) is
+//! `tinybox_core::shell::scan`.
//! - [`classification`]: read/write/network/install/destructive bucket lists
//! and the hidden-execution structural guard.
mod classification;
mod command_name;
mod env_guard;
-mod quoting;
pub(super) use classification::{classify_segment, has_hidden_execution};
-pub(super) use command_name::{command_basename, is_command_executor, normalized_command_name};
-pub(super) use env_guard::{
- has_dangerous_env_prefix, has_leading_env_assignment, skip_env_assignments,
-};
-pub(super) use quoting::{
- contains_unquoted_char, contains_unquoted_single_ampersand, split_unquoted_segments,
- strip_quoted_heredoc_bodies,
-};
+pub(super) use command_name::is_command_executor;
+pub(super) use env_guard::has_dangerous_env_prefix;
diff --git a/crates/openhuman-core/src/security/policy/policy_command/quoting.rs b/crates/openhuman-core/src/security/policy/policy_command/quoting.rs
deleted file mode 100644
index 53ce1a9958..0000000000
--- a/crates/openhuman-core/src/security/policy/policy_command/quoting.rs
+++ /dev/null
@@ -1,445 +0,0 @@
-//! Quote-aware shell-string scanning: splitting a command into `;`/`|`/`&&`/
-//! `||`-separated segments, and detecting unquoted control characters
-//! (`&`, arbitrary redirects) without being fooled by quoted literals, plus a
-//! pre-pass that blanks quoted-heredoc bodies so document text is not scanned
-//! as shell syntax.
-
-use std::borrow::Cow;
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-enum QuoteState {
- None,
- Single,
- Double,
-}
-
-/// Split a shell command into sub-commands by unquoted separators.
-///
-/// Separators:
-/// - `;` and newline
-/// - `|`
-/// - `&&`, `||`
-///
-/// Characters inside single or double quotes are treated as literals, so
-/// `sqlite3 db "SELECT 1; SELECT 2;"` remains a single segment.
-pub(in crate::security::policy) fn split_unquoted_segments(command: &str) -> Vec<String> {
- let mut segments = Vec::new();
- let mut current = String::new();
- let mut quote = QuoteState::None;
- let mut escaped = false;
- let mut chars = command.chars().peekable();
-
- let push_segment = |segments: &mut Vec<String>, current: &mut String| {
- let trimmed = current.trim();
- if !trimmed.is_empty() {
- segments.push(trimmed.to_string());
- }
- current.clear();
- };
-
- while let Some(ch) = chars.next() {
- match quote {
- QuoteState::Single => {
- if ch == '\'' {
- quote = QuoteState::None;
- }
- current.push(ch);
- }
- QuoteState::Double => {
- if escaped {
- escaped = false;
- current.push(ch);
- continue;
- }
- if ch == '\\' {
- escaped = true;
- current.push(ch);
- continue;
- }
- if ch == '"' {
- quote = QuoteState::None;
- }
- current.push(ch);
- }
- QuoteState::None => {
- if escaped {
- escaped = false;
- current.push(ch);
- continue;
- }
- if ch == '\\' {
- escaped = true;
- current.push(ch);
- continue;
- }
-
- match ch {
- '\'' => {
- quote = QuoteState::Single;
- current.push(ch);
- }
- '"' => {
- quote = QuoteState::Double;
- current.push(ch);
- }
- ';' | '\n' => push_segment(&mut segments, &mut current),
- '|' => {
- if chars.next_if_eq(&'|').is_some() {
- // Consume full `||`; both characters are separators.
- }
- push_segment(&mut segments, &mut current);
- }
- '&' => {
- if chars.next_if_eq(&'&').is_some() {
- // `&&` is a separator; single `&` is handled separately.
- push_segment(&mut segments, &mut current);
- } else {
- current.push(ch);
- }
- }
- _ => current.push(ch),
- }
- }
- }
- }
-
- let trimmed = current.trim();
- if !trimmed.is_empty() {
- segments.push(trimmed.to_string());
- }
-
- segments
-}
-
-/// Detect a single unquoted `&` operator (background/chain). `&&` is allowed.
-///
-/// We treat any standalone `&` as unsafe in policy validation because it can
-/// chain hidden sub-commands and escape foreground timeout expectations.
-pub(in crate::security::policy) fn contains_unquoted_single_ampersand(command: &str) -> bool {
- let mut quote = QuoteState::None;
- let mut escaped = false;
- let mut chars = command.chars().peekable();
-
- while let Some(ch) = chars.next() {
- match quote {
- QuoteState::Single => {
- if ch == '\'' {
- quote = QuoteState::None;
- }
- }
- QuoteState::Double => {
- if escaped {
- escaped = false;
- continue;
- }
- if ch == '\\' {
- escaped = true;
- continue;
- }
- if ch == '"' {
- quote = QuoteState::None;
- }
- }
- QuoteState::None => {
- if escaped {
- escaped = false;
- continue;
- }
- if ch == '\\' {
- escaped = true;
- continue;
- }
- match ch {
- '\'' => quote = QuoteState::Single,
- '"' => quote = QuoteState::Double,
- '&' if chars.next_if_eq(&'&').is_none() => {
- return true;
- }
- _ => {}
- }
- }
- }
- }
-
- false
-}
-
-/// Like [`contains_unquoted_single_ampersand`] but ignores file-descriptor
-/// duplication redirects, where the `&` is part of a redirect operator rather
-/// than a background/separator: `2>&1`, `>&2` (prev char `>`), and `&>file`
-/// (next char `>`). Used by [`super::classification::has_hidden_execution`] so
-/// a benign `… 2>&1` — which `classify_command` already accounts for as a
-/// `Write` redirect — is not mistaken for a backgrounded command and
-/// hard-blocked after the human approved it. A standalone `&` (e.g. `cmd &`,
-/// `a & b`) still returns true, since it can run a second command
-/// `classify_command` wouldn't see.
-pub(super) fn contains_unquoted_background_ampersand(command: &str) -> bool {
- let mut quote = QuoteState::None;
- let mut escaped = false;
- let mut prev = '\0';
- let mut chars = command.chars().peekable();
-
- while let Some(ch) = chars.next() {
- match quote {
- QuoteState::Single => {
- if ch == '\'' {
- quote = QuoteState::None;
- }
- }
- QuoteState::Double => {
- if escaped {
- escaped = false;
- prev = ch;
- continue;
- }
- if ch == '\\' {
- escaped = true;
- prev = ch;
- continue;
- }
- if ch == '"' {
- quote = QuoteState::None;
- }
- }
- QuoteState::None => {
- if escaped {
- escaped = false;
- prev = ch;
- continue;
- }
- if ch == '\\' {
- escaped = true;
- prev = ch;
- continue;
- }
- match ch {
- '\'' => quote = QuoteState::Single,
- '"' => quote = QuoteState::Double,
- '&' => {
- if chars.next_if_eq(&'&').is_some() {
- // `&&` logical AND — consume both, not background.
- } else {
- let next = chars.peek().copied().unwrap_or('\0');
- // Skip fd-dup redirects: `2>&1`/`>&2` (prev `>`) and
- // `&>file` (next `>`).
- if prev != '>' && next != '>' {
- return true;
- }
- }
- }
- _ => {}
- }
- }
- }
- prev = ch;
- }
-
- false
-}
-
-/// Detect an unquoted character in a shell command.
-pub(in crate::security::policy) fn contains_unquoted_char(command: &str, target: char) -> bool {
- let mut quote = QuoteState::None;
- let mut escaped = false;
-
- for ch in command.chars() {
- match quote {
- QuoteState::Single => {
- if ch == '\'' {
- quote = QuoteState::None;
- }
- }
- QuoteState::Double => {
- if escaped {
- escaped = false;
- continue;
- }
- if ch == '\\' {
- escaped = true;
- continue;
- }
- if ch == '"' {
- quote = QuoteState::None;
- continue;
- }
- }
- QuoteState::None => {
- if escaped {
- escaped = false;
- continue;
- }
- if ch == '\\' {
- escaped = true;
- continue;
- }
- match ch {
- '\'' => quote = QuoteState::Single,
- '"' => quote = QuoteState::Double,
- _ if ch == target => return true,
- _ => {}
- }
- }
- }
- }
-
- false
-}
-
-/// Blank out the body of every **quoted-delimiter** heredoc in `command`.
-///
-/// `classify_command` and the structural guards scan the raw command string, so
-/// until now a heredoc body was read as live shell text. That is wrong for a
-/// quoted delimiter: in `cat > f << 'EOF' … EOF` the shell performs no
-/// expansion inside the body, so an `&`, a `` ` `` or a `$(` there is data.
-/// Measured consequence (life-scenario `meal-plan`): a recipe document was
-/// refused as "background (&) is not allowed" because four dinner titles read
-/// "Chicken & Spinach".
-///
-/// An **unquoted** delimiter (`<< EOF`) is deliberately left alone — expansion
-/// *is* live inside that body, so `$(rm -rf ~)` there really would execute and
-/// must keep tripping the guard.
-///
-/// Body lines are replaced by empty lines rather than removed, so line counts,
-/// the surrounding command text and the `>` of the redirect are all preserved:
-/// a heredoc write still classifies as [`CommandClass::Write`] and still
-/// prompts. Returns [`Cow::Borrowed`] when the command has no quoted heredoc,
-/// which is the overwhelmingly common case.
-pub(in crate::security::policy) fn strip_quoted_heredoc_bodies(command: &str) -> Cow<'_, str> {
- if !command.contains("<<") {
- return Cow::Borrowed(command);
- }
-
- let mut delimiters: Vec<String> = Vec::new();
- let mut quote = QuoteState::None;
- let mut escaped = false;
- let mut chars = command.char_indices().peekable();
- // Byte offsets of the `<<` operators whose delimiter is quoted, in order.
- let mut operators: Vec<usize> = Vec::new();
-
- while let Some((idx, ch)) = chars.next() {
- match quote {
- QuoteState::Single => {
- if ch == '\'' {
- quote = QuoteState::None;
- }
- }
- QuoteState::Double => {
- if escaped {
- escaped = false;
- continue;
- }
- match ch {
- '\\' => escaped = true,
- '"' => quote = QuoteState::None,
- _ => {}
- }
- }
- QuoteState::None => {
- if escaped {
- escaped = false;
- continue;
- }
- match ch {
- '\\' => escaped = true,
- '\'' => quote = QuoteState::Single,
- '"' => quote = QuoteState::Double,
- '<' if chars.next_if(|(_, c)| *c == '<').is_some() => {
- // `<<<` is a here-string, not a heredoc: no body follows.
- if chars.next_if(|(_, c)| *c == '<').is_some() {
- continue;
- }
- let rest = &command[idx + 2..];
- if let Some((delim, consumed)) = quoted_heredoc_delimiter(rest) {
- delimiters.push(delim);
- operators.push(idx);
- // Skip past the delimiter token so its quotes do not
- // re-enter the quote state machine.
- for _ in 0..consumed {
- chars.next();
- }
- }
- }
- _ => {}
- }
- }
- }
- }
-
- if operators.is_empty() {
- return Cow::Borrowed(command);
- }
-
- // Walk the lines. Once the line carrying the Nth operator ends, every
- // following line is body until its terminator line appears.
- let mut out = String::with_capacity(command.len());
- let mut next_delim = 0usize;
- let mut open: Option<String> = None;
- let mut consumed_bytes = 0usize;
-
- for line in command.split_inclusive('\n') {
- let line_start = consumed_bytes;
- consumed_bytes += line.len();
-
- if let Some(delim) = open.clone() {
- if line.trim() == delim {
- open = None;
- out.push_str(line);
- } else {
- // Blank the body, keeping the newline so offsets stay sane.
- if line.ends_with('\n') {
- out.push('\n');
- }
- }
- continue;
- }
-
- out.push_str(line);
- let line_end = line_start + line.len();
- while next_delim < operators.len() && operators[next_delim] < line_end {
- // The last operator on a line wins: `cat << 'A' << 'B'` reads A's
- // body first, but only tracking one at a time is enough for the
- // guard, and a nested case simply keeps scanning as today.
- open = Some(delimiters[next_delim].clone());
- next_delim += 1;
- }
- }
-
- Cow::Owned(out)
-}
-
-/// Parse a heredoc delimiter token immediately after `<<`, returning the
-/// delimiter and how many chars of `rest` it spans — **only** when the token is
-/// quoted (`'EOF'` or `"EOF"`), optionally preceded by `-` and whitespace.
-/// An unquoted delimiter returns `None`, because its body is still expanded.
-fn quoted_heredoc_delimiter(rest: &str) -> Option<(String, usize)> {
- let mut consumed = 0usize;
- let mut chars = rest.chars().peekable();
-
- if chars.peek() == Some(&'-') {
- chars.next();
- consumed += 1;
- }
- while chars.peek().is_some_and(|c| *c == ' ' || *c == '\t') {
- chars.next();
- consumed += 1;
- }
-
- let quote = match chars.next() {
- Some(q @ ('\'' | '"')) => q,
- _ => return None,
- };
- consumed += 1;
-
- let mut delim = String::new();
- for c in chars {
- consumed += 1;
- if c == quote {
- return (!delim.is_empty()).then_some((delim, consumed));
- }
- if c == '\n' {
- return None;
- }
- delim.push(c);
- }
- None
-}