Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 39 additions & 4 deletions crates/openhuman-core/src/security/approval/engine_stub.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
//! It keeps the lifecycle the module defines in memory: a request is pending, a
//! person approves or denies it, an approval is reserved once and its outcome
//! recorded, a request past its window expires. It applies the user's posture the
//! way the module does (auto-approve everything, a tool grant, a flow grant) and
//! records what the gate asked, so a test can pin what was sent. It is not the
//! module: what the module itself answers is pinned by the module-backed tests
//! in `native/engine_tests.rs`.
//! way the module does (auto-approve everything, a tool grant, a flow grant),
//! imports the legacy `auto_approve` list once as tool grants as the native
//! engine does, and records what the gate asked, so a test can pin what was
//! sent. It is not the module: the module-backed tests in
//! `native/engine_tests.rs` are not compiled today, so nothing here is checked
//! against the module's own answers.

use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicBool, Ordering};
Expand Down Expand Up @@ -76,6 +78,9 @@ pub(crate) struct StubEngine {
trust: Mutex<std::collections::BTreeSet<(String, String)>>,
/// Durable whole-tool trust keyed by the exact tenant and posture variant.
tool_trust: Mutex<HashSet<(Tenant, Variant, String)>>,
/// Legacy `auto_approve` entries already imported, per tenant. The module
/// answers a repeat import as already done, so a revoked grant stays revoked.
imported: Mutex<HashSet<(Tenant, String)>>,
}

impl std::fmt::Debug for StubEngine {
Expand Down Expand Up @@ -133,6 +138,15 @@ impl StubEngine {
ids.into_iter().map(|(id, _)| id.clone()).collect()
}

/// Revoke a durable tool grant, as a person does in the trust settings. The
/// tool stays imported: a later check does not grant it again.
pub(crate) fn revoke_tool_grant(&self, tenant: &Tenant, variant: Variant, tool: &str) {
self.tool_trust
.lock()
.unwrap_or_else(PoisonError::into_inner)
.remove(&(tenant.clone(), variant, tool.to_owned()));
}

/// Make every later `check` fail, as a module that cannot answer does.
pub(crate) fn refuse_checks(&self, refuse: bool) {
self.refuse.store(refuse, Ordering::SeqCst);
Expand Down Expand Up @@ -237,6 +251,27 @@ impl ApprovalEngine for StubEngine {
if self.refuse.load(Ordering::SeqCst) {
return Err(EngineError::Unavailable("the stub engine refuses".into()));
}
// As `NativeEngine::check`: the legacy list becomes durable tool trust
// the first time each tool is seen (ImportTrustSource2), outside SaaS
// and for the standard posture only.
#[cfg(feature = "legacy-import")]
if !crate::core::runtime::is_saas() && input.variant == Variant::Standard {
let mut imported = self.imported.lock().unwrap_or_else(PoisonError::into_inner);
let mut trust = self
.tool_trust
.lock()
.unwrap_or_else(PoisonError::into_inner);
// The importer skips names the module would not accept as a tool.
for tool in input
.legacy_tool_grants
.iter()
.filter(|tool| tinysecurity_bus::is_host_tool_name2(tool))
{
if imported.insert((input.tenant.clone(), tool.clone())) {
trust.insert((input.tenant.clone(), Variant::Standard, tool.clone()));
Comment thread
M3gA-Mind marked this conversation as resolved.
Resolved
}
}
}
let trusted_tool = self
.tool_trust
.lock()
Expand Down
13 changes: 9 additions & 4 deletions crates/openhuman-core/src/security/approval/gate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,15 @@
//! 1. Agent harness calls [`ApprovalGate::intercept`] with the tool
//! name, a redacted JSON of the arguments, and a short summary.
//! 2. Gate registers the call's posture with TinySecurity. Durable whole-tool
//! trust is resolved by the module under the exact approval scope;
//! `autonomy.auto_approve` is not replayed, so revocations cannot be
//! resurrected from legacy config. `ApproveAlwaysForTool` records a grant
//! through `GrantTool2` after resolving the current call.
//! trust is resolved by the module under the exact approval scope.
//! `ApproveAlwaysForTool` resolves the current call once. For a process
//! request, `approval_decide` then saves the tool to `autonomy.auto_approve`
//! (best-effort: a failed save only means the next call prompts again), and
//! the native engine imports each entry as a module grant the first time it
//! sees it (`legacy-import`, outside SaaS, standard posture). An entry is
//! imported only once, so a revoked grant is not resurrected from the list.
//! An agent's request is approved once and nothing is saved: an agent's
//! "Always allow" comes from its own access.
//! 3. Otherwise: persist a row in `pending_approvals`, publish a
//! [`DomainEvent::ApprovalRequested`] event so the UI can pop a
//! toast, and park the call on a `oneshot::Sender` keyed by
Expand Down
53 changes: 50 additions & 3 deletions crates/openhuman-core/src/security/approval/gate_agent_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,10 @@ async fn the_gate_off_switch_still_refuses_an_unlabelled_origin() {
);
}

/// A legacy `auto_approve` entry is imported once as a module tool grant, as
/// the native engine does. Once that grant is revoked, the stale list entry
/// does not bring it back, and another agent never inherits it.
#[cfg(feature = "legacy-import")]
#[tokio::test]
async fn legacy_auto_approve_lists_are_not_replayed_as_module_grants() {
let (gate, _dir) = test_gate();
Expand All @@ -96,6 +100,22 @@ async fn legacy_auto_approve_lists_are_not_replayed_as_module_grants() {
..SecurityPolicy::default()
};

let imported = gated_call(
&gate,
agent_ctx("listed", Some(listed.clone()), false),
web_origin(),
"shell",
)
.await;
assert!(
matches!(imported, Some(GateOutcome::Allow)),
"the first sight of a listed tool imports it as a grant: {imported:?}"
);
let seen = stub_of(&gate).seen();
assert!(seen[0].posture.auto_approve_all == false);
assert_eq!(seen[0].legacy_tool_grants, ["shell"]);

stub_of(&gate).revoke_tool_grant(&seen[0].tenant, seen[0].variant, "shell");
let configured = gated_call(
&gate,
agent_ctx("listed", Some(listed), false),
Expand All @@ -107,9 +127,6 @@ async fn legacy_auto_approve_lists_are_not_replayed_as_module_grants() {
!matches!(configured, Some(GateOutcome::Allow)),
"legacy config must not resurrect a revoked durable grant: {configured:?}"
);
let seen = stub_of(&gate).seen();
assert!(seen[0].posture.auto_approve_all == false);
assert_eq!(seen[0].legacy_tool_grants, ["shell"]);

let unconfigured = gated_call(
&gate,
Expand All @@ -124,6 +141,36 @@ async fn legacy_auto_approve_lists_are_not_replayed_as_module_grants() {
);
}

/// The native importer skips an `auto_approve` entry the module would not
/// accept as a tool name (`is_host_tool_name2`), so such an entry never becomes
/// a grant, as in production. `path_check` reads like a tool but is one of the
/// module's effect classes.
#[cfg(feature = "legacy-import")]
#[tokio::test]
async fn a_legacy_entry_that_is_not_a_tool_name_is_not_imported() {
let (gate, _dir) = test_gate();
let invalid = "path_check";
assert!(!tinysecurity_bus::is_host_tool_name2(invalid));
let listed = SecurityPolicy {
auto_approve: vec![invalid.into()],
auto_approve_all: false,
..SecurityPolicy::default()
};

let outcome = gated_call(
&gate,
agent_ctx("invalid-entry", Some(listed), false),
web_origin(),
invalid,
)
.await;

assert!(
!matches!(outcome, Some(GateOutcome::Allow)),
"an entry that is not a tool name must not be trusted: {outcome:?}"
);
}

#[tokio::test]
async fn an_agent_without_auto_approve_all_parks_under_a_process_policy_that_has_it() {
let (gate, dir) = test_gate();
Expand Down
28 changes: 18 additions & 10 deletions crates/openhuman-core/src/security/approval/gate_core_flow_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,14 +226,18 @@ async fn durable_tool_trust_skips_prompt() {
/// "Always allow" on a parked `create_workflow` round-trips: the decided row is
/// persisted to `autonomy.auto_approve` (what `approval::rpc::approval_decide`
/// does for `ApproveAlwaysForTool`; the RPC itself reads the process-wide gate,
/// which tests must not install), and the next `create_workflow` is allowed
/// without a second prompt.
/// which tests must not install), the engine imports it as a tool grant, and
/// the next `create_workflow` is allowed without a second prompt.
#[cfg(feature = "legacy-import")]
#[tokio::test]
async fn approve_always_for_create_workflow_persists_and_skips_the_next_prompt() {
let (gate, dir) = test_gate();
let gate = Arc::new(gate);
let _env = EnvVarGuard::workspace_async(dir.path()).await;
crate::security::live_policy::install(
// Thread-scoped, restored on drop (including on panic): this test's
// allowlist never reaches a sibling gate test through the process-global
// live policy, which is installed nowhere here.
let _policy = crate::security::live_policy::install_scoped(
Arc::new(crate::security::SecurityPolicy::default()),
dir.path().to_path_buf(),
dir.path().to_path_buf(),
Expand Down Expand Up @@ -293,6 +297,17 @@ async fn approve_always_for_create_workflow_persists_and_skips_the_next_prompt()
.any(|tool| tool == "create_workflow"),
"Always allow must persist create_workflow to autonomy.auto_approve"
);
// What `live_policy::reload_from` does for an installed live policy, on
// this thread only.
let _reloaded = crate::security::live_policy::install_scoped(
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Arc::new(crate::security::SecurityPolicy::from_config(
&saved.autonomy,
dir.path(),
dir.path(),
)),
dir.path().to_path_buf(),
dir.path().to_path_buf(),
);

let second = tokio::time::timeout(Duration::from_secs(5), intercept(gate.clone()))
.await
Expand All @@ -303,13 +318,6 @@ async fn approve_always_for_create_workflow_persists_and_skips_the_next_prompt()
gate.list_pending().unwrap().is_empty(),
"the second create_workflow must not re-prompt"
);

// Leave no allowlisted create_workflow behind for sibling gate tests.
crate::security::live_policy::install(
Arc::new(crate::security::SecurityPolicy::default()),
dir.path().to_path_buf(),
dir.path().to_path_buf(),
);
}

/// With `auto_approve_all: true`, a WebChat-origin call resolves to
Expand Down
6 changes: 4 additions & 2 deletions crates/openhuman-core/src/security/approval/gate_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,8 +197,10 @@ impl ApprovalGate {
}
}
// `ApproveAlwaysForTool` persistence is handled by the `approval_decide`
// RPC handler after this call has been released. The module records the
// whole-tool grant under the parked request's exact subject.
// RPC handler after this call has been released. For a process request
// it saves the tool to `autonomy.auto_approve` (best-effort), which the
// native engine imports as a grant on the next check; an agent's
// request is approved once and nothing is saved.
if let Some(tx) = self.parked.take_waiter(request_id) {
let _ = tx.send(decision);
}
Expand Down
5 changes: 3 additions & 2 deletions crates/openhuman-core/src/security/policy/enforcement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,8 +244,9 @@ impl SecurityPolicy {
}

// `auto_approve` is the user's "Always allow" allowlist: the
// `ApprovalGate` reads it via `live_policy::current()` and skips the
// interactive prompt for any tool named in it. Tier + `CommandClass`
// `ApprovalGate` hands it (via `live_policy`) to the native engine,
// which imports each tool once as a TinySecurity grant that skips the
// interactive prompt. Tier + `CommandClass`
// (and the unconditional read-only / forbidden-path / high-risk denials)
// still run *before* the gate, so the allowlist can only suppress the
// human prompt — it can never override a hard policy denial.
Expand Down
Loading