From 1ee04bb23b69566422dab8c72dad25d96494890f Mon Sep 17 00:00:00 2001 From: M3gA-Mind Date: Thu, 5 Nov 2026 21:28:22 +0530 Subject: [PATCH 1/5] test(hooks): which hooks.json command hooks the host runs With the staged TinySecurity release: a project-layer hook that copies a private key, a user-layer echo, and a user-layer hook that names the key. On main the project hook runs on the host and copies the key, and so does the user hook that names it (TS-E2E-019). --- crates/openhuman-cli/Cargo.toml | 7 +++ tests/ts_e2e_hooks.rs | 101 ++++++++++++++++++++++++++++++++ 2 files changed, 108 insertions(+) create mode 100644 tests/ts_e2e_hooks.rs 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/tests/ts_e2e_hooks.rs b/tests/ts_e2e_hooks.rs new file mode 100644 index 00000000000..058908899d3 --- /dev/null +++ b/tests/ts_e2e_hooks.rs @@ -0,0 +1,101 @@ +//! 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}; + +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"), + &[ + "echo ran".to_owned(), + 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 ran = |hook: &str| { + fired["result"]["result"]["runs"] + .as_array() + .is_some_and(|runs| runs.iter().any(|run| run["hook"] == hook)) + }; + + assert!( + !mark("project-ran").exists() && !mark("project-key").exists(), + "a project hook ran on the host\n{context}" + ); + assert!( + ran("user:echo"), + "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; + }); +} From f3be91e4a010a163b00a974b0823e1e97da124e9 Mon Sep 17 00:00:00 2001 From: M3gA-Mind Date: Thu, 5 Nov 2026 21:28:22 +0530 Subject: [PATCH 2/5] fix(hooks): check command hooks with TinySecurity and stop running project hooks A command hook ran on the host with no TinySecurity check, including hooks from a project's .openhuman/hooks.json, the layer a cloned repository controls. A project could copy credentials out on the next shell call. Hooks are now admitted when they load. Every project-layer command hook is dropped with a warning: it cannot be isolated yet, because the engine spawns hook processes synchronously and TinyBox's native jail does not run on Linux (TS-E2E-020). Every other command hook passes the same command check a scheduled shell job does, and a refused one is dropped with a warning. A config that cannot be read drops every command hook. Prompt hooks spawn nothing and are unchanged. Fixes TS-E2E-019. --- crates/openhuman-core/src/hooks/host.rs | 64 ++++++++++++++++++++++++- 1 file changed, 63 insertions(+), 1 deletion(-) diff --git a/crates/openhuman-core/src/hooks/host.rs b/crates/openhuman-core/src/hooks/host.rs index 4ddbf458bb4..58077294005 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,66 @@ 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| { + let security = crate::security::SecurityPolicy::from_config( + &config.autonomy, + &config.workspace_dir, + &config.action_dir, + ); + (config, security) + }) + .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((config, security)) => { + crate::cron::scheduler::shell_job::authorize_shell_command( + config, + security, + &definition.command, + ) + .await + .err() + } + 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); +} + /// Re-read every `hooks.json` layer and install the result. /// /// The engine's own [`HookEngine::reload`] reuses the environment it was built @@ -59,11 +120,12 @@ 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(); + admit_command_hooks(ctx, &mut loaded).await; for warning in &loaded.warnings { log::warn!("[hooks] {warning}"); } From ee3cb9290a7c75785a54e1abacac67a63b041ed8 Mon Sep 17 00:00:00 2001 From: M3gA-Mind Date: Fri, 6 Nov 2026 11:49:29 +0530 Subject: [PATCH 3/5] fix(hooks): admit command hooks without spending budget, under the reload context Admission asked TinySecurity at the Execute stage, so every reload spent one action of the hourly budget per hook. It now asks at Authorize, which filters what may load and spends nothing. Each later run is not charged: the engine spawns hook processes synchronously, which leaves no async seam for a per-run check (the same gap that keeps project hooks from being jailed). The check now runs under the reload's own context (DispatchCtx::enter): TinySecurity's command check reloads config through the ambient context, which SaaS startup does not bind, so every non-project command hook was dropped there. docs/gitbooks/en/developing/hooks.md now says project-layer command hooks do not run, what the command check refuses, and moves the example to the user layer. --- crates/openhuman-core/src/hooks/host.rs | 47 ++++++++++++++++++------- docs/gitbooks/en/developing/hooks.md | 28 ++++++++++----- 2 files changed, 54 insertions(+), 21 deletions(-) diff --git a/crates/openhuman-core/src/hooks/host.rs b/crates/openhuman-core/src/hooks/host.rs index 58077294005..a86425b0f65 100644 --- a/crates/openhuman-core/src/hooks/host.rs +++ b/crates/openhuman-core/src/hooks/host.rs @@ -62,12 +62,11 @@ async fn admit_command_hooks(ctx: &DispatchCtx, loaded: &mut HookConfig) { .load_config() .await .map(|config| { - let security = crate::security::SecurityPolicy::from_config( + crate::security::SecurityPolicy::from_config( &config.autonomy, &config.workspace_dir, &config.action_dir, - ); - (config, security) + ) }) .map_err(|error| error.to_string()); let mut refused = Vec::new(); @@ -80,15 +79,7 @@ async fn admit_command_hooks(ctx: &DispatchCtx, loaded: &mut HookConfig) { Some("project hooks need isolation, which is not available yet".to_owned()) } else { match &checker { - Ok((config, security)) => { - crate::cron::scheduler::shell_job::authorize_shell_command( - config, - security, - &definition.command, - ) - .await - .err() - } + Ok(security) => check_hook_command(security, &definition.command).await, Err(error) => Some(format!("cannot read config to check it: {error}")), } }; @@ -105,6 +96,34 @@ async fn admit_command_hooks(ctx: &DispatchCtx, loaded: &mut HookConfig) { 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. +/// 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) if verdict.gate == GateDecision::Block => { + Some("blocked by security policy: command rejected".to_owned()) + } + Ok(_) => None, + 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 @@ -125,7 +144,9 @@ pub async fn reload( }) .await .unwrap_or_default(); - admit_command_hooks(ctx, &mut loaded).await; + // 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 From c4145d52157bc888e7e35c1d7ab20bc50122b7a8 Mon Sep 17 00:00:00 2001 From: M3gA-Mind Date: Fri, 6 Nov 2026 14:45:24 +0530 Subject: [PATCH 4/5] fix(hooks): admit hooks under the configured privacy mode; prove the user hook ran Hook admission built its policy with from_config, which leaves the privacy mode Standard. Hooks load before the live policy is installed, and with security off the local-only refusal of network commands reads only the policy's mode or the live one, so under [privacy] mode = "local_only" a hook such as curl was admitted. The admission policy now carries config.privacy.mode. The staging script no longer relies on set -e, which bash ignores inside the if that runs it: every step (prepare, download, digest, copy, extract, resolve) checks its own result, so a failed download or a digest mismatch fails staging before tar sees the archive, and nothing is exported. ts_e2e_hooks: a run is listed even when its process failed to spawn, so the allowed user hook now answers with a valid decision carrying a value only it prints, and the test requires that value and a null error. --- crates/openhuman-core/src/hooks/host.rs | 4 +++ scripts/ci/ts-e2e-stage-modules.sh | 39 +++++++++++-------------- tests/ts_e2e_hooks.rs | 24 ++++++++++++--- 3 files changed, 41 insertions(+), 26 deletions(-) diff --git a/crates/openhuman-core/src/hooks/host.rs b/crates/openhuman-core/src/hooks/host.rs index a86425b0f65..b3c7fb27c6e 100644 --- a/crates/openhuman-core/src/hooks/host.rs +++ b/crates/openhuman-core/src/hooks/host.rs @@ -62,11 +62,15 @@ async fn admit_command_hooks(ctx: &DispatchCtx, loaded: &mut HookConfig) { .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(); 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 index 058908899d3..2842c2506ed 100644 --- a/tests/ts_e2e_hooks.rs +++ b/tests/ts_e2e_hooks.rs @@ -13,6 +13,9 @@ 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 @@ -58,7 +61,7 @@ fn project_command_hooks_do_not_run_and_user_hooks_pass_the_command_check() { write_hooks( &host.home.join(".openhuman"), &[ - "echo ran".to_owned(), + format!("echo '{{\"agent_message\":\"{USER_HOOK_RAN}\"}}'"), format!( "cat '{}' > '{}'", key.display(), @@ -75,18 +78,31 @@ fn project_command_hooks_do_not_run_and_user_hooks_pass_the_command_check() { ) .await; let context = format!("hooks_reload: {reloaded}\nhooks_test: {fired}"); - let ran = |hook: &str| { + let runs = |hook: &str| -> Vec { fired["result"]["result"]["runs"] .as_array() - .is_some_and(|runs| runs.iter().any(|run| run["hook"] == hook)) + .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!( - ran("user:echo"), + answered, "a user hook the command check allows must still run\n{context}" ); assert!( From 4a4d9ee73576b70e949539a982e5b5953215cc9d Mon Sep 17 00:00:00 2001 From: M3gA-Mind Date: Fri, 6 Nov 2026 18:14:24 +0530 Subject: [PATCH 5/5] fix(hooks): do not admit a command hook whose check asks for approval check_hook_command refused only a Block gate. Under supervised autonomy with approval enabled an allowlisted command can come back Prompt, and a hook runs unattended, so admitting it ran the command without the approval it needs. Only Allow now admits the hook; Prompt is dropped with "needs approval, which a hook cannot ask for". --- crates/openhuman-core/src/hooks/host.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/crates/openhuman-core/src/hooks/host.rs b/crates/openhuman-core/src/hooks/host.rs index b3c7fb27c6e..372b933e1b4 100644 --- a/crates/openhuman-core/src/hooks/host.rs +++ b/crates/openhuman-core/src/hooks/host.rs @@ -104,6 +104,7 @@ async fn admit_command_hooks(ctx: &DispatchCtx, loaded: &mut HookConfig) { /// /// 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( @@ -120,10 +121,13 @@ async fn check_hook_command( }) .await { - Ok(verdict) if verdict.gate == GateDecision::Block => { - Some("blocked by security policy: command rejected".to_owned()) - } - Ok(_) => None, + 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()), } }