From 3d97535120cd4e18ecd01542e4f7fbcadbf9301c Mon Sep 17 00:00:00 2001 From: Luke Tornquist Date: Mon, 16 Nov 2026 20:15:09 -0500 Subject: [PATCH] buzz-db: check workflow references in app code before FK retirement (#9399) --- .../src/store/admission_postgres_tests.rs | 5 + crates/buzz-db/src/store/workflow.rs | 123 +++++ crates/buzz-db/src/store/workflow/deletion.rs | 19 +- .../src/store/workflow/deletion_tests.rs | 266 ++++++++++- .../src/store/workflow/reference_tests.rs | 445 ++++++++++++++++++ crates/buzz-db/src/test_support.rs | 83 +++- 6 files changed, 910 insertions(+), 31 deletions(-) create mode 100644 crates/buzz-db/src/store/workflow/reference_tests.rs diff --git a/crates/buzz-db/src/store/admission_postgres_tests.rs b/crates/buzz-db/src/store/admission_postgres_tests.rs index 150f517922..f0ce61d78f 100644 --- a/crates/buzz-db/src/store/admission_postgres_tests.rs +++ b/crates/buzz-db/src/store/admission_postgres_tests.rs @@ -380,6 +380,11 @@ async fn workflow_writers_require_application_admission() { .expect_err("approval update must reject"), ); } + // The fixture's session runs with foreign-key triggers off, so the owner + // must exist for the workflow writer's own reference check. + super::user::ensure_user(&db.pool, communities[0], &[1; 32]) + .await + .expect("active workflow owner"); super::workflow::create_workflow( &db.pool, communities[0], diff --git a/crates/buzz-db/src/store/workflow.rs b/crates/buzz-db/src/store/workflow.rs index e29ed47950..52ed1b897e 100644 --- a/crates/buzz-db/src/store/workflow.rs +++ b/crates/buzz-db/src/store/workflow.rs @@ -10,6 +10,10 @@ mod deletion; pub use deletion::WorkflowDeletionOutcome; +#[cfg(test)] +#[path = "workflow/reference_tests.rs"] +mod reference_postgres_tests; + use std::fmt; use std::str::FromStr; @@ -318,11 +322,107 @@ pub struct ApprovalRecord { pub created_at: DateTime, } +// -- Reference checks --------------------------------------------------------- +// +// Every workflow-table reference is checked in the writing transaction, and the +// parent row is locked `FOR KEY SHARE`: the lock a foreign key's check takes, so +// a concurrent delete of the parent (which locks it `FOR UPDATE` first, see +// `workflow/deletion.rs`) either waits for this transaction or runs first and +// makes the check fail. While the foreign keys still exist the two checks are +// idempotent; once they are dropped these checks are the only guard. +// +// A missing parent is `DbError::NotFound`, never a silent success. + +/// Lock `workflows (community_id, id)` `FOR KEY SHARE`, or fail with `NotFound`. +async fn require_workflow( + conn: &mut sqlx::PgConnection, + community_id: CommunityId, + workflow_id: Uuid, +) -> Result<()> { + sqlx::query_scalar::<_, i32>( + "SELECT 1 FROM workflows WHERE community_id = $1 AND id = $2 FOR KEY SHARE", + ) + .bind(community_id.as_uuid()) + .bind(workflow_id) + .fetch_optional(conn) + .await? + .map(|_| ()) + .ok_or_else(|| DbError::NotFound(format!("workflow {workflow_id}"))) +} + +/// Lock `workflow_runs (community_id, id)` `FOR KEY SHARE`, or fail with `NotFound`. +async fn require_workflow_run( + conn: &mut sqlx::PgConnection, + community_id: CommunityId, + run_id: Uuid, +) -> Result<()> { + sqlx::query_scalar::<_, i32>( + "SELECT 1 FROM workflow_runs WHERE community_id = $1 AND id = $2 FOR KEY SHARE", + ) + .bind(community_id.as_uuid()) + .bind(run_id) + .fetch_optional(conn) + .await? + .map(|_| ()) + .ok_or_else(|| DbError::NotFound(format!("workflow_run {run_id}"))) +} + +/// Lock `users (community_id, pubkey)` `FOR KEY SHARE`, or fail with `NotFound`. +async fn require_workflow_owner( + conn: &mut sqlx::PgConnection, + community_id: CommunityId, + owner_pubkey: &[u8], +) -> Result<()> { + sqlx::query_scalar::<_, i32>( + "SELECT 1 FROM users WHERE community_id = $1 AND pubkey = $2 FOR KEY SHARE", + ) + .bind(community_id.as_uuid()) + .bind(owner_pubkey) + .fetch_optional(conn) + .await? + .map(|_| ()) + .ok_or_else(|| DbError::NotFound("workflow owner user".to_owned())) +} + +/// Lock `channels (community_id, id)` `FOR KEY SHARE`, or fail with `NotFound`. +async fn require_workflow_channel( + conn: &mut sqlx::PgConnection, + community_id: CommunityId, + channel_id: Uuid, +) -> Result<()> { + sqlx::query_scalar::<_, i32>( + "SELECT 1 FROM channels WHERE community_id = $1 AND id = $2 FOR KEY SHARE", + ) + .bind(community_id.as_uuid()) + .bind(channel_id) + .fetch_optional(conn) + .await? + .map(|_| ()) + .ok_or_else(|| DbError::NotFound(format!("channel {channel_id}"))) +} + +/// Check the parents a `workflows` row references: its owner, then its channel. +async fn require_workflow_parents( + conn: &mut sqlx::PgConnection, + community_id: CommunityId, + owner_pubkey: &[u8], + channel_id: Option, +) -> Result<()> { + require_workflow_owner(conn, community_id, owner_pubkey).await?; + if let Some(channel_id) = channel_id { + require_workflow_channel(conn, community_id, channel_id).await?; + } + Ok(()) +} + // -- Workflow CRUD ------------------------------------------------------------ /// Insert a new workflow record. Returns the new workflow's UUID. /// New workflows start as `active` and `enabled = TRUE`. /// +/// The owner (`users`) and the channel, when set, must exist in `community_id`; +/// otherwise this returns [`DbError::NotFound`] and writes nothing. +/// /// NOTE: see the cache-invalidation note on [`update_workflow`]. The relay's /// creation path is [`upsert_workflow`] via event ingest. (No current callers.) pub async fn create_workflow( @@ -342,6 +442,7 @@ pub async fn create_workflow( .await?; let id = Uuid::new_v4(); + require_workflow_parents(tx.conn(), community_id, owner_pubkey, channel_id).await?; sqlx::query( r#" INSERT INTO workflows @@ -368,6 +469,10 @@ pub async fn create_workflow( /// Updates are allowed only when the existing row has the same owner and /// channel. That keeps a learned workflow UUID from becoming a cross-user or /// cross-channel overwrite primitive while still making retries idempotent. +/// +/// The owner (`users`) and the channel, when set, must exist in `community_id` +/// or this returns [`DbError::NotFound`] and writes nothing. That check runs +/// first, so a missing parent wins over the owner/channel mismatch rejection. #[allow(clippy::too_many_arguments)] pub async fn upsert_workflow( pool: &PgPool, @@ -385,6 +490,7 @@ pub async fn upsert_workflow( crate::observability::WriterOperation::EventWrite, ) .await?; + require_workflow_parents(tx.conn(), community_id, owner_pubkey, channel_id).await?; let row = sqlx::query( r#" INSERT INTO workflows @@ -559,6 +665,13 @@ pub async fn list_all_enabled_workflows(pool: &PgPool) -> Result { /// /// The `token` parameter is the raw (plaintext) token. It is hashed with /// SHA-256 before storage so the DB never holds the raw value. +/// +/// Both the workflow and the run must exist in `community_id`; otherwise this +/// returns [`DbError::NotFound`] and writes nothing. pub async fn create_approval(pool: &PgPool, params: CreateApprovalParams<'_>) -> Result<()> { let CreateApprovalParams { community_id, @@ -1137,6 +1258,8 @@ pub async fn create_approval(pool: &PgPool, params: CreateApprovalParams<'_>) -> ) .await?; + require_workflow(tx.conn(), community_id, workflow_id).await?; + require_workflow_run(tx.conn(), community_id, run_id).await?; sqlx::query( r#" INSERT INTO workflow_approvals diff --git a/crates/buzz-db/src/store/workflow/deletion.rs b/crates/buzz-db/src/store/workflow/deletion.rs index cd8a5dedda..c9a6d287c3 100644 --- a/crates/buzz-db/src/store/workflow/deletion.rs +++ b/crates/buzz-db/src/store/workflow/deletion.rs @@ -118,8 +118,10 @@ async fn delete_workflow_in_transaction( // The owner predicate is in the locking SELECT; FOR UPDATE keeps it // binding for the deletes below. let workflow_id = Uuid::parse_str(d_tag).ok(); - // Lock the workflow first: a concurrent run or fire insert must lock it for - // its foreign key, so the child deletes below see every committed child. + // Lock the workflow first: a concurrent run, approval or fire insert must + // lock it `FOR KEY SHARE` (the reference checks in `workflow.rs`), so the + // child deletes below see every committed child, and an insert that starts + // later finds the workflow gone. let target: Option = sqlx::query_scalar( "SELECT id FROM workflows WHERE community_id = $1 AND owner_pubkey = $2 \ AND id = COALESCE($3::uuid, (SELECT id FROM workflows \ @@ -160,10 +162,12 @@ async fn delete_workflow_in_transaction( /// or any of its runs), then runs. Returns the workflow's `channel_id`. async fn delete_workflow_with_children(tx: &mut AdmittedTx, id: Uuid) -> Result> { let community = *tx.community().as_uuid(); - // Fires go before the run lock. A new fire must key-share lock the workflow, - // which is already locked. Attaching a run to a fire locks the fire row and - // then the run, so taking the run lock first would invert that order and can - // deadlock; deleting the fire first waits for any in-flight attach instead. + // Fires go before the run lock. A new fire claim key-share locks the + // workflow, which is already locked. Attaching a run to a fire locks the + // fire row and, while the fire's run foreign key exists, then key-share + // locks the run, so taking the run lock first would invert that order and + // can deadlock; deleting the fire first waits for any in-flight attach + // instead, and an attach that starts later finds no fire to update. sqlx::query( "DELETE FROM scheduled_workflow_fires WHERE community_id = $1 AND workflow_id = $2", ) @@ -172,7 +176,8 @@ async fn delete_workflow_with_children(tx: &mut AdmittedTx, id: Uuid) -> Result< .execute(tx.conn()) .await?; // The workflow lock stops new runs, but an approval naming another workflow - // can still reference one of these runs; it key-share locks only that run. + // can still reference one of these runs; its reference check key-share locks + // only that run. // Lock the runs (in a fixed order) so such an insert either commits before // the approval delete below or waits until this transaction ends. sqlx::query( diff --git a/crates/buzz-db/src/store/workflow/deletion_tests.rs b/crates/buzz-db/src/store/workflow/deletion_tests.rs index 7ddcfa3b0c..1ece8bd27e 100644 --- a/crates/buzz-db/src/store/workflow/deletion_tests.rs +++ b/crates/buzz-db/src/store/workflow/deletion_tests.rs @@ -460,14 +460,18 @@ async fn workflow_deletion_removes_children_without_cascades() { } /// A run inserted concurrently with the delete holds the workflow's key-share -/// lock. The delete must wait for it at its row lock and then remove the run; -/// with no cascade, a delete that took its child snapshot first would fail the -/// foreign-key check on the workflow. +/// lock, taken by the run writer's reference check. The delete must wait for it +/// at its row lock and then remove the run; if it took its child snapshot +/// first, the run would commit after the child delete and dangle. The +/// run-to-workflow foreign key is dropped, so only the explicit lock can make +/// the delete wait. #[tokio::test] #[ignore = "requires Postgres"] async fn workflow_deletion_waits_for_and_removes_concurrent_run() { let (db, community) = setup().await; crate::test_support::retire_foreign_key_delete_actions(&db.pool).await; + crate::test_support::drop_foreign_keys_between(&db.pool, &[("workflow_runs", "workflows")]) + .await; let keys = Keys::generate(); let owner = keys.public_key().to_bytes(); let id = Uuid::new_v4(); @@ -476,6 +480,9 @@ async fn workflow_deletion_waits_for_and_removes_concurrent_run() { seed(&db, community, &keys, id, &d_tag, now).await; let mut inserter = db.pool.begin().await.expect("begin run insert"); + super::super::require_workflow(&mut inserter, community, id) + .await + .expect("lock workflow as the run writer does"); sqlx::query( "INSERT INTO workflow_runs (community_id, id, workflow_id, status, current_step, execution_trace) \ VALUES ($1, $2, $3, 'pending', 0, '[]')", @@ -509,15 +516,24 @@ async fn workflow_deletion_waits_for_and_removes_concurrent_run() { } /// An approval naming another workflow but one of this workflow's runs only -/// key-share locks that run, so the workflow lock does not exclude it. The -/// delete must lock the runs, wait for the insert, and then remove it; with no -/// cascade, committing it between the approval and run deletes would fail the -/// run delete's foreign-key check. +/// key-share locks that run (in its reference check), so the workflow lock does +/// not exclude it. The delete must lock the runs, wait for the insert, and then +/// remove it; if the approval committed between the approval and run deletes it +/// would dangle. The approval foreign keys are dropped, so only the explicit +/// locks can make the delete wait. #[tokio::test] #[ignore = "requires Postgres"] async fn workflow_deletion_waits_for_and_removes_concurrent_cross_workflow_approval() { let (db, community) = setup().await; crate::test_support::retire_foreign_key_delete_actions(&db.pool).await; + crate::test_support::drop_foreign_keys_between( + &db.pool, + &[ + ("workflow_approvals", "workflows"), + ("workflow_approvals", "workflow_runs"), + ], + ) + .await; let keys = Keys::generate(); let owner = keys.public_key().to_bytes(); let id = Uuid::new_v4(); @@ -538,6 +554,12 @@ async fn workflow_deletion_waits_for_and_removes_concurrent_cross_workflow_appro .expect("run"); let mut inserter = db.pool.begin().await.expect("begin approval insert"); + super::super::require_workflow(&mut inserter, community, other) + .await + .expect("lock workflow as the approval writer does"); + super::super::require_workflow_run(&mut inserter, community, run_id) + .await + .expect("lock run as the approval writer does"); sqlx::query( "INSERT INTO workflow_approvals (community_id, token, workflow_id, run_id, step_id, \ step_index, approver_spec, status, expires_at) \ @@ -580,9 +602,10 @@ async fn workflow_deletion_waits_for_and_removes_concurrent_cross_workflow_appro } /// Attaching a run to a scheduled fire locks the fire row, then key-share -/// locks the run for its foreign key. The delete must take those two in the -/// same order (fire before run), so an attach in flight when the delete -/// starts completes and is then removed, rather than deadlocking with it. +/// locks the run for the fire's run foreign key, which this test keeps (the +/// attach writer is unchanged). The delete must take those two in the same +/// order (fire before run), so an attach in flight when the delete starts +/// completes and is then removed, rather than deadlocking with it. #[tokio::test] #[ignore = "requires Postgres"] async fn workflow_deletion_waits_for_concurrent_fire_attach_without_deadlock() { @@ -665,3 +688,226 @@ async fn workflow_deletion_waits_for_concurrent_fire_attach_without_deadlock() { ); } } + +/// Take the locks a workflow delete takes first: the workflow row and its +/// runs, `FOR UPDATE`. The caller finishes the delete with +/// [`delete_workflow_with_children`] and commits. +async fn begin_delete_holding_locks(db: &Db, community: CommunityId, id: Uuid) -> AdmittedTx { + let mut tx = db + .begin_event_write_transaction(community) + .await + .expect("begin delete"); + sqlx::query("SELECT id FROM workflows WHERE community_id = $1 AND id = $2 FOR UPDATE") + .bind(community.as_uuid()) + .bind(id) + .execute(tx.conn()) + .await + .expect("lock workflow"); + sqlx::query( + "SELECT id FROM workflow_runs WHERE community_id = $1 AND workflow_id = $2 \ + ORDER BY id FOR UPDATE", + ) + .bind(community.as_uuid()) + .bind(id) + .execute(tx.conn()) + .await + .expect("lock runs"); + tx +} + +/// Run `writer` on its own connection while `holder` has the workflow locked, +/// wait until it is blocked on a lock, then finish the delete and commit. +/// Returns the writer's result, which ran strictly after the delete. +async fn write_while_delete_holds_locks( + db: &Db, + mut holder: AdmittedTx, + workflow_id: Uuid, + writer: impl FnOnce(Db) -> std::pin::Pin + Send>>, +) -> T { + let name = format!("workflow-writer-{}", Uuid::new_v4().simple()); + let writer_db = Db::from_pool(crate::test_support::named_pool(&name).await); + let write = tokio::spawn(writer(writer_db)); + crate::test_support::wait_for_lock_wait(&db.pool, &name).await; + delete_workflow_with_children(&mut holder, workflow_id) + .await + .expect("delete workflow"); + holder.commit().await.expect("commit delete"); + write.await.expect("join writer") +} + +/// With the fire-to-workflow foreign key dropped, a fire claim racing a +/// workflow delete must wait on the workflow row (its `FOR KEY SHARE`) and then +/// find no workflow. Without that lock the claim reads its snapshot while the +/// delete is uncommitted, inserts after the delete removed the fires, and leaves +/// an orphan fire nothing cleans up. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn fire_claim_waits_for_workflow_delete_and_leaves_no_orphan_fire() { + let (db, community) = setup().await; + crate::test_support::drop_foreign_keys_between( + &db.pool, + &[("scheduled_workflow_fires", "workflows")], + ) + .await; + let keys = Keys::generate(); + let id = Uuid::new_v4(); + seed( + &db, + community, + &keys, + id, + &id.to_string(), + Timestamp::now().as_secs(), + ) + .await; + + let holder = begin_delete_holding_locks(&db, community, id).await; + let claim = write_while_delete_holds_locks(&db, holder, id, move |writer| { + Box::pin(async move { + writer + .claim_scheduled_workflow_fire(community, id, chrono::Utc::now()) + .await + }) + }) + .await; + + assert!( + matches!(claim, Ok(None)), + "a claim after the delete must lose, got {claim:?}" + ); + assert_eq!( + count_where( + &db, + "scheduled_workflow_fires", + "workflow_id", + community, + id + ) + .await, + 0, + "no orphan fire may survive the delete" + ); +} + +/// A run writer racing a workflow delete waits on the workflow row and then +/// fails, instead of committing a run for a workflow that is gone. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn run_create_waits_for_workflow_delete_and_leaves_no_orphan_run() { + let (db, community) = setup().await; + crate::test_support::drop_foreign_keys_between(&db.pool, &[("workflow_runs", "workflows")]) + .await; + let keys = Keys::generate(); + let id = Uuid::new_v4(); + seed( + &db, + community, + &keys, + id, + &id.to_string(), + Timestamp::now().as_secs(), + ) + .await; + + let holder = begin_delete_holding_locks(&db, community, id).await; + let created = write_while_delete_holds_locks(&db, holder, id, move |writer| { + Box::pin(async move { + writer + .create_workflow_run( + community, + id, + None, + None, + &crate::workflow::RunCause::Schedule, + ) + .await + }) + }) + .await; + + assert!( + matches!(created, Err(DbError::NotFound(_))), + "a run created after the delete must be rejected, got {created:?}" + ); + assert_eq!( + count_where(&db, "workflow_runs", "workflow_id", community, id).await, + 0, + "no orphan run may survive the delete" + ); +} + +/// An approval racing the delete of the workflow it names, or of the run it +/// names under another workflow, waits on that parent's lock and then fails. +async fn approval_waits_for_delete_and_leaves_no_orphan_approval(names_deleted_workflow: bool) { + let (db, community) = setup().await; + crate::test_support::drop_foreign_keys_between( + &db.pool, + &[ + ("workflow_runs", "workflows"), + ("workflow_approvals", "workflows"), + ("workflow_approvals", "workflow_runs"), + ], + ) + .await; + let keys = Keys::generate(); + let now = Timestamp::now().as_secs(); + let id = Uuid::new_v4(); + seed(&db, community, &keys, id, &id.to_string(), now).await; + let other = Uuid::new_v4(); + seed(&db, community, &keys, other, &other.to_string(), now).await; + let run_id = create_workflow_run( + &db.pool, + community, + id, + None, + None, + &crate::workflow::RunCause::Schedule, + ) + .await + .expect("run"); + // Either the approval names the workflow being deleted, or it names the + // surviving workflow and only its run belongs to the deleted one. + let approval_workflow = if names_deleted_workflow { id } else { other }; + + let holder = begin_delete_holding_locks(&db, community, id).await; + let approved = write_while_delete_holds_locks(&db, holder, id, move |writer| { + Box::pin(async move { + writer + .create_approval(crate::workflow::CreateApprovalParams { + community_id: community, + token: "racing-approval", + workflow_id: approval_workflow, + run_id, + step_id: "gate", + step_index: 0, + approver_spec: "@anyone", + expires_at: chrono::Utc::now() + chrono::Duration::hours(1), + }) + .await + }) + }) + .await; + + assert!( + matches!(approved, Err(DbError::NotFound(_))), + "an approval after the delete must be rejected, got {approved:?}" + ); + assert_eq!( + count_where(&db, "workflow_approvals", "run_id", community, run_id).await, + 0, + "no orphan approval may survive the delete" + ); + assert!(get_workflow(&db.pool, community, other).await.is_ok()); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn approval_create_waits_for_workflow_delete_and_leaves_no_orphan_approval() { + approval_waits_for_delete_and_leaves_no_orphan_approval(true).await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn cross_workflow_approval_create_waits_for_run_delete_and_leaves_no_orphan_approval() { + approval_waits_for_delete_and_leaves_no_orphan_approval(false).await; +} diff --git a/crates/buzz-db/src/store/workflow/reference_tests.rs b/crates/buzz-db/src/store/workflow/reference_tests.rs new file mode 100644 index 0000000000..b5b1477adf --- /dev/null +++ b/crates/buzz-db/src/store/workflow/reference_tests.rs @@ -0,0 +1,445 @@ +//! A writer into a workflow table rejects a missing parent in application +//! code. Each test drops the foreign keys it covers from the per-test database +//! first, so a pass proves the in-transaction check rather than the constraint. + +use super::*; +use crate::user::ensure_user; + +async fn setup() -> (Db, CommunityId) { + let pool = PgPool::connect(&crate::test_support::database_url()) + .await + .expect("connect test database"); + let db = Db::from_pool(pool); + let community = new_community(&db).await; + (db, community) +} + +async fn new_community(db: &Db) -> CommunityId { + db.ensure_configured_community(&format!("workflow-ref-{}.example", Uuid::new_v4())) + .await + .expect("create community") + .id +} + +async fn new_channel(db: &Db, community: CommunityId, owner: &[u8]) -> Uuid { + let id = Uuid::new_v4(); + sqlx::query( + "INSERT INTO channels (id, community_id, name, created_by) VALUES ($1, $2, $3, $4)", + ) + .bind(id) + .bind(community.as_uuid()) + .bind(format!("ch-{}", id.simple())) + .bind(owner) + .execute(&db.pool) + .await + .expect("insert channel"); + id +} + +/// A workflow with an existing owner and no channel. +async fn new_workflow(db: &Db, community: CommunityId, owner: &[u8]) -> Uuid { + ensure_user(&db.pool, community, owner) + .await + .expect("ensure owner"); + create_workflow( + &db.pool, + community, + None, + owner, + "reference-test", + r#"{"trigger":{"on":"manual"},"steps":[]}"#, + &[0; 32], + ) + .await + .expect("create workflow") +} + +async fn count(db: &Db, table: &str, community: CommunityId) -> i64 { + sqlx::query_scalar(sqlx::AssertSqlSafe(format!( + "SELECT count(*) FROM {table} WHERE community_id = $1" + ))) + .bind(community.as_uuid()) + .fetch_one(&db.pool) + .await + .expect("count rows") +} + +fn assert_not_found(result: Result, what: &str) { + match result { + Err(DbError::NotFound(message)) => { + assert!(message.contains(what), "unexpected message: {message}") + } + other => panic!("expected NotFound({what}), got {other:?}"), + } +} + +const DEFINITION: &str = r#"{"trigger":{"on":"manual"},"steps":[]}"#; + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn create_workflow_rejects_missing_owner_or_channel_without_foreign_keys() { + let (db, community) = setup().await; + crate::test_support::drop_foreign_keys_between( + &db.pool, + &[("workflows", "users"), ("workflows", "channels")], + ) + .await; + let owner = [0x11; 32]; + let create = |channel: Option, owner: [u8; 32]| { + let pool = db.pool.clone(); + async move { + create_workflow( + &pool, community, channel, &owner, "wf", DEFINITION, &[0; 32], + ) + .await + } + }; + + // Unknown owner. + assert_not_found(create(None, owner).await, "owner"); + + // The owner exists only in another community. + let other = new_community(&db).await; + ensure_user(&db.pool, other, &owner) + .await + .expect("other user"); + assert_not_found(create(None, owner).await, "owner"); + + // Known owner, unknown channel; and a channel that exists only elsewhere. + ensure_user(&db.pool, community, &owner) + .await + .expect("owner"); + assert_not_found(create(Some(Uuid::new_v4()), owner).await, "channel"); + let elsewhere = new_channel(&db, other, &owner).await; + assert_not_found(create(Some(elsewhere), owner).await, "channel"); + assert_eq!(count(&db, "workflows", community).await, 0); + + // Control: valid parents are accepted. + let channel = new_channel(&db, community, &owner).await; + create(Some(channel), owner).await.expect("valid parents"); + assert_eq!(count(&db, "workflows", community).await, 1); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn upsert_workflow_rejects_missing_owner_or_channel_without_foreign_keys() { + let (db, community) = setup().await; + crate::test_support::drop_foreign_keys_between( + &db.pool, + &[("workflows", "users"), ("workflows", "channels")], + ) + .await; + let owner = [0x12; 32]; + let upsert = |channel: Option, owner: [u8; 32]| { + let pool = db.pool.clone(); + async move { + upsert_workflow( + &pool, + community, + Uuid::new_v4(), + channel, + &owner, + "wf", + DEFINITION, + &[0; 32], + ) + .await + } + }; + + assert_not_found(upsert(None, owner).await, "owner"); + let other = new_community(&db).await; + ensure_user(&db.pool, other, &owner) + .await + .expect("other user"); + assert_not_found(upsert(None, owner).await, "owner"); + + ensure_user(&db.pool, community, &owner) + .await + .expect("owner"); + assert_not_found(upsert(Some(Uuid::new_v4()), owner).await, "channel"); + let elsewhere = new_channel(&db, other, &owner).await; + assert_not_found(upsert(Some(elsewhere), owner).await, "channel"); + assert_eq!(count(&db, "workflows", community).await, 0); + + // Control: valid parents are accepted, and a retry of the same row is idempotent. + let channel = new_channel(&db, community, &owner).await; + let id = Uuid::new_v4(); + for _ in 0..2 { + upsert_workflow( + &db.pool, + community, + id, + Some(channel), + &owner, + "wf", + DEFINITION, + &[0; 32], + ) + .await + .expect("valid parents"); + } + assert_eq!(count(&db, "workflows", community).await, 1); + + // An existing ID: a different valid owner or channel is the overwrite + // boundary (`AccessDenied`); a missing owner or channel fails the reference + // check first (`NotFound`). Neither attempt touches the stored row. + let other_owner = [0x22; 32]; + ensure_user(&db.pool, community, &other_owner) + .await + .expect("other owner"); + let other_channel = new_channel(&db, community, &owner).await; + let overwrite = |channel: Option, owner: [u8; 32]| { + let pool = db.pool.clone(); + async move { + upsert_workflow( + &pool, + community, + id, + channel, + &owner, + "hijack", + r#"{"trigger":{"on":"manual"},"steps":[{"id":"x"}]}"#, + &[1; 32], + ) + .await + } + }; + for (label, result) in [ + ("other owner", overwrite(Some(channel), other_owner).await), + ("other channel", overwrite(Some(other_channel), owner).await), + ] { + assert!( + matches!(result, Err(DbError::AccessDenied(_))), + "{label}: expected AccessDenied, got {result:?}" + ); + } + assert_not_found(overwrite(Some(channel), [0x23; 32]).await, "owner"); + assert_not_found(overwrite(Some(Uuid::new_v4()), owner).await, "channel"); + + let stored = get_workflow(&db.pool, community, id) + .await + .expect("stored workflow"); + assert_eq!(stored.owner_pubkey, owner.to_vec()); + assert_eq!(stored.channel_id, Some(channel)); + assert_eq!(stored.name, "wf"); + assert_eq!(stored.definition_hash, vec![0; 32]); + assert_eq!(count(&db, "workflows", community).await, 1); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn create_workflow_run_rejects_missing_workflow_without_foreign_key() { + let (db, community) = setup().await; + crate::test_support::drop_foreign_keys_between(&db.pool, &[("workflow_runs", "workflows")]) + .await; + let owner = [0x13; 32]; + + assert_not_found( + create_workflow_run( + &db.pool, + community, + Uuid::new_v4(), + None, + None, + &RunCause::Schedule, + ) + .await, + "workflow", + ); + // The workflow exists only in another community. + let other = new_community(&db).await; + let elsewhere = new_workflow(&db, other, &owner).await; + assert_not_found( + create_workflow_run( + &db.pool, + community, + elsewhere, + None, + None, + &RunCause::Schedule, + ) + .await, + "workflow", + ); + assert_eq!(count(&db, "workflow_runs", community).await, 0); + assert_eq!(count(&db, "workflow_runs", other).await, 0); + + let workflow = new_workflow(&db, community, &owner).await; + create_workflow_run( + &db.pool, + community, + workflow, + None, + None, + &RunCause::Schedule, + ) + .await + .expect("existing workflow"); + assert_eq!(count(&db, "workflow_runs", community).await, 1); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn create_approval_rejects_missing_workflow_or_run_without_foreign_keys() { + let (db, community) = setup().await; + crate::test_support::drop_foreign_keys_between( + &db.pool, + &[ + ("workflow_approvals", "workflows"), + ("workflow_approvals", "workflow_runs"), + ], + ) + .await; + let owner = [0x14; 32]; + let workflow = new_workflow(&db, community, &owner).await; + let run = create_workflow_run( + &db.pool, + community, + workflow, + None, + None, + &RunCause::Schedule, + ) + .await + .expect("run"); + let approve = |workflow_id: Uuid, run_id: Uuid, token: &'static str| { + let pool = db.pool.clone(); + async move { + create_approval( + &pool, + CreateApprovalParams { + community_id: community, + token, + workflow_id, + run_id, + step_id: "gate", + step_index: 0, + approver_spec: "@anyone", + expires_at: Utc::now() + chrono::Duration::hours(1), + }, + ) + .await + } + }; + + assert_not_found( + approve(Uuid::new_v4(), run, "no-workflow").await, + "workflow", + ); + assert_not_found( + approve(workflow, Uuid::new_v4(), "no-run").await, + "workflow_run", + ); + + // Both exist, but only in another community. + let other = new_community(&db).await; + let other_workflow = new_workflow(&db, other, &owner).await; + let other_run = create_workflow_run( + &db.pool, + other, + other_workflow, + None, + None, + &RunCause::Schedule, + ) + .await + .expect("other run"); + assert_not_found( + approve(other_workflow, run, "workflow-elsewhere").await, + "workflow", + ); + assert_not_found( + approve(workflow, other_run, "run-elsewhere").await, + "workflow_run", + ); + assert_eq!(count(&db, "workflow_approvals", community).await, 0); + assert_eq!(count(&db, "workflow_approvals", other).await, 0); + + approve(workflow, run, "valid") + .await + .expect("valid parents"); + assert_eq!(count(&db, "workflow_approvals", community).await, 1); +} + +/// The owner and channel checks hold `FOR KEY SHARE` on the parent rows, so a +/// concurrent delete or key update of a parent waits for the writer. The +/// foreign keys are dropped, so only the explicit lock can block the writer +/// behind a parent held `FOR UPDATE`. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn workflow_writers_key_share_lock_owner_and_channel_without_foreign_keys() { + let (db, community) = setup().await; + crate::test_support::drop_foreign_keys_between( + &db.pool, + &[("workflows", "users"), ("workflows", "channels")], + ) + .await; + let owner = [0x15; 32]; + ensure_user(&db.pool, community, &owner) + .await + .expect("owner"); + let channel = new_channel(&db, community, &owner).await; + + for writer_is_upsert in [false, true] { + for lock_channel in [false, true] { + let mut holder = db.pool.begin().await.expect("begin parent lock holder"); + if lock_channel { + sqlx::query( + "SELECT 1 FROM channels WHERE community_id = $1 AND id = $2 FOR UPDATE", + ) + .bind(community.as_uuid()) + .bind(channel) + .execute(&mut *holder) + .await + .expect("lock channel"); + } else { + sqlx::query( + "SELECT 1 FROM users WHERE community_id = $1 AND pubkey = $2 FOR UPDATE", + ) + .bind(community.as_uuid()) + .bind(owner.as_slice()) + .execute(&mut *holder) + .await + .expect("lock owner"); + } + + let name = format!("workflow-writer-{}", Uuid::new_v4().simple()); + let pool = crate::test_support::named_pool(&name).await; + let write = tokio::spawn(async move { + if writer_is_upsert { + upsert_workflow( + &pool, + community, + Uuid::new_v4(), + Some(channel), + &owner, + "wf", + DEFINITION, + &[0; 32], + ) + .await + } else { + create_workflow( + &pool, + community, + Some(channel), + &owner, + "wf", + DEFINITION, + &[0; 32], + ) + .await + .map(|_| ()) + } + }); + crate::test_support::wait_for_lock_wait(&db.pool, &name).await; + holder.commit().await.expect("release parent lock"); + write + .await + .expect("join writer") + .expect("writer proceeds once the parent lock is released"); + } + } + assert_eq!(count(&db, "workflows", community).await, 4); +} diff --git a/crates/buzz-db/src/test_support.rs b/crates/buzz-db/src/test_support.rs index 93a25a0ff8..783da0e7f7 100644 --- a/crates/buzz-db/src/test_support.rs +++ b/crates/buzz-db/src/test_support.rs @@ -488,20 +488,7 @@ pub(crate) fn desired_state_schema_dir() -> std::path::PathBuf { /// which excludes the run's `_desired` template. The name is the only check: /// a manually created database with that shape would pass. pub(crate) async fn retire_foreign_key_delete_actions(pool: &sqlx::PgPool) { - let database: String = sqlx::query_scalar("SELECT current_database()") - .fetch_one(pool) - .await - .expect("read current database"); - assert!( - database - .strip_prefix("buzz_nt_") - .is_some_and(|hash| hash.len() == 24 - && hash - .bytes() - .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))), - "refusing to rewrite foreign keys in shared database {database}; \ - run this test through scripts/postgres-test-run.sh" - ); + assert_per_test_database(pool).await; sqlx::raw_sql( r#"DO $$ DECLARE c record; @@ -528,6 +515,74 @@ pub(crate) async fn retire_foreign_key_delete_actions(pool: &sqlx::PgPool) { assert_eq!(remaining, 0, "every foreign-key delete action is retired"); } +/// Refuse to continue unless `pool` is this test process's own database (named +/// `buzz_nt_` plus 24 hex digits by the per-test wrapper), so a schema rewrite +/// cannot reach a shared database or the run's `_desired` template. +async fn assert_per_test_database(pool: &sqlx::PgPool) { + let database: String = sqlx::query_scalar("SELECT current_database()") + .fetch_one(pool) + .await + .expect("read current database"); + assert!( + database + .strip_prefix("buzz_nt_") + .is_some_and(|hash| hash.len() == 24 + && hash + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))), + "refusing to rewrite foreign keys in shared database {database}; \ + run this test through scripts/postgres-test-run.sh" + ); +} + +/// Drop every foreign key from `child` to `parent` in this test's database, for +/// each `(child, parent)` pair: the schema a foreign-key retirement targets. +/// A test that then expects the writer to reject a missing parent proves the +/// application check, because the constraint can no longer do the work. +/// +/// Refuses databases that are not the per-test wrapper's, like +/// [`retire_foreign_key_delete_actions`]. Panics if a pair has no foreign key, +/// so a renamed table cannot turn the test into a silent no-op. +pub(crate) async fn drop_foreign_keys_between(pool: &sqlx::PgPool, pairs: &[(&str, &str)]) { + assert_per_test_database(pool).await; + for (child, parent) in pairs { + let constraints: Vec = sqlx::query_scalar( + "SELECT conname FROM pg_constraint \ + WHERE contype = 'f' AND conrelid = $1::text::regclass AND confrelid = $2::text::regclass", + ) + .bind(child) + .bind(parent) + .fetch_all(pool) + .await + .expect("list foreign keys"); + assert!( + !constraints.is_empty(), + "no foreign key from {child} to {parent} to drop" + ); + for name in constraints { + sqlx::query(sqlx::AssertSqlSafe(format!( + "ALTER TABLE {child} DROP CONSTRAINT \"{name}\"" + ))) + .execute(pool) + .await + .expect("drop foreign key"); + } + let remaining: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pg_constraint \ + WHERE contype = 'f' AND conrelid = $1::text::regclass AND confrelid = $2::text::regclass", + ) + .bind(child) + .bind(parent) + .fetch_one(pool) + .await + .expect("recount foreign keys"); + assert_eq!( + remaining, 0, + "foreign keys from {child} to {parent} dropped" + ); + } +} + /// A single-connection pool whose session carries `application_name`, so /// [`wait_for_lock_wait`] can tell when its statement is blocked. pub(crate) async fn named_pool(application_name: &str) -> sqlx::PgPool {