From f79b4be4a3413c16c5555501c689d69bb96e27e0 Mon Sep 17 00:00:00 2001 From: Logan Johnson Date: Mon, 24 Aug 2026 14:09:03 -0400 Subject: [PATCH] feat(workflows): bind owner triggers to signed revisions Co-authored-by: Larry <8cf5a83f590ec0955b11647d1c88f796a98e088c30a492c58e0e46c3026ae7a4@buzz.block.builderlab.xyz> Signed-off-by: loganj --- crates/buzz-cli/src/commands/workflows.rs | 30 ++- crates/buzz-db/src/lib.rs | 27 ++- crates/buzz-db/src/migration.rs | 9 +- crates/buzz-db/src/workflow.rs | 169 ++++++++++++++- .../src/handlers/command_executor.rs | 174 ++++++++++++--- crates/buzz-sdk/src/builders.rs | 17 +- .../tests/e2e_workflow_agent_owner.rs | 205 ++++++++++++++++++ crates/buzz-workflow/src/executor.rs | 4 + crates/buzz-workflow/src/lib.rs | 1 + desktop/src-tauri/src/commands/workflows.rs | 22 +- .../src-tauri/src/commands/workflows_tests.rs | 14 ++ desktop/src-tauri/src/events.rs | 25 +++ desktop/src-tauri/src/events/workflows.rs | 13 +- .../0033_workflow_definition_event_id.sql | 6 + schema/schema.sql | 5 + 15 files changed, 667 insertions(+), 54 deletions(-) create mode 100644 crates/buzz-test-client/tests/e2e_workflow_agent_owner.rs create mode 100644 migrations/0033_workflow_definition_event_id.sql diff --git a/crates/buzz-cli/src/commands/workflows.rs b/crates/buzz-cli/src/commands/workflows.rs index 0028dfc766..e87edd114b 100644 --- a/crates/buzz-cli/src/commands/workflows.rs +++ b/crates/buzz-cli/src/commands/workflows.rs @@ -162,6 +162,25 @@ pub async fn cmd_delete_workflow(client: &BuzzClient, workflow_id: &str) -> Resu Ok(()) } +async fn current_workflow_revision( + client: &BuzzClient, + workflow_id: &str, +) -> Result { + let filter = serde_json::json!({ + "kinds": [30620], + "#d": [workflow_id], + "limit": 1 + }); + let response = client.query(&filter).await?; + let events: Vec = serde_json::from_str(&response).unwrap_or_default(); + events + .first() + .and_then(|event| event.get("id")) + .and_then(|id| id.as_str()) + .map(str::to_owned) + .ok_or_else(|| CliError::NotFound(format!("workflow {workflow_id} not found"))) +} + /// Trigger a workflow — sign and submit a kind:46020 event. /// /// When `inputs` is provided, it is parsed as a JSON object and used as the @@ -172,6 +191,7 @@ pub async fn cmd_trigger_workflow( inputs: Option<&str>, ) -> Result<(), CliError> { let wf_uuid = parse_uuid(workflow_id)?; + let revision = current_workflow_revision(client, workflow_id).await?; if let Some(raw) = inputs { // Parse and validate it is a JSON object, then build the event manually @@ -183,8 +203,12 @@ pub async fn cmd_trigger_workflow( } let content = serde_json::to_string(&parsed).unwrap_or_default(); use nostr::{EventBuilder, Kind, Tag}; - let tags = vec![Tag::parse(["d", &wf_uuid.to_string()]) - .map_err(|e| CliError::Other(format!("tag error: {e}")))?]; + let tags = vec![ + Tag::parse(["d", &wf_uuid.to_string()]) + .map_err(|e| CliError::Other(format!("tag error: {e}")))?, + Tag::parse(["e", revision.as_str()]) + .map_err(|e| CliError::Other(format!("tag error: {e}")))?, + ]; let builder = EventBuilder::new( Kind::Custom(buzz_sdk::kind::KIND_WORKFLOW_TRIGGER as u16), &content, @@ -194,7 +218,7 @@ pub async fn cmd_trigger_workflow( let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); } else { - let builder = buzz_sdk::build_workflow_trigger(wf_uuid).map_err(sdk_err)?; + let builder = buzz_sdk::build_workflow_trigger(wf_uuid, &revision).map_err(sdk_err)?; let event = client.sign_event(builder)?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); diff --git a/crates/buzz-db/src/lib.rs b/crates/buzz-db/src/lib.rs index 3ff230f950..0c57f2c04f 100644 --- a/crates/buzz-db/src/lib.rs +++ b/crates/buzz-db/src/lib.rs @@ -3852,11 +3852,12 @@ impl Db { .await } - /// Insert or update a workflow using its NIP-33 `d`-tag UUID. + /// Atomically insert or update a workflow using its NIP-33 `d`-tag UUID. #[allow(clippy::too_many_arguments)] #[datastore_span(name = "upsert_workflow", system = "postgresql")] pub async fn upsert_workflow( &self, + tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, community_id: CommunityId, id: Uuid, channel_id: Option, @@ -3864,9 +3865,10 @@ impl Db { name: &str, definition_json: &str, definition_hash: &[u8], + definition_event_id: &[u8], ) -> Result<()> { workflow::upsert_workflow( - &self.pool, + tx.as_mut(), community_id, id, channel_id, @@ -3874,6 +3876,7 @@ impl Db { name, definition_json, definition_hash, + definition_event_id, ) .await } @@ -4069,6 +4072,26 @@ impl Db { workflow::find_by_owner_and_name(&self.pool, community_id, owner_pubkey, name).await } + /// Create a new workflow run on an existing transaction. + #[datastore_span(name = "create_workflow_run_in_transaction", system = "postgresql")] + pub async fn create_workflow_run_in_transaction( + &self, + tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + community_id: CommunityId, + workflow_id: Uuid, + trigger_event_id: Option<&[u8]>, + trigger_context: Option<&serde_json::Value>, + ) -> Result { + workflow::create_workflow_run_in_transaction( + tx, + community_id, + workflow_id, + trigger_event_id, + trigger_context, + ) + .await + } + /// Create a new workflow run. #[datastore_span(name = "create_workflow_run", system = "postgresql")] pub async fn create_workflow_run( diff --git a/crates/buzz-db/src/migration.rs b/crates/buzz-db/src/migration.rs index 94c7aea2fa..80be5328d3 100644 --- a/crates/buzz-db/src/migration.rs +++ b/crates/buzz-db/src/migration.rs @@ -640,7 +640,7 @@ mod tests { let mut migrations: Vec<_> = MIGRATOR.iter().collect(); migrations.sort_by_key(|migration| migration.version); - assert_eq!(migrations.len(), 32); + assert_eq!(migrations.len(), 33); assert_eq!(migrations[0].version, 1); assert_eq!(&*migrations[0].description, "initial schema"); assert!(migrations[0] @@ -1067,6 +1067,13 @@ mod tests { assert!(roster_fence.contains("snapshot_members IS DISTINCT FROM canonical_members")); assert!(roster_fence.contains("ERRCODE = '23514'")); + // Exact workflow-definition revision persistence is additive and keeps + // pre-migration rows nullable until their next signed definition write. + assert_eq!(migrations[32].version, 33); + let workflow_revision = migrations[32].sql.as_str(); + assert!(workflow_revision.contains("ADD COLUMN definition_event_id BYTEA")); + assert!(workflow_revision.contains("octet_length(definition_event_id) = 32")); + // Fresh desired-state bootstrap must install the identical executable // fence as migration 0032. CI and isolated relay startup use schema.sql // without running migrations, so drift reopens rolling-deploy races. diff --git a/crates/buzz-db/src/workflow.rs b/crates/buzz-db/src/workflow.rs index e970e978aa..7eccafc5d5 100644 --- a/crates/buzz-db/src/workflow.rs +++ b/crates/buzz-db/src/workflow.rs @@ -177,6 +177,8 @@ pub struct WorkflowRecord { pub definition: serde_json::Value, /// SHA-256 hash of the canonical definition JSON. pub definition_hash: Vec, + /// Exact owner-signed kind:30620 event that materialized this revision. + pub definition_event_id: Option>, /// Current lifecycle status of the workflow definition. pub status: WorkflowStatus, /// Whether the workflow will fire on matching events. @@ -314,7 +316,7 @@ pub async fn create_workflow( /// cross-channel overwrite primitive while still making retries idempotent. #[allow(clippy::too_many_arguments)] pub async fn upsert_workflow( - pool: &PgPool, + conn: &mut sqlx::PgConnection, community_id: CommunityId, id: Uuid, channel_id: Option, @@ -322,16 +324,18 @@ pub async fn upsert_workflow( name: &str, definition_json: &str, definition_hash: &[u8], + definition_event_id: &[u8], ) -> Result<()> { let row = sqlx::query( r#" INSERT INTO workflows - (community_id, id, name, owner_pubkey, channel_id, definition, definition_hash, status, enabled) - VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7, 'active', TRUE) + (community_id, id, name, owner_pubkey, channel_id, definition, definition_hash, definition_event_id, status, enabled) + VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7, $8, 'active', TRUE) ON CONFLICT (community_id, id) DO UPDATE SET name = EXCLUDED.name, definition = EXCLUDED.definition, definition_hash = EXCLUDED.definition_hash, + definition_event_id = EXCLUDED.definition_event_id, updated_at = NOW() WHERE workflows.owner_pubkey = EXCLUDED.owner_pubkey AND workflows.channel_id IS NOT DISTINCT FROM EXCLUDED.channel_id @@ -345,7 +349,8 @@ pub async fn upsert_workflow( .bind(channel_id) .bind(definition_json) .bind(definition_hash) - .fetch_optional(pool) + .bind(definition_event_id) + .fetch_optional(conn) .await?; if row.is_none() { @@ -370,7 +375,7 @@ pub async fn get_workflow( ) -> Result { let row = sqlx::query( r#" - SELECT id, community_id, name, owner_pubkey, channel_id, definition, definition_hash, + SELECT id, community_id, name, owner_pubkey, channel_id, definition, definition_hash, definition_event_id, status::text AS status, enabled, created_at, updated_at FROM workflows WHERE community_id = $1 AND id = $2 @@ -401,7 +406,7 @@ pub async fn list_channel_workflows( let rows = sqlx::query( r#" - SELECT id, community_id, name, owner_pubkey, channel_id, definition, definition_hash, + SELECT id, community_id, name, owner_pubkey, channel_id, definition, definition_hash, definition_event_id, status::text AS status, enabled, created_at, updated_at FROM workflows WHERE community_id = $1 AND channel_id = $2 @@ -432,7 +437,7 @@ pub async fn list_enabled_channel_workflows( ) -> Result> { let rows = sqlx::query( r#" - SELECT id, community_id, name, owner_pubkey, channel_id, definition, definition_hash, + SELECT id, community_id, name, owner_pubkey, channel_id, definition, definition_hash, definition_event_id, status::text AS status, enabled, created_at, updated_at FROM workflows WHERE community_id = $1 @@ -460,7 +465,7 @@ pub async fn list_enabled_channel_workflows( pub async fn list_all_enabled_workflows(pool: &PgPool) -> Result> { let rows = sqlx::query( r#" - SELECT w.id, w.community_id, w.name, w.owner_pubkey, w.channel_id, w.definition, w.definition_hash, + SELECT w.id, w.community_id, w.name, w.owner_pubkey, w.channel_id, w.definition, w.definition_hash, w.definition_event_id, w.status::text AS status, w.enabled, w.created_at, w.updated_at FROM workflows w JOIN communities c ON c.id = w.community_id @@ -793,6 +798,37 @@ pub async fn delete_workflow_for_owner( // -- Workflow Run CRUD -------------------------------------------------------- +/// Insert a new workflow run on the caller's transaction. +/// +/// Command handlers use this with the transaction that persisted the trigger +/// event so both rows commit or roll back together. +pub async fn create_workflow_run_in_transaction( + tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + community_id: CommunityId, + workflow_id: Uuid, + trigger_event_id: Option<&[u8]>, + trigger_context: Option<&serde_json::Value>, +) -> Result { + let id = Uuid::new_v4(); + + sqlx::query( + r#" + INSERT INTO workflow_runs + (community_id, id, workflow_id, status, trigger_event_id, current_step, execution_trace, trigger_context) + VALUES ($1, $2, $3, 'pending', $4, 0, '[]', $5) + "#, + ) + .bind(community_id.as_uuid()) + .bind(id) + .bind(workflow_id) + .bind(trigger_event_id) + .bind(trigger_context) + .execute(&mut **tx) + .await?; + + Ok(id) +} + /// Insert a new workflow run. Returns the new run's UUID. /// /// `trigger_context` is the serialized `TriggerContext` for this run. It is stored @@ -1183,6 +1219,7 @@ fn row_to_workflow_record(row: sqlx::postgres::PgRow) -> Result channel_id, definition: row.try_get("definition")?, definition_hash: row.try_get("definition_hash")?, + definition_event_id: row.try_get("definition_event_id")?, status, enabled, created_at: row.try_get("created_at")?, @@ -1247,7 +1284,7 @@ pub async fn find_by_owner_and_name( ) -> Result> { let row = sqlx::query( r#" - SELECT id, community_id, name, owner_pubkey, channel_id, definition, definition_hash, + SELECT id, community_id, name, owner_pubkey, channel_id, definition, definition_hash, definition_event_id, status::text AS status, enabled, created_at, updated_at FROM workflows WHERE community_id = $1 AND owner_pubkey = $2 AND name = $3 @@ -1382,6 +1419,7 @@ mod tests { channel_id: Some(channel_id), definition: def.clone(), definition_hash: vec![0x01, 0x02, 0x03, 0x04], + definition_event_id: None, status: WorkflowStatus::Active, enabled: true, created_at: now, @@ -1412,6 +1450,7 @@ mod tests { channel_id: None, definition: serde_json::json!({}), definition_hash: vec![], + definition_event_id: None, status: WorkflowStatus::Active, enabled: true, created_at: now, @@ -1434,6 +1473,7 @@ mod tests { channel_id: None, definition: serde_json::json!({}), definition_hash: vec![0xAA], + definition_event_id: None, status: WorkflowStatus::Active, enabled: true, created_at: now, @@ -1463,6 +1503,7 @@ mod tests { channel_id: None, definition: serde_json::json!({}), definition_hash: vec![], + definition_event_id: None, status: status.clone(), enabled: true, created_at: now, @@ -1483,6 +1524,7 @@ mod tests { channel_id: None, definition: serde_json::json!({}), definition_hash: vec![], + definition_event_id: None, status: WorkflowStatus::Active, enabled: false, created_at: now, @@ -2129,6 +2171,115 @@ mod tests { .expect("insert workflow"); } + #[tokio::test] + #[ignore = "requires Postgres"] + async fn workflow_run_transaction_rolls_back_and_retry_creates_exactly_one_run() { + let pool = setup_pool().await; + let community = make_community(&pool).await; + let workflow_id = Uuid::new_v4(); + insert_workflow_with_ids( + &pool, + community, + workflow_id, + Uuid::new_v4(), + "atomic-trigger", + ) + .await; + let trigger_event_id = vec![0x7au8; 32]; + let trigger_pubkey = vec![0x7bu8; 32]; + let trigger_sig = vec![0x7cu8; 64]; + + let mut aborted = pool.begin().await.expect("begin aborted transaction"); + sqlx::query( + "INSERT INTO events \ + (community_id, id, pubkey, created_at, kind, tags, content, sig, received_at) \ + VALUES ($1, $2, $3, NOW(), 46020, '[]'::jsonb, '', $4, NOW())", + ) + .bind(community.as_uuid()) + .bind(trigger_event_id.as_slice()) + .bind(trigger_pubkey.as_slice()) + .bind(trigger_sig.as_slice()) + .execute(&mut *aborted) + .await + .expect("insert trigger event before abort"); + create_workflow_run_in_transaction( + &mut aborted, + community, + workflow_id, + Some(&trigger_event_id), + None, + ) + .await + .expect("insert run before abort"); + aborted.rollback().await.expect("roll back run"); + + let after_abort_event: i64 = + sqlx::query_scalar("SELECT COUNT(*) FROM events WHERE community_id = $1 AND id = $2") + .bind(community.as_uuid()) + .bind(&trigger_event_id) + .fetch_one(&pool) + .await + .expect("count rolled-back trigger events"); + assert_eq!( + after_abort_event, 0, + "aborted trigger must leave no event row" + ); + let after_abort: i64 = sqlx::query_scalar( + "SELECT COUNT(*) FROM workflow_runs WHERE community_id = $1 AND trigger_event_id = $2", + ) + .bind(community.as_uuid()) + .bind(&trigger_event_id) + .fetch_one(&pool) + .await + .expect("count rolled-back runs"); + assert_eq!(after_abort, 0, "aborted trigger must leave no run row"); + + let mut retry = pool.begin().await.expect("begin retry transaction"); + sqlx::query( + "INSERT INTO events \ + (community_id, id, pubkey, created_at, kind, tags, content, sig, received_at) \ + VALUES ($1, $2, $3, NOW(), 46020, '[]'::jsonb, '', $4, NOW())", + ) + .bind(community.as_uuid()) + .bind(trigger_event_id.as_slice()) + .bind(trigger_pubkey.as_slice()) + .bind(trigger_sig.as_slice()) + .execute(&mut *retry) + .await + .expect("insert trigger event on retry"); + create_workflow_run_in_transaction( + &mut retry, + community, + workflow_id, + Some(&trigger_event_id), + None, + ) + .await + .expect("insert retry run"); + retry.commit().await.expect("commit retry run"); + + let after_retry_event: i64 = + sqlx::query_scalar("SELECT COUNT(*) FROM events WHERE community_id = $1 AND id = $2") + .bind(community.as_uuid()) + .bind(&trigger_event_id) + .fetch_one(&pool) + .await + .expect("count committed trigger events"); + assert_eq!( + after_retry_event, 1, + "retry must create exactly one event row" + ); + let after_retry: i64 = sqlx::query_scalar( + "SELECT COUNT(*) FROM workflow_runs WHERE community_id = $1 AND trigger_event_id = $2", + ) + .bind(community.as_uuid()) + .bind(&trigger_event_id) + .fetch_one(&pool) + .await + .expect("count committed retry runs"); + assert_eq!(after_retry, 1, "retry must create exactly one run row"); + } + /// Issue 4 (workflow identity): the same workflow UUID and channel UUID can /// exist in communities A and B (PK `(community_id, id)`). A request-scoped /// `get_workflow` / `list_enabled_channel_workflows` MUST return only the diff --git a/crates/buzz-relay/src/handlers/command_executor.rs b/crates/buzz-relay/src/handlers/command_executor.rs index d8569a7a86..5f2a08d7ff 100644 --- a/crates/buzz-relay/src/handlers/command_executor.rs +++ b/crates/buzz-relay/src/handlers/command_executor.rs @@ -92,12 +92,11 @@ enum PersistResult { /// If the event is a duplicate (ON CONFLICT DO NOTHING), the transaction is /// rolled back and `PersistResult::Duplicate` is returned — no mutations needed. /// -/// NOTE: Domain mutations (open_dm, upsert_workflow, etc.) execute on the -/// connection pool, NOT inside this transaction. The pattern is idempotent but -/// not strictly atomic: if a mutation succeeds but commit fails, the mutation -/// persists without the event record. On retry, the event INSERT succeeds -/// (no conflict), and the mutation re-executes — which is safe for idempotent -/// operations (open_dm, hide_dm, update_approval, upsert_workflow). +/// NOTE: Most domain mutations still execute on the connection pool rather +/// than in this transaction. Workflow-definition ingestion is the exception: +/// its materialized workflow row and exact signed revision are written through +/// this transaction so the event and revision binding commit atomically. +/// Other operations remain idempotent but not strictly atomic. #[datastore_span(name = "persist_command_event", system = "postgresql")] async fn persist_command_event( db: &buzz_db::Db, @@ -809,8 +808,9 @@ async fn handle_workflow_def( .map_err(|e| IngestError::Internal(format!("error: json serialize: {e}")))?; let hash = compute_definition_hash(&definition_json_final); - // Persist the command event — returns open transaction - let tx = match persist_command_event(&state.db, tenant, event, None).await? { + // Persist the command event — returns the transaction that will also own + // the materialized workflow revision update. + let mut tx = match persist_command_event(&state.db, tenant, event, Some(channel_id)).await? { PersistResult::Duplicate => { return Ok(IngestResult { event_id: event.id.to_hex(), @@ -842,6 +842,7 @@ async fn handle_workflow_def( state .db .upsert_workflow( + &mut tx, community_id, workflow_id, Some(channel_id), @@ -849,6 +850,7 @@ async fn handle_workflow_def( &workflow_name, &definition_json_final, &hash, + event.id.as_bytes(), ) .await .map_err(|e| match e { @@ -858,17 +860,18 @@ async fn handle_workflow_def( other => IngestError::Internal(format!("error: db upsert_workflow: {other}")), })?; - // Drop the trigger-path cache entry so the new/updated definition fires on - // the next matching event instead of after the cache TTL. - state - .workflow_engine - .invalidate_channel_workflows(community_id, channel_id); - // Commit the event transaction after the idempotent workflow upsert succeeds. tx.commit() .await .map_err(|e| IngestError::Internal(format!("error: commit transaction: {e}")))?; + // Invalidate only after commit. Invalidating while the new row is still + // invisible lets a concurrent trigger refill the cache with the old + // definition and retain it until TTL expiry. + state + .workflow_engine + .invalidate_channel_workflows(community_id, channel_id); + // 5. Return response let mut resp = serde_json::json!({ "workflow_id": workflow_id.to_string(), @@ -884,6 +887,92 @@ async fn handle_workflow_def( }) } +async fn caller_controls_workflow( + state: &Arc, + community_id: CommunityId, + workflow_owner: &[u8], + caller: &[u8], +) -> Result { + if workflow_owner == caller { + return Ok(true); + } + + state + .db + .is_agent_owner(community_id, workflow_owner, caller) + .await + .map_err(|e| IngestError::Internal(format!("error: workflow owner check: {e}"))) +} + +fn exact_tag_value<'a>(event: &'a Event, name: &str) -> Option<&'a str> { + let mut values = event.tags.iter().filter_map(|tag| { + (tag.kind().to_string() == name) + .then(|| tag.content()) + .flatten() + }); + let value = values.next()?; + values.next().is_none().then_some(value) +} + +async fn verify_workflow_revision( + state: &Arc, + community_id: CommunityId, + workflow: &buzz_db::workflow::WorkflowRecord, + requested_revision: &[u8], +) -> Result<(), IngestError> { + let Some(persisted_revision) = workflow.definition_event_id.as_deref() else { + return Err(IngestError::Rejected( + "invalid: owner-signed workflow revision is unavailable".into(), + )); + }; + if persisted_revision != requested_revision { + return Err(IngestError::Rejected( + "conflict: workflow revision does not match current definition".into(), + )); + } + + let stored = state + .db + .get_event_by_id(community_id, persisted_revision) + .await + .map_err(|e| IngestError::Internal(format!("error: workflow revision lookup: {e}")))? + .ok_or_else(|| { + IngestError::Rejected("invalid: signed workflow revision not found".into()) + })?; + let definition_event = &stored.event; + let workflow_id = workflow.id.to_string(); + let workflow_channel_id = workflow.channel_id.map(|id| id.to_string()); + if definition_event.id.as_bytes() != persisted_revision + || !definition_event.verify_id() + || !definition_event.verify_signature() + || definition_event.kind.as_u16() as u32 != KIND_WORKFLOW_DEF + || definition_event.pubkey.to_bytes().as_slice() != workflow.owner_pubkey + || exact_tag_value(definition_event, "d") != Some(workflow_id.as_str()) + || workflow_channel_id.is_none() + || exact_tag_value(definition_event, "h") != workflow_channel_id.as_deref() + || stored.channel_id != workflow.channel_id + { + return Err(IngestError::Rejected( + "invalid: signed workflow revision binding mismatch".into(), + )); + } + + let (_, signed_json) = buzz_workflow::WorkflowEngine::parse_yaml(&definition_event.content) + .map_err(|_| { + IngestError::Rejected("invalid: signed workflow revision is malformed".into()) + })?; + let signed_definition: serde_json::Value = + serde_json::from_str(&signed_json).map_err(|_| { + IngestError::Rejected("invalid: signed workflow revision is malformed".into()) + })?; + if signed_definition != webhook_secret::strip_secret(&workflow.definition) { + return Err(IngestError::Rejected( + "invalid: signed workflow revision differs from materialized definition".into(), + )); + } + Ok(()) +} + async fn handle_workflow_trigger( tenant: &TenantContext, state: &Arc, @@ -892,13 +981,21 @@ async fn handle_workflow_trigger( ) -> Result { let self_bytes = auth.pubkey().to_bytes().to_vec(); - // 1. Extract workflow reference from `d` tag or `e` tag - let workflow_id_str = extract_d_tag(event) - .or_else(|| extract_e_tag(event)) - .ok_or_else(|| { - IngestError::Rejected("invalid: missing workflow reference (d or e tag)".into()) - })?; - let workflow_id = Uuid::parse_str(&workflow_id_str) + // 1. Bind the command to both the workflow UUID and one exact signed revision. + let workflow_id_str = exact_tag_value(event, "d").ok_or_else(|| { + IngestError::Rejected("invalid: expected exactly one workflow d tag".into()) + })?; + let revision_hex = exact_tag_value(event, "e").ok_or_else(|| { + IngestError::Rejected("invalid: expected exactly one workflow revision e tag".into()) + })?; + let requested_revision = hex::decode(revision_hex) + .map_err(|_| IngestError::Rejected("invalid: bad workflow revision event id".into()))?; + if requested_revision.len() != 32 { + return Err(IngestError::Rejected( + "invalid: bad workflow revision event id".into(), + )); + } + let workflow_id = Uuid::parse_str(workflow_id_str) .map_err(|_| IngestError::Rejected("invalid: bad workflow_id format".into()))?; // 2. Validate workflow exists — scoped to the caller's community. The same @@ -912,15 +1009,17 @@ async fn handle_workflow_trigger( .await .map_err(|_| IngestError::Rejected("invalid: workflow not found".into()))?; - // 3. Manual triggers execute with the workflow owner's authority, so only - // the owner may start them. Channel membership alone is insufficient: a - // member could otherwise invoke another user's webhook or message actions. - if workflow.owner_pubkey != self_bytes { + // 3. Manual triggers execute with the workflow owner's authority. Permit + // that principal and, for a managed agent, its immutable human owner. + // Channel membership alone remains insufficient. + if !caller_controls_workflow(state, community_id, &workflow.owner_pubkey, &self_bytes).await? { return Err(IngestError::Rejected( "forbidden: not authorized to trigger this workflow".into(), )); } + verify_workflow_revision(state, community_id, &workflow, &requested_revision).await?; + // SEC-006: manual triggers must honor the workflow's lifecycle state and // recheck the owner's *current* channel authority before creating a run. // Without this, a disabled workflow — including one disabled because its @@ -949,7 +1048,7 @@ async fn handle_workflow_trigger( // Persist the command event under the workflow channel even though the // trigger event itself only carries the workflow UUID. Storing channel // triggers as global events leaks workflow IDs to unrelated relay members. - let tx = match persist_command_event(&state.db, tenant, event, workflow.channel_id).await? { + let mut tx = match persist_command_event(&state.db, tenant, event, workflow.channel_id).await? { PersistResult::Duplicate => { return Ok(IngestResult { event_id: event.id.to_hex(), @@ -967,6 +1066,7 @@ async fn handle_workflow_trigger( .map(|id| id.to_string()) .unwrap_or_default(), author: hex::encode(&self_bytes), + definition_event_id: revision_hex.to_owned(), ..Default::default() }; if !event.content.is_empty() { @@ -985,7 +1085,8 @@ async fn handle_workflow_trigger( let event_id_bytes = event.id.as_bytes().to_vec(); let run_id = state .db - .create_workflow_run( + .create_workflow_run_in_transaction( + &mut tx, community_id, workflow_id, Some(&event_id_bytes), @@ -1566,16 +1667,27 @@ mod tests { let workflow_id = Uuid::new_v4(); let created_at = Timestamp::now().as_secs(); let create = workflow_event(&keys, workflow_id, created_at, None, "create"); + let channel_id = Uuid::parse_str( + exact_tag_value(&create, "h").expect("workflow definition channel tag"), + ) + .expect("workflow definition channel UUID"); - let PersistResult::Inserted(tx) = persist_command_event(&db, &tenant, &create, None) - .await - .expect("persist create") + let PersistResult::Inserted(tx) = + persist_command_event(&db, &tenant, &create, Some(channel_id)) + .await + .expect("persist create") else { panic!("first create must insert"); }; tx.commit().await.expect("commit create"); + let stored_create = db + .get_event_by_id(tenant.community(), create.id.as_bytes()) + .await + .expect("load persisted workflow definition") + .expect("persisted workflow definition"); + assert_eq!(stored_create.channel_id, Some(channel_id)); assert!(matches!( - persist_command_event(&db, &tenant, &create, None) + persist_command_event(&db, &tenant, &create, Some(channel_id)) .await .expect("replay create"), PersistResult::Duplicate diff --git a/crates/buzz-sdk/src/builders.rs b/crates/buzz-sdk/src/builders.rs index 71c0f1e73d..c8fdc83223 100644 --- a/crates/buzz-sdk/src/builders.rs +++ b/crates/buzz-sdk/src/builders.rs @@ -1640,9 +1640,16 @@ pub fn build_workflow_delete( build_delete_addressable(KIND_WORKFLOW_DEF, author_pubkey, &workflow_id.to_string()) } -/// Build a workflow trigger event (kind 46020). -pub fn build_workflow_trigger(workflow_id: Uuid) -> Result { - let tags = vec![tag(&["d", &workflow_id.to_string()])?]; +/// Build a workflow trigger event (kind 46020) bound to an exact signed revision. +pub fn build_workflow_trigger( + workflow_id: Uuid, + definition_event_id: &str, +) -> Result { + let revision = check_hex_exact(definition_event_id, 64, "definition_event_id")?; + let tags = vec![ + tag(&["d", &workflow_id.to_string()])?, + tag(&["e", &revision])?, + ]; Ok(EventBuilder::new(Kind::Custom(KIND_WORKFLOW_TRIGGER as u16), "").tags(tags)) } @@ -4010,9 +4017,11 @@ mod tests { #[test] fn workflow_trigger_happy_path() { let wid = uuid(); - let ev = sign(build_workflow_trigger(wid).unwrap()); + let ev = sign(build_workflow_trigger(wid, &"ab".repeat(32)).unwrap()); assert_eq!(ev.kind.as_u16(), 46020); assert!(has_tag(&ev, "d", &wid.to_string())); + assert!(has_tag(&ev, "e", &"ab".repeat(32))); + assert!(build_workflow_trigger(wid, "not-an-event-id").is_err()); } #[test] diff --git a/crates/buzz-test-client/tests/e2e_workflow_agent_owner.rs b/crates/buzz-test-client/tests/e2e_workflow_agent_owner.rs new file mode 100644 index 0000000000..d93609b0ea --- /dev/null +++ b/crates/buzz-test-client/tests/e2e_workflow_agent_owner.rs @@ -0,0 +1,205 @@ +//! End-to-end authorization and revision-binding coverage for agent-owned workflows. +//! +//! Run against a local relay with: +//! `cargo test -p buzz-test-client --test e2e_workflow_agent_owner -- --ignored` + +use buzz_sdk::nip_oa; +use buzz_test_client::BuzzTestClient; +use nostr::{EventBuilder, Keys, Kind, Tag}; + +fn relay_url() -> String { + std::env::var("RELAY_URL").unwrap_or_else(|_| "ws://localhost:3000".to_string()) +} + +fn workflow_yaml(text: &str) -> String { + format!( + "name: Agent-owned workflow\n\ + trigger:\n\ + \x20 on: webhook\n\ + steps:\n\ + \x20 - id: notify\n\ + \x20 action: send_message\n\ + \x20 text: {text}\n" + ) +} + +async fn connect_agent_with_owner(agent: &Keys, owner: &Keys) -> BuzzTestClient { + let tag_json = + nip_oa::compute_auth_tag(owner, &agent.public_key(), "").expect("compute NIP-OA auth tag"); + let auth_tag = nip_oa::parse_auth_tag(&tag_json).expect("parse NIP-OA auth tag"); + let mut client = BuzzTestClient::connect_unauthenticated(&relay_url()) + .await + .expect("connect agent"); + client + .authenticate_with_nip_oa(agent, &auth_tag) + .await + .expect("authenticate agent with NIP-OA"); + client +} + +fn trigger(keys: &Keys, workflow_id: uuid::Uuid, revision: &str) -> nostr::Event { + buzz_sdk::build_workflow_trigger(workflow_id, revision) + .expect("build workflow trigger") + .sign_with_keys(keys) + .expect("sign workflow trigger") +} + +#[tokio::test] +#[ignore] +async fn agent_and_human_owner_trigger_exact_revision_but_unrelated_member_cannot() { + let owner = Keys::generate(); + let agent = Keys::generate(); + let unrelated = Keys::generate(); + let channel_id = uuid::Uuid::new_v4(); + let workflow_id = uuid::Uuid::new_v4(); + + // NIP-OA authentication materializes the immutable community-scoped + // agent→owner relationship used by workflow authorization. + let mut agent_client = connect_agent_with_owner(&agent, &owner).await; + + let create_channel = EventBuilder::new(Kind::Custom(9007), "") + .tags([ + Tag::parse(["h", &channel_id.to_string()]).unwrap(), + Tag::parse(["name", "workflow-agent-owner-e2e"]).unwrap(), + Tag::parse(["channel_type", "stream"]).unwrap(), + Tag::parse(["visibility", "open"]).unwrap(), + ]) + .sign_with_keys(&agent) + .unwrap(); + let response = agent_client + .send_event(create_channel) + .await + .expect("create channel"); + assert!(response.accepted, "channel rejected: {}", response.message); + + let definition = + buzz_sdk::build_workflow_def(channel_id, workflow_id, &workflow_yaml("owner-triggered")) + .expect("build workflow definition") + .sign_with_keys(&agent) + .expect("sign workflow definition"); + let revision = definition.id.to_hex(); + let response = agent_client + .send_event(definition) + .await + .expect("define workflow"); + assert!( + response.accepted, + "definition rejected: {}", + response.message + ); + + let add_unrelated = EventBuilder::new(Kind::Custom(9000), "") + .tags([ + Tag::parse(["h", &channel_id.to_string()]).unwrap(), + Tag::parse(["p", &unrelated.public_key().to_hex()]).unwrap(), + ]) + .sign_with_keys(&agent) + .expect("sign add-member event"); + let response = agent_client + .send_event(add_unrelated) + .await + .expect("add unrelated member"); + assert!( + response.accepted, + "add member rejected: {}", + response.message + ); + + let response = agent_client + .send_event(trigger(&agent, workflow_id, &revision)) + .await + .expect("send agent trigger"); + assert!( + response.accepted, + "agent trigger rejected: {}", + response.message + ); + + let mut unrelated_client = BuzzTestClient::connect(&relay_url(), &unrelated) + .await + .expect("connect unrelated user"); + let response = unrelated_client + .send_event(trigger(&unrelated, workflow_id, &revision)) + .await + .expect("send unrelated trigger"); + assert!(!response.accepted, "unrelated member triggered workflow"); + assert!(response.message.contains("not authorized to trigger")); + + let mut owner_client = BuzzTestClient::connect(&relay_url(), &owner) + .await + .expect("connect human owner"); + let response = owner_client + .send_event(trigger(&owner, workflow_id, &revision)) + .await + .expect("send owner trigger"); + assert!( + response.accepted, + "owner trigger rejected: {}", + response.message + ); + + let missing_revision = EventBuilder::new(Kind::Custom(46020), "") + .tags([Tag::parse(["d", &workflow_id.to_string()]).unwrap()]) + .sign_with_keys(&owner) + .unwrap(); + let response = owner_client + .send_event(missing_revision) + .await + .expect("send unbound trigger"); + assert!(!response.accepted, "trigger without revision was accepted"); + assert!(response.message.contains("workflow revision e tag")); + + let wrong_revision = "ab".repeat(32); + let response = owner_client + .send_event(trigger(&owner, workflow_id, &wrong_revision)) + .await + .expect("send wrong-revision trigger"); + assert!(!response.accepted, "wrong revision was accepted"); + assert!(response + .message + .contains("does not match current definition")); + + // A valid old revision becomes stale immediately after an agent-signed update. + // NIP-33 revisions use second-granularity timestamps. Advance past the + // creation second so this update is newer regardless of the event-ID + // tie-breaker for equal timestamps. + tokio::time::sleep(std::time::Duration::from_secs(1)).await; + let update = buzz_sdk::build_workflow_update( + channel_id, + workflow_id, + &workflow_yaml("updated"), + &revision, + ) + .expect("build workflow update") + .sign_with_keys(&agent) + .expect("sign workflow update"); + let current_revision = update.id.to_hex(); + let response = agent_client + .send_event(update) + .await + .expect("update workflow"); + assert!(response.accepted, "update rejected: {}", response.message); + + let response = owner_client + .send_event(trigger(&owner, workflow_id, &revision)) + .await + .expect("send stale trigger"); + assert!(!response.accepted, "stale revision was accepted"); + assert!(response + .message + .contains("does not match current definition")); + + let response = owner_client + .send_event(trigger(&owner, workflow_id, ¤t_revision)) + .await + .expect("send current trigger"); + assert!( + response.accepted, + "current revision rejected: {}", + response.message + ); + + agent_client.disconnect().await.ok(); + unrelated_client.disconnect().await.ok(); + owner_client.disconnect().await.ok(); +} diff --git a/crates/buzz-workflow/src/executor.rs b/crates/buzz-workflow/src/executor.rs index 5c712dcff7..9aa9d4c3a2 100644 --- a/crates/buzz-workflow/src/executor.rs +++ b/crates/buzz-workflow/src/executor.rs @@ -43,6 +43,9 @@ pub struct TriggerContext { pub is_reply: bool, /// Arbitrary webhook body fields (webhook trigger). pub webhook_fields: HashMap, + /// Exact owner-signed kind:30620 definition revision executed by this run. + #[serde(default)] + pub definition_event_id: String, } impl TriggerContext { @@ -1312,6 +1315,7 @@ mod tests { message_id: "event-id-hex".to_owned(), is_reply: false, webhook_fields: HashMap::new(), + definition_event_id: String::new(), } } diff --git a/crates/buzz-workflow/src/lib.rs b/crates/buzz-workflow/src/lib.rs index bceb6d8bd8..6ab072a5bd 100644 --- a/crates/buzz-workflow/src/lib.rs +++ b/crates/buzz-workflow/src/lib.rs @@ -999,6 +999,7 @@ pub fn build_trigger_context(event: &buzz_core::StoredEvent) -> executor::Trigge message_id, is_reply: event_is_reply(&event.event), webhook_fields: HashMap::new(), + definition_event_id: String::new(), } } diff --git a/desktop/src-tauri/src/commands/workflows.rs b/desktop/src-tauri/src/commands/workflows.rs index c4e5d38c8b..beac00e675 100644 --- a/desktop/src-tauri/src/commands/workflows.rs +++ b/desktop/src-tauri/src/commands/workflows.rs @@ -323,7 +323,20 @@ pub async fn trigger_workflow( workflow_id: String, state: State<'_, AppState>, ) -> Result { - let builder = events::build_workflow_trigger(&workflow_id)?; + // Resolve the current signed definition at trigger time. The relay binds + // authorization and execution to this exact revision and rejects a stale + // result if an update races this command. + let prior = query_relay( + &state, + &[serde_json::json!({ + "kinds": [30620], + "#d": [workflow_id.clone()], + "limit": 1 + })], + ) + .await?; + let definition_event_id = current_workflow_revision(&prior)?; + let builder = events::build_workflow_trigger(&workflow_id, &definition_event_id)?; let result = submit_event(builder, &state).await?; trigger_wire_from_message(workflow_id, &result.message) } @@ -371,6 +384,13 @@ pub async fn deny_approval( // ── Helpers (pure, unit-tested in workflows_tests.rs) ───────────────────────── +fn current_workflow_revision(events: &[nostr::Event]) -> Result { + events + .first() + .map(|event| event.id.to_hex()) + .ok_or_else(|| "workflow not found".to_string()) +} + fn trigger_wire_from_message( workflow_id: String, message: &str, diff --git a/desktop/src-tauri/src/commands/workflows_tests.rs b/desktop/src-tauri/src/commands/workflows_tests.rs index 6523d45862..4df97831f7 100644 --- a/desktop/src-tauri/src/commands/workflows_tests.rs +++ b/desktop/src-tauri/src/commands/workflows_tests.rs @@ -273,6 +273,20 @@ fn channel_workflow_filters_accepts_empty_input() { ); } +#[test] +fn trigger_command_uses_current_definition_event_id() { + let event = wf_event(WF, CHAN, YAML); + let revision = event.id.to_hex(); + assert_eq!( + current_workflow_revision(std::slice::from_ref(&event)).as_deref(), + Ok(revision.as_str()) + ); + assert_eq!( + current_workflow_revision(&[]).expect_err("empty result must fail"), + "workflow not found" + ); +} + #[test] fn trigger_response_uses_persisted_run_id_contract() { let wire = trigger_wire_from_message( diff --git a/desktop/src-tauri/src/events.rs b/desktop/src-tauri/src/events.rs index 1828b3f560..8c57e0d976 100644 --- a/desktop/src-tauri/src/events.rs +++ b/desktop/src-tauri/src/events.rs @@ -769,6 +769,31 @@ pub use workflows::{ mod tests { use super::*; use nostr::Keys; + #[test] + fn workflow_trigger_binds_exact_definition_revision() { + let workflow_id = Uuid::new_v4().to_string(); + let revision = "ab".repeat(32); + let event = build_workflow_trigger(&workflow_id, &revision) + .expect("build workflow trigger") + .sign_with_keys(&Keys::generate()) + .expect("sign workflow trigger"); + let tags: Vec> = event + .tags + .iter() + .map(|tag| tag.as_slice().to_vec()) + .collect(); + + assert_eq!(event.kind, Kind::Custom(46020)); + assert_eq!( + tags, + vec![ + vec!["d".to_string(), workflow_id.clone()], + vec!["e".to_string(), revision.clone()], + ] + ); + assert!(build_workflow_trigger(&workflow_id, "not-an-event-id").is_err()); + } + #[test] fn channel_builders_reject_hash_only_names() { let channel_id = Uuid::new_v4(); diff --git a/desktop/src-tauri/src/events/workflows.rs b/desktop/src-tauri/src/events/workflows.rs index 8615f73851..b73f8fca4f 100644 --- a/desktop/src-tauri/src/events/workflows.rs +++ b/desktop/src-tauri/src/events/workflows.rs @@ -31,9 +31,16 @@ pub fn build_workflow_delete( Ok(EventBuilder::new(Kind::Custom(5), "").tags(tags)) } -/// Kind 46020 — trigger a workflow run by id. -pub fn build_workflow_trigger(workflow_id: &str) -> Result { - let tags = vec![tag(vec!["d", workflow_id])?]; +/// Kind 46020 — trigger a workflow run by id, bound to one exact definition revision. +pub fn build_workflow_trigger( + workflow_id: &str, + definition_event_id: &str, +) -> Result { + EventId::from_hex(definition_event_id).map_err(|_| "invalid workflow revision".to_string())?; + let tags = vec![ + tag(vec!["d", workflow_id])?, + tag(vec!["e", definition_event_id])?, + ]; Ok(EventBuilder::new(Kind::Custom(46020), "").tags(tags)) } diff --git a/migrations/0033_workflow_definition_event_id.sql b/migrations/0033_workflow_definition_event_id.sql new file mode 100644 index 0000000000..c733a83850 --- /dev/null +++ b/migrations/0033_workflow_definition_event_id.sql @@ -0,0 +1,6 @@ +-- Bind each materialized workflow row to the exact owner-signed kind:30620 +-- revision that produced it. Existing rows remain nullable until re-saved; +-- revision-bound execution fails closed when the revision is unavailable. +ALTER TABLE workflows + ADD COLUMN definition_event_id BYTEA + CHECK (definition_event_id IS NULL OR octet_length(definition_event_id) = 32); diff --git a/schema/schema.sql b/schema/schema.sql index 6e14e6be1b..734cdb315e 100644 --- a/schema/schema.sql +++ b/schema/schema.sql @@ -368,6 +368,11 @@ CREATE TABLE workflows ( channel_id UUID, definition JSONB NOT NULL, definition_hash BYTEA NOT NULL, + -- Exact owner-signed kind:30620 revision that materialized this row. + -- Nullable only for pre-0033 rows; revision-bound execution fails closed until re-saved. + definition_event_id BYTEA CHECK ( + definition_event_id IS NULL OR octet_length(definition_event_id) = 32 + ), status workflow_status NOT NULL DEFAULT 'active', enabled BOOLEAN NOT NULL DEFAULT TRUE, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),