The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(security): add approval gate with agent, document, and flow-trust stores
Steven Enamakel84832dccd5ed
diff --git a/crates/openhuman-core/src/security/approval/gate.rs b/crates/openhuman-core/src/security/approval/gate.rsindex d413d50555..99a652e09f 100644--- a/crates/openhuman-core/src/security/approval/gate.rs+++ b/crates/openhuman-core/src/security/approval/gate.rs@@ -322,7 +322,7 @@ struct WaiterGuard<'a> {thread_key: Option<String>,/// Storage scope of the parking call, kept for `Drop`: the acting agent's/// task-local is gone by then.- docs: Result<Option<super::store_documents::Docs>, String>,+ docs: Result<super::store_documents::Docs, String>,armed: bool,}@@ -355,7 +355,6 @@ impl Drop for WaiterGuard<'_> {.clear_thread_route_if_owned(thread_key, &self.request_id);}let decided = store::decide_captured(- &self.gate.config,&self.docs,&self.request_id,ApprovalDecision::Deny,diff --git a/crates/openhuman-core/src/security/approval/mod.rs b/crates/openhuman-core/src/security/approval/mod.rsindex 35756c0f35..25e4ecacf6 100644--- a/crates/openhuman-core/src/security/approval/mod.rs+++ b/crates/openhuman-core/src/security/approval/mod.rs@@ -3,7 +3,7 @@//! [`ApprovalGate`] (in [`gate`]) is the single approval path — async//! middleware between the agent and any tool whose//! [`tinytools::Tool::external_effect`] returns `true`. It-//! persists pending rows in SQLite, parks the tool-call future on a oneshot,+//! persists pending rows in the storage backend, parks the tool-call future on a oneshot,//! and resumes when the UI dispatches `approval_decide`. Introduced for issue//! #1339 so external-channel writes (Slack post, email send, calendar create,//! …) cannot fire without explicit user consent.@@ -22,6 +22,7 @@ pub mod rpc;pub mod schemas;pub mod store;mod store_documents;+mod store_import;pub(crate) use store_documents::import_source;pub mod types;diff --git a/crates/openhuman-core/src/security/approval/store_agent.rs b/crates/openhuman-core/src/security/approval/store_agent.rsindex 8e1cfd74ea..ee4cce341c 100644--- a/crates/openhuman-core/src/security/approval/store_agent.rs+++ b/crates/openhuman-core/src/security/approval/store_agent.rs@@ -1,16 +1,14 @@//! Approval rows by the embedded agent that parked them, and whether the//! store exists to hold any.-use crate::storage::rusqlite;-use anyhow::{Context, Result};-use rusqlite::params;+use anyhow::Result;use super::{Config, PendingApproval};-/// Whether the approval store has been created for `config`'s workspace.-/// A configured document store always exists.-pub fn exists(config: &Config) -> bool {- crate::storage::installed().is_some() || super::db_path(config).is_file()+/// Whether the approval store exists for `config`'s workspace. The document+/// store is created on first use, so it always does.+pub fn exists(_config: &Config) -> bool {+ true}/// [`list_pending`](super::list_pending) narrowed to the rows of `agent` (see@@ -28,28 +26,5 @@ pub fn list_pending_for_agent(/// The agent that parked the still-undecided `request_id`: `Ok(None)` when no/// such row exists, `Ok(Some(None))` for a row the process parked itself.pub fn pending_agent(config: &Config, request_id: &str) -> Result<Option<Option<String>>> {- if let Some(docs) = super::super::store_documents::current(config)? {- return docs.pending_agent(request_id);- }- super::with_connection(config, |conn| {- let mut stmt = conn- .prepare(- "SELECT agent_id FROM pending_approvals- WHERE request_id = ?1 AND decided_at IS NULL",- )- .context("[approval::store] prepare pending_agent")?;- let mut rows = stmt- .query(params![request_id])- .context("[approval::store] query pending_agent")?;- match rows- .next()- .context("[approval::store] pending_agent next")?- {- Some(row) => Ok(Some(- row.get::<_, Option<String>>(0)- .context("[approval::store] pending_agent decode")?,- )),- None => Ok(None),- }- })+ super::super::store_documents::current(config)?.pending_agent(request_id)}diff --git a/crates/openhuman-core/src/security/approval/store_documents.rs b/crates/openhuman-core/src/security/approval/store_documents.rsindex c69d93fffd..7bda87c068 100644--- a/crates/openhuman-core/src/security/approval/store_documents.rs+++ b/crates/openhuman-core/src/security/approval/store_documents.rs@@ -28,7 +28,7 @@ use chrono::{DateTime, Utc};use serde_json::{json, Value};use crate::config::Config;-use crate::storage::local::{self, ImportPlan};+use crate::storage::local;use crate::storage::{block_on, DocumentStore, DocumentStoreExt, ScopedStorage, StorageError};use tinystoragedrivers::{CollectionSpec, ErrorKind, Filter, IndexSpec, Precondition, Query, Sort, Versioned,@@ -44,31 +44,23 @@ pub(super) const FLOW_TRUST: &str = "approval_flow_trust";/// Compare-and-swap attempts before a contended update gives up.const CAS_ATTEMPTS: usize = 32;+const DOMAIN: &str = "approval::store";+/// The approval store over one scoped document handle.#[derive(Clone)]pub(super) struct Docs {docs: Arc<dyn DocumentStore>,}-/// The document store to use for this call: the host's configured backend-/// or, by default, the document tables in `approval.db` (the legacy tables-/// imported on first open). `None` keeps the legacy tables.+/// The document store for this call: the storage backend, in the acting scope.////// # Errors////// When the storage scope cannot be resolved — in SaaS mode with no acting/// agent — so the call fails rather than reading a shared bucket.-pub(super) fn current(config: &Config) -> Result<Option<Docs>> {- let plan = ImportPlan {- domain: "approval::store",- tables: super::store::import::TABLES,- read: &|| super::store::import::read(config),- };- let Some(opened) = local::open(config, &super::store::db_path(config), collections, &plan)?- else {- return Ok(None);- };- Ok(Some(Docs::new(&opened.scoped()?)))+pub(super) fn current(config: &Config) -> Result<Docs> {+ let opened = local::open(DOMAIN, &config.workspace_dir)?;+ Ok(Docs::new(&opened.scoped()?))}/// The legacy `approval.db`, as the storage importer reads it.@@ -77,7 +69,7 @@ pub(crate) fn import_source() -> crate::storage::import::Source {domain: "approval",db: "approval/approval.db",collections,- read_legacy: |scratch, _real| super::store::import::read(scratch),+ read_legacy: |scratch, _real| super::store_import::read(scratch),rekey: |record, _config| record,}}diff --git a/crates/openhuman-core/src/security/approval/store_flow_trust.rs b/crates/openhuman-core/src/security/approval/store_flow_trust.rsindex be253f0a6a..7b5c821190 100644--- a/crates/openhuman-core/src/security/approval/store_flow_trust.rs+++ b/crates/openhuman-core/src/security/approval/store_flow_trust.rs@@ -6,15 +6,11 @@//! this flow" grants used by `ApprovalGate::intercept_audited` to//! short-circuit parking for a trusted flow/tool pair.-use crate::storage::rusqlite;-use anyhow::{Context, Result};-use chrono::Utc;-use rusqlite::params;+use anyhow::Result;use crate::config::Config;use super::super::types::{ApprovalDecision, ApprovalSourceContext};-use super::with_connection;/// The action summary of a flow pre-authorization audit row.const PREAUTHORIZATION_SUMMARY: &str = "Pre-authorized for this flow when it was saved and enabled";@@ -33,8 +29,7 @@ pub fn record_flow_preauthorization(tool_name: &str,session_id: &str,) -> Result<()> {- if let Some(docs) = super::super::store_documents::current(config)? {- return docs.insert_decided(+ super::super::store_documents::current(config)?.insert_decided(tool_name,PREAUTHORIZATION_SUMMARY,session_id,@@ -44,36 +39,7 @@ pub fn record_flow_preauthorization(node_id: None,},ApprovalDecision::ApproveAlwaysForFlow,- );- }- with_connection(config, |conn| {- let now = Utc::now().to_rfc3339();- let source_context = serde_json::to_string(&ApprovalSourceContext::Flow {- flow_id: flow_id.to_string(),- run_id: String::new(),- node_id: None,- })- .context("[approval::store] serialize preauthorization source_context")?;- conn.execute(- "INSERT INTO pending_approvals- (request_id, tool_name, action_summary, args_redacted,- session_id, created_at, expires_at, source_context,- decided_at, decision)- VALUES (?1, ?2, ?3, ?4, ?5, ?6, NULL, ?7, ?6, ?8)",- params![- uuid::Uuid::new_v4().to_string(),- tool_name,- PREAUTHORIZATION_SUMMARY,- "{}",- session_id,- now,- source_context,- ApprovalDecision::ApproveAlwaysForFlow.as_str(),- ],)- .context("[approval::store] insert preauthorization audit row")?;- Ok(())- })}/// Grant "approve always for this flow" trust to a `(flow_id, tool_name)`@@ -81,18 +47,7 @@ pub fn record_flow_preauthorization(/// flow-origin park. `INSERT OR IGNORE` makes re-granting an already-trusted/// pair a harmless no-op rather than a primary-key error.pub fn insert_flow_trust(config: &Config, flow_id: &str, tool_name: &str) -> Result<()> {- if let Some(docs) = super::super::store_documents::current(config)? {- return docs.insert_flow_trust(flow_id, tool_name);- }- with_connection(config, |conn| {- conn.execute(- "INSERT OR IGNORE INTO flow_tool_trust (flow_id, tool_name, created_at)- VALUES (?1, ?2, ?3)",- params![flow_id, tool_name, Utc::now().to_rfc3339()],- )- .context("[approval::store] insert_flow_trust")?;- Ok(())- })+ super::super::store_documents::current(config)?.insert_flow_trust(flow_id, tool_name)}/// List every `tool_name` currently holding "approve always for this flow"@@ -100,23 +55,7 @@ pub fn insert_flow_trust(config: &Config, flow_id: &str, tool_name: &str) -> Res/// save-time pre-authorization manifest (`flows_approval_manifest`) to diff/// "what the graph needs" against "what is already granted".pub fn list_flow_trust(config: &Config, flow_id: &str) -> Result<Vec<String>> {- if let Some(docs) = super::super::store_documents::current(config)? {- return docs.list_flow_trust(flow_id);- }- with_connection(config, |conn| {- let mut stmt = conn- .prepare(- "SELECT tool_name FROM flow_tool_trust- WHERE flow_id = ?1 ORDER BY tool_name",- )- .context("[approval::store] list_flow_trust prepare")?;- let names = stmt- .query_map(params![flow_id], |row| row.get::<_, String>(0))- .context("[approval::store] list_flow_trust query")?- .collect::<std::result::Result<Vec<_>, _>>()- .context("[approval::store] list_flow_trust rows")?;- Ok(names)- })+ super::super::store_documents::current(config)?.list_flow_trust(flow_id)}/// Delete flow trust rows for `flow_id`. With `tool_names: None` every grant@@ -128,52 +67,12 @@ pub fn delete_flow_trust(flow_id: &str,tool_names: Option<&[String]>,) -> Result<usize> {- if let Some(docs) = super::super::store_documents::current(config)? {- return docs.delete_flow_trust(flow_id, tool_names);- }- with_connection(config, |conn| {- let removed = match tool_names {- None => conn- .execute(- "DELETE FROM flow_tool_trust WHERE flow_id = ?1",- params![flow_id],- )- .context("[approval::store] delete_flow_trust all")?,- Some(names) => {- let mut removed = 0usize;- for name in names {- removed += conn- .execute(- "DELETE FROM flow_tool_trust- WHERE flow_id = ?1 AND tool_name = ?2",- params![flow_id, name],- )- .context("[approval::store] delete_flow_trust named")?;- }- removed- }- };- Ok(removed)- })+ super::super::store_documents::current(config)?.delete_flow_trust(flow_id, tool_names)}/// Whether `(flow_id, tool_name)` was previously granted "approve always for/// this flow" trust. Consulted by [`super::gate::ApprovalGate::intercept_audited`]/// before parking a `Workflow`-origin tool call.pub fn is_flow_tool_trusted(config: &Config, flow_id: &str, tool_name: &str) -> Result<bool> {- if let Some(docs) = super::super::store_documents::current(config)? {- return docs.is_flow_tool_trusted(flow_id, tool_name);- }- with_connection(config, |conn| {- let exists: bool = conn- .query_row(- "SELECT EXISTS(- SELECT 1 FROM flow_tool_trust WHERE flow_id = ?1 AND tool_name = ?2- )",- params![flow_id, tool_name],- |row| row.get(0),- )- .context("[approval::store] is_flow_tool_trusted")?;- Ok(exists)- })+ super::super::store_documents::current(config)?.is_flow_tool_trusted(flow_id, tool_name)}