Skip to content

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

test(security): add approval store import tests

Steven Enamakele48a2a3af3a7
diff --git a/crates/openhuman-core/src/security/approval/store_import_tests.rs b/crates/openhuman-core/src/security/approval/store_import_tests.rs
index 23d6ec7a79..0de966c46b 100644
--- a/crates/openhuman-core/src/security/approval/store_import_tests.rs
+++ b/crates/openhuman-core/src/security/approval/store_import_tests.rs
@@ -1,73 +1,104 @@
use super::*;
use crate::security::approval::store as live;
-use crate::security::approval::types::{
- ApprovalDecision, ApprovalSourceContext, ExecutionOutcome, PendingApproval,
-};
-use crate::storage::local::{forget, table_names};
-use crate::storage::rusqlite;
+use crate::security::approval::types::{ApprovalDecision, ApprovalSourceContext};
+use crate::storage::import::{run_with, Outcome};
+use crate::storage::DocumentStore;
use chrono::{Duration, Utc};
-use serde_json::json;
use tempfile::TempDir;
-fn workspace() -> (TempDir, Config, Config) {
+fn workspace() -> (TempDir, Config) {
let dir = TempDir::new().unwrap();
- let mut classic = Config {
+ let config = Config {
workspace_dir: dir.path().to_path_buf(),
..Config::default()
};
- classic.storage.url = Some("classic".into());
- let default = Config {
- workspace_dir: dir.path().to_path_buf(),
- ..Config::default()
- };
- (dir, classic, default)
+ (dir, config)
}
-fn request(id: &str, expires_in: i64) -> PendingApproval {
- PendingApproval {
- request_id: id.to_string(),
- tool_name: "composio".to_string(),
- action_summary: format!("summary {id}"),
- args_redacted: json!({ "action": "execute", "id": id }),
- created_at: Utc::now(),
- expires_at: Some(Utc::now() + Duration::minutes(expires_in)),
- source_context: Some(ApprovalSourceContext::Flow {
- flow_id: "flow-1".into(),
- run_id: "run-1".into(),
- node_id: None,
- }),
- tool_call_id: Some(format!("call-{id}")),
- agent_id: Some("agent-7".into()),
- }
+/// Writes a `pending_approvals` row the way the retired store did.
+#[allow(clippy::too_many_arguments)]
+fn seed_request(
+ config: &Config,
+ id: &str,
+ expires_in_minutes: i64,
+ decision: Option<&str>,
+ executed: bool,
+) {
+ with_connection(config, |conn| {
+ let now = Utc::now();
+ conn.execute(
+ "INSERT INTO pending_approvals
+ (request_id, tool_name, action_summary, args_redacted, session_id,
+ created_at, expires_at, decided_at, decision, executed_at,
+ execution_outcome, source_context, tool_call_id, agent_id)
+ VALUES (?1, 'composio', ?2, ?3, 'sess', ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, 'agent-7')",
+ params![
+ id,
+ format!("summary {id}"),
+ format!(r#"{{"action":"execute","id":"{id}"}}"#),
+ now.to_rfc3339(),
+ (now + Duration::minutes(expires_in_minutes)).to_rfc3339(),
+ decision.map(|_| now.to_rfc3339()),
+ decision,
+ executed.then(|| now.to_rfc3339()),
+ executed.then_some("success"),
+ serde_json::to_string(&ApprovalSourceContext::Flow {
+ flow_id: "flow-1".into(),
+ run_id: "run-1".into(),
+ node_id: None,
+ })
+ .unwrap(),
+ format!("call-{id}"),
+ ],
+ )?;
+ Ok(())
+ })
+ .unwrap();
+}
+
+fn seed_trust(config: &Config, flow: &str, tool: &str) {
+ 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, tool, Utc::now().to_rfc3339()],
+ )?;
+ Ok(())
+ })
+ .unwrap();
+}
+
+fn import(config: &Config) -> Outcome {
+ let backend = crate::storage::local::backend_for(&config.workspace_dir).unwrap();
+ run_with(&backend, config, &[super::super::import_source()])
+ .remove(0)
+ .outcome
+ .unwrap()
}
#[test]
-fn legacy_rows_are_imported_once_through_the_public_api() {
- let (_dir, classic, default) = workspace();
- // Build the legacy database with the legacy code.
- live::insert_pending(&classic, &request("pending-1", 10), "sess").unwrap();
- live::insert_pending(&classic, &request("approved-1", 10), "sess").unwrap();
- live::insert_pending(&classic, &request("denied-1", 10), "sess").unwrap();
- live::insert_pending(&classic, &request("stale-1", -5), "sess").unwrap();
- live::decide(&classic, "approved-1", ApprovalDecision::ApproveOnce).unwrap();
- live::record_execution(&classic, "approved-1", ExecutionOutcome::Success, None).unwrap();
- live::decide(&classic, "denied-1", ApprovalDecision::Deny).unwrap();
- live::insert_flow_trust(&classic, "flow-1", "shell").unwrap();
- live::insert_flow_trust(&classic, "flow-1", "http").unwrap();
- live::record_flow_preauthorization(&classic, "flow-2", "shell", "sess").unwrap();
- let db = live::db_path(&classic);
- assert!(table_names(&db).contains(&"pending_approvals".to_string()));
+fn legacy_rows_are_imported_once_and_the_file_is_left_alone() {
+ let (_dir, config) = workspace();
+ seed_request(&config, "pending-1", 10, None, false);
+ seed_request(&config, "approved-1", 10, Some("approve_once"), true);
+ seed_request(&config, "denied-1", 10, Some("deny"), false);
+ seed_request(&config, "stale-1", -5, None, false);
+ seed_trust(&config, "flow-1", "shell");
+ seed_trust(&config, "flow-1", "http");
+ let db = db_path(&config);
+ let before = std::fs::read(&db).unwrap();
+
+ assert!(matches!(
+ import(&config),
+ Outcome::Imported { found: 6, written: 6 }
+ ));
- // The default opens the same file and sees every row.
- let pending = live::list_pending(&default).unwrap();
+ let pending = live::list_pending(&config).unwrap();
let mut ids: Vec<_> = pending.iter().map(|p| p.request_id.as_str()).collect();
ids.sort_unstable();
// Listing expires the stale request, as it always did.
assert_eq!(ids, ["pending-1"]);
- let first = pending
- .iter()
- .find(|p| p.request_id == "pending-1")
- .unwrap();
+ let first = &pending[0];
assert_eq!(first.tool_name, "composio");
assert_eq!(first.action_summary, "summary pending-1");
assert_eq!(first.args_redacted["id"], "pending-1");
@@ -78,75 +109,44 @@ fn legacy_rows_are_imported_once_through_the_public_api() {
Some(ApprovalSourceContext::Flow { ref flow_id, .. }) if flow_id == "flow-1"
));
assert_eq!(
- live::get_decision(&default, "approved-1").unwrap(),
+ live::get_decision(&config, "approved-1").unwrap(),
Some(ApprovalDecision::ApproveOnce)
);
assert_eq!(
- live::get_decision(&default, "denied-1").unwrap(),
+ live::get_decision(&config, "denied-1").unwrap(),
Some(ApprovalDecision::Deny)
);
- let audit = live::list_recent_decisions(&default, 10).unwrap();
- let mut audited: Vec<_> = audit.iter().map(|a| a.decision).collect();
- audited.sort_by_key(|d| d.as_str());
- assert_eq!(
- audit.len(),
- 4,
- "approve, deny, the flow pre-authorization and the expired request"
- );
- assert!(audited.contains(&ApprovalDecision::ApproveAlwaysForFlow));
- assert!(live::is_flow_tool_trusted(&default, "flow-1", "shell").unwrap());
- assert!(live::is_flow_tool_trusted(&default, "flow-1", "http").unwrap());
- assert!(!live::is_flow_tool_trusted(&default, "flow-2", "http").unwrap());
+ assert!(live::is_flow_tool_trusted(&config, "flow-1", "shell").unwrap());
+ assert!(live::is_flow_tool_trusted(&config, "flow-1", "http").unwrap());
+ assert!(!live::is_flow_tool_trusted(&config, "flow-2", "http").unwrap());
// The expiry key was imported: the stale request was expired.
assert_eq!(
- live::get_decision(&default, "stale-1").unwrap(),
+ live::get_decision(&config, "stale-1").unwrap(),
Some(ApprovalDecision::Deny)
);
+ assert_eq!(std::fs::read(&db).unwrap(), before, "approval.db untouched");
- // The old tables are kept under their retired names.
- let tables = table_names(&db);
- assert!(tables.contains(&"_legacy_pending_approvals".to_string()));
- assert!(tables.contains(&"_legacy_flow_tool_trust".to_string()));
- assert!(!tables.contains(&"pending_approvals".to_string()));
- let conn = rusqlite::Connection::open(&db).unwrap();
- let kept: i64 = conn
- .query_row("SELECT COUNT(*) FROM _legacy_pending_approvals", [], |r| {
- r.get(0)
- })
- .unwrap();
- assert_eq!(kept, 5);
-
- // A restart does not import again: a change made since stays made.
- live::decide(&default, "pending-1", ApprovalDecision::Deny).unwrap();
- forget(&db);
+ // A second run does not import again: a change made since stays made.
+ live::decide(&config, "pending-1", ApprovalDecision::Deny).unwrap();
+ assert!(matches!(import(&config), Outcome::AlreadyDone));
assert_eq!(
- live::get_decision(&default, "pending-1").unwrap(),
+ live::get_decision(&config, "pending-1").unwrap(),
Some(ApprovalDecision::Deny)
);
- assert!(live::list_pending(&default).unwrap().is_empty());
+ assert!(live::list_pending(&config).unwrap().is_empty());
}
#[test]
fn a_workspace_with_no_legacy_file_starts_empty() {
- let (_dir, _classic, default) = workspace();
- assert!(live::list_pending(&default).unwrap().is_empty());
- assert!(!table_names(&live::db_path(&default))
- .iter()
- .any(|t| t.starts_with("_legacy_")));
-}
-
-#[test]
-fn the_classic_opt_out_keeps_the_legacy_tables() {
- let (_dir, classic, _default) = workspace();
- live::insert_pending(&classic, &request("a", 10), "sess").unwrap();
- assert_eq!(live::list_pending(&classic).unwrap().len(), 1);
- assert!(table_names(&live::db_path(&classic)).contains(&"pending_approvals".to_string()));
+ let (_dir, config) = workspace();
+ assert!(matches!(import(&config), Outcome::NoSource));
+ assert!(live::list_pending(&config).unwrap().is_empty());
}
#[test]
-fn an_old_schema_missing_a_table_is_imported_and_fully_retired() {
- let (_dir, _classic, default) = workspace();
- let db = live::db_path(&default);
+fn an_old_schema_is_brought_forward_and_its_session_ids_scrubbed() {
+ let (_dir, config) = workspace();
+ let db = db_path(&config);
std::fs::create_dir_all(db.parent().unwrap()).unwrap();
{
// The first schema: no audit/agent columns, and no flow_tool_trust.
@@ -167,30 +167,31 @@ fn an_old_schema_missing_a_table_is_imported_and_fully_retired() {
)
.unwrap();
}
- let pending = live::list_pending(&default).unwrap();
+ let before = std::fs::read(&db).unwrap();
+
+ assert!(matches!(import(&config), Outcome::Imported { .. }));
+ let pending = live::list_pending(&config).unwrap();
assert_eq!(pending.len(), 1);
assert_eq!(pending[0].request_id, "old");
-
- // Both tables are retired, including the one the reader had to create, so
- // a restart finds nothing to import and nothing alternates.
- let tables = table_names(&db);
- assert!(tables.contains(&"_legacy_pending_approvals".to_string()));
- assert!(tables.contains(&"_legacy_flow_tool_trust".to_string()));
- forget(&db);
- assert_eq!(live::list_pending(&default).unwrap().len(), 1);
- assert!(
- !table_names(&db).iter().any(|t| t.ends_with("_2")),
- "{:?}",
- table_names(&db)
- );
+ assert!(pending[0].agent_id.is_none(), "an old row is the process's own");
// The credential-shaped session id was scrubbed before it was read.
- let conn = rusqlite::Connection::open(&db).unwrap();
- let session: String = conn
- .query_row(
- "SELECT session_id FROM _legacy_pending_approvals",
- [],
- |r| r.get(0),
- )
+ let docs = crate::storage::local::open("test", &config.workspace_dir)
+ .unwrap()
+ .scoped()
+ .unwrap();
+ let docs = std::sync::Arc::clone(docs.documents());
+ let stored = crate::storage::block_on(async move { docs.get("approvals", "old").await })
+ .unwrap()
+ .unwrap();
+ assert_eq!(stored.doc["session_id"], PRE_MIGRATION_SESSION_ID);
+ assert_eq!(std::fs::read(&db).unwrap(), before, "approval.db untouched");
+}
+
+#[test]
+fn the_schema_migration_surfaces_non_duplicate_alter_errors() {
+ let conn = rusqlite::Connection::open_in_memory().unwrap();
+ conn.execute_batch("CREATE VIEW pending_approvals AS SELECT 1 AS id")
.unwrap();
- assert_eq!(session, live::PRE_MIGRATION_SESSION_ID);
+ let error = migrate_columns(&conn).expect_err("a view cannot be migrated as a table");
+ assert!(error.to_string().contains("add column executed_at"));
}