From d83771b6df64c6ab16a967ffc82d089307b1fded Mon Sep 17 00:00:00 2001 From: Maciej Myszkiewicz Date: Fri, 9 Oct 2026 23:56:20 +0200 Subject: [PATCH 01/11] fix(security): carve the account dir's secrets and privilege files out of agent surface MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `is_workspace_internal_path` carved out `config.toml` alone (#5505), leaving four siblings in the account dir reachable through a trusted root over it: - `.secret_key`, the keyring's on-disk encryption key. `is_always_forbidden` covers ~/.ssh, ~/.gnupg, ~/.aws and the Windows DPAPI stores, not this one. - `auth-profiles.json`, the credential profiles that key decrypts. - `config.toml.bak`, the config being replaced, preserved on save by `config::schema::load::atomic_commit` — the same autonomy settings and `files_dir_history` one save behind. - `claude_code_settings.json`, where `full_access` switches the Claude Code provider to `--permission-mode bypassPermissions` with no `--disallowedTools`, i.e. its full native toolset incl. Bash and network. Those calls do not reach the approval gate either: that provider advertises `tool_calling: false` because it runs its tools internally and never returns them to the harness, so `ApprovalSecurityMiddleware` never sees them. Matched by name within the account dir, so the #5505 model is unchanged: the directory stays reachable and only the carve-out list grows. A directory rule was the first attempt and is wrong — a turn-workspace checkout and a granted trusted root both legitimately sit beside the workspace, so `write_into_the_scoped_turn_root_is_allowed` and `trusted_readwrite_root_allows_write` fail under it. Only reachable with `[autonomy] enabled = true` plus a trusted root over the account dir (or `workspace_only = false`); with the policy off — the shipped default — `is_path_string_allowed` returns before this check. Defence in depth for the posture that opted into containment, which is the posture the existing carve-out was added for. --- .../src/security/policy/path_checks.rs | 36 +++++-- .../policy/policy_workspace_internal_tests.rs | 93 +++++++++++++++++++ .../src/security/policy/types.rs | 15 ++- 3 files changed, 134 insertions(+), 10 deletions(-) diff --git a/crates/openhuman-core/src/security/policy/path_checks.rs b/crates/openhuman-core/src/security/policy/path_checks.rs index 2ce92958193..edd6427be95 100644 --- a/crates/openhuman-core/src/security/policy/path_checks.rs +++ b/crates/openhuman-core/src/security/policy/path_checks.rs @@ -2,7 +2,7 @@ use std::path::{Path, PathBuf}; use super::types::{SecurityPolicy, TrustedAccess, POLICY_BLOCKED_MARKER}; use super::types::{ - ACCOUNT_CONFIG_FILE, ARTIFACTS_DIR, ARTIFACT_TOOL_RESULTS_DIR, WORKSPACE_INTERNAL_DIRS, + ACCOUNT_INTERNAL_FILES, ARTIFACTS_DIR, ARTIFACT_TOOL_RESULTS_DIR, WORKSPACE_INTERNAL_DIRS, WORKSPACE_INTERNAL_FILES, }; @@ -394,13 +394,35 @@ impl SecurityPolicy { (Ok(w), Ok(p)) => (w.as_path(), p.as_path()), _ => (self.workspace_dir.as_path(), path), }; - // The account config (`/config.toml`, the workspace's - // sibling) holds the autonomy policy itself and the files folders the - // artifact escape guard trusts (`files_dir_override`, - // `files_dir_history`, #5505). A trusted root over the account or data - // dir must not let the agent rewrite either. + // The account dir (`/`, the workspace's parent) is + // reachable on purpose: a trusted root over it grants its files, and + // #5505 carved out `config.toml` alone because that one holds the + // autonomy policy and the folders the artifact escape guard trusts. + // + // Four more files there carry secrets or privilege and belong in the + // same carve-out. `.secret_key` is the keyring's on-disk encryption key + // and `auth-profiles.json` the credential profiles it decrypts — + // `is_always_forbidden` covers `~/.ssh` and friends but not these. + // `config.toml.bak` is the config one save behind, written by + // `config::schema::load::atomic_commit`. And `claude_code_settings.json` + // switches the Claude Code provider to `--permission-mode + // bypassPermissions` with its full native toolset (Bash, network) — + // calls that never reach the approval gate, because that provider runs + // its tools internally and never returns them to the harness. + // + // Matched by name within the account dir, which keeps every other file + // there reachable exactly as before. if let Some(account_dir) = ws.parent() { - if check_path == account_dir.join(ACCOUNT_CONFIG_FILE) { + if check_path.parent() == Some(account_dir) + && check_path + .file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| ACCOUNT_INTERNAL_FILES.contains(&name)) + { + log::trace!( + "[security:policy] account-dir core state is not agent surface (path={})", + check_path.display() + ); return true; } } diff --git a/crates/openhuman-core/src/security/policy/policy_workspace_internal_tests.rs b/crates/openhuman-core/src/security/policy/policy_workspace_internal_tests.rs index b01c572d603..51c7830ebca 100644 --- a/crates/openhuman-core/src/security/policy/policy_workspace_internal_tests.rs +++ b/crates/openhuman-core/src/security/policy/policy_workspace_internal_tests.rs @@ -279,3 +279,96 @@ async fn the_account_config_beside_the_workspace_is_internal() { .is_err()); assert!(policy.validate_path(¬es.to_string_lossy()).await.is_ok()); } + +/// #5505 carved out `config.toml` alone, leaving four siblings that carry +/// secrets or privilege agent-reachable: the keyring's on-disk encryption key, +/// the credential profiles it decrypts, the config one save behind, and the +/// Claude Code `full_access` toggle (which switches that provider to +/// `--permission-mode bypassPermissions` with its full native toolset, whose +/// calls never reach the approval gate). +#[test] +fn account_dir_secrets_and_privilege_files_are_internal() { + let tmp = tempfile::tempdir().expect("tempdir"); + let account = tmp.path().join("users").join("u1"); + let ws = account.join("workspace"); + std::fs::create_dir_all(&ws).expect("create workspace"); + let policy = SecurityPolicy { + workspace_dir: ws, + action_dir: tmp.path().join("projects"), + ..SecurityPolicy::default() + }; + + // Pinned before this change, and unchanged by it. + assert!(policy.is_workspace_internal_path(&account.join("config.toml"))); + // Each of these was reachable before it. + for name in [ + "config.toml.bak", + ".secret_key", + "auth-profiles.json", + "claude_code_settings.json", + ] { + assert!( + policy.is_workspace_internal_path(&account.join(name)), + "{name} must not be part of the agent's action surface" + ); + } +} + +/// The account dir stays reachable otherwise — that is deliberate (#5505), and +/// the carve-out must not widen into a containment boundary. A same-named file +/// elsewhere is likewise none of the policy's business. +#[test] +fn account_dir_carve_out_does_not_capture_unrelated_files() { + let tmp = tempfile::tempdir().expect("tempdir"); + let account = tmp.path().join("users").join("u1"); + let ws = account.join("workspace"); + let action = tmp.path().join("projects"); + std::fs::create_dir_all(&ws).expect("create workspace"); + std::fs::create_dir_all(&action).expect("create action dir"); + let policy = SecurityPolicy { + workspace_dir: ws, + action_dir: action.clone(), + ..SecurityPolicy::default() + }; + + assert!(!policy.is_workspace_internal_path(&account.join("notes.txt"))); + assert!(!policy.is_workspace_internal_path(&account.join("checkout"))); + // A project of the user's own that happens to carry one of these names is + // not account state — the match is scoped to the account dir itself. + assert!(!policy.is_workspace_internal_path(&action.join("claude_code_settings.json"))); + assert!(!policy.is_workspace_internal_path(&action.join("app").join(".secret_key"))); +} + +/// End to end through the gate every file tool goes through, with a trusted +/// root over the account dir — the configuration the carve-out exists for. +#[tokio::test] +async fn trusted_root_over_the_account_dir_cannot_reach_the_keyring_key() { + let tmp = tempfile::tempdir().expect("tempdir"); + let account = tmp.path().join("users").join("u1"); + let ws = account.join("workspace"); + std::fs::create_dir_all(&ws).expect("create workspace"); + let key = account.join(".secret_key"); + std::fs::write(&key, "key material").expect("write key"); + let settings = account.join("claude_code_settings.json"); + std::fs::write(&settings, "{}").expect("write settings"); + let policy = SecurityPolicy { + workspace_dir: ws, + action_dir: tmp.path().join("projects"), + workspace_only: false, + trusted_roots: vec![TrustedRoot { + path: account.to_string_lossy().into_owned(), + access: TrustedAccess::ReadWrite, + }], + ..SecurityPolicy::default() + }; + + for path in [&key, &settings] { + let shown = path.to_string_lossy(); + assert!(!policy.is_path_string_allowed(&shown), "{shown}"); + assert!(policy.validate_path(&shown).await.is_err(), "{shown}"); + assert!( + policy.validate_parent_path(&shown).await.is_err(), + "{shown}" + ); + } +} diff --git a/crates/openhuman-core/src/security/policy/types.rs b/crates/openhuman-core/src/security/policy/types.rs index f658e5e7219..79662da8453 100644 --- a/crates/openhuman-core/src/security/policy/types.rs +++ b/crates/openhuman-core/src/security/policy/types.rs @@ -194,9 +194,18 @@ pub(super) const WORKSPACE_INTERNAL_DIRS: &[&str] = &[ /// internal state (see `is_workspace_internal_path`); only /// [`ARTIFACT_TOOL_RESULTS_DIR`] inside it stays agent-readable. pub(super) const ARTIFACTS_DIR: &str = "artifacts"; -/// The account config file, stored beside `workspace_dir` (see -/// `is_workspace_internal_path`). -pub(super) const ACCOUNT_CONFIG_FILE: &str = "config.toml"; +/// Files in the account dir (`workspace_dir`'s parent) that are core state +/// rather than agent surface. That directory is otherwise reachable by design +/// — a trusted root over it grants its files (#5505) — so this is the +/// carve-out list, not a containment boundary. See `is_workspace_internal_path` +/// for why each entry is on it. +pub(super) const ACCOUNT_INTERNAL_FILES: &[&str] = &[ + "config.toml", + "config.toml.bak", + ".secret_key", + "auth-profiles.json", + "claude_code_settings.json", +]; /// Where oversized tool outputs are persisted for the agent to read back. pub(super) const ARTIFACT_TOOL_RESULTS_DIR: &str = "tool-results"; From 01d6e11af0fa3037986f02870a507d366fb67d9c Mon Sep 17 00:00:00 2001 From: Maciej Myszkiewicz Date: Fri, 9 Oct 2026 23:56:20 +0200 Subject: [PATCH 02/11] fix(security): report the approval gate's real arming state at boot The gate-install log asserted that "Prompt-class external-effect tool calls park for approval in interactive chat turns" on every install. The gate is installed independently of `[autonomy] enabled`, but what reaches it is not: `shell`, `node_exec`, `npm_exec` and `python_exec` derive `external_effect_with_args` from `SecurityPolicy::gate_decision`, which returns `Allow` for every `CommandClass` while the policy is off (the shipped default). They therefore report no external effect and the gate is never consulted for them, so nothing parks. `approval::gate::arming_note` keeps the old sentence verbatim when the policy is armed and otherwise says that nothing parks, why, and what to set. A pure function so the wording is testable without booting a runtime. `AGENTS.md` and the `AutonomyConfig::enabled` doc were already accurate about this; only the log line was not, and it is the one place an operator reads to learn whether they are protected. --- .../src/core/runtime/bootstrap.rs | 4 ++-- .../src/security/approval/gate.rs | 24 +++++++++++++++++++ .../src/security/approval/gate_tests.rs | 12 ++++++++++ 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/crates/openhuman-core/src/core/runtime/bootstrap.rs b/crates/openhuman-core/src/core/runtime/bootstrap.rs index 12cdee27a59..078012a2d67 100644 --- a/crates/openhuman-core/src/core/runtime/bootstrap.rs +++ b/crates/openhuman-core/src/core/runtime/bootstrap.rs @@ -334,8 +334,8 @@ pub(crate) async fn bootstrap_core_runtime( let _ = crate::security::approval::ApprovalGate::init_global(cfg.clone(), session_id.clone()); log::info!( - "[runtime] approval gate installed (on by default; set OPENHUMAN_APPROVAL_GATE=0 to disable, session_id={session_id}) — \ - Prompt-class external-effect tool calls park for approval in interactive chat turns" + "[runtime] approval gate installed (on by default; set OPENHUMAN_APPROVAL_GATE=0 to disable, session_id={session_id}) — {}", + crate::security::approval::gate::arming_note(cfg.autonomy.enabled) ); // (The approval/plan-review surface bridge is registered unconditionally // above — it must run even when this gate-install branch is skipped.) diff --git a/crates/openhuman-core/src/security/approval/gate.rs b/crates/openhuman-core/src/security/approval/gate.rs index 5ce2fc4b043..76f301a3a62 100644 --- a/crates/openhuman-core/src/security/approval/gate.rs +++ b/crates/openhuman-core/src/security/approval/gate.rs @@ -411,6 +411,30 @@ fn publish_flow_gate_notification( }); } +/// What an installed gate will actually park, given the autonomy policy's +/// master switch. +/// +/// The gate is installed independently of `[autonomy] enabled`, but what +/// *reaches* it is not. A tool declares itself external-effect through +/// [`crate::security::SecurityPolicy::gate_decision`], which returns +/// `GateDecision::Allow` for every [`crate::security::CommandClass`] while the +/// policy is off — and off is the shipped default +/// (`AutonomyConfig::enabled = false`). `shell`, `node_exec`, `npm_exec` and +/// `python_exec` derive `external_effect_with_args` from exactly that call, so +/// they report no external effect and the gate is never consulted for them. +/// +/// The boot line is the one place an operator learns whether they are +/// protected, so it must not claim a park that cannot happen. +pub(crate) fn arming_note(autonomy_enabled: bool) -> &'static str { + if autonomy_enabled { + "Prompt-class external-effect tool calls park for approval in interactive chat turns" + } else { + "nothing parks yet: [autonomy] enabled = false (the shipped default) makes gate_decision() \ + return Allow for every command class, so shell/node_exec/npm_exec/python_exec report no \ + external effect and never reach the gate — set [autonomy] enabled = true to arm it" + } +} + #[cfg(test)] #[path = "gate_tests.rs"] mod tests; diff --git a/crates/openhuman-core/src/security/approval/gate_tests.rs b/crates/openhuman-core/src/security/approval/gate_tests.rs index 3704352a6dc..28251586414 100644 --- a/crates/openhuman-core/src/security/approval/gate_tests.rs +++ b/crates/openhuman-core/src/security/approval/gate_tests.rs @@ -210,3 +210,15 @@ mod origin_intercept_tests; mod triage_tests; #[path = "gate_ttl_and_triage_tests.rs"] mod ttl_and_triage_tests; + +/// The boot line is where an operator learns whether the installed gate can +/// park anything, so it must track `[autonomy] enabled` rather than assert a +/// park unconditionally. +#[test] +fn arming_note_tracks_the_autonomy_master_switch() { + assert!(arming_note(true).contains("park for approval")); + + let disabled = arming_note(false); + assert!(disabled.contains("nothing parks"), "{disabled}"); + assert!(disabled.contains("[autonomy] enabled = true"), "{disabled}"); +} From 040b607a29525b3eea843678cf794826004b21fa Mon Sep 17 00:00:00 2001 From: Maciej Myszkiewicz Date: Sat, 10 Oct 2026 01:19:23 +0200 Subject: [PATCH 03/11] fix(security): key the account-dir carve-out on the configured root, fold case, resolve symlinks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three gaps in the first revision, each found by Codex review and reproduced against source before fixing: - The account root was inferred from `workspace_dir`'s parent, which is the wrong directory whenever the two are split: `RuntimeBuilder::workspace_dir` moves internal state while "the credential root (`config_path`'s parent) stays where the `Workspace` put it", and the legacy `/workspace` layout keeps config in a sibling `/.openhuman`. `SecurityPolicy` now carries `account_dir: Option` with a `with_account_dir()` builder in the shape of the existing `with_privacy_mode()`. Both roots are checked — the union only refuses more — so the 73 `from_config` call sites that set nothing keep today's behaviour. This also fixes the pre-existing `config.toml` carve-out, wrong in those layouts since #5505. - The name match was case-sensitive. On Windows and a default case-insensitive macOS volume an agent allowed to create files in the account root can create `CLAUDE_CODE_SETTINGS.JSON`, which `settings::load` later opens in lower case and resolves to the same file, so `full_access` still took effect. Matched with `eq_ignore_ascii_case` now. - A symlinked account root let creation of a not-yet-existing protected file through. The canonicalization above the check drops the canonical workspace when `path.canonicalize()` fails — which is always the case for a file being created — so a raw parent was compared against a canonical directory. `dir_forms()` offers raw and canonical on both sides. `live_policy` stores the account root and re-applies it in `reload_from`, the same way it already does for the privacy mode: that function rebuilds through `from_config`, which cannot infer the root, so without this the field would be right at boot and silently lost on the next `config.update_autonomy_settings`. Wired at the six sites that hold a real `Config`: core bootstrap, channels startup, `security::ops`, `memory::brain`, and embed's agent build and attachments. `InstalledSeams` needs none — it installs a policy the embedder built, and `live_policy::install` seeds the root from it. --- .../runtime/startup/start_channels.rs | 3 +- .../src/core/runtime/bootstrap.rs | 3 +- crates/openhuman-core/src/memory/brain.rs | 3 +- .../src/security/approval/gate.rs | 13 ++- .../src/security/approval/gate_tests.rs | 7 +- .../src/security/live_policy.rs | 19 +++- crates/openhuman-core/src/security/ops.rs | 3 +- .../src/security/policy/enforcement.rs | 19 ++++ .../src/security/policy/path_checks.rs | 72 ++++++++++-- .../policy/policy_workspace_internal_tests.rs | 107 ++++++++++++++++++ .../src/security/policy/types.rs | 12 ++ .../openhuman-embed/src/agent/attachments.rs | 13 ++- crates/openhuman-embed/src/agent/build.rs | 3 +- 13 files changed, 255 insertions(+), 22 deletions(-) diff --git a/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs b/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs index 270b2a5c6c0..6a327fb3a98 100644 --- a/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs +++ b/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs @@ -155,7 +155,8 @@ async fn start_channels_inner(mut config: Config) -> Result<()> { &config.workspace_dir, &config.action_dir, ) - .with_privacy_mode(config.privacy.mode), + .with_privacy_mode(config.privacy.mode) + .with_account_dir(config.config_path.parent()), ), config.workspace_dir.clone(), config.action_dir.clone(), diff --git a/crates/openhuman-core/src/core/runtime/bootstrap.rs b/crates/openhuman-core/src/core/runtime/bootstrap.rs index 078012a2d67..0a629b3d64e 100644 --- a/crates/openhuman-core/src/core/runtime/bootstrap.rs +++ b/crates/openhuman-core/src/core/runtime/bootstrap.rs @@ -225,7 +225,8 @@ pub(crate) async fn bootstrap_core_runtime( &workspace_dir, &action_dir, ) - .with_privacy_mode(cfg.privacy.mode), + .with_privacy_mode(cfg.privacy.mode) + .with_account_dir(cfg.config_path.parent()), ), workspace_dir.clone(), action_dir, diff --git a/crates/openhuman-core/src/memory/brain.rs b/crates/openhuman-core/src/memory/brain.rs index ae17416dc71..269dbf661f6 100644 --- a/crates/openhuman-core/src/memory/brain.rs +++ b/crates/openhuman-core/src/memory/brain.rs @@ -310,7 +310,8 @@ async fn ingest_path(config: &Config, path: &str) -> MemoryResult &'static str { if autonomy_enabled { "Prompt-class external-effect tool calls park for approval in interactive chat turns" } else { - "nothing parks yet: [autonomy] enabled = false (the shipped default) makes gate_decision() \ - return Allow for every command class, so shell/node_exec/npm_exec/python_exec report no \ - external effect and never reach the gate — set [autonomy] enabled = true to arm it" + "command tools do not park: [autonomy] enabled = false (the shipped default) makes \ + gate_decision() return Allow for every command class, so shell/node_exec/npm_exec/\ + python_exec report no external effect and never reach the gate. Tools that declare an \ + external effect outright (schedule, channel sends, …) still park — set [autonomy] \ + enabled = true to gate commands too" } } diff --git a/crates/openhuman-core/src/security/approval/gate_tests.rs b/crates/openhuman-core/src/security/approval/gate_tests.rs index 28251586414..11d4f55c4b2 100644 --- a/crates/openhuman-core/src/security/approval/gate_tests.rs +++ b/crates/openhuman-core/src/security/approval/gate_tests.rs @@ -219,6 +219,11 @@ fn arming_note_tracks_the_autonomy_master_switch() { assert!(arming_note(true).contains("park for approval")); let disabled = arming_note(false); - assert!(disabled.contains("nothing parks"), "{disabled}"); + // Scoped to the four command tools, and explicit that other + // external-effect tools still park — `ScheduleTool` returns `true` for + // every mutating action regardless of the policy. + assert!(disabled.contains("command tools do not park"), "{disabled}"); + assert!(disabled.contains("still park"), "{disabled}"); assert!(disabled.contains("[autonomy] enabled = true"), "{disabled}"); + assert!(!disabled.contains("nothing parks"), "{disabled}"); } diff --git a/crates/openhuman-core/src/security/live_policy.rs b/crates/openhuman-core/src/security/live_policy.rs index f2b4d52f494..a9fbe443ab8 100644 --- a/crates/openhuman-core/src/security/live_policy.rs +++ b/crates/openhuman-core/src/security/live_policy.rs @@ -25,6 +25,11 @@ struct LiveState { policy: RwLock>, workspace_dir: RwLock, action_dir: RwLock, + /// Stored account / credential root so an autonomy-only [`reload_from`] + /// preserves it. `from_config` cannot infer it (see + /// [`SecurityPolicy::account_dir`]), so without this a reload would + /// silently fall back to guarding `workspace_dir`'s parent. + account_dir: RwLock>, /// Stored Privacy Mode so an autonomy-only [`reload_from`] preserves the /// active mode (autonomy config carries no privacy field) and a later /// [`reload_privacy`] can swap it without rebuilding from a full `Config`. @@ -47,6 +52,7 @@ pub fn install( policy: RwLock::new(Arc::clone(&policy)), workspace_dir: RwLock::new(workspace_dir.clone()), action_dir: RwLock::new(action_dir.clone()), + account_dir: RwLock::new(policy.account_dir.clone()), privacy_mode: RwLock::new(policy.privacy_mode), generation: AtomicU64::new(0), }); @@ -65,6 +71,11 @@ pub fn install( if let Ok(mut guard) = state.privacy_mode.write() { *guard = policy.privacy_mode; } + // Same reasoning as the privacy mode above: re-seed on every install, not + // just the first, or a reload rebuilds without the account root. + if let Ok(mut guard) = state.account_dir.write() { + *guard = policy.account_dir.clone(); + } log::debug!( "[privacy][live_policy] installed policy with privacy_mode={:?}", policy.privacy_mode @@ -218,9 +229,15 @@ pub fn reload_from(autonomy_config: &crate::config::AutonomyConfig) { // privacy mode so an autonomy-only change does not silently reset egress // posture (autonomy config carries no privacy field). let stored_privacy = state.privacy_mode.read().map(|g| *g).unwrap_or_default(); + let stored_account = state + .account_dir + .read() + .map(|g| g.clone()) + .unwrap_or_default(); let rebuilt = Arc::new( SecurityPolicy::from_config(autonomy_config, &workspace, &action) - .with_privacy_mode(stored_privacy), + .with_privacy_mode(stored_privacy) + .with_account_dir(stored_account.as_deref()), ); if let Ok(mut guard) = state.policy.write() { *guard = rebuilt; diff --git a/crates/openhuman-core/src/security/ops.rs b/crates/openhuman-core/src/security/ops.rs index b46fdb7849d..915e42ef131 100644 --- a/crates/openhuman-core/src/security/ops.rs +++ b/crates/openhuman-core/src/security/ops.rs @@ -19,7 +19,8 @@ fn policy_info_payload(policy: SecurityPolicy) -> serde_json::Value { pub fn security_policy_info_for_config(config: &Config) -> Outcome { let policy = - SecurityPolicy::from_config(&config.autonomy, &config.workspace_dir, &config.action_dir); + SecurityPolicy::from_config(&config.autonomy, &config.workspace_dir, &config.action_dir) + .with_account_dir(config.config_path.parent()); let payload = policy_info_payload(policy); Outcome::single_log(payload, "security_policy_info computed from active config") } diff --git a/crates/openhuman-core/src/security/policy/enforcement.rs b/crates/openhuman-core/src/security/policy/enforcement.rs index 650a2a53983..89548275a3c 100644 --- a/crates/openhuman-core/src/security/policy/enforcement.rs +++ b/crates/openhuman-core/src/security/policy/enforcement.rs @@ -258,6 +258,10 @@ impl SecurityPolicy { // effective enforcement mode correct without touching every caller. privacy_mode: crate::config::PrivacyMode::default(), workspace_dir: workspace_dir.to_path_buf(), + // The caller layers the real credential root on with + // `with_account_dir`; unset keeps the `workspace_dir`-parent + // inference every existing call site already relied on. + account_dir: None, action_dir: action_dir.to_path_buf(), workspace_only: autonomy_config.workspace_only, allowed_commands: autonomy_config.allowed_commands.clone(), @@ -291,6 +295,21 @@ impl SecurityPolicy { self } + /// Return a copy of this policy with the account / credential root set — + /// `config_path`'s parent, which is not always `workspace_dir`'s parent + /// (see [`SecurityPolicy::account_dir`]). Builder-style to match + /// [`with_privacy_mode`](Self::with_privacy_mode), so a call site reads as + /// `SecurityPolicy::from_config(..).with_account_dir(config.config_path.parent())`. + #[must_use] + pub fn with_account_dir(mut self, account_dir: Option<&Path>) -> Self { + self.account_dir = account_dir.map(Path::to_path_buf); + log::debug!( + "[openhuman:policy] account dir set on SecurityPolicy: {:?}", + self.account_dir + ); + self + } + /// The active data-egress posture (Privacy Mode). Read by the inference /// chokepoint to enforce local-only model routing; later slices (S4/S7) also /// branch on `Sensitive` here. diff --git a/crates/openhuman-core/src/security/policy/path_checks.rs b/crates/openhuman-core/src/security/policy/path_checks.rs index edd6427be95..bc52875dcd6 100644 --- a/crates/openhuman-core/src/security/policy/path_checks.rs +++ b/crates/openhuman-core/src/security/policy/path_checks.rs @@ -380,6 +380,49 @@ impl SecurityPolicy { Ok(result) } + /// The directories whose own entries are account-level core state. + /// + /// The configured credential root ([`SecurityPolicy::account_dir`], + /// `config_path`'s parent) when the host set it, plus `workspace_dir`'s + /// parent — the same directory in the default layout and the only thing + /// available when nothing was set. Both are checked: the union can only + /// refuse more, so a call site that never sets `account_dir` keeps exactly + /// the behaviour it had. + /// + /// Each is offered in raw and canonical form, and so is the parent they are + /// compared against ([`Self::dir_forms`]). Comparing one raw path with one + /// canonical path never matches: a symlinked account root resolves to its + /// backing directory, and on macOS canonicalization also rewrites `/var` + /// to `/private/var`. The requested file itself usually cannot be + /// canonicalized at all — it does not exist yet, which is exactly the + /// case that matters for creating one. + fn account_state_dirs(&self, ws: &Path) -> Vec { + let mut dirs: Vec = Vec::new(); + for candidate in [self.account_dir.as_deref(), ws.parent()] + .into_iter() + .flatten() + { + for form in Self::dir_forms(candidate) { + if !dirs.contains(&form) { + dirs.push(form); + } + } + } + dirs + } + + /// A directory as written and as the filesystem resolves it, so either side + /// of a comparison can be matched whichever form the caller supplied. + fn dir_forms(dir: &Path) -> Vec { + let mut forms = vec![dir.to_path_buf()]; + if let Ok(canonical) = dir.canonicalize() { + if canonical != forms[0] { + forms.push(canonical); + } + } + forms + } + /// Returns `true` if `path` falls under one of the internal-state /// subdirectories or files within `workspace_dir`. Agent tools must not /// write to these locations — they contain memory DBs, session transcripts, @@ -411,13 +454,28 @@ impl SecurityPolicy { // its tools internally and never returns them to the harness. // // Matched by name within the account dir, which keeps every other file - // there reachable exactly as before. - if let Some(account_dir) = ws.parent() { - if check_path.parent() == Some(account_dir) - && check_path - .file_name() - .and_then(|name| name.to_str()) - .is_some_and(|name| ACCOUNT_INTERNAL_FILES.contains(&name)) + // there reachable exactly as before. Case-insensitively, because on + // Windows and a default case-insensitive macOS volume an agent that may + // create `CLAUDE_CODE_SETTINGS.JSON` creates the very file the + // provider later opens in lower case. + if let Some(parent) = check_path.parent() { + let is_account_file = check_path + .file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| { + ACCOUNT_INTERNAL_FILES + .iter() + .any(|entry| entry.eq_ignore_ascii_case(name)) + }); + // Resolve the parent that exists rather than the file that may + // not, so creating a protected name through a symlinked account + // root is refused too. + let parent_forms = Self::dir_forms(parent); + if is_account_file + && self + .account_state_dirs(ws) + .iter() + .any(|dir| parent_forms.iter().any(|form| form == dir)) { log::trace!( "[security:policy] account-dir core state is not agent surface (path={})", diff --git a/crates/openhuman-core/src/security/policy/policy_workspace_internal_tests.rs b/crates/openhuman-core/src/security/policy/policy_workspace_internal_tests.rs index 51c7830ebca..ebac28c416b 100644 --- a/crates/openhuman-core/src/security/policy/policy_workspace_internal_tests.rs +++ b/crates/openhuman-core/src/security/policy/policy_workspace_internal_tests.rs @@ -372,3 +372,110 @@ async fn trusted_root_over_the_account_dir_cannot_reach_the_keyring_key() { ); } } + +/// The account root is not always `workspace_dir`'s parent: `RuntimeBuilder:: +/// workspace_dir` splits internal state from the credential root, and the +/// legacy `/workspace` layout keeps config in a sibling +/// `/.openhuman`. Inferring it from the workspace guards the wrong +/// directory, leaving the credential key and the `full_access` toggle +/// reachable. +#[test] +fn configured_account_root_is_guarded_when_it_is_not_the_workspace_parent() { + let tmp = tempfile::tempdir().expect("tempdir"); + let proj = tmp.path().join("proj"); + let ws = proj.join("workspace"); + let account = proj.join(".openhuman"); + std::fs::create_dir_all(&ws).expect("create workspace"); + std::fs::create_dir_all(&account).expect("create account dir"); + + let inferred = SecurityPolicy { + workspace_dir: ws.clone(), + action_dir: proj.join("code"), + ..SecurityPolicy::default() + }; + // What the workspace-parent inference alone can see: nothing, because the + // real config root is a sibling the predicate never looks at. + assert!(!inferred.is_workspace_internal_path(&account.join(".secret_key"))); + + let configured = SecurityPolicy { + account_dir: Some(account.clone()), + ..inferred + }; + for name in [ + ".secret_key", + "auth-profiles.json", + "claude_code_settings.json", + ] { + assert!( + configured.is_workspace_internal_path(&account.join(name)), + "{name} in the configured account root must not be agent surface" + ); + } + // The carve-out does not widen inside that root either. + assert!(!configured.is_workspace_internal_path(&account.join("notes.txt"))); + // And the workspace-parent inference is still applied alongside it, so a + // call site that sets nothing keeps exactly the behaviour it had. + assert!(configured.is_workspace_internal_path(&proj.join("config.toml"))); +} + +/// On Windows and a default case-insensitive macOS volume, an agent allowed to +/// create files in the account root can create `CLAUDE_CODE_SETTINGS.JSON`; +/// the provider later opens the lower-case name and resolves the same file, so +/// a case-sensitive match would let `{"full_access": true}` through. +#[test] +fn account_file_names_match_regardless_of_case() { + let tmp = tempfile::tempdir().expect("tempdir"); + let account = tmp.path().join("users").join("u1"); + let ws = account.join("workspace"); + std::fs::create_dir_all(&ws).expect("create workspace"); + let policy = SecurityPolicy { + workspace_dir: ws, + action_dir: tmp.path().join("projects"), + ..SecurityPolicy::default() + }; + + for name in [ + "CLAUDE_CODE_SETTINGS.JSON", + "Claude_Code_Settings.Json", + ".Secret_Key", + "CONFIG.TOML", + "Auth-Profiles.JSON", + ] { + assert!( + policy.is_workspace_internal_path(&account.join(name)), + "{name} must not be creatable in the account root" + ); + } + // Not a blanket prefix match — an unrelated name is still reachable. + assert!(!policy.is_workspace_internal_path(&account.join("secret_key_notes.md"))); +} + +/// A symlinked account root must not expose creation of a protected file that +/// does not exist yet. The canonicalization above this check drops the +/// canonical workspace whenever the requested path cannot be canonicalized +/// (which is the case for a file still to be created), so the account-root +/// comparison has to resolve the *directory* rather than rely on the path. +#[cfg(unix)] +#[test] +fn symlinked_account_root_still_guards_a_file_that_does_not_exist_yet() { + let tmp = tempfile::tempdir().expect("tempdir"); + let backing = tmp.path().join("backing"); + let link = tmp.path().join("link"); + std::fs::create_dir_all(backing.join("workspace")).expect("create backing workspace"); + std::os::unix::fs::symlink(&backing, &link).expect("symlink the account root"); + + let policy = SecurityPolicy { + workspace_dir: link.join("workspace"), + action_dir: tmp.path().join("projects"), + ..SecurityPolicy::default() + }; + + // Requested through the symlink, and through the backing path it resolves + // to; neither may be creatable. + assert!(policy.is_workspace_internal_path(&link.join("claude_code_settings.json"))); + assert!( + policy.is_workspace_internal_path(&backing.join("claude_code_settings.json")), + "the backing path of a symlinked account root must be guarded too" + ); + assert!(policy.is_workspace_internal_path(&backing.join(".secret_key"))); +} diff --git a/crates/openhuman-core/src/security/policy/types.rs b/crates/openhuman-core/src/security/policy/types.rs index 79662da8453..593b2b2a8ac 100644 --- a/crates/openhuman-core/src/security/policy/types.rs +++ b/crates/openhuman-core/src/security/policy/types.rs @@ -277,6 +277,17 @@ pub struct SecurityPolicy { /// intentionally NOT implemented in S1 (#4435). pub privacy_mode: PrivacyMode, pub workspace_dir: PathBuf, + /// The account / credential root — `config_path`'s parent — when the host + /// supplied it. `None` falls back to `workspace_dir`'s parent, which is the + /// same directory in the default layout. + /// + /// Needed as its own field because the two can be split deliberately: + /// `RuntimeBuilder::workspace_dir` moves internal state while leaving the + /// credential root where the `Workspace` put it, and the legacy + /// `/workspace` layout keeps config in a sibling `/.openhuman` + /// (`config::schema::load::dirs`). Inferring the account dir from the + /// workspace guards the wrong directory in both. + pub account_dir: Option, /// Agent action sandbox root — tools resolve relative paths and default /// their cwd here instead of `workspace_dir`. Kept separate so internal /// state (memory DBs, sessions, tokens) under `workspace_dir` is not @@ -354,6 +365,7 @@ impl Default for SecurityPolicy { autonomy: AutonomyLevel::Supervised, privacy_mode: PrivacyMode::Standard, workspace_dir: PathBuf::from("."), + account_dir: None, action_dir: PathBuf::from("."), workspace_only: true, // When adding a new entry to this allowlist, re-audit diff --git a/crates/openhuman-embed/src/agent/attachments.rs b/crates/openhuman-embed/src/agent/attachments.rs index 0d387982507..e18a3a0010c 100644 --- a/crates/openhuman-embed/src/agent/attachments.rs +++ b/crates/openhuman-embed/src/agent/attachments.rs @@ -73,11 +73,14 @@ impl Agent { .map(|entry| entry.name), ); let config = &self.inner.config; - let security = Arc::new(openhuman_core::security::SecurityPolicy::from_config( - &config.autonomy, - &config.workspace_dir, - &config.action_dir, - )); + let security = Arc::new( + openhuman_core::security::SecurityPolicy::from_config( + &config.autonomy, + &config.workspace_dir, + &config.action_dir, + ) + .with_account_dir(config.config_path.parent()), + ); occupied.extend( openhuman_core::tools::ops::all_tools( Arc::new(config.clone()), diff --git a/crates/openhuman-embed/src/agent/build.rs b/crates/openhuman-embed/src/agent/build.rs index 9f8cd616c4e..f6d10436e24 100644 --- a/crates/openhuman-embed/src/agent/build.rs +++ b/crates/openhuman-embed/src/agent/build.rs @@ -216,7 +216,8 @@ pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result Date: Sun, 11 Oct 2026 13:51:46 +0200 Subject: [PATCH 04/11] fix(security): take the account root through one constructor, and scope its names per root MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two review findings, the second of which made the previous revision half a fix. **The union over-refused in a split layout.** All five names were applied to both the configured account root and the workspace's parent, so with `workspace_dir = /proj/workspace` and `account_dir = /proj/.openhuman`, the user's own `/proj/.secret_key` was classified as account state and refused. Which names count now depends on which root matched: the configured credential root holds all five; the workspace's parent keeps only the historical `config.toml` rule once a root is configured, since the two are then different directories and that parent may be the project root; with nothing configured the parent *is* the account root and still holds all five, so the default layout is unchanged. **The carve-out only reached 6 production paths out of ~32.** Twenty-six `SecurityPolicy::from_config` call sites had no `with_account_dir` — MCP tool dispatch, all three cron paths, flows capabilities and the approval manifest, `session_host/builder` and `artifact_wiring`, the three attachment path-validation sites, `runtime/node`, `agent/artifacts` and `integrations/file_storage`. Those kept the `workspace_dir`-parent inference, which is the account root in the default layout and the wrong directory in a split or legacy one — the exact defect this change exists to fix. Chaining `with_account_dir` at 26 more sites would have fixed the symptom and left the footgun, so `SecurityPolicy::for_config(&config)` (and `for_config_in(&config, action_root)` for callers scoping to a root of their own) now does `from_config` plus the account root in one call, and every production construction goes through it. `from_config` stays for tests and for the two sites that assemble their dirs by hand. Tests cover the two distinct failure modes rather than the one that is easy to write: `for_config_attaches_the_configs_account_root` pins the constructor, and `account_root_survives_an_autonomy_reload` pins the silent one — `reload_from` rebuilds through `from_config`, so without the stored copy the root is correct at boot and lost on the first `config.update_autonomy_settings`. `the_workspace_parent_keeps_only_the_config_rule_when_a_root_is_configured` pins the narrowing. `trusted_root_over_the_account_dir_cannot_reach_the_keyring_key` gained a positive control: a sibling file in the same account dir must still be allowed. A tempdir usually sits under a root `forbidden_paths` already lists, so without it those refusals could have held for an unrelated reason. --- .../openhuman-core/src/agent/artifacts/ops.rs | 6 +- .../src/agent/attachments/mod.rs | 2 +- .../src/agent/attachments/provider_cache.rs | 12 +-- .../src/agent/attachments/provider_source.rs | 12 +-- .../session_host/builder/builder_build.rs | 8 +- .../src/agent/session_host/builder/factory.rs | 6 +- .../runtime/startup/start_channels.rs | 10 +-- crates/openhuman-core/src/cron/ops.rs | 12 +-- crates/openhuman-core/src/cron/scheduler.rs | 6 +- .../src/cron/scheduler/retry.rs | 3 +- .../src/flows/ops/approval_manifest.rs | 3 +- .../src/flows/tinyflows/caps/ops.rs | 6 +- .../file_storage/tools/registry.rs | 6 +- .../src/mcp/server/tools/dispatch.rs | 6 +- .../src/mcp/server/write_dispatch.rs | 3 +- crates/openhuman-core/src/memory/brain.rs | 7 +- crates/openhuman-core/src/runtime/node/ops.rs | 9 +-- .../src/security/live_policy_tests.rs | 39 +++++++++ crates/openhuman-core/src/security/ops.rs | 4 +- .../src/security/policy/enforcement.rs | 24 ++++++ .../src/security/policy/path_checks.rs | 74 +++++++---------- .../policy/policy_workspace_internal_tests.rs | 81 +++++++++++++++++++ .../src/security/policy/types.rs | 8 +- .../openhuman-embed/src/agent/attachments.rs | 9 +-- crates/openhuman-embed/src/agent/build.rs | 10 +-- 25 files changed, 211 insertions(+), 155 deletions(-) diff --git a/crates/openhuman-core/src/agent/artifacts/ops.rs b/crates/openhuman-core/src/agent/artifacts/ops.rs index eb0cca8b579..ca169c8e00e 100644 --- a/crates/openhuman-core/src/agent/artifacts/ops.rs +++ b/crates/openhuman-core/src/agent/artifacts/ops.rs @@ -205,11 +205,7 @@ async fn regenerate_presentation( // A fresh policy from the live config — cheap, sync, and mirrors how // the agent harness builds the same tool (see `tools::ops`). - let security = std::sync::Arc::new(SecurityPolicy::from_config( - &config.autonomy, - &config.workspace_dir, - &config.action_dir, - )); + let security = std::sync::Arc::new(SecurityPolicy::for_config(&config)); let tool = PresentationTool::with_config( config.workspace_dir.clone(), super::files::FileRoots::from_config(config), diff --git a/crates/openhuman-core/src/agent/attachments/mod.rs b/crates/openhuman-core/src/agent/attachments/mod.rs index 8ff5861567e..7918479b8d3 100644 --- a/crates/openhuman-core/src/agent/attachments/mod.rs +++ b/crates/openhuman-core/src/agent/attachments/mod.rs @@ -157,7 +157,7 @@ pub(crate) fn action_root(config: &Config, scope: &AttachmentAccessScope) -> Pat } fn policy(config: &Config, root: &Path) -> SecurityPolicy { - SecurityPolicy::from_config(&config.autonomy, &config.workspace_dir, root) + SecurityPolicy::for_config_in(config, root) } /// Resolve a local attachment under the same filesystem policy as acting diff --git a/crates/openhuman-core/src/agent/attachments/provider_cache.rs b/crates/openhuman-core/src/agent/attachments/provider_cache.rs index b9d90d2d2fb..cac50cbcd22 100644 --- a/crates/openhuman-core/src/agent/attachments/provider_cache.rs +++ b/crates/openhuman-core/src/agent/attachments/provider_cache.rs @@ -70,11 +70,7 @@ impl AttachmentModel { .parent()? .join(".openhuman-derived") .join("readout.txt"); - let policy = crate::security::SecurityPolicy::from_config( - &self.config.autonomy, - &self.config.workspace_dir, - &root, - ); + let policy = crate::security::SecurityPolicy::for_config_in(&self.config, &root); if !policy.is_resolved_path_allowed_for(&cache, true) { return None; } @@ -127,11 +123,7 @@ impl AttachmentModel { }; let parent = cache.parent().expect("derivative parent"); let root = super::super::action_root(&self.config, scope); - let policy = crate::security::SecurityPolicy::from_config( - &self.config.autonomy, - &self.config.workspace_dir, - &root, - ); + let policy = crate::security::SecurityPolicy::for_config_in(&self.config, &root); if policy .validate_parent_path(&cache.to_string_lossy()) .await diff --git a/crates/openhuman-core/src/agent/attachments/provider_source.rs b/crates/openhuman-core/src/agent/attachments/provider_source.rs index 8445ba7508f..9f506125d9a 100644 --- a/crates/openhuman-core/src/agent/attachments/provider_source.rs +++ b/crates/openhuman-core/src/agent/attachments/provider_source.rs @@ -180,11 +180,7 @@ impl AttachmentModel { .join(id) .join(super::super::filename(name)); let root = super::super::action_root(&self.config, scope); - let preliminary = crate::security::SecurityPolicy::from_config( - &self.config.autonomy, - &self.config.workspace_dir, - &root, - ); + let preliminary = crate::security::SecurityPolicy::for_config_in(&self.config, &root); preliminary .validate_parent_path(&root.join(&relative).to_string_lossy()) .await @@ -195,11 +191,7 @@ impl AttachmentModel { let root = tokio::fs::canonicalize(root) .await .map_err(|e| tinyinference_llm::Error::Model(e.to_string()))?; - let policy = crate::security::SecurityPolicy::from_config( - &self.config.autonomy, - &self.config.workspace_dir, - &root, - ); + let policy = crate::security::SecurityPolicy::for_config_in(&self.config, &root); let path = root.join(&relative); policy .validate_parent_path(&path.to_string_lossy()) diff --git a/crates/openhuman-core/src/agent/session_host/builder/builder_build.rs b/crates/openhuman-core/src/agent/session_host/builder/builder_build.rs index d8cc248d40f..608362a3f97 100644 --- a/crates/openhuman-core/src/agent/session_host/builder/builder_build.rs +++ b/crates/openhuman-core/src/agent/session_host/builder/builder_build.rs @@ -379,10 +379,10 @@ impl SessionHostBuilder { }); let hosted_base = definitions.map(|definitions| { Arc::new(crate::agent::tinyagents::host::OpenHumanHostBase { - security_policy: Arc::new(crate::security::SecurityPolicy::from_config( - &hosted_config.autonomy, - &workspace_dir, - &action_dir, + // `hosted_config`'s own dirs were just set from these two, so + // this is the same policy plus the config's account root. + security_policy: Arc::new(crate::security::SecurityPolicy::for_config( + &hosted_config, )), config: Arc::clone(&hosted_config), definitions, diff --git a/crates/openhuman-core/src/agent/session_host/builder/factory.rs b/crates/openhuman-core/src/agent/session_host/builder/factory.rs index a50fd418ebb..d8f7a62a63e 100644 --- a/crates/openhuman-core/src/agent/session_host/builder/factory.rs +++ b/crates/openhuman-core/src/agent/session_host/builder/factory.rs @@ -156,11 +156,7 @@ impl OpenHumanSessionHost { let runtime: Arc = Arc::from( host_runtime::create_runtime(&config.runtime, config.shell.hide_window)?, ); - let security = Arc::new(SecurityPolicy::from_config( - &config.autonomy, - &config.workspace_dir, - &config.action_dir, - )); + let security = Arc::new(SecurityPolicy::for_config(config)); // Phase 1 of #1401: see comment in channels/runtime/startup.rs. let audit = crate::security::get_or_create_workspace_audit_logger( crate::config::AuditConfig::default(), diff --git a/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs b/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs index 6a327fb3a98..56c9b487ffd 100644 --- a/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs +++ b/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs @@ -150,13 +150,9 @@ async fn start_channels_inner(mut config: Config) -> Result<()> { // and picked up by the next session. let security = crate::security::live_policy::install( Arc::new( - SecurityPolicy::from_config( - &config.autonomy, - &config.workspace_dir, - &config.action_dir, - ) - .with_privacy_mode(config.privacy.mode) - .with_account_dir(config.config_path.parent()), + SecurityPolicy::for_config(&config) + .with_privacy_mode(config.privacy.mode) + .with_account_dir(config.config_path.parent()), ), config.workspace_dir.clone(), config.action_dir.clone(), diff --git a/crates/openhuman-core/src/cron/ops.rs b/crates/openhuman-core/src/cron/ops.rs index 2d1cdb94b3b..a50876fe6c4 100644 --- a/crates/openhuman-core/src/cron/ops.rs +++ b/crates/openhuman-core/src/cron/ops.rs @@ -118,11 +118,7 @@ pub fn update_cron_job( }; if let Some(ref cmd) = command { - let security = SecurityPolicy::from_config( - &config.autonomy, - &config.workspace_dir, - &config.action_dir, - ); + let security = SecurityPolicy::for_config(config); if !security.is_command_allowed(cmd) { anyhow::bail!("Command blocked by security policy: {cmd}"); } @@ -182,11 +178,7 @@ pub async fn cron_update( } if let Some(command) = &patch.command { - let security = SecurityPolicy::from_config( - &config.autonomy, - &config.workspace_dir, - &config.action_dir, - ); + let security = SecurityPolicy::for_config(config); if !security.is_command_allowed(command) { return Err(format!("Command blocked by security policy: {command}")); } diff --git a/crates/openhuman-core/src/cron/scheduler.rs b/crates/openhuman-core/src/cron/scheduler.rs index 5c64479da1e..04d69ee3b44 100644 --- a/crates/openhuman-core/src/cron/scheduler.rs +++ b/crates/openhuman-core/src/cron/scheduler.rs @@ -65,11 +65,7 @@ pub async fn run(config: Config) -> Result<()> { let poll_secs = config.reliability.scheduler_poll_secs.max(MIN_POLL_SECONDS); let mut interval = time::interval(Duration::from_secs(poll_secs)); - let security = Arc::new(SecurityPolicy::from_config( - &config.autonomy, - &config.workspace_dir, - &config.action_dir, - )); + let security = Arc::new(SecurityPolicy::for_config(&config)); BUS.publish(DomainEvent::SystemStartup { component: "scheduler".to_string(), diff --git a/crates/openhuman-core/src/cron/scheduler/retry.rs b/crates/openhuman-core/src/cron/scheduler/retry.rs index d26d53a607f..a73b4189be7 100644 --- a/crates/openhuman-core/src/cron/scheduler/retry.rs +++ b/crates/openhuman-core/src/cron/scheduler/retry.rs @@ -24,8 +24,7 @@ pub(super) fn agent_session_target_tag(target: &SessionTarget) -> &'static str { /// Run `job` now under the caller's `run_id` (also the id its delivery and /// run record use). pub async fn execute_job_now(config: &Config, job: &CronJob, run_id: &str) -> (bool, String) { - let security = - SecurityPolicy::from_config(&config.autonomy, &config.workspace_dir, &config.action_dir); + let security = SecurityPolicy::for_config(config); execute_job_with_retry_for_run(config, &security, job, run_id).await } diff --git a/crates/openhuman-core/src/flows/ops/approval_manifest.rs b/crates/openhuman-core/src/flows/ops/approval_manifest.rs index 68f6c776678..9f2305ba81b 100644 --- a/crates/openhuman-core/src/flows/ops/approval_manifest.rs +++ b/crates/openhuman-core/src/flows/ops/approval_manifest.rs @@ -37,8 +37,7 @@ pub async fn compute_approval_manifest(config: &Config, graph: &WorkflowGraph) - use crate::flows::tinyflows::caps::classify_composio_action_for_tier; use crate::security::{CommandClass, GateDecision, SecurityPolicy}; - let security = - SecurityPolicy::from_config(&config.autonomy, &config.workspace_dir, &config.action_dir); + let security = SecurityPolicy::for_config(config); let mut entries: Vec = Vec::new(); // Approvable/blocked rows dedupe on the trust key (`tool_name`) — two diff --git a/crates/openhuman-core/src/flows/tinyflows/caps/ops.rs b/crates/openhuman-core/src/flows/tinyflows/caps/ops.rs index 176bb393e37..802aed5e2cb 100644 --- a/crates/openhuman-core/src/flows/tinyflows/caps/ops.rs +++ b/crates/openhuman-core/src/flows/tinyflows/caps/ops.rs @@ -597,11 +597,7 @@ impl ToolInvoker for OpenHumanTools { /// flow-scoped memory: `OpenHumanMemory` tags memory items with /// `flows::flow_tag`, derived independently from the run's trusted origin. pub fn build_capabilities(config: Arc, state_namespace: impl Into) -> Capabilities { - let security = Arc::new(SecurityPolicy::from_config( - &config.autonomy, - &config.workspace_dir, - &config.action_dir, - )); + let security = Arc::new(SecurityPolicy::for_config(&config)); let http_config = config.http_request.clone(); let http_creds = Arc::new(HttpCredentialsStore::from_config(&config)); diff --git a/crates/openhuman-core/src/integrations/file_storage/tools/registry.rs b/crates/openhuman-core/src/integrations/file_storage/tools/registry.rs index 8dce9c3eb22..642bc7bd27e 100644 --- a/crates/openhuman-core/src/integrations/file_storage/tools/registry.rs +++ b/crates/openhuman-core/src/integrations/file_storage/tools/registry.rs @@ -24,11 +24,7 @@ pub fn build_file_storage_tools(root_config: &Config, action_dir: &Path) -> Vec< }; let action_dir = action_dir.to_path_buf(); - let security = Arc::new(SecurityPolicy::from_config( - &root_config.autonomy, - &root_config.workspace_dir, - &root_config.action_dir, - )); + let security = Arc::new(SecurityPolicy::for_config(root_config)); let tools: Vec> = vec![ Box::new(StorageUploadFileTool::new_with_security( Arc::clone(&client), diff --git a/crates/openhuman-core/src/mcp/server/tools/dispatch.rs b/crates/openhuman-core/src/mcp/server/tools/dispatch.rs index 889731f61a0..b708d393b92 100644 --- a/crates/openhuman-core/src/mcp/server/tools/dispatch.rs +++ b/crates/openhuman-core/src/mcp/server/tools/dispatch.rs @@ -177,8 +177,7 @@ async fn enforce_read_policy(tool_name: &str) -> Result<(), ToolCallError> { ))); } }; - let policy = - SecurityPolicy::from_config(&config.autonomy, &config.workspace_dir, &config.action_dir); + let policy = SecurityPolicy::for_config(&config); // A policy denial *is* something the caller can act on (toggle autonomy, // approve the tool) — keep that as `InvalidParams` so clients surface the // reason text instead of a generic internal-error banner. @@ -199,8 +198,7 @@ async fn enforce_act_policy(tool_name: &str) -> Result<(), ToolCallError> { ))); } }; - let policy = - SecurityPolicy::from_config(&config.autonomy, &config.workspace_dir, &config.action_dir); + let policy = SecurityPolicy::for_config(&config); policy .enforce_tool_operation(ToolOperation::Act, tool_name) .map_err(ToolCallError::InvalidParams) diff --git a/crates/openhuman-core/src/mcp/server/write_dispatch.rs b/crates/openhuman-core/src/mcp/server/write_dispatch.rs index 837d8a92ead..5efec2e4994 100644 --- a/crates/openhuman-core/src/mcp/server/write_dispatch.rs +++ b/crates/openhuman-core/src/mcp/server/write_dispatch.rs @@ -32,8 +32,7 @@ pub(super) fn enforce_write_policy_for_config( tool_name: &str, config: &Config, ) -> Result<(), ToolCallError> { - let policy = - SecurityPolicy::from_config(&config.autonomy, &config.workspace_dir, &config.action_dir); + let policy = SecurityPolicy::for_config(config); match policy.enforce_tool_operation(ToolOperation::Act, tool_name) { Ok(()) => Ok(()), Err(message) => { diff --git a/crates/openhuman-core/src/memory/brain.rs b/crates/openhuman-core/src/memory/brain.rs index 269dbf661f6..4307f996506 100644 --- a/crates/openhuman-core/src/memory/brain.rs +++ b/crates/openhuman-core/src/memory/brain.rs @@ -306,12 +306,7 @@ pub struct BrainIngestView { /// /// [`SecurityPolicy::validate_path`]: crate::security::SecurityPolicy::validate_path async fn ingest_path(config: &Config, path: &str) -> MemoryResult { - let policy = crate::security::SecurityPolicy::from_config( - &config.autonomy, - &config.workspace_dir, - &config.action_dir, - ) - .with_account_dir(config.config_path.parent()); + let policy = crate::security::SecurityPolicy::for_config(config); policy.validate_path(path.trim()).await.map_err(|error| { tracing::warn!("[memory:brain] ingest path refused by the security policy"); MemoryError::invalid(format!("cannot read the file: {error}")) diff --git a/crates/openhuman-core/src/runtime/node/ops.rs b/crates/openhuman-core/src/runtime/node/ops.rs index bf13fcac460..b71e439f630 100644 --- a/crates/openhuman-core/src/runtime/node/ops.rs +++ b/crates/openhuman-core/src/runtime/node/ops.rs @@ -81,11 +81,7 @@ pub fn build_runtime_tools(config: &Config) -> Result>, String workspace = %config.workspace_dir.display(), "[runtime_node::ops] build_runtime_tools: start" ); - let security = Arc::new(SecurityPolicy::from_config( - &config.autonomy, - &config.workspace_dir, - &config.action_dir, - )); + let security = Arc::new(SecurityPolicy::for_config(config)); // Phase 1 of #1401: see comment in channels/runtime/startup.rs. let audit = crate::security::get_or_create_workspace_audit_logger( crate::config::AuditConfig::default(), @@ -133,8 +129,7 @@ pub fn classify_tool_call( args: &serde_json::Value, ) -> Result { debug!(tool_name, "[runtime_node::ops] classify_tool_call: start"); - let security = - SecurityPolicy::from_config(&config.autonomy, &config.workspace_dir, &config.action_dir); + let security = SecurityPolicy::for_config(config); let tools = build_runtime_tools(config)?; let tool = tools .into_iter() diff --git a/crates/openhuman-core/src/security/live_policy_tests.rs b/crates/openhuman-core/src/security/live_policy_tests.rs index 436cc9edbdf..00858747919 100644 --- a/crates/openhuman-core/src/security/live_policy_tests.rs +++ b/crates/openhuman-core/src/security/live_policy_tests.rs @@ -232,3 +232,42 @@ async fn effective_falls_back_to_the_process_policy_for_an_agent_without_one() { crate::core::runtime::CoreContext::scope(agent_context(None), async { effective() }).await; assert!(Arc::ptr_eq(&seen.expect("process policy"), &process)); } + +/// `reload_from` rebuilds through `from_config`, which cannot infer the account +/// root (it is not derivable from `workspace_dir`). Without the stored copy the +/// field would be right at boot and silently lost on the first +/// `config.update_autonomy_settings`, which is the hard kind of bug to notice: +/// the predicate still runs, just against the wrong directory. +#[test] +fn account_root_survives_an_autonomy_reload() { + // Same process-global lock as the other live-policy tests. + let _env = crate::config::TEST_ENV_LOCK.blocking_lock(); + let account = std::env::temp_dir().join("openhuman_live_policy_account"); + let workspace = account.join("workspace"); + let installed = Arc::new( + SecurityPolicy { + workspace_dir: workspace.clone(), + ..SecurityPolicy::default() + } + .with_account_dir(Some(account.as_path())), + ); + install(installed, workspace.clone(), workspace.clone()); + assert_eq!( + current().expect("policy installed").account_dir.as_deref(), + Some(account.as_path()) + ); + + reload_from(&AutonomyConfig { + level: AutonomyLevel::Full, + ..AutonomyConfig::default() + }); + + assert_eq!( + current() + .expect("policy still installed") + .account_dir + .as_deref(), + Some(account.as_path()), + "the configured account root must survive a reload" + ); +} diff --git a/crates/openhuman-core/src/security/ops.rs b/crates/openhuman-core/src/security/ops.rs index 915e42ef131..f01700eb9c4 100644 --- a/crates/openhuman-core/src/security/ops.rs +++ b/crates/openhuman-core/src/security/ops.rs @@ -18,9 +18,7 @@ fn policy_info_payload(policy: SecurityPolicy) -> serde_json::Value { } pub fn security_policy_info_for_config(config: &Config) -> Outcome { - let policy = - SecurityPolicy::from_config(&config.autonomy, &config.workspace_dir, &config.action_dir) - .with_account_dir(config.config_path.parent()); + let policy = SecurityPolicy::for_config(config); let payload = policy_info_payload(policy); Outcome::single_log(payload, "security_policy_info computed from active config") } diff --git a/crates/openhuman-core/src/security/policy/enforcement.rs b/crates/openhuman-core/src/security/policy/enforcement.rs index 89548275a3c..8f13e3a40cf 100644 --- a/crates/openhuman-core/src/security/policy/enforcement.rs +++ b/crates/openhuman-core/src/security/policy/enforcement.rs @@ -295,6 +295,30 @@ impl SecurityPolicy { self } + /// [`from_config`](Self::from_config) for a whole [`Config`], with that + /// config's own account root attached. + /// + /// This is the form almost every caller wants, and the reason it exists is + /// that the alternative is a footgun: the account root is not derivable + /// from `workspace_dir` (see [`SecurityPolicy::account_dir`]), so it has to + /// be chained on, and a carve-out that silently does not apply wherever one + /// call site forgot is worse than no carve-out — you cannot tell the two + /// apart by reading the predicate. Prefer this over `from_config` wherever + /// a `Config` is in hand. + #[must_use] + pub fn for_config(config: &crate::config::Config) -> Self { + Self::for_config_in(config, &config.action_dir) + } + + /// [`for_config`](Self::for_config) with the action root overridden, for the + /// callers that scope a policy to a directory of their own (an attachment + /// root, a turn workspace) rather than the config's `action_dir`. + #[must_use] + pub fn for_config_in(config: &crate::config::Config, action_dir: &Path) -> Self { + Self::from_config(&config.autonomy, &config.workspace_dir, action_dir) + .with_account_dir(config.config_path.parent()) + } + /// Return a copy of this policy with the account / credential root set — /// `config_path`'s parent, which is not always `workspace_dir`'s parent /// (see [`SecurityPolicy::account_dir`]). Builder-style to match diff --git a/crates/openhuman-core/src/security/policy/path_checks.rs b/crates/openhuman-core/src/security/policy/path_checks.rs index bc52875dcd6..fa7ac48199e 100644 --- a/crates/openhuman-core/src/security/policy/path_checks.rs +++ b/crates/openhuman-core/src/security/policy/path_checks.rs @@ -2,8 +2,8 @@ use std::path::{Path, PathBuf}; use super::types::{SecurityPolicy, TrustedAccess, POLICY_BLOCKED_MARKER}; use super::types::{ - ACCOUNT_INTERNAL_FILES, ARTIFACTS_DIR, ARTIFACT_TOOL_RESULTS_DIR, WORKSPACE_INTERNAL_DIRS, - WORKSPACE_INTERNAL_FILES, + ACCOUNT_CONFIG_FILE, ACCOUNT_INTERNAL_FILES, ARTIFACTS_DIR, ARTIFACT_TOOL_RESULTS_DIR, + WORKSPACE_INTERNAL_DIRS, WORKSPACE_INTERNAL_FILES, }; impl SecurityPolicy { @@ -380,37 +380,6 @@ impl SecurityPolicy { Ok(result) } - /// The directories whose own entries are account-level core state. - /// - /// The configured credential root ([`SecurityPolicy::account_dir`], - /// `config_path`'s parent) when the host set it, plus `workspace_dir`'s - /// parent — the same directory in the default layout and the only thing - /// available when nothing was set. Both are checked: the union can only - /// refuse more, so a call site that never sets `account_dir` keeps exactly - /// the behaviour it had. - /// - /// Each is offered in raw and canonical form, and so is the parent they are - /// compared against ([`Self::dir_forms`]). Comparing one raw path with one - /// canonical path never matches: a symlinked account root resolves to its - /// backing directory, and on macOS canonicalization also rewrites `/var` - /// to `/private/var`. The requested file itself usually cannot be - /// canonicalized at all — it does not exist yet, which is exactly the - /// case that matters for creating one. - fn account_state_dirs(&self, ws: &Path) -> Vec { - let mut dirs: Vec = Vec::new(); - for candidate in [self.account_dir.as_deref(), ws.parent()] - .into_iter() - .flatten() - { - for form in Self::dir_forms(candidate) { - if !dirs.contains(&form) { - dirs.push(form); - } - } - } - dirs - } - /// A directory as written and as the filesystem resolves it, so either side /// of a comparison can be matched whichever form the caller supplied. fn dir_forms(dir: &Path) -> Vec { @@ -458,25 +427,38 @@ impl SecurityPolicy { // Windows and a default case-insensitive macOS volume an agent that may // create `CLAUDE_CODE_SETTINGS.JSON` creates the very file the // provider later opens in lower case. - if let Some(parent) = check_path.parent() { - let is_account_file = check_path - .file_name() - .and_then(|name| name.to_str()) - .is_some_and(|name| { - ACCOUNT_INTERNAL_FILES - .iter() - .any(|entry| entry.eq_ignore_ascii_case(name)) - }); + if let Some((parent, name)) = check_path + .parent() + .zip(check_path.file_name().and_then(|name| name.to_str())) + { // Resolve the parent that exists rather than the file that may // not, so creating a protected name through a symlinked account // root is refused too. let parent_forms = Self::dir_forms(parent); - if is_account_file - && self - .account_state_dirs(ws) + let under = |root: &Path, names: &[&str]| { + Self::dir_forms(root) .iter() .any(|dir| parent_forms.iter().any(|form| form == dir)) - { + && names.iter().any(|entry| entry.eq_ignore_ascii_case(name)) + }; + let configured = self.account_dir.as_deref(); + // Which names count depends on which root matched. The configured + // credential root holds all of them. The workspace's parent keeps + // only the historical `config.toml` rule once a root is configured, + // because the two are then different directories and that parent + // may be the user's own project root — `/proj/.secret_key` beside + // `/proj/workspace` is their file, not account state. With nothing + // configured the parent *is* the account root, so it holds all. + let hit = configured.is_some_and(|root| under(root, ACCOUNT_INTERNAL_FILES)) + || ws.parent().is_some_and(|root| { + let names: &[&str] = if configured.is_some() { + &[ACCOUNT_CONFIG_FILE] + } else { + ACCOUNT_INTERNAL_FILES + }; + under(root, names) + }); + if hit { log::trace!( "[security:policy] account-dir core state is not agent surface (path={})", check_path.display() diff --git a/crates/openhuman-core/src/security/policy/policy_workspace_internal_tests.rs b/crates/openhuman-core/src/security/policy/policy_workspace_internal_tests.rs index ebac28c416b..b5608ca164b 100644 --- a/crates/openhuman-core/src/security/policy/policy_workspace_internal_tests.rs +++ b/crates/openhuman-core/src/security/policy/policy_workspace_internal_tests.rs @@ -371,6 +371,21 @@ async fn trusted_root_over_the_account_dir_cannot_reach_the_keyring_key() { "{shown}" ); } + + // Positive control, raised in review: a tempdir usually sits under a root + // that `SecurityPolicy::default()`'s `forbidden_paths` already lists, so + // without this the refusals above could be true for a reason that has + // nothing to do with the carve-out. A sibling file in the same account dir + // must still be reachable — which also re-pins #5505's "other files there + // stay reachable" through the full gate, not just the predicate. + let notes = account.join("notes.txt"); + std::fs::write(¬es, "hello").expect("write notes"); + let shown = notes.to_string_lossy(); + assert!( + policy.is_path_string_allowed(&shown), + "the trusted root must still reach a non-carved-out file: {shown}" + ); + assert!(policy.validate_path(&shown).await.is_ok(), "{shown}"); } /// The account root is not always `workspace_dir`'s parent: `RuntimeBuilder:: @@ -479,3 +494,69 @@ fn symlinked_account_root_still_guards_a_file_that_does_not_exist_yet() { ); assert!(policy.is_workspace_internal_path(&backing.join(".secret_key"))); } + +/// Raised in review: with a split layout the union applied all five names to +/// the workspace's parent too, so `/proj/.secret_key` — the user's own file in +/// their project root — was classified as account state. Only the historical +/// `config.toml` rule belongs to that parent once a root is configured. +#[test] +fn the_workspace_parent_keeps_only_the_config_rule_when_a_root_is_configured() { + let tmp = tempfile::tempdir().expect("tempdir"); + let proj = tmp.path().join("proj"); + let ws = proj.join("workspace"); + let account = proj.join(".openhuman"); + std::fs::create_dir_all(&ws).expect("create workspace"); + std::fs::create_dir_all(&account).expect("create account dir"); + let policy = SecurityPolicy { + workspace_dir: ws, + action_dir: proj.clone(), + ..SecurityPolicy::default() + } + .with_account_dir(Some(account.as_path())); + + // The configured root holds all five. + for name in [ + "config.toml", + "config.toml.bak", + ".secret_key", + "auth-profiles.json", + "claude_code_settings.json", + ] { + assert!( + policy.is_workspace_internal_path(&account.join(name)), + "{name} in the configured account root must be internal" + ); + } + // The workspace's parent keeps the historical rule, and nothing more. + assert!(policy.is_workspace_internal_path(&proj.join("config.toml"))); + for name in [ + "config.toml.bak", + ".secret_key", + "auth-profiles.json", + "claude_code_settings.json", + ] { + assert!( + !policy.is_workspace_internal_path(&proj.join(name)), + "{name} beside the workspace is the user's file, not account state" + ); + } +} + +/// `for_config` is what every production call site now uses, so pin that it +/// attaches the config's own account root rather than leaving the predicate on +/// the `workspace_dir`-parent inference. +#[test] +fn for_config_attaches_the_configs_account_root() { + let tmp = tempfile::tempdir().expect("tempdir"); + let account = tmp.path().join("users").join("u1"); + let config = crate::config::Config { + config_path: account.join("config.toml"), + workspace_dir: account.join("workspace"), + action_dir: tmp.path().join("projects"), + ..crate::config::Config::default() + }; + + let policy = SecurityPolicy::for_config(&config); + assert_eq!(policy.account_dir.as_deref(), Some(account.as_path())); + assert!(policy.is_workspace_internal_path(&account.join(".secret_key"))); +} diff --git a/crates/openhuman-core/src/security/policy/types.rs b/crates/openhuman-core/src/security/policy/types.rs index 593b2b2a8ac..8cb8aa621c6 100644 --- a/crates/openhuman-core/src/security/policy/types.rs +++ b/crates/openhuman-core/src/security/policy/types.rs @@ -199,8 +199,14 @@ pub(super) const ARTIFACTS_DIR: &str = "artifacts"; /// — a trusted root over it grants its files (#5505) — so this is the /// carve-out list, not a containment boundary. See `is_workspace_internal_path` /// for why each entry is on it. +/// The account config, the one name the workspace-parent fallback has always +/// refused (#5505). Kept separate from the rest of +/// [`ACCOUNT_INTERNAL_FILES`] because a configured account root and the +/// workspace's parent are not always the same directory, and only this name +/// applies to the latter once they diverge. +pub(super) const ACCOUNT_CONFIG_FILE: &str = "config.toml"; pub(super) const ACCOUNT_INTERNAL_FILES: &[&str] = &[ - "config.toml", + ACCOUNT_CONFIG_FILE, "config.toml.bak", ".secret_key", "auth-profiles.json", diff --git a/crates/openhuman-embed/src/agent/attachments.rs b/crates/openhuman-embed/src/agent/attachments.rs index e18a3a0010c..2c0422e465d 100644 --- a/crates/openhuman-embed/src/agent/attachments.rs +++ b/crates/openhuman-embed/src/agent/attachments.rs @@ -73,14 +73,7 @@ impl Agent { .map(|entry| entry.name), ); let config = &self.inner.config; - let security = Arc::new( - openhuman_core::security::SecurityPolicy::from_config( - &config.autonomy, - &config.workspace_dir, - &config.action_dir, - ) - .with_account_dir(config.config_path.parent()), - ); + let security = Arc::new(openhuman_core::security::SecurityPolicy::for_config(config)); occupied.extend( openhuman_core::tools::ops::all_tools( Arc::new(config.clone()), diff --git a/crates/openhuman-embed/src/agent/build.rs b/crates/openhuman-embed/src/agent/build.rs index f6d10436e24..bc85215d070 100644 --- a/crates/openhuman-embed/src/agent/build.rs +++ b/crates/openhuman-embed/src/agent/build.rs @@ -211,13 +211,9 @@ pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result Date: Sun, 11 Oct 2026 22:27:30 +0200 Subject: [PATCH 05/11] fix(security): carry the account root through the call sites main added since MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Post-merge follow-up. Re-running the audit after merging `upstream/main` surfaced six more production `SecurityPolicy::from_config` call sites with no account root, all of them arrivals from main: `tools/native_ops.rs`, the new `profiles/` domain (`host`, `cron`, `capabilities`), `cron/schemas.rs` and `channels/providers/relay/ops.rs`. That is the argument for `for_config` stated better than the PR description managed: the footgun is live. New code keeps landing on the fallback because the account root has to be chained on by hand, and a carve-out that silently does not apply is indistinguishable from one that does by reading the predicate. All six now go through `for_config` / `for_config_in`, and the audit in the PR description returns nothing again. Two conflicts came with the merge, both resolved on the semantics rather than by picking a side: - `cron/ops.rs` — main replaced the inline `is_command_allowed` check with `scheduler::shell_job::authorize_shell_command`. Kept main's call with this branch's constructor. - `tools/native_ops.rs` — the file moved here from `runtime/node/ops.rs` and main dropped the policy construction at the conflicting line, so main's side stands; the policy it does build further down is converted instead. Also included, and deliberately flagged rather than slipped in: `cron/ops.rs` gains `get_job` to its `crate::cron` import. Without it `cargo test -p openhuman --lib` does not compile on `main` at all — `cron/ops_tests.rs` calls `get_job` through `use super::*` and `ops.rs` does not import it — so the test and coverage lanes cannot pass for any PR, including this one. The one-line import is unrelated to this change's subject; it is here because leaving it out would show a red test lane that a reviewer would reasonably attribute to this PR. --- crates/openhuman-core/src/channels/providers/relay/ops.rs | 6 ++---- crates/openhuman-core/src/cron/ops.rs | 4 +++- crates/openhuman-core/src/cron/schemas.rs | 6 +----- crates/openhuman-core/src/profiles/capabilities.rs | 6 +----- crates/openhuman-core/src/profiles/cron.rs | 6 +----- crates/openhuman-core/src/profiles/host.rs | 7 +------ crates/openhuman-core/src/tools/native_ops.rs | 6 +----- 7 files changed, 10 insertions(+), 31 deletions(-) diff --git a/crates/openhuman-core/src/channels/providers/relay/ops.rs b/crates/openhuman-core/src/channels/providers/relay/ops.rs index 43d5a83279c..f2eb51fa06d 100644 --- a/crates/openhuman-core/src/channels/providers/relay/ops.rs +++ b/crates/openhuman-core/src/channels/providers/relay/ops.rs @@ -101,10 +101,8 @@ pub(crate) async fn run_relay_turn( params.message_id.clone(), )); - let security = Arc::new( - SecurityPolicy::from_config(&config.autonomy, &config.workspace_dir, &config.action_dir) - .with_privacy_mode(config.privacy.mode), - ); + let security = + Arc::new(SecurityPolicy::for_config(&config).with_privacy_mode(config.privacy.mode)); let parts = match build_channel_turn_parts(&config, &security, PromptToolDescs::Registered) { Ok(parts) => parts, Err(error) => { diff --git a/crates/openhuman-core/src/cron/ops.rs b/crates/openhuman-core/src/cron/ops.rs index 7a215f8a52f..8046fccda87 100644 --- a/crates/openhuman-core/src/cron/ops.rs +++ b/crates/openhuman-core/src/cron/ops.rs @@ -1,6 +1,8 @@ use crate::config::Config; use crate::core::Outcome; -use crate::cron::{self, add_shell_job, update_job, CronJob, CronJobPatch, CronRun, Schedule}; +use crate::cron::{ + self, add_shell_job, get_job, update_job, CronJob, CronJobPatch, CronRun, Schedule, +}; use crate::security::SecurityPolicy; use anyhow::Result; use once_cell::sync::Lazy; diff --git a/crates/openhuman-core/src/cron/schemas.rs b/crates/openhuman-core/src/cron/schemas.rs index 88a04a2329e..090dc8beae7 100644 --- a/crates/openhuman-core/src/cron/schemas.rs +++ b/crates/openhuman-core/src/cron/schemas.rs @@ -351,11 +351,7 @@ fn handle_add(params: Map) -> ControllerFuture { let job = match job_type { "shell" => { let cmd = command.ok_or("'command' is required for shell jobs")?; - let security = crate::security::SecurityPolicy::from_config( - &config.autonomy, - &config.workspace_dir, - &config.action_dir, - ); + let security = crate::security::SecurityPolicy::for_config(&config); crate::cron::scheduler::shell_job::authorize_shell_command( &config, &security, &cmd, ) diff --git a/crates/openhuman-core/src/profiles/capabilities.rs b/crates/openhuman-core/src/profiles/capabilities.rs index 04f7a4f33c0..800868ac3e0 100644 --- a/crates/openhuman-core/src/profiles/capabilities.rs +++ b/crates/openhuman-core/src/profiles/capabilities.rs @@ -166,11 +166,7 @@ impl ProfileCapabilities { // profile. The named packs narrow registration within those domains. let assembly = ctx.derive_with(ContextOverlay::new(config.clone(), ctx.domains(), groups)); - let security = Arc::new(crate::security::SecurityPolicy::from_config( - &config.autonomy, - &config.workspace_dir, - &config.action_dir, - )); + let security = Arc::new(crate::security::SecurityPolicy::for_config(config)); let native = CoreContext::sync_scope(assembly, || { crate::tools::ops::all_tools( Arc::new(config.clone()), diff --git a/crates/openhuman-core/src/profiles/cron.rs b/crates/openhuman-core/src/profiles/cron.rs index ea2e07ae88c..1d4348c7cf9 100644 --- a/crates/openhuman-core/src/profiles/cron.rs +++ b/crates/openhuman-core/src/profiles/cron.rs @@ -121,11 +121,7 @@ pub async fn sweep(host: &ProfileHost, now: DateTime) -> SweepReport { let count = claimed.len(); let profile_config = profile.config.clone(); let outcome = CoreContext::scope(Arc::clone(profile.context()), async move { - let security = Arc::new(crate::security::SecurityPolicy::from_config( - &profile_config.autonomy, - &profile_config.workspace_dir, - &profile_config.action_dir, - )); + let security = Arc::new(crate::security::SecurityPolicy::for_config(&profile_config)); let mut dispatcher = JobDispatcher::new(profile_config.scheduler.max_concurrent); dispatcher .dispatch(&profile_config, &security, claimed) diff --git a/crates/openhuman-core/src/profiles/host.rs b/crates/openhuman-core/src/profiles/host.rs index e2bfcfef667..f3f27097bc5 100644 --- a/crates/openhuman-core/src/profiles/host.rs +++ b/crates/openhuman-core/src/profiles/host.rs @@ -630,12 +630,7 @@ pub(super) fn create_dirs(layout: &ProfileLayout) -> Result<(), String> { /// its workspace and sandbox, never the operator's live policy. fn profile_policy(config: &Config) -> Arc { Arc::new( - crate::security::SecurityPolicy::from_config( - &config.autonomy, - &config.workspace_dir, - &config.action_dir, - ) - .with_privacy_mode(config.privacy.mode), + crate::security::SecurityPolicy::for_config(config).with_privacy_mode(config.privacy.mode), ) } diff --git a/crates/openhuman-core/src/tools/native_ops.rs b/crates/openhuman-core/src/tools/native_ops.rs index fe1e6920682..b11b1b48200 100644 --- a/crates/openhuman-core/src/tools/native_ops.rs +++ b/crates/openhuman-core/src/tools/native_ops.rs @@ -76,11 +76,7 @@ pub fn build_runtime_tools(config: &Config) -> Result>, String workspace = %config.workspace_dir.display(), "[native_ops] build_runtime_tools: start" ); - let security = Arc::new(SecurityPolicy::from_config( - &config.autonomy, - &config.workspace_dir, - &config.action_dir, - )); + let security = Arc::new(SecurityPolicy::for_config(config)); // Phase 1 of #1401: see comment in channels/runtime/startup.rs. let audit = crate::security::get_or_create_workspace_audit_logger( crate::config::AuditConfig::default(), From 8ded19357d0b088b762f2680b89e0464cc40726f Mon Sep 17 00:00:00 2001 From: Maciej Myszkiewicz Date: Mon, 19 Oct 2026 15:10:14 +0200 Subject: [PATCH 06/11] test(security): assert the account root on the existing reload cycle, not a new one MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The account-root assertion arrived as its own test, `account_root_survives_an_autonomy_reload`, which installed the *process-global* `SecurityPolicy` and reloaded it. That destabilised the suite, and the reason took three steps to pin down: - **Attribution.** The suite failed on `intercept_with_external_channel_origin_persists_and_ttl_denies` ("audit row never appeared"), a test in a file this branch does not touch — but it passed on its own, and the suite passed 1004/0 with only the new test skipped. So the trigger was the new test, not the one that failed. - **Mechanism.** That test waits for a `shell` call to *park*. The new test reloaded into `AutonomyConfig { level: Full, .. }`, and `Full` answers `Allow` for the `Write` class, so the call stops parking. `AutonomyConfig::default()` is `enabled: false`, which answers `Allow` too, so the first version was worse. - **The obvious fixes were not enough, and that was measured.** Restoring the previous policy at the end did nothing, because the interference is concurrent rather than sequential. Switching the reload to `Supervised` gave one green run and one red one — on a *different* test (`validate_path_expands_tilde_before_workspace_join`), while the skip-the-new-test baseline was 2/2 green. The problem was not the level; it was adding a third cycle of global-policy mutation to a suite where several env-sensitive tests read that global without serialising against it. So the assertion now rides on the install/reload cycle `install_then_reload_swaps_policy_and_bumps_generation` already performs: no new global mutation, same coverage. It still pins the thing the `live_policy` change fixed — `reload_from` rebuilds through `from_config`, which cannot infer the account root, so without the stored copy the field is right at boot and lost on the first `config.update_autonomy_settings`. The comment in the test says why the assertion lives there rather than in a test of its own, so it does not get "tidied" back out into one and wake the same race. Suite: 1004 passed, 0 failed, twice. --- .../src/security/live_policy_tests.rs | 71 +++++++------------ 1 file changed, 25 insertions(+), 46 deletions(-) diff --git a/crates/openhuman-core/src/security/live_policy_tests.rs b/crates/openhuman-core/src/security/live_policy_tests.rs index 0ede4e7c2b4..d52363cd782 100644 --- a/crates/openhuman-core/src/security/live_policy_tests.rs +++ b/crates/openhuman-core/src/security/live_policy_tests.rs @@ -46,11 +46,21 @@ fn install_then_reload_swaps_policy_and_bumps_generation() { // which all take this same lock — otherwise a parallel install races. let _env = crate::config::TEST_ENV_LOCK.blocking_lock(); let workspace = std::env::temp_dir().join("openhuman_live_policy_test"); - let initial = Arc::new(SecurityPolicy { - autonomy: AutonomyLevel::Supervised, - workspace_dir: workspace.clone(), - ..SecurityPolicy::default() - }); + // The account root rides along on this cycle rather than in a test of its + // own: asserting it needs an install and a reload, and a third test + // mutating this process-global measurably destabilises the env-sensitive + // tests that read it (an added install/reload cycle turned the suite from + // 2/2 green into an intermittent failure in `trusted_roots` and the + // approval origin-intercept tests). + let account = workspace.join("account"); + let initial = Arc::new( + SecurityPolicy { + autonomy: AutonomyLevel::Supervised, + workspace_dir: workspace.clone(), + ..SecurityPolicy::default() + } + .with_account_dir(Some(account.as_path())), + ); install(initial, workspace.clone(), workspace.clone()); let before = generation(); @@ -68,9 +78,17 @@ fn install_then_reload_swaps_policy_and_bumps_generation() { reload_from(&cfg); assert!(generation() > before, "generation must increase on reload"); + let after = current().expect("policy still installed"); + assert_eq!(after.autonomy, AutonomyLevel::Full); + // `reload_from` rebuilds through `from_config`, which cannot infer the + // account root (it is not derivable from `workspace_dir`). Without the + // stored copy the field would be right at boot and silently lost on the + // first `config.update_autonomy_settings` — the predicate would still run, + // just against the wrong directory. assert_eq!( - current().expect("policy still installed").autonomy, - AutonomyLevel::Full + after.account_dir.as_deref(), + Some(account.as_path()), + "the configured account root must survive a reload" ); } @@ -261,42 +279,3 @@ async fn an_explicit_context_policy_wins_over_the_ambient_one() { assert!(Arc::ptr_eq(&seen.expect("explicit policy"), &explicit)); } - -/// `reload_from` rebuilds through `from_config`, which cannot infer the account -/// root (it is not derivable from `workspace_dir`). Without the stored copy the -/// field would be right at boot and silently lost on the first -/// `config.update_autonomy_settings`, which is the hard kind of bug to notice: -/// the predicate still runs, just against the wrong directory. -#[test] -fn account_root_survives_an_autonomy_reload() { - // Same process-global lock as the other live-policy tests. - let _env = crate::config::TEST_ENV_LOCK.blocking_lock(); - let account = std::env::temp_dir().join("openhuman_live_policy_account"); - let workspace = account.join("workspace"); - let installed = Arc::new( - SecurityPolicy { - workspace_dir: workspace.clone(), - ..SecurityPolicy::default() - } - .with_account_dir(Some(account.as_path())), - ); - install(installed, workspace.clone(), workspace.clone()); - assert_eq!( - current().expect("policy installed").account_dir.as_deref(), - Some(account.as_path()) - ); - - reload_from(&AutonomyConfig { - level: AutonomyLevel::Full, - ..AutonomyConfig::default() - }); - - assert_eq!( - current() - .expect("policy still installed") - .account_dir - .as_deref(), - Some(account.as_path()), - "the configured account root must survive a reload" - ); -} From f2bf19588c1acdd1ac3235660456c69d0d5a9a0b Mon Sep 17 00:00:00 2001 From: Maciej Myszkiewicz Date: Mon, 19 Oct 2026 23:45:44 +0200 Subject: [PATCH 07/11] fix(cron): drop the unreferenced scheduler retry file this branch resurrected MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CodeRabbit flagged `cron/scheduler/retry.rs` as a second, unreachable retry path. It was right, and the file was this branch's fault rather than main's. What I verified before removing it: - `cron/scheduler.rs` declares `agent_run`, `builtin`, `delivery`, `executor`, `failure_classification`, `origin_context`, `origin_delivery`, `run_delivery` and `shell_job` — not `retry`. No `mod retry`, no `#[path = ".../retry.rs"]` and no `include!` names it anywhere in the crate, so rustc never compiled it. That is also why its missing `DispatchCtx` arguments never broke the build. - It does not exist on `upstream/main`, and in this branch's diff against the merge base it is a *new* 297-line file — the only file this branch adds. - `agent_session_target_tag`, which it defines, already lives in `scheduler/executor.rs`, so the file was a stale duplicate of logic main had already moved. How it got here: the `for_config` conversion touched this file back when main still had it. Main then removed it and folded that logic into `executor.rs`, which made an earlier `git merge upstream/main` a modify/delete conflict on a file I had edited — and I resolved it by keeping my copy. That silently restored a file main had deleted. The conversion inside it was therefore pointless, and carrying it made this PR look like it was adding a competing scheduler path. I checked whether the same accident restored anything else: `retry.rs` is the only file this branch adds and the only one absent from main, so this was the single instance. Deleting a file rustc never compiled cannot change the build, so this does not invalidate the `clippy --features "$(bash scripts/ci/product-features.sh --core)"` run that passed on the merge commit. --- .../src/cron/scheduler/retry.rs | 297 ------------------ 1 file changed, 297 deletions(-) delete mode 100644 crates/openhuman-core/src/cron/scheduler/retry.rs diff --git a/crates/openhuman-core/src/cron/scheduler/retry.rs b/crates/openhuman-core/src/cron/scheduler/retry.rs deleted file mode 100644 index 852d79c176a..00000000000 --- a/crates/openhuman-core/src/cron/scheduler/retry.rs +++ /dev/null @@ -1,297 +0,0 @@ -//! The per-job retry loop with exponential backoff, its permanent-halt -//! short-circuits, and the retries-exhausted observability report. - -use super::agent_run::{run_agent_job_for_run, run_flow_schedule_job}; -use super::failure_classification::{ - is_api_key_unset_failure, is_budget_exhausted_failure, is_insufficient_credits_failure, - is_local_provider_unreachable_failure, is_session_expired_failure, permanent_halt_message, -}; -use super::shell_job::run_job_command; -use crate::config::Config; -use crate::cron::{CronJob, JobType, SessionTarget}; -use crate::security::SecurityPolicy; -use chrono::Utc; -use tokio::time::{self, Duration}; - -pub(super) fn agent_session_target_tag(target: &SessionTarget) -> &'static str { - match target { - SessionTarget::Main => "main", - SessionTarget::Isolated => "isolated", - SessionTarget::Current => "current", - } -} - -/// Run `job` now under the caller's `run_id` (also the id its delivery and -/// run record use). -pub async fn execute_job_now(config: &Config, job: &CronJob, run_id: &str) -> (bool, String) { - let security = SecurityPolicy::for_config(config); - execute_job_with_retry_for_run(config, &security, job, run_id).await -} - -/// [`execute_job_with_retry_for_run`] under a fresh run id. -#[cfg(test)] -pub(super) async fn execute_job_with_retry( - config: &Config, - security: &SecurityPolicy, - job: &CronJob, -) -> (bool, String) { - let run_id = uuid::Uuid::new_v4().to_string(); - execute_job_with_retry_for_run(config, security, job, &run_id).await -} - -pub(super) async fn execute_job_with_retry_for_run( - config: &Config, - security: &SecurityPolicy, - job: &CronJob, - run_id: &str, -) -> (bool, String) { - let mut last_output = String::new(); - let mut last_agent_error: Option = None; - // A per-job override (`cron::policy`) wins; `Some(0)` is one attempt. An - // unreadable policy refuses the run (and any later attempt) outright. - if let Err(error) = crate::cron::limits::check_run(config, job) { - return (false, error.to_string()); - } - let policy = match crate::cron::policy::get_policy(config, &job.id) { - Ok(policy) => policy, - Err(error) => return (false, error.to_string()), - }; - let retries = crate::cron::policy::effective_retries(config, &policy); - let mut backoff_ms = config.reliability.provider_backoff_ms.max(200); - let mut session_expired = false; - let mut credits_exhausted = false; - let mut budget_exhausted = false; - let mut key_unset = false; - let mut local_unreachable = false; - - for attempt in 0..=retries { - if attempt > 0 { - if let Err(error) = crate::cron::policy::get_policy(config, &job.id) { - return (false, error.to_string()); - } - } - let (success, output, agent_error) = match job.job_type { - JobType::Shell => { - let (success, output) = run_job_command(config, security, job).await; - (success, output, None) - } - JobType::Agent => run_agent_job_for_run(config, job, run_id).await, - JobType::Flow => { - let (success, output) = run_flow_schedule_job(job).await; - (success, output, None) - } - }; - last_output = output; - if agent_error.is_some() { - last_agent_error = agent_error; - } - - if success { - return (true, last_output); - } - - if last_output.starts_with("blocked by security policy:") { - // Deterministic policy violations are not retryable. - return (false, last_output); - } - - if is_session_expired_failure( - &job.job_type, - last_agent_error.as_deref(), - last_output.as_str(), - ) { - // Halt on the first occurrence — the inference layer already - // published `SessionExpired`, retries cannot recover until the - // user re-auths, and the classifier considers this expected - // user state (TAURI-RUST-N). See `is_session_expired_failure` - // for the full rationale. - session_expired = true; - break; - } - - if is_insufficient_credits_failure( - &job.job_type, - last_agent_error.as_deref(), - last_output.as_str(), - ) { - // Halt on the first occurrence — a BYO provider 402 (out of - // balance) is permanent across the backoff loop, and the - // provider emit site already demoted it from Sentry. Skipping - // the retries-exhausted `report_error` below keeps the residual - // off Sentry at source, independent of the `before_send` chain - // (TAURI-RUST-514). See `is_insufficient_credits_failure`. - // Metadata-only log (no raw provider body — see CLAUDE.md). - log::debug!( - "[cron] action=halt_on_insufficient_credits_402 job_id={} attempt={} retries={}", - job.id.as_str(), - attempt, - retries - ); - credits_exhausted = true; - break; - } - - if is_budget_exhausted_failure( - &job.job_type, - last_agent_error.as_deref(), - last_output.as_str(), - ) { - // Halt on the first occurrence — a managed-backend budget 400 - // (USER_INSUFFICIENT_CREDITS) is permanent across the backoff - // loop. The tag-gated `is_budget_event` before_send filter never - // matches this cron re-report, so suppressing the report here - // keeps it off Sentry at source (TAURI-RUST-BMW). See - // `is_budget_exhausted_failure`. Metadata-only log (no raw body). - log::debug!( - "[cron] action=halt_on_budget_exhausted_400 job_id={} attempt={} retries={}", - job.id.as_str(), - attempt, - retries - ); - budget_exhausted = true; - break; - } - - if is_api_key_unset_failure( - &job.job_type, - last_agent_error.as_deref(), - last_output.as_str(), - ) { - // Halt on the first occurrence — a configured provider with no - // API key fails deterministically at the credential guard before - // any HTTP, so the missing key is permanent across the backoff - // loop. The bare cron `report_error` below bypasses the - // `ApiKeyMissing` `expected_error_kind` demotion, so suppressing - // here keeps the residual off Sentry at source (TAURI-RUST-HCK). - // The failure stays visible to the user via the alerts tab - // (`push_cron_alert`) + run history. See `is_api_key_unset_failure`. - // Metadata-only log (no raw provider body — see CLAUDE.md). - log::debug!( - "[cron] action=halt_on_api_key_unset job_id={} attempt={} retries={}", - job.id.as_str(), - attempt, - retries - ); - key_unset = true; - break; - } - - if is_local_provider_unreachable_failure( - &job.job_type, - last_agent_error.as_deref(), - last_output.as_str(), - ) { - // Halt on the first occurrence — a local LLM provider refusing the - // loopback connection (LM Studio / Ollama not running) cannot - // recover across the backoff loop, and the provider/agent emit - // sites already demoted it from Sentry (`LoopbackUnavailable`). - // The bare cron `report_error` below bypasses that demotion, so - // suppressing here keeps the residual off Sentry at source - // (TAURI-RUST-12K). The failure stays visible via the run history - // + cron alert. See `is_local_provider_unreachable_failure`. - // Metadata-only log (no raw provider body — see CLAUDE.md). - log::debug!( - "[cron] action=halt_on_local_provider_unreachable job_id={} attempt={} retries={}", - job.id.as_str(), - attempt, - retries - ); - local_unreachable = true; - break; - } - - if attempt < retries { - let jitter_ms = u64::from(Utc::now().timestamp_subsec_millis() % 250); - time::sleep(Duration::from_millis(backoff_ms + jitter_ms)).await; - backoff_ms = (backoff_ms.saturating_mul(2)).min(30_000); - } - } - - // Permanent user-config / billing states are demoted at source: halt the - // loop and skip the retries-exhausted report, independent of the tag-gated - // before_send filters that the cron re-report does not match. Covers BYO - // 402 out-of-credit + managed-backend 400 out-of-budget (TAURI-RUST-514 / - // -BMW) and a configured provider with no API key (TAURI-RUST-HCK). The - // `session_expired` (TAURI-RUST-N) and `local_unreachable` (a local LLM - // server refusing the loopback connection, TAURI-RUST-12K) halts are the - // same shape — suppress the bypassing bare report — but carry no - // user-config remediation surface, so they gate the report directly rather - // than routing through `permanent_config_halt`'s UserErrorCenter swap. - let permanent_config_halt = credits_exhausted || budget_exhausted || key_unset; - if matches!(job.job_type, JobType::Agent) - && !session_expired - && !local_unreachable - && !permanent_config_halt - { - let report_message = last_agent_error.as_deref().unwrap_or(last_output.as_str()); - crate::core::observability::report_error( - report_message, - "cron", - "agent_job", - &[ - ("job_id", job.id.as_str()), - ("agent_id", job.agent_id.as_deref().unwrap_or("none")), - ( - "session_target", - agent_session_target_tag(&job.session_target), - ), - ("failure", "retries_exhausted"), - ], - ); - } else if matches!(job.job_type, JobType::Agent) && permanent_config_halt { - // Suppressed the retries-exhausted Sentry report for a permanent - // user-config / billing state. Metadata-only breadcrumb so the - // suppression is diagnosable in production without the raw provider body. - let (reason, user_error_kind) = if credits_exhausted { - ("insufficient_credits_402", "insufficient_credits") - } else if budget_exhausted { - ("budget_exhausted_400", "budget_exceeded") - } else { - ("api_key_unset", "api_key_missing") - }; - log::debug!( - "[cron] action=suppress_retries_exhausted_report reason={reason} job_id={} retries={}", - job.id.as_str(), - retries - ); - // Replace the generic agent-failure copy with the specific, actionable - // (static, leak-safe) reason so the hoisted /notifications alert + run - // history tell the user the exact next step rather than "Something went - // wrong" (CodeRabbit #4169). The raw `last_agent_error` chain is NEVER - // surfaced here — only the `&'static str` constants from - // `permanent_halt_message`. - last_output = permanent_halt_message(credits_exhausted, budget_exhausted).to_string(); - // Also surface the actionable state to the UserErrorCenter so the user - // can fix it (add an API key / top up credits / raise the budget) even - // with no chat thread open. Broadcast-only + metadata-only — see - // `publish_cron_user_error` (#4165 / TAURI-RUST-HCK follow-up). - publish_cron_user_error(user_error_kind); - } - - (false, last_output) -} - -/// Surface a permanent cron user-config / billing halt to every connected -/// client's UserErrorCenter. -/// -/// Broadcasts a metadata-only `user_error` web-channel event to the `"system"` -/// room (which every socket auto-joins). The payload carries only the stable -/// `kind` token in `error_type` — one of `api_key_missing` / `insufficient_credits` -/// / `budget_exceeded`, mirroring the frontend `UserErrorKind` discriminator — -/// plus `error_source = "cron"`. It NEVER carries the raw provider body (see the -/// metadata-only rule in CLAUDE.md), so no secrets / PII leave the core. -/// -/// The frontend `socketService` listens for `user_error` and routes it through -/// the same classifier the chat runtime uses, so a background (no-delivery) job -/// failure is no longer silent — it lands in the shell's UserErrorCenter with a -/// deep-link action even though no chat thread is active. -pub(super) fn publish_cron_user_error(kind: &str) { - log::debug!("[cron] action=surface_user_error kind={kind}"); - crate::web_chat::publish_web_channel_event(crate::web_chat::WebChannelEvent { - event: "user_error".to_string(), - client_id: "system".to_string(), - error_type: Some(kind.to_string()), - error_source: Some("cron".to_string()), - ..Default::default() - }); -} From b7f6b66ee75573b160418f5ed57d6b8c2d2f2fec Mon Sep 17 00:00:00 2001 From: Maciej Myszkiewicz Date: Tue, 20 Oct 2026 02:50:55 +0200 Subject: [PATCH 08/11] refactor(security): drop the account-root call this branch already makes twice MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two call sites chained `.with_account_dir(config.config_path.parent())` onto a `SecurityPolicy::for_config(..)` that already does exactly that: `for_config` -> `for_config_in` -> `from_config(..).with_account_dir( config.config_path.parent())`. The second call set the identical value, so this is a no-op at runtime — but it reads as though `for_config` could not be trusted to attach the root, which is the whole point of introducing it in this PR. Sites: `openhuman-embed/src/agent/build.rs` and `channels/runtime/startup/start_channels.rs`. Found by grepping this branch's own diff for `for_config` followed by `with_account_dir`; those were the only two, and `enforcement.rs` is the definition itself rather than a caller. `live_policy::install` is unaffected: it seeds its stored account root from `policy.account_dir` on every install, not from a separate argument, and `for_config` has already populated that field. So the value the live policy keeps — and re-applies on an autonomy-only `reload_from` — is unchanged. Verified with the two lane checks this touches rather than the default feature set: `cargo clippy -p openhuman --features "$(bash scripts/ci/product-features.sh --core)" -- -D warnings` and `cargo clippy -p openhuman-embed --all-targets -- -D warnings` both exit 0, and `cargo test -p openhuman --lib --features -- security::` is 1009 passed, 0 failed — including `for_config_attaches_the_configs_account_root` and `install_then_reload_swaps_policy_and_bumps_generation`, the two that would catch a lost account root. --- .../src/channels/runtime/startup/start_channels.rs | 4 ++-- crates/openhuman-embed/src/agent/build.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs b/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs index 3849ce0c650..c18f16f3869 100644 --- a/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs +++ b/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs @@ -107,8 +107,8 @@ async fn start_channels_inner(mut config: Config, session: CancellationToken) -> let security = crate::security::live_policy::install( Arc::new( SecurityPolicy::for_config(&config) - .with_privacy_mode(config.privacy.mode) - .with_account_dir(config.config_path.parent()), + // `for_config` already attaches the config's account root. + .with_privacy_mode(config.privacy.mode), ), config.workspace_dir.clone(), config.action_dir.clone(), diff --git a/crates/openhuman-embed/src/agent/build.rs b/crates/openhuman-embed/src/agent/build.rs index 4c8b50a5e59..196afb75e3a 100644 --- a/crates/openhuman-embed/src/agent/build.rs +++ b/crates/openhuman-embed/src/agent/build.rs @@ -310,9 +310,9 @@ pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result Date: Sat, 31 Oct 2026 11:29:18 +0100 Subject: [PATCH 09/11] test(security): import the pub(super) account constants explicitly `use super::*` does not reach them: they are `pub(super)` items of `policy::types`, and `policy::mod` does not re-export them. --- crates/openhuman-core/src/security/policy/native_paths_tests.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/openhuman-core/src/security/policy/native_paths_tests.rs b/crates/openhuman-core/src/security/policy/native_paths_tests.rs index da7cf2c05ac..b870cbd6dd0 100644 --- a/crates/openhuman-core/src/security/policy/native_paths_tests.rs +++ b/crates/openhuman-core/src/security/policy/native_paths_tests.rs @@ -1,3 +1,4 @@ +use super::types::{ACCOUNT_CONFIG_FILE, ACCOUNT_INTERNAL_FILES}; use super::*; /// The reserved paths the host hands TinySecurity, as plain path buffers. From f96294491d5c355f68495dbbbaf749c2b8b5cfab Mon Sep 17 00:00:00 2001 From: M3gA-Mind Date: Mon, 9 Nov 2026 17:43:23 +0530 Subject: [PATCH 10/11] Pass config straight to SecurityPolicy::for_config in write_dispatch config is already a &Config, so borrowing it again trips clippy's needless_borrow and fails rust-lint. --- crates/openhuman-core/src/mcp/server/write_dispatch.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/openhuman-core/src/mcp/server/write_dispatch.rs b/crates/openhuman-core/src/mcp/server/write_dispatch.rs index 461c9e983ff..bb64ae43504 100644 --- a/crates/openhuman-core/src/mcp/server/write_dispatch.rs +++ b/crates/openhuman-core/src/mcp/server/write_dispatch.rs @@ -35,7 +35,7 @@ pub(super) async fn enforce_write_policy_for_config( tool_name: &str, config: &Config, ) -> Result<(), ToolCallError> { - let policy = SecurityPolicy::for_config(&config); + let policy = SecurityPolicy::for_config(config); match policy .enforce_tool_operation(ToolOperation::Act, tool_name) .await From 84eec3dfe100ef868e3bdbffa01ac8ccea1dbdbd Mon Sep 17 00:00:00 2001 From: M3gA-Mind Date: Mon, 9 Nov 2026 18:06:06 +0530 Subject: [PATCH 11/11] Build every config policy through for_config so none loses the account root Eight production sites still built their policy with SecurityPolicy::from_config(&config.autonomy, &config.workspace_dir, &config.action_dir), which leaves account_dir unset. In a split layout (config beside, not above, the workspace) those policies guarded only config.toml and left .secret_key, auth-profiles.json, config.toml.bak and claude_code_settings.json reachable: the session factory, the cron dispatcher and shell-job handler, flow authoring and the flow caps host, command hooks, speech output and the sandbox spawn plan. All eight now call for_config, which takes the account root from config_path. Two tests keep it that way: one checks that for_config and for_config_in both carry config_path's parent and reserve the account files under it, and one scans the core, embed and tinyhumans sources and fails on any new production from_config call outside the three sites that set the account root themselves (bootstrap, live_policy's reload, and enforcement). --- .../builder/factory/build_session.rs | 6 +- .../src/cron/scheduler/dispatcher.rs | 6 +- .../src/cron/schemas/handlers.rs | 6 +- .../src/flows/authoring_host.rs | 6 +- .../src/flows/caps_host/binding.rs | 6 +- crates/openhuman-core/src/hooks/host.rs | 8 +- .../inference/host_runtime/service/speech.rs | 6 +- .../src/sandbox/spawn_plan/facts.rs | 7 +- .../src/security/policy/native_paths_tests.rs | 102 ++++++++++++++++++ 9 files changed, 111 insertions(+), 42 deletions(-) diff --git a/crates/openhuman-core/src/agent/session_host/builder/factory/build_session.rs b/crates/openhuman-core/src/agent/session_host/builder/factory/build_session.rs index 0f523288e7c..b3ce33fee4c 100644 --- a/crates/openhuman-core/src/agent/session_host/builder/factory/build_session.rs +++ b/crates/openhuman-core/src/agent/session_host/builder/factory/build_session.rs @@ -20,11 +20,7 @@ impl OpenHumanSessionHost { let runtime: Arc = Arc::from( host_runtime::create_runtime(&config.runtime, config.shell.hide_window)?, ); - let security = Arc::new(SecurityPolicy::from_config( - &config.autonomy, - &config.workspace_dir, - &config.action_dir, - )); + let security = Arc::new(SecurityPolicy::for_config(config)); let audit = crate::security::get_or_create_workspace_audit_sink( config.audit.clone(), config.workspace_dir.clone(), diff --git a/crates/openhuman-core/src/cron/scheduler/dispatcher.rs b/crates/openhuman-core/src/cron/scheduler/dispatcher.rs index b8023a2adc3..6162ff796d6 100644 --- a/crates/openhuman-core/src/cron/scheduler/dispatcher.rs +++ b/crates/openhuman-core/src/cron/scheduler/dispatcher.rs @@ -81,11 +81,7 @@ async fn own_manual_run( // Keep the invocation's CoreContext strongly pinned while Binding itself // retains only a Weak reference. The task is the acyclic lifetime owner. let _context_pin = ctx.core().cloned(); - let security = Arc::new(SecurityPolicy::from_config( - &config.autonomy, - &config.workspace_dir, - &config.action_dir, - )); + let security = Arc::new(SecurityPolicy::for_config(&config)); let binding = Binding::new(&ctx, &config, security); let host = bus_host::register(binding.clone()) .await diff --git a/crates/openhuman-core/src/cron/schemas/handlers.rs b/crates/openhuman-core/src/cron/schemas/handlers.rs index b0d89e16daf..7c1074d564b 100644 --- a/crates/openhuman-core/src/cron/schemas/handlers.rs +++ b/crates/openhuman-core/src/cron/schemas/handlers.rs @@ -81,11 +81,7 @@ pub(super) fn handle_add(ctx: DispatchCtx, params: Map) -> Contro let job = match job_type { "shell" => { let cmd = command.ok_or("'command' is required for shell jobs")?; - let security = crate::security::SecurityPolicy::from_config( - &config.autonomy, - &config.workspace_dir, - &config.action_dir, - ); + let security = crate::security::SecurityPolicy::for_config(&config); crate::cron::scheduler::shell_job::authorize_shell_command( &config, &security, &cmd, ) diff --git a/crates/openhuman-core/src/flows/authoring_host.rs b/crates/openhuman-core/src/flows/authoring_host.rs index d5a691dfbaf..e56cf626c23 100644 --- a/crates/openhuman-core/src/flows/authoring_host.rs +++ b/crates/openhuman-core/src/flows/authoring_host.rs @@ -126,11 +126,7 @@ impl ApprovalCallbacks { use crate::security::SecurityPolicy; use tinyflows_bus::catalog::{ManifestCandidate, ManifestClass}; - let security = SecurityPolicy::from_config( - &config.autonomy, - &config.workspace_dir, - &config.action_dir, - ); + let security = SecurityPolicy::for_config(&config); async fn gated( security: &SecurityPolicy, class: CommandClass, diff --git a/crates/openhuman-core/src/flows/caps_host/binding.rs b/crates/openhuman-core/src/flows/caps_host/binding.rs index 1fe57a8bbfd..5e1df72793a 100644 --- a/crates/openhuman-core/src/flows/caps_host/binding.rs +++ b/crates/openhuman-core/src/flows/caps_host/binding.rs @@ -182,11 +182,7 @@ pub(crate) async fn serve( }, }; let ctx = ctx.with_turn_origin(origin); - let security = Arc::new(crate::security::SecurityPolicy::from_config( - &config.autonomy, - &config.workspace_dir, - &config.action_dir, - )); + let security = Arc::new(crate::security::SecurityPolicy::for_config(&config)); let approval = crate::security::approval::ApprovalTurnContext { flow_run: Some(crate::security::approval::FlowRunContext { flow_id: flow_id.clone(), diff --git a/crates/openhuman-core/src/hooks/host.rs b/crates/openhuman-core/src/hooks/host.rs index 372b933e1b4..d57a82118e2 100644 --- a/crates/openhuman-core/src/hooks/host.rs +++ b/crates/openhuman-core/src/hooks/host.rs @@ -65,12 +65,8 @@ async fn admit_command_hooks(ctx: &DispatchCtx, loaded: &mut HookConfig) { // 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) + crate::security::SecurityPolicy::for_config(&config) + .with_privacy_mode(config.privacy.mode) }) .map_err(|error| error.to_string()); let mut refused = Vec::new(); diff --git a/crates/openhuman-core/src/inference/host_runtime/service/speech.rs b/crates/openhuman-core/src/inference/host_runtime/service/speech.rs index ee3dc0afc92..d70f9be94b5 100644 --- a/crates/openhuman-core/src/inference/host_runtime/service/speech.rs +++ b/crates/openhuman-core/src/inference/host_runtime/service/speech.rs @@ -197,11 +197,7 @@ async fn validated_tts_output_path( let candidate_string = candidate .to_str() .ok_or_else(|| "invalid output_path".to_string())?; - let mut policy = crate::security::SecurityPolicy::from_config( - &config.autonomy, - &config.workspace_dir, - &config.action_dir, - ); + let mut policy = crate::security::SecurityPolicy::for_config(config); policy.trusted_roots.push(crate::security::TrustedRoot { path: config.workspace_dir.display().to_string(), access: crate::security::TrustedAccess::ReadWrite, diff --git a/crates/openhuman-core/src/sandbox/spawn_plan/facts.rs b/crates/openhuman-core/src/sandbox/spawn_plan/facts.rs index fb588b00000..673c1f512a4 100644 --- a/crates/openhuman-core/src/sandbox/spawn_plan/facts.rs +++ b/crates/openhuman-core/src/sandbox/spawn_plan/facts.rs @@ -169,12 +169,7 @@ fn configured(config: &Config) -> bool { /// chose for this spawn (its workspace and the mounts it resolved). The module still /// refuses the protected floor and the core's internal state under every root. fn paths(config: &Config, policy: &SandboxPolicy) -> PathPolicy { - let mut paths = crate::security::SecurityPolicy::from_config( - &config.autonomy, - &config.workspace_dir, - &config.action_dir, - ) - .native_path_policy(); + let mut paths = crate::security::SecurityPolicy::for_config(config).native_path_policy(); // Reserved names protect internal files from the path tools (`.env`, `SOUL.md`...) // wherever they sit under the action dir. A jail's workspace grant is the whole // action dir by design, so under that rule no workspace could ever be granted. diff --git a/crates/openhuman-core/src/security/policy/native_paths_tests.rs b/crates/openhuman-core/src/security/policy/native_paths_tests.rs index b870cbd6dd0..d5d5ecbc8ad 100644 --- a/crates/openhuman-core/src/security/policy/native_paths_tests.rs +++ b/crates/openhuman-core/src/security/policy/native_paths_tests.rs @@ -82,3 +82,105 @@ fn a_coincident_account_root_reserves_the_config_once() { reservation must not be pushed twice" ); } + +fn config_with(workspace: &str, config_path: &str) -> crate::config::Config { + crate::config::Config { + workspace_dir: PathBuf::from(workspace), + action_dir: PathBuf::from(workspace), + config_path: PathBuf::from(config_path), + ..crate::config::Config::default() + } +} + +#[test] +fn every_config_constructor_carries_the_config_paths_account_root() { + // The split layout again: the account root is `config_path`'s parent, + // not `workspace_dir`'s, so it can only come from the config. + let config = config_with("/proj/workspace", "/proj/.openhuman/config.toml"); + let account = PathBuf::from("/proj/.openhuman"); + + for (name, policy) in [ + ("for_config", SecurityPolicy::for_config(&config)), + ( + "for_config_in", + SecurityPolicy::for_config_in(&config, std::path::Path::new("/proj/turn")), + ), + ] { + assert_eq!( + policy.account_dir.as_deref(), + Some(account.as_path()), + "{name}" + ); + let reserved = reserved(&policy); + assert!( + reserved.contains(&account.join(".secret_key")), + "{name} does not reserve the account files: {reserved:?}" + ); + } +} + +/// A policy built from a whole `Config` must go through `for_config` / +/// `for_config_in`, or it silently loses the account root and guards only +/// `config.toml`. Only the sites that build from dirs of their own and chain +/// `with_account_dir` themselves may call `from_config` directly. +#[test] +fn production_code_builds_config_policies_through_for_config() { + const ALLOWED: &[&str] = &[ + "openhuman-core/src/core/runtime/bootstrap.rs", + "openhuman-core/src/security/live_policy.rs", + "openhuman-core/src/security/policy/enforcement.rs", + ]; + fn walk(dir: &std::path::Path, out: &mut Vec) { + for entry in std::fs::read_dir(dir).expect("read source dir") { + let path = entry.expect("source dir entry").path(); + if path.is_dir() { + if path.file_name().is_some_and(|name| name != "tests") { + walk(&path, out); + } + } else if path.extension().is_some_and(|ext| ext == "rs") + && !path.to_string_lossy().ends_with("tests.rs") + { + out.push(path); + } + } + } + + let crates = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .expect("crates dir"); + let mut files = Vec::new(); + for krate in ["openhuman-core", "openhuman-embed", "openhuman-tinyhumans"] { + walk(&crates.join(krate).join("src"), &mut files); + } + // The scan has to see the tree, or an empty walk would pass. + assert!(files.len() > 100, "only {} source files found", files.len()); + + let offenders: Vec = files + .iter() + .filter_map(|path| { + let rel = path + .strip_prefix(crates) + .ok()? + .to_string_lossy() + .replace('\\', "/"); + if ALLOWED.contains(&rel.as_str()) { + return None; + } + let source = std::fs::read_to_string(path).ok()?; + let hits: Vec = source + .lines() + .enumerate() + .filter(|(_, line)| { + !line.trim_start().starts_with("//") + && line.contains("SecurityPolicy::from_config(") + }) + .map(|(index, _)| index + 1) + .collect(); + (!hits.is_empty()).then(|| format!("{rel}:{hits:?}")) + }) + .collect(); + assert!( + offenders.is_empty(), + "use SecurityPolicy::for_config / for_config_in instead: {offenders:?}" + ); +}