Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(security): persist approval decisions across restarts

Steven Enamakel85827726634c
diff --git a/crates/openhuman-core/src/security/approval/gate_intercept.rs b/crates/openhuman-core/src/security/approval/gate_intercept.rs
index f9b72e2b9e..17d36313af 100644
--- a/crates/openhuman-core/src/security/approval/gate_intercept.rs
+++ b/crates/openhuman-core/src/security/approval/gate_intercept.rs
@@ -619,7 +619,7 @@ impl ApprovalGate {
gate: self,
request_id: request_id.clone(),
thread_key: thread_key.clone(),
- docs: store::capture_docs(&self.gate.config),
+ docs: store::capture_docs(&self.config),
armed: true,
};
diff --git a/crates/openhuman-core/src/security/approval/store.rs b/crates/openhuman-core/src/security/approval/store.rs
index d625ca9bf3..75953ce991 100644
--- a/crates/openhuman-core/src/security/approval/store.rs
+++ b/crates/openhuman-core/src/security/approval/store.rs
@@ -202,13 +202,13 @@ fn migrate_session_id_scrub(conn: &Connection) -> Result<()> {
Ok(())
}
-fn db_path(config: &Config) -> std::path::PathBuf {
+pub(super) fn db_path(config: &Config) -> std::path::PathBuf {
config.workspace_dir.join("approval").join("approval.db")
}
/// Open (and migrate) the approval DB, then call `f` with a live
/// connection. Mirrors `notifications/store.rs::with_connection`.
-fn with_connection<T>(config: &Config, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
+pub(super) fn with_connection<T>(config: &Config, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
let db_path = db_path(config);
tracing::trace!(
@@ -740,6 +740,8 @@ fn parse_rfc3339(input: &str) -> DateTime<Utc> {
.unwrap_or_else(|_| Utc::now())
}
+#[path = "store_import.rs"]
+pub(super) mod import;
#[path = "store_agent.rs"]
mod agent_rows;
pub use agent_rows::{exists, list_pending_for_agent, pending_agent};
diff --git a/crates/openhuman-core/src/security/approval/store_documents.rs b/crates/openhuman-core/src/security/approval/store_documents.rs
index 0f423d9f0c..be26419a35 100644
--- a/crates/openhuman-core/src/security/approval/store_documents.rs
+++ b/crates/openhuman-core/src/security/approval/store_documents.rs
@@ -27,9 +27,9 @@ use anyhow::{anyhow, Context, Result};
use chrono::{DateTime, Utc};
use serde_json::{json, Value};
-use crate::storage::{
- block_on, current_scoped, DocumentStore, DocumentStoreExt, ScopedStorage, StorageError,
-};
+use crate::config::Config;
+use crate::storage::local::{self, ImportPlan};
+use crate::storage::{block_on, DocumentStore, DocumentStoreExt, ScopedStorage, StorageError};
use tinystoragedrivers::{
CollectionSpec, ErrorKind, Filter, IndexSpec, Precondition, Query, Sort, Versioned,
};
@@ -38,8 +38,8 @@ use super::types::{
ApprovalAuditEntry, ApprovalDecision, ApprovalSourceContext, ExecutionOutcome, PendingApproval,
};
-const APPROVALS: &str = "approvals";
-const FLOW_TRUST: &str = "approval_flow_trust";
+pub(super) const APPROVALS: &str = "approvals";
+pub(super) const FLOW_TRUST: &str = "approval_flow_trust";
/// Compare-and-swap attempts before a contended update gives up.
const CAS_ATTEMPTS: usize = 32;
@@ -50,16 +50,36 @@ pub(super) struct Docs {
docs: Arc<dyn DocumentStore>,
}
-/// The document store to use for this call, when the host configured one.
+/// 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.
///
/// # 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() -> Result<Option<Docs>> {
- Ok(current_scoped()
- .context("[approval::store] resolve the storage scope")?
- .map(|scoped| Docs::new(&scoped)))
+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()?)))
+}
+
+/// The collections the approval store keeps.
+pub(super) fn collections() -> Vec<CollectionSpec> {
+ vec![
+ CollectionSpec::new(APPROVALS)
+ .index(IndexSpec::new("by_pending", ["pending", "created_at"]))
+ .index(IndexSpec::new("by_decided", ["pending", "decided_at"]))
+ .index(IndexSpec::new("by_session", ["session_id", "pending"])),
+ CollectionSpec::new(FLOW_TRUST).index(IndexSpec::new("by_flow", ["flow_id", "tool_name"])),
+ ]
}
fn storage(error: StorageError) -> anyhow::Error {
@@ -67,13 +87,13 @@ fn storage(error: StorageError) -> anyhow::Error {
}
/// Fixed-width (nanosecond, `Z`) so the strings sort in time order.
-fn rfc3339(at: DateTime<Utc>) -> String {
+pub(super) fn rfc3339(at: DateTime<Utc>) -> String {
at.to_rfc3339_opts(chrono::SecondsFormat::Nanos, true)
}
/// The comparable expiry key: nanoseconds since the epoch, falling back to
/// milliseconds for instants beyond the i64-nanosecond range (year 2262).
-fn expiry_key(at: DateTime<Utc>) -> i64 {
+pub(super) fn expiry_key(at: DateTime<Utc>) -> i64 {
at.timestamp_nanos_opt()
.unwrap_or_else(|| at.timestamp_millis().saturating_mul(1_000_000))
}
@@ -445,22 +465,15 @@ impl Docs {
/// The id of a `(flow_id, tool_name)` grant: length-prefixed, so no two
/// pairs collide.
-fn trust_id(flow_id: &str, tool_name: &str) -> String {
+pub(super) fn trust_id(flow_id: &str, tool_name: &str) -> String {
format!("{}:{flow_id}/{tool_name}", flow_id.len())
}
async fn declare(docs: &Arc<dyn DocumentStore>) -> Result<(), StorageError> {
- docs.ensure_collection(
- &CollectionSpec::new(APPROVALS)
- .index(IndexSpec::new("by_pending", ["pending", "created_at"]))
- .index(IndexSpec::new("by_decided", ["pending", "decided_at"]))
- .index(IndexSpec::new("by_session", ["session_id", "pending"])),
- )
- .await?;
- docs.ensure_collection(
- &CollectionSpec::new(FLOW_TRUST).index(IndexSpec::new("by_flow", ["flow_id", "tool_name"])),
- )
- .await
+ for spec in collections() {
+ docs.ensure_collection(&spec).await?;
+ }
+ Ok(())
}
/// Applies `change` to the request `id` under compare-and-swap and returns
diff --git a/crates/openhuman-core/src/security/approval/store_import.rs b/crates/openhuman-core/src/security/approval/store_import.rs
new file mode 100644
index 0000000000..c55243f263
--- /dev/null
+++ b/crates/openhuman-core/src/security/approval/store_import.rs
@@ -0,0 +1,125 @@
+//! One-shot import of the legacy `approval.db` tables into the document
+//! layout (`store_documents.rs`).
+//!
+//! `pending_approvals` becomes one `approvals` document per request and
+//! `flow_tool_trust` one `approval_flow_trust` document per grant. Documents
+//! are shaped exactly as `store_documents.rs` writes them: timestamps in its
+//! fixed-width form, `pending` as a boolean, `expires_ts` as the comparable
+//! expiry key, optional columns left out when NULL. The driver
+//! ([`crate::storage::local`]) writes them and then renames both tables to
+//! `_legacy_<name>`.
+
+use anyhow::{Context, Result};
+use chrono::{DateTime, Utc};
+use rusqlite::Connection;
+use serde_json::{json, Map, Value};
+
+use super::super::store_documents::{expiry_key, rfc3339, trust_id, APPROVALS, FLOW_TRUST};
+use crate::config::Config;
+use crate::storage::local::{table_exists, ImportDoc};
+
+/// The legacy tables this import retires.
+pub(super) const TABLES: &[&str] = &["pending_approvals", "flow_tool_trust"];
+
+/// Reads every legacy row, after bringing an old schema forward.
+pub(super) fn read(config: &Config) -> Result<Vec<ImportDoc>> {
+ super::with_connection(config, read_rows)
+}
+
+fn instant(raw: &str) -> Option<DateTime<Utc>> {
+ DateTime::parse_from_rfc3339(raw)
+ .ok()
+ .map(|at| at.with_timezone(&Utc))
+}
+
+/// `raw` in the document layout's fixed-width form, or unchanged when it is
+/// not a timestamp (kept rather than dropped, so nothing is lost).
+fn normalized(raw: &str) -> String {
+ instant(raw).map_or_else(|| raw.to_string(), rfc3339)
+}
+
+fn read_rows(conn: &Connection) -> Result<Vec<ImportDoc>> {
+ let mut docs = Vec::new();
+ if table_exists(conn, "pending_approvals")? {
+ let mut stmt = conn
+ .prepare(
+ "SELECT request_id, tool_name, action_summary, args_redacted, session_id,
+ created_at, expires_at, decided_at, decision, executed_at,
+ execution_outcome, execution_error, source_context,
+ tool_call_id, agent_id
+ FROM pending_approvals ORDER BY rowid",
+ )
+ .context("[approval::import] prepare pending_approvals")?;
+ let rows = stmt
+ .query_map([], |row| {
+ let text = |i: usize| row.get::<_, Option<String>>(i);
+ let mut doc = Map::new();
+ let created = row.get::<_, String>(5)?;
+ let expires = text(6)?;
+ let decided = text(7)?;
+ doc.insert("tool_name".into(), json!(row.get::<_, String>(1)?));
+ doc.insert("action_summary".into(), json!(row.get::<_, String>(2)?));
+ doc.insert("args_redacted".into(), json!(row.get::<_, String>(3)?));
+ doc.insert("session_id".into(), json!(row.get::<_, String>(4)?));
+ doc.insert("created_at".into(), json!(normalized(&created)));
+ if let Some(expires) = &expires {
+ doc.insert("expires_at".into(), json!(normalized(expires)));
+ if let Some(at) = instant(expires) {
+ doc.insert("expires_ts".into(), json!(expiry_key(at)));
+ }
+ }
+ doc.insert("pending".into(), json!(decided.is_none()));
+ for (field, value) in [
+ ("decided_at", decided.as_deref().map(normalized)),
+ ("decision", text(8)?),
+ ("executed_at", text(9)?.as_deref().map(normalized)),
+ ("execution_outcome", text(10)?),
+ ("execution_error", text(11)?),
+ ("source_context", text(12)?),
+ ("tool_call_id", text(13)?),
+ ("agent_id", text(14)?),
+ ] {
+ if let Some(value) = value {
+ doc.insert(field.into(), json!(value));
+ }
+ }
+ Ok(ImportDoc {
+ collection: APPROVALS,
+ id: row.get(0)?,
+ doc: Value::Object(doc),
+ })
+ })
+ .context("[approval::import] query pending_approvals")?;
+ for row in rows {
+ docs.push(row.context("[approval::import] decode a pending_approvals row")?);
+ }
+ }
+ if table_exists(conn, "flow_tool_trust")? {
+ let mut stmt = conn
+ .prepare("SELECT flow_id, tool_name, created_at FROM flow_tool_trust ORDER BY rowid")
+ .context("[approval::import] prepare flow_tool_trust")?;
+ let rows = stmt
+ .query_map([], |row| {
+ Ok((
+ row.get::<_, String>(0)?,
+ row.get::<_, String>(1)?,
+ row.get::<_, String>(2)?,
+ ))
+ })
+ .context("[approval::import] query flow_tool_trust")?;
+ for row in rows {
+ let (flow_id, tool_name, created) =
+ row.context("[approval::import] decode a flow_tool_trust row")?;
+ docs.push(ImportDoc {
+ collection: FLOW_TRUST,
+ id: trust_id(&flow_id, &tool_name),
+ doc: json!({
+ "flow_id": flow_id,
+ "tool_name": tool_name,
+ "created_at": normalized(&created),
+ }),
+ });
+ }
+ }
+ Ok(docs)
+}