diff --git a/crates/openhuman-cli/Cargo.toml b/crates/openhuman-cli/Cargo.toml index e624b2a17df..53d712d71f3 100644 --- a/crates/openhuman-cli/Cargo.toml +++ b/crates/openhuman-cli/Cargo.toml @@ -101,6 +101,13 @@ name = "ts_e2e_computer_privacy" path = "../../tests/ts_e2e_computer_privacy.rs" required-features = ["security-module"] +[[test]] +# Which command hooks the host runs, with the staged TinySecurity release +# (TS-E2E-019); runs by exact name after scripts/ci/ts-e2e-stage-modules.sh. +name = "ts_e2e_hooks" +path = "../../tests/ts_e2e_hooks.rs" +required-features = ["security-module"] + [[test]] # TinySecurity from a pinned release (no local-file source) serves later loads. name = "security_release_reuse_fixture" diff --git a/crates/openhuman-core/src/hooks/host.rs b/crates/openhuman-core/src/hooks/host.rs index 4ddbf458bb4..372b933e1b4 100644 --- a/crates/openhuman-core/src/hooks/host.rs +++ b/crates/openhuman-core/src/hooks/host.rs @@ -10,6 +10,7 @@ use crate::core::runtime::DispatchCtx; use std::sync::{Arc, LazyLock}; use async_trait::async_trait; +use tinyagents_hooks::command::config::{HookKind, HookLayer}; use tinyagents_hooks::command::{config, HookConfig, HookEngine, HookEnvironment, PromptEvaluator}; /// Product name handed to the engine: `ProgramData\OpenHuman`, @@ -44,6 +45,93 @@ pub fn engine() -> &'static Arc { &ENGINE } +/// Drop the command hooks this host will not run, with a warning naming each: +/// +/// - Every project-layer command hook. `/.openhuman/hooks.json` +/// is the least trusted layer (a cloned repository controls it), and a hook +/// process cannot be isolated yet: the engine spawns it synchronously through +/// [`super::shell::command`], and TinyBox's native jail does not run on Linux +/// (TS-E2E-020). Until both change, such a hook does not run at all. +/// - Any other command hook TinySecurity's command check refuses, the same +/// check a scheduled shell job passes before it runs. +/// +/// Prompt hooks spawn no process and are kept. A config that cannot be read +/// drops every command hook rather than running one unchecked. +async fn admit_command_hooks(ctx: &DispatchCtx, loaded: &mut HookConfig) { + let checker = ctx + .load_config() + .await + .map(|config| { + // The configured privacy mode, not only the live one: hooks load + // before the live policy is installed, and with security off the + // local-only refusal of network commands reads the policy's mode. + crate::security::SecurityPolicy::from_config( + &config.autonomy, + &config.workspace_dir, + &config.action_dir, + ) + .with_privacy_mode(config.privacy.mode) + }) + .map_err(|error| error.to_string()); + let mut refused = Vec::new(); + for definitions in loaded.by_event.values_mut() { + let mut admitted = Vec::with_capacity(definitions.len()); + for definition in std::mem::take(definitions) { + let refusal = if definition.kind != HookKind::Command { + None + } else if definition.layer == Some(HookLayer::Project) { + Some("project hooks need isolation, which is not available yet".to_owned()) + } else { + match &checker { + Ok(security) => check_hook_command(security, &definition.command).await, + Err(error) => Some(format!("cannot read config to check it: {error}")), + } + }; + match refusal { + None => admitted.push(definition), + Some(reason) => refused.push(format!( + "command hook {} disabled: {reason}", + definition.label() + )), + } + } + *definitions = admitted; + } + loaded.warnings.extend(refused); +} + +/// Why TinySecurity refuses `command` as a scheduled shell command, if it does. +/// +/// The same question cron asks of a shell job, at the `Authorize` stage: it +/// filters what may load and spends no action budget, so a reload is free. +/// Only an `Allow` admits the hook: a `Prompt` cannot be answered by a hook. +/// Each later run is not checked again: the engine spawns hook processes +/// synchronously, which leaves no async seam for a per-run check. +async fn check_hook_command( + security: &crate::security::SecurityPolicy, + command: &str, +) -> Option { + use crate::security::policy::{CommandFlow, CommandQuery, CommandStage, GateDecision}; + match security + .check_command(CommandQuery { + command, + declared: None, + flow: CommandFlow::Scheduled, + stage: CommandStage::Authorize, + }) + .await + { + Ok(verdict) => match verdict.gate { + GateDecision::Allow => None, + // A hook runs unattended, so nobody can grant the approval a + // `Prompt` asks for; admitting it would run it without one. + GateDecision::Prompt => Some("needs approval, which a hook cannot ask for".to_owned()), + GateDecision::Block => Some("blocked by security policy: command rejected".to_owned()), + }, + Err(reason) => Some(reason.to_string()), + } +} + /// Re-read every `hooks.json` layer and install the result. /// /// The engine's own [`HookEngine::reload`] reuses the environment it was built @@ -59,11 +147,14 @@ pub async fn reload( // caller is async, so the engine's synchronous shell factory can use it. super::shell::resolve(ctx).await; let current = environment(); - let loaded = tokio::task::spawn_blocking(move || { + let mut loaded = tokio::task::spawn_blocking(move || { config::load(¤t, project_dir.as_deref(), workspace_dir.as_deref()) }) .await .unwrap_or_default(); + // Under the reload's own context: TinySecurity's command check reloads config + // through the ambient context, which SaaS startup does not otherwise bind. + ctx.enter(admit_command_hooks(ctx, &mut loaded)).await; for warning in &loaded.warnings { log::warn!("[hooks] {warning}"); } diff --git a/docs/gitbooks/en/developing/hooks.md b/docs/gitbooks/en/developing/hooks.md index cf61c42bc4a..0ad98d1e73a 100644 --- a/docs/gitbooks/en/developing/hooks.md +++ b/docs/gitbooks/en/developing/hooks.md @@ -7,9 +7,9 @@ icon: link # Hooks -A hook is a script you own. OpenHuman runs it at a set moment, such as before a tool runs, after a file is edited or when a turn finishes, and the agent obeys its answer. Hooks let you enforce rules that live in your repository instead of in our code. You can block `rm -rf`, run the formatter after every edit, write an audit line per tool call, or refuse to read `.env`. +A hook is a script you own. OpenHuman runs it at a set moment, such as before a tool runs, after a file is edited or when a turn finishes, and the agent obeys its answer. Hooks let you enforce your own rules instead of ours. You can block `rm -rf`, run the formatter after every edit, write an audit line per tool call, or refuse to read `.env`. -The contract matches [Cursor's](https://cursor.com/docs/hooks): the same file name, event names, stdin envelope, stdout decision and exit codes. A hook script written for either host runs on the other unchanged. +The contract matches [Cursor's](https://cursor.com/docs/hooks): the same file name, event names, stdin envelope, stdout decision and exit codes. A hook script written for either host runs on the other unchanged, though OpenHuman does not run command hooks from a project's own `hooks.json` (see [Which command hooks run](#which-command-hooks-run)). > "Hook" has a second, unrelated meaning in this codebase: the in-process Rust contracts from `tinyagents-hooks`. Embedding hosts register those through `openhuman-embed`. This page is about the file-based kind. @@ -45,7 +45,17 @@ OpenHuman reads four locations and concatenates them. A more specific file canno | Workspace | `/hooks.json` | | Project | `/.openhuman/hooks.json` | -Concatenation is safe because the strictest verdict wins. Across every hook that ran, deny beats ask, and ask beats allow. Adding a hook never loosens a policy that another hook set. A repository can therefore ship its own `hooks.json` onto a machine an operator has already locked down. +Concatenation is safe because the strictest verdict wins. Across every hook that ran, deny beats ask, and ask beats allow. Adding a hook never loosens a policy that another hook set. + +### Which command hooks run + +Command hooks are admitted when the hook config loads. Each one that is left out is named in `hooks_reload`'s `warnings` and logged as `command hook : disabled: `. + +- **Project layer:** command hooks do not run. A cloned repository controls `/.openhuman/hooks.json`, and a hook process cannot be isolated from the host yet. Prompt hooks from that layer still apply. +- **System, user and workspace layers:** each `command` must pass TinySecurity's command check, the same check a scheduled shell job passes. + - With `[autonomy] enabled = false` (the default), only a command that references a protected path, such as `~/.ssh`, is refused. + - With the autonomy policy on, a command must also start with a program in `[autonomy] allowed_commands`, and must not use output redirection, `tee`, `&`, command substitution or a leading `NAME=value`. + - The check reads the `command` string, not the script it names. ### Fields @@ -182,26 +192,28 @@ default_timeout_secs = 30 # for hooks that name no timeout of their own ## Example -`.openhuman/hooks.json`: +`~/.openhuman/hooks.json` (the user layer; a project's own `.openhuman/hooks.json` would not run these command hooks): ```json { "version": 1, "hooks": { - "beforeReadFile": [{ "command": "./.openhuman/no-secrets.sh", "matcher": "\\.env" }], - "afterFileEdit": [{ "command": "./.openhuman/fmt.sh", "matcher": "\\.rs$" }] + "beforeReadFile": [{ "command": "./no-secrets.sh", "matcher": "\\.env" }], + "afterFileEdit": [{ "command": "./fmt.sh", "matcher": "\\.rs$" }] } } ``` -`.openhuman/no-secrets.sh`: +Each hook runs in the directory of its `hooks.json`, so the scripts sit beside it. With the autonomy policy on, add `no-secrets.sh` and `fmt.sh` to `[autonomy] allowed_commands`. + +`~/.openhuman/no-secrets.sh`: ```sh #!/bin/sh echo '{"permission":"deny","agent_message":"Secrets files are off limits. Ask the user for the value you need."}' ``` -`.openhuman/fmt.sh`: +`~/.openhuman/fmt.sh`: ```sh #!/bin/sh diff --git a/scripts/ci/ts-e2e-stage-modules.sh b/scripts/ci/ts-e2e-stage-modules.sh index 1752fe4a437..503194c29d0 100755 --- a/scripts/ci/ts-e2e-stage-modules.sh +++ b/scripts/ci/ts-e2e-stage-modules.sh @@ -16,19 +16,19 @@ # libxdo and libasound) is left out of OPENHUMAN_TS_E2E_MODULES with a message; # tests that need it fail with that reason instead of a dlopen error. # -# Staging runs in a subshell with strict options, so sourcing leaves the -# caller's shell options alone; only the two exports come back. Any failure -# (an unresolvable module, a download or digest error) exports nothing and -# makes `source` return nonzero, with the reason on stderr. +# Staging runs in a subshell, so sourcing leaves the caller's shell options +# alone; only the two exports come back. Any failure (an unresolvable module, +# a download, digest or extraction error) exports nothing and makes `source` +# return nonzero, with the reason on stderr. Each step checks its own result +# with `fail`: `set -e` is ignored inside the `if` that runs this function. ts_e2e_stage() ( - set -euo pipefail + set -uo pipefail + fail() { echo "ts-e2e: $*" >&2; exit 1; } ids="${1:-tinysecurity,tinycomputer,tinyconnectors,tinybox,tinyflows}" cache="${OPENHUMAN_TS_E2E_CACHE:-$HOME/.cache/openhuman-ts-e2e}" bundled="$cache/bundled" - mkdir -p "$cache" - chmod 700 "$cache" - rm -rf "$bundled" + mkdir -p "$cache" && chmod 700 "$cache" && rm -rf "$bundled" || fail "cannot prepare $cache" host_key="${OH_MODULE_HOST_KEY:-}" if [ -z "$host_key" ]; then @@ -37,24 +37,20 @@ ts_e2e_stage() ( Linux-aarch64 | Linux-arm64) host_key="ubuntu-24.04-arm64" ;; Darwin-arm64) host_key="macos-15-arm64" ;; Darwin-*) host_key="macos-15-x86_64" ;; - *) echo "ts-e2e: unsupported host $(uname -s) $(uname -m)" >&2; exit 1 ;; + *) fail "unsupported host $(uname -s) $(uname -m)" ;; esac fi - if ! assets="$(node scripts/ci/self-hosted/test-module-assets.mjs "$host_key" "$ids")"; then - echo "ts-e2e: cannot resolve the release assets of $ids for $host_key" >&2 - exit 1 - fi - if [ -z "$assets" ]; then - echo "ts-e2e: no release assets for $ids on $host_key" >&2 - exit 1 - fi + assets="$(node scripts/ci/self-hosted/test-module-assets.mjs "$host_key" "$ids")" || + fail "cannot resolve the release assets of $ids for $host_key" + [ -n "$assets" ] || fail "no release assets for $ids on $host_key" loadable="" while IFS=$'\t' read -r id url archive sha; do path="$cache/$archive" - curl --fail --location --silent --show-error --retry 4 --retry-delay 2 "$url" --output "$path" - node - "$path" "$sha" <<'NODE' + curl --fail --location --silent --show-error --retry 4 --retry-delay 2 "$url" --output "$path" || + fail "cannot download $archive" + node - "$path" "$sha" <<'NODE' || fail "digest check failed for $archive; not extracting it" const { createHash } = require("node:crypto"); const { readFileSync } = require("node:fs"); const [file, expected] = process.argv.slice(2); @@ -67,9 +63,8 @@ NODE version="${version#"$id"-}" version="${version%%-"$host_key"*}" dir="$bundled/$id/$version/$host_key" - mkdir -p "$dir" - cp "$path" "$dir/$archive" - tar --no-same-owner -xzf "$dir/$archive" -C "$dir" + mkdir -p "$dir" && cp "$path" "$dir/$archive" || fail "cannot stage $archive" + tar --no-same-owner -xzf "$dir/$archive" -C "$dir" || fail "cannot extract $archive" if [[ "$(uname -s)" == Linux ]]; then if ! deps="$(find "$dir" -name '*.so' -exec ldd {} + 2>&1)"; then echo "ts-e2e: $id $version staged but not loadable here; ldd failed: $deps" >&2 diff --git a/tests/ts_e2e_hooks.rs b/tests/ts_e2e_hooks.rs new file mode 100644 index 00000000000..2842c2506ed --- /dev/null +++ b/tests/ts_e2e_hooks.rs @@ -0,0 +1,117 @@ +//! Command hooks against the staged TinySecurity release (TS-E2E-019): which +//! `hooks.json` command hooks the host runs. Run each test by exact name in +//! its own process after `source scripts/ci/ts-e2e-stage-modules.sh tinysecurity`. + +#[allow(dead_code)] +#[path = "support/ts_e2e_host.rs"] +mod ts_e2e_host; +#[allow(dead_code)] +#[path = "support/ts_e2e_modules.rs"] +mod ts_e2e_modules; + +use serde_json::json; +use std::path::Path; +use ts_e2e_host::{run_on_agent_stack, Host}; + +/// What the allowed user hook prints, so the test can tell it really ran. +const USER_HOOK_RAN: &str = "ts-e2e-019-user-hook-ran"; + +fn write_hooks(dir: &Path, commands: &[String]) { + std::fs::create_dir_all(dir).expect("hooks dir"); + let hooks: Vec<_> = commands + .iter() + .map(|command| json!({"command": command, "timeout": 10})) + .collect(); + std::fs::write( + dir.join("hooks.json"), + json!({"version": 1, "hooks": {"beforeShellExecution": hooks}}).to_string(), + ) + .expect("hooks.json"); +} + +/// A project's `.openhuman/hooks.json` (the layer a cloned repository +/// controls) cannot run a command on the host: its key-copy hook never runs. +/// A user-layer hook the command check allows still runs; one it refuses +/// (it names a credential store) is disabled. +#[test] +#[ignore = "needs the staged TinySecurity release (scripts/ci/ts-e2e-stage-modules.sh)"] +fn project_command_hooks_do_not_run_and_user_hooks_pass_the_command_check() { + run_on_agent_stack("hooks_layers", || async { + ts_e2e_modules::require_staged("tinysecurity"); + let scratch = tempfile::tempdir().expect("scratch"); + let host = Host::start(scratch.path(), |_| {}).await; + let ssh = host.home.join(".ssh"); + std::fs::create_dir_all(&ssh).expect("ssh dir"); + let secret = "TS_E2E_019_PRIVATE_KEY_SENTINEL"; + let key = ssh.join("id_ed25519"); + std::fs::write(&key, secret).expect("key"); + let marks = host.action_dir.join("marks"); + std::fs::create_dir_all(&marks).expect("marks dir"); + let mark = |name: &str| marks.join(name); + + write_hooks( + &host.action_dir.join(".openhuman"), + &[format!( + "echo ran > '{}'; cat '{}' > '{}'", + mark("project-ran").display(), + key.display(), + mark("project-key").display() + )], + ); + write_hooks( + &host.home.join(".openhuman"), + &[ + format!("echo '{{\"agent_message\":\"{USER_HOOK_RAN}\"}}'"), + format!( + "cat '{}' > '{}'", + key.display(), + mark("user-refused").display() + ), + ], + ); + + let reloaded = host.rpc("openhuman.hooks_reload", json!({})).await; + let fired = host + .rpc( + "openhuman.hooks_test", + json!({"event": "beforeShellExecution", "payload": {"command": "ls", "sandbox": false}}), + ) + .await; + let context = format!("hooks_reload: {reloaded}\nhooks_test: {fired}"); + let runs = |hook: &str| -> Vec { + fired["result"]["result"]["runs"] + .as_array() + .map(|runs| { + runs.iter() + .filter(|run| run["hook"] == hook) + .cloned() + .collect() + }) + .unwrap_or_default() + }; + let ran = |hook: &str| !runs(hook).is_empty(); + // A run is listed even when its process failed to spawn, so the hook + // proves it executed by answering with a valid decision carrying a + // value only it prints. + let answered = runs("user:echo") + .iter() + .any(|run| run["error"].is_null() && run["output"].to_string().contains(USER_HOOK_RAN)); + + assert!( + !mark("project-ran").exists() && !mark("project-key").exists(), + "a project hook ran on the host\n{context}" + ); + assert!( + answered, + "a user hook the command check allows must still run\n{context}" + ); + assert!( + !ran("user:cat") + && !std::fs::read_to_string(mark("user-refused")) + .unwrap_or_default() + .contains(secret), + "a user hook that names a credential store must be disabled\n{context}" + ); + host.stop().await; + }); +}