diff --git a/crates/buzz-db/src/store/moderation.rs b/crates/buzz-db/src/store/moderation.rs index 00bcb3af87..0452a51a8c 100644 --- a/crates/buzz-db/src/store/moderation.rs +++ b/crates/buzz-db/src/store/moderation.rs @@ -360,6 +360,7 @@ pub async fn ban_member( crate::observability::WriterOperation::Authorization, ) .await?; + crate::relay_invite::lock_admission(tx.conn(), community).await?; sqlx::query( r#" INSERT INTO community_bans ( @@ -380,8 +381,8 @@ pub async fn ban_member( .bind(actor) .execute(tx.conn()) .await?; + crate::relay_invite::revoke_banned_issuer_invites(tx.conn(), community, pubkey).await?; tx.commit().await?; - Ok(()) } @@ -548,6 +549,7 @@ pub async fn timeout_member( crate::observability::WriterOperation::Authorization, ) .await?; + crate::relay_invite::lock_admission(tx.conn(), community).await?; sqlx::query( r#" INSERT INTO community_bans ( @@ -567,8 +569,8 @@ pub async fn timeout_member( .bind(actor) .execute(tx.conn()) .await?; + crate::relay_invite::revoke_banned_issuer_invites(tx.conn(), community, pubkey).await?; tx.commit().await?; - Ok(()) } diff --git a/crates/buzz-db/src/store/relay_admin_actions.rs b/crates/buzz-db/src/store/relay_admin_actions.rs index 305ab18de2..01c2b97236 100644 --- a/crates/buzz-db/src/store/relay_admin_actions.rs +++ b/crates/buzz-db/src/store/relay_admin_actions.rs @@ -473,8 +473,9 @@ pub async fn execute_ban_with_marker( crate::observability::WriterOperation::Authorization, ) .await?; + crate::relay_invite::lock_admission(tx.conn(), community_id).await?; - // Verify lease ownership first — abort without touching domain rows if the + // Verify lease ownership before domain writes — abort if the // lease is already gone. This prevents the commit entirely on a stale worker. let owned: bool = sqlx::query_scalar( r#" @@ -523,6 +524,8 @@ pub async fn execute_ban_with_marker( .execute(tx.conn()) .await?; + crate::relay_invite::revoke_banned_issuer_invites(tx.conn(), community_id, target_pubkey).await?; + let marker = sqlx::query( r#" UPDATE relay_admin_actions @@ -569,6 +572,7 @@ pub async fn execute_timeout_with_marker( crate::observability::WriterOperation::Authorization, ) .await?; + crate::relay_invite::lock_admission(tx.conn(), community_id).await?; let owned: bool = sqlx::query_scalar( r#" @@ -616,6 +620,8 @@ pub async fn execute_timeout_with_marker( .execute(tx.conn()) .await?; + crate::relay_invite::revoke_banned_issuer_invites(tx.conn(), community_id, target_pubkey).await?; + let marker = sqlx::query( r#" UPDATE relay_admin_actions diff --git a/crates/buzz-db/src/store/relay_invite.rs b/crates/buzz-db/src/store/relay_invite.rs index f6df89c81e..27c5cf83c7 100644 --- a/crates/buzz-db/src/store/relay_invite.rs +++ b/crates/buzz-db/src/store/relay_invite.rs @@ -30,7 +30,9 @@ use crate::error::Result; use crate::{CommunityId, Db}; mod claim_owner; +mod revocation; pub use claim_owner::{claim_relay_membership_with_owner, MembershipClaimResult}; +pub(crate) use revocation::{revoke_banned_issuer_invites, revoke_restricted_agent_invites}; /// Outcome of a v2 invite claim. Expected invalid/expired/exhausted states are /// typed variants so the relay layer can map them to distinct HTTP responses @@ -1123,3 +1125,6 @@ mod upgrade_postgres_tests; #[cfg(test)] mod owner_admission_postgres_tests; + +#[cfg(test)] +mod writer_protocol_postgres_tests; diff --git a/crates/buzz-db/src/store/relay_invite/claim_owner.rs b/crates/buzz-db/src/store/relay_invite/claim_owner.rs index 5eeaf5b1d5..e7f96a48f9 100644 --- a/crates/buzz-db/src/store/relay_invite/claim_owner.rs +++ b/crates/buzz-db/src/store/relay_invite/claim_owner.rs @@ -81,7 +81,12 @@ pub(super) async fn persist_claim_owner( .rows_affected(); } let link_created = sqlx::query("UPDATE users SET agent_owner_pubkey=$3 WHERE community_id=$1 AND pubkey=$2 AND agent_owner_pubkey IS NULL") - .bind(community.as_uuid()).bind(claimant_bytes).bind(owner_bytes).execute(&mut **tx).await?.rows_affected() > 0; + .bind(community.as_uuid()).bind(&claimant_bytes).bind(&owner_bytes).execute(&mut **tx).await?.rows_affected() > 0; + // Defensive parity with other owner writers; admission already rejects banned owners. + if link_created { + super::revoke_restricted_agent_invites(tx, community, &claimant_bytes, &owner_bytes) + .await?; + } Ok(OwnerPersistence { link_created, users_created, diff --git a/crates/buzz-db/src/store/relay_invite/revocation.rs b/crates/buzz-db/src/store/relay_invite/revocation.rs new file mode 100644 index 0000000000..adf0846db0 --- /dev/null +++ b/crates/buzz-db/src/store/relay_invite/revocation.rs @@ -0,0 +1,52 @@ +//! Application-owned revocation, under the admission lock and in the writer's commit. +use crate::{error::Result, CommunityId}; +use sqlx::{Postgres, Transaction}; + +/// Durably revoke an active banned principal's invites and its verified agents' invites. +/// The caller holds the admission lock before writing restriction or invite rows. +pub(crate) async fn revoke_banned_issuer_invites( + tx: &mut Transaction<'_, Postgres>, + community: CommunityId, + pubkey: &[u8], +) -> Result<()> { + sqlx::query( + "UPDATE relay_invites SET revoked_at = clock_timestamp() \ + WHERE community_id = $1 AND revoked_at IS NULL \ + AND (created_by = encode($2::bytea, 'hex') OR created_by IN (\ + SELECT encode(pubkey, 'hex') FROM users \ + WHERE community_id = $1 AND agent_owner_pubkey = $2\ + )) AND EXISTS (\ + SELECT 1 FROM community_bans WHERE community_id = $1 AND pubkey = $2 \ + AND banned AND (ban_expires_at IS NULL OR ban_expires_at > clock_timestamp())\ + )", + ) + .bind(community.as_uuid()) + .bind(pubkey) + .execute(&mut **tx) + .await?; + Ok(()) +} + +/// Durably revoke an agent's invites when its newly verified owner is actively banned. +/// Timeouts block admission temporarily but never durably revoke invites. +pub(crate) async fn revoke_restricted_agent_invites( + tx: &mut Transaction<'_, Postgres>, + community: CommunityId, + agent_pubkey: &[u8], + owner_pubkey: &[u8], +) -> Result<()> { + sqlx::query( + "UPDATE relay_invites SET revoked_at = clock_timestamp() \ + WHERE community_id = $1 AND created_by = encode($2::bytea, 'hex') \ + AND revoked_at IS NULL AND EXISTS (\ + SELECT 1 FROM community_bans WHERE community_id = $1 AND pubkey = $3 \ + AND banned AND (ban_expires_at IS NULL OR ban_expires_at > clock_timestamp())\ + )", + ) + .bind(community.as_uuid()) + .bind(agent_pubkey) + .bind(owner_pubkey) + .execute(&mut **tx) + .await?; + Ok(()) +} diff --git a/crates/buzz-db/src/store/relay_invite/revocation_postgres_tests.rs b/crates/buzz-db/src/store/relay_invite/revocation_postgres_tests.rs index a472cab39c..03bfb5311f 100644 --- a/crates/buzz-db/src/store/relay_invite/revocation_postgres_tests.rs +++ b/crates/buzz-db/src/store/relay_invite/revocation_postgres_tests.rs @@ -2,7 +2,7 @@ use super::*; use crate::moderation::{ban_member, unban_member}; use uuid::Uuid; -async fn fixture() -> (PgPool, CommunityId, String, String) { +pub(super) async fn fixture() -> (PgPool, CommunityId, String, String) { let pool = PgPool::connect(&crate::test_support::database_url()) .await .unwrap(); @@ -186,15 +186,10 @@ async fn issuer_agent_revocation_survives_owner_unban() { ); } -async fn queued_claim( - pool: &PgPool, - community: CommunityId, - code: &str, - claimant: String, -) -> tokio::task::JoinHandle> { +pub(super) async fn named_pool() -> (PgPool, String) { let name = format!("invite-race-{}", Uuid::new_v4()); let connection_name = name.clone(); - let claim_pool = sqlx::postgres::PgPoolOptions::new() + let pool = sqlx::postgres::PgPoolOptions::new() .max_connections(1) .after_connect(move |conn, _| { let name = connection_name.clone(); @@ -209,19 +204,49 @@ async fn queued_claim( .connect(&crate::test_support::database_url()) .await .unwrap(); + (pool, name) +} + +pub(super) async fn wait_for_lock( + pool: &PgPool, + name: &str, + kind: &str, + task: &tokio::task::JoinHandle, +) { + tokio::time::timeout(std::time::Duration::from_secs(5), async { + loop { + let waiting: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM pg_locks l JOIN pg_stat_activity a ON a.pid=l.pid \ + WHERE a.application_name=$1 AND l.locktype=$2 AND NOT l.granted)", + ) + .bind(name) + .bind(kind) + .fetch_one(pool) + .await + .unwrap(); + if waiting { + break; + } + assert!(!task.is_finished(), "writer bypassed expected {kind} lock"); + tokio::task::yield_now().await; + } + }) + .await + .expect("writer must observably wait on the expected lock"); +} + +async fn queued_claim( + pool: &PgPool, + community: CommunityId, + code: &str, + claimant: String, +) -> tokio::task::JoinHandle> { + let (claim_pool, name) = named_pool().await; let hash = hash_v2_code(code); let claim = tokio::spawn(async move { claim_relay_invite(&claim_pool, community, &hash, &claimant, None).await }); - tokio::time::timeout(std::time::Duration::from_secs(5),async { - loop { - let waiting: bool=sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM pg_locks l JOIN pg_stat_activity a ON a.pid=l.pid WHERE a.application_name=$1 AND l.locktype='advisory' AND NOT l.granted)") - .bind(&name).fetch_one(pool).await.unwrap(); - if waiting {break;} - assert!(!claim.is_finished(),"claim bypassed the production admission lock"); - tokio::task::yield_now().await; - } - }).await.expect("claim must observably wait on the admission lock"); + wait_for_lock(pool, &name, "advisory", &claim).await; claim } @@ -233,12 +258,40 @@ async fn claimant_ban_and_timeout_commit_before_queued_claim_without_consuming_a let invite = mint_relay_invite(&pool, community, &issuer, 3600, Some(1)) .await .unwrap(); - let mut restriction = pool.begin().await.unwrap(); - sqlx::query("INSERT INTO community_bans(community_id,pubkey,banned,muted_until,actor_pubkey) VALUES($1,$2,$3,CASE WHEN $3 THEN NULL ELSE clock_timestamp()+interval '1 hour' END,$4)") - .bind(community.as_uuid()).bind(vec![2u8;32]).bind(!timeout).bind(vec![3u8;32]) - .execute(&mut *restriction).await.unwrap(); + // Hold the existing restriction row so the production writer stops only + // after acquiring admission. The claim must queue behind that writer. + ban_member(&pool, community, &[2; 32], &[3; 32], None, None) + .await + .unwrap(); + unban_member(&pool, community, &[2; 32], &[3; 32]) + .await + .unwrap(); + let mut row_lock = pool.begin().await.unwrap(); + sqlx::query("SELECT pubkey FROM community_bans WHERE community_id=$1 FOR UPDATE") + .bind(community.as_uuid()) + .fetch_one(&mut *row_lock) + .await + .unwrap(); + let (writer_pool, name) = named_pool().await; + let restriction = tokio::spawn(async move { + if timeout { + crate::moderation::timeout_member( + &writer_pool, + community, + &[2; 32], + &[3; 32], + Utc::now() + chrono::Duration::hours(1), + None, + ) + .await + } else { + ban_member(&writer_pool, community, &[2; 32], &[3; 32], None, None).await + } + }); + wait_for_lock(&pool, &name, "transactionid", &restriction).await; let claim = queued_claim(&pool, community, &invite.code, claimant.clone()).await; - restriction.commit().await.unwrap(); + row_lock.commit().await.unwrap(); + restriction.await.unwrap().unwrap(); assert_eq!(claim.await.unwrap().unwrap(), ClaimOutcome::Restricted); let uses: i32 = sqlx::query_scalar( "SELECT use_count FROM relay_invites WHERE community_id=$1 AND id=$2", @@ -274,16 +327,21 @@ async fn owner_materialization_commits_before_queued_agent_claim() { ban_member(&pool, community, &[4; 32], &[3; 32], None, None) .await .unwrap(); - let mut owner = pool.begin().await.unwrap(); - sqlx::query("UPDATE users SET agent_owner_pubkey=$3 WHERE community_id=$1 AND pubkey=$2") + let mut row_lock = pool.begin().await.unwrap(); + sqlx::query("SELECT pubkey FROM users WHERE community_id=$1 AND pubkey=$2 FOR UPDATE") .bind(community.as_uuid()) .bind(vec![2u8; 32]) - .bind(vec![4u8; 32]) - .execute(&mut *owner) + .fetch_one(&mut *row_lock) .await .unwrap(); + let (writer_pool, name) = named_pool().await; + let owner = tokio::spawn(async move { + crate::user::set_agent_owner(&writer_pool, community, &[2; 32], &[4; 32]).await + }); + wait_for_lock(&pool, &name, "transactionid", &owner).await; let claim = queued_claim(&pool, community, &invite.code, agent).await; - owner.commit().await.unwrap(); + row_lock.commit().await.unwrap(); + assert!(owner.await.unwrap().unwrap()); assert_eq!(claim.await.unwrap().unwrap(), ClaimOutcome::Restricted); } diff --git a/crates/buzz-db/src/store/relay_invite/upgrade_postgres_tests.rs b/crates/buzz-db/src/store/relay_invite/upgrade_postgres_tests.rs index bde32e697a..74ad798865 100644 --- a/crates/buzz-db/src/store/relay_invite/upgrade_postgres_tests.rs +++ b/crates/buzz-db/src/store/relay_invite/upgrade_postgres_tests.rs @@ -76,7 +76,7 @@ async fn assert_repaired_and_fenced(pool: &PgPool, communities: &[Uuid]) { ); let triggers: i64=sqlx::query_scalar("SELECT count(*) FROM pg_trigger WHERE NOT tgisinternal AND tgname IN ('invite_restriction_lock','invite_issuer_revocation','invite_owner_lock','invite_owner_revocation','community_write_fence_relay_invites')") .fetch_one(pool).await.unwrap(); - assert_eq!(triggers, 5); + assert_eq!(triggers, 1, "only the community deletion fence remains"); } #[tokio::test] @@ -99,15 +99,10 @@ async fn migration_schema_desired_upgrade_reconciles_the_same_populated_history( .unwrap(); for sql in [ include_str!("../../../../../schema/functions/invite_admission_lock.sql"), - include_str!("../../../../../schema/functions/lock_invite_restrictions.sql"), - include_str!("../../../../../schema/functions/revoke_banned_issuer_invites.sql"), - include_str!("../../../../../schema/functions/revoke_restricted_agent_invites.sql"), include_str!("../../../../../schema/functions/backfill_invite_revocations.sql"), ] { sqlx::raw_sql(sql).execute(&pool).await.unwrap(); } - sqlx::raw_sql("CREATE TRIGGER invite_restriction_lock BEFORE INSERT OR UPDATE ON community_bans FOR EACH ROW EXECUTE FUNCTION lock_invite_restrictions(); CREATE TRIGGER invite_issuer_revocation AFTER INSERT OR UPDATE ON community_bans FOR EACH ROW EXECUTE FUNCTION revoke_banned_issuer_invites(); CREATE TRIGGER invite_owner_lock BEFORE INSERT OR UPDATE OF agent_owner_pubkey ON users FOR EACH ROW EXECUTE FUNCTION lock_invite_restrictions(); CREATE TRIGGER invite_owner_revocation AFTER INSERT OR UPDATE OF agent_owner_pubkey ON users FOR EACH ROW EXECUTE FUNCTION revoke_restricted_agent_invites();") - .execute(&pool).await.unwrap(); let still_unrepaired: i64 = sqlx::query_scalar("SELECT count(*) FROM relay_invites WHERE revoked_at IS NULL") .fetch_one(&pool) diff --git a/crates/buzz-db/src/store/relay_invite/writer_protocol_postgres_tests.rs b/crates/buzz-db/src/store/relay_invite/writer_protocol_postgres_tests.rs new file mode 100644 index 0000000000..608ac81bb9 --- /dev/null +++ b/crates/buzz-db/src/store/relay_invite/writer_protocol_postgres_tests.rs @@ -0,0 +1,357 @@ +use super::revocation_postgres_tests::{fixture, named_pool, wait_for_lock}; +use super::*; + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn authorization_owner_writer_waits_before_claim_owner_row_and_links_once() { + let (pool, community, _, claimant) = fixture().await; + let owner = hex::encode([4; 32]); + for key in [[2; 32], [4; 32]] { + crate::user::ensure_user(&pool, community, &key) + .await + .unwrap(); + } + let mut claim = pool.begin().await.unwrap(); + lock_admission(&mut claim, community).await.unwrap(); + let (writer_pool, name) = named_pool().await; + let setter = tokio::spawn(async move { + Db::from_pool(writer_pool) + .set_agent_owner_for_authorization(community, &[2; 32], &[4; 32]) + .await + }); + wait_for_lock(&pool, &name, "advisory", &setter).await; + // Exercise the production claim persistence while the setter is queued. + // If the setter locks the user first, this bounded operation cannot finish. + let written = tokio::time::timeout( + std::time::Duration::from_secs(5), + super::claim_owner::persist_claim_owner(&mut claim, community, &claimant, Some(&owner)), + ) + .await + .unwrap() + .unwrap(); + assert!(written.link_created); + claim.commit().await.unwrap(); + assert!( + !tokio::time::timeout(std::time::Duration::from_secs(5), setter) + .await + .unwrap() + .unwrap() + .unwrap() + ); + assert_eq!( + crate::user::get_agent_channel_policy(&pool, community, &[2; 32]) + .await + .unwrap() + .unwrap() + .1, + Some(vec![4; 32]) + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn ensure_user_insert_and_conflict_do_not_take_admission_lock() { + let (pool, community, _, _) = fixture().await; + let mut claim = pool.begin().await.unwrap(); + lock_admission(&mut claim, community).await.unwrap(); + let (writer_pool, name) = named_pool().await; + for expected in [true, false] { + let mut table_lock = pool.begin().await.unwrap(); + sqlx::query("LOCK TABLE users IN ACCESS EXCLUSIVE MODE") + .execute(&mut *table_lock) + .await + .unwrap(); + let insert_pool = writer_pool.clone(); + let insert = tokio::spawn(async move { + crate::user::ensure_user(&insert_pool, community, &[5; 32]).await + }); + // Inspect the writer while its INSERT is in flight, not after its + // autocommit releases locks. It must reach the table behind admission. + wait_for_lock(&pool, &name, "relation", &insert).await; + let locks: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pg_locks l JOIN pg_stat_activity a ON a.pid=l.pid \ + WHERE a.application_name=$1 AND l.locktype='advisory'", + ) + .bind(&name) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!( + locks, 0, + "user insert must not hold or wait on advisory locks" + ); + table_lock.commit().await.unwrap(); + assert_eq!( + tokio::time::timeout(std::time::Duration::from_secs(5), insert) + .await + .unwrap() + .unwrap() + .unwrap(), + expected + ); + } + claim.rollback().await.unwrap(); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn linking_banned_owner_revokes_agent_invites_but_timeout_does_not() { + for banned in [true, false] { + let (pool, community, issuer, claimant) = fixture().await; + for key in [[1; 32], [4; 32]] { + crate::user::ensure_user(&pool, community, &key) + .await + .unwrap(); + } + let invite = mint_relay_invite(&pool, community, &issuer, 3600, Some(1)) + .await + .unwrap(); + if banned { + crate::moderation::ban_member(&pool, community, &[4; 32], &[3; 32], None, None) + .await + .unwrap(); + } else { + crate::moderation::timeout_member( + &pool, + community, + &[4; 32], + &[3; 32], + Utc::now() + chrono::Duration::hours(1), + None, + ) + .await + .unwrap(); + } + assert!( + crate::user::set_agent_owner(&pool, community, &[1; 32], &[4; 32]) + .await + .unwrap() + ); + let revoked: bool = + sqlx::query_scalar("SELECT revoked_at IS NOT NULL FROM relay_invites WHERE id=$1") + .bind(invite.invite_id) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(revoked, banned); + if banned { + crate::moderation::unban_member(&pool, community, &[4; 32], &[3; 32]) + .await + .unwrap(); + assert_eq!( + claim_relay_invite( + &pool, + community, + &hash_v2_code(&invite.code), + &claimant, + None + ) + .await + .unwrap(), + ClaimOutcome::Revoked + ); + } else { + assert_eq!( + claim_relay_invite( + &pool, + community, + &hash_v2_code(&invite.code), + &claimant, + None + ) + .await + .unwrap(), + ClaimOutcome::IssuerRestricted + ); + crate::moderation::untimeout_member(&pool, community, &[4; 32], &[3; 32]) + .await + .unwrap(); + assert!(matches!( + claim_relay_invite( + &pool, + community, + &hash_v2_code(&invite.code), + &claimant, + None + ) + .await + .unwrap(), + ClaimOutcome::Joined { .. } + )); + } + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn marker_writers_serialize_before_rows_and_commit_revocation_with_marker() { + for timeout in [false, true] { + let (pool, community, issuer, _) = fixture().await; + let invite = mint_relay_invite(&pool, community, &issuer, 3600, None) + .await + .unwrap(); + for key in [[1; 32], [4; 32]] { + crate::user::ensure_user(&pool, community, &key) + .await + .unwrap(); + } + crate::user::set_agent_owner(&pool, community, &[4; 32], &[1; 32]) + .await + .unwrap(); + let agent_invite = mint_relay_invite(&pool, community, &hex::encode([4; 32]), 3600, None) + .await + .unwrap(); + if timeout { + // A timeout must also repair revocation for an existing active ban, + // rather than revoking invites for timeout-only principals. + crate::moderation::ban_member(&pool, community, &[1; 32], &[3; 32], None, None) + .await + .unwrap(); + sqlx::query("UPDATE relay_invites SET revoked_at=NULL WHERE id IN ($1,$2)") + .bind(invite.invite_id) + .bind(agent_invite.invite_id) + .execute(&pool) + .await + .unwrap(); + } + let action = uuid::Uuid::new_v4(); + let lease = uuid::Uuid::new_v4(); + sqlx::query("INSERT INTO relay_admin_actions \ + (id, report_community_id, request_id, actor_pubkey, actor_role, action, state, \ + enforcement_target_pubkey, timeout_secs, timeout_until, action_lease_token, action_lease_expires_at) \ + VALUES ($1,$2,$1,$3,'operator',$4,'enforcing',$5, \ + CASE WHEN $6 THEN 3600 END, CASE WHEN $6 THEN clock_timestamp()+interval '1 hour' END, \ + $7,clock_timestamp()+interval '1 hour')") + .bind(action).bind(community.as_uuid()).bind(vec![3u8;32]) + .bind(if timeout {"timeout"} else {"ban"}).bind(vec![1u8;32]).bind(timeout).bind(lease) + .execute(&pool).await.unwrap(); + let mut admission = pool.begin().await.unwrap(); + lock_admission(&mut admission, community).await.unwrap(); + let (writer_pool, name) = named_pool().await; + let writer = tokio::spawn(async move { + if timeout { + crate::relay_admin_actions::execute_timeout_with_marker( + &writer_pool, + action, + lease, + community, + &[1; 32], + &[3; 32], + Utc::now() + chrono::Duration::hours(1), + None, + ) + .await + } else { + crate::relay_admin_actions::execute_ban_with_marker( + &writer_pool, + action, + lease, + community, + &[1; 32], + &[3; 32], + None, + ) + .await + } + }); + wait_for_lock(&pool, &name, "advisory", &writer).await; + // The action row must still be free while admission is held. This also + // prevents future inversion with action-row locking. + sqlx::query("SELECT id FROM relay_admin_actions WHERE id=$1 FOR UPDATE NOWAIT") + .bind(action) + .fetch_one(&mut *admission) + .await + .unwrap(); + admission.commit().await.unwrap(); + assert!(writer.await.unwrap().unwrap()); + let state: (bool, Option) = sqlx::query_as( + "SELECT i.revoked_at IS NOT NULL, a.step_marker FROM relay_invites i \ + JOIN relay_admin_actions a ON a.id=$2 WHERE i.id=$1", + ) + .bind(invite.invite_id) + .bind(action) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(state, (true, Some("mutation_committed".into()))); + let agent_revoked: bool = + sqlx::query_scalar("SELECT revoked_at IS NOT NULL FROM relay_invites WHERE id=$1") + .bind(agent_invite.invite_id) + .fetch_one(&pool) + .await + .unwrap(); + assert!(agent_revoked, "marker ban also revokes owned-agent invites"); + // Already marked: revocation and domain mutations must roll back too. + sqlx::query("UPDATE relay_invites SET revoked_at=NULL WHERE id IN ($1,$2)") + .bind(invite.invite_id) + .bind(agent_invite.invite_id) + .execute(&pool) + .await + .unwrap(); + let repeated = if timeout { + crate::relay_admin_actions::execute_timeout_with_marker( + &pool, + action, + lease, + community, + &[1; 32], + &[3; 32], + Utc::now() + chrono::Duration::hours(1), + None, + ) + .await + } else { + crate::relay_admin_actions::execute_ban_with_marker( + &pool, action, lease, community, &[1; 32], &[3; 32], None, + ) + .await + } + .unwrap(); + assert!(!repeated); + let revoked: bool = + sqlx::query_scalar("SELECT revoked_at IS NOT NULL FROM relay_invites WHERE id=$1") + .bind(invite.invite_id) + .fetch_one(&pool) + .await + .unwrap(); + assert!(!revoked, "failed marker must not commit revocation"); + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn linked_authorization_owner_and_missing_agent_do_not_wait_on_admission() { + let (pool, community, _, _) = fixture().await; + for key in [[2; 32], [4; 32]] { + crate::user::ensure_user(&pool, community, &key) + .await + .unwrap(); + } + assert!( + crate::user::set_agent_owner(&pool, community, &[2; 32], &[4; 32]) + .await + .unwrap() + ); + let mut claim = pool.begin().await.unwrap(); + lock_admission(&mut claim, community).await.unwrap(); + let db = Db::from_pool(pool.clone()); + for owner in [[4; 32], [6; 32]] { + assert!(!tokio::time::timeout( + std::time::Duration::from_secs(5), + db.set_agent_owner_for_authorization(community, &[2; 32], &owner) + ) + .await + .unwrap() + .unwrap()); + } + assert!(matches!( + tokio::time::timeout( + std::time::Duration::from_secs(5), + db.set_agent_owner_for_authorization(community, &[7; 32], &[4; 32]) + ) + .await + .unwrap(), + Err(crate::DbError::NotFound(_)) + )); + claim.rollback().await.unwrap(); +} diff --git a/crates/buzz-db/src/store/user.rs b/crates/buzz-db/src/store/user.rs index d767b56c75..f019759665 100644 --- a/crates/buzz-db/src/store/user.rs +++ b/crates/buzz-db/src/store/user.rs @@ -353,7 +353,29 @@ async fn set_agent_owner_with_operation( owner_pubkey: &[u8], operation: crate::observability::WriterOperation, ) -> Result { + let mut connection = crate::observability::acquire_writer(pool, operation).await?; + // Ownership is first-write-wins and is never cleared by supported writers. + // Already-linked agents are the common authorization path: avoid queuing + // those read-only calls behind a community's claim/restriction transaction. + let recorded: Option>> = sqlx::query_scalar( + "SELECT agent_owner_pubkey FROM users WHERE community_id = $1 AND pubkey = $2", + ) + .bind(community_id.as_uuid()) + .bind(agent_pubkey) + .fetch_optional(&mut *connection) + .await?; + match recorded { + None => { + return Err(crate::error::DbError::NotFound( + "agent pubkey not found in users table".into(), + )) + } + Some(Some(_)) => return Ok(false), + Some(None) => {} + } + drop(connection); let mut tx = crate::begin_community_write_transaction(pool, community_id, operation).await?; + crate::relay_invite::lock_admission(tx.conn(), community_id).await?; // Conditional UPDATE: only set owner if currently NULL. This makes // "first mint wins" atomic — no TOCTOU race between concurrent mints. let result = sqlx::query( @@ -382,6 +404,13 @@ async fn set_agent_owner_with_operation( tx.commit().await?; return Ok(false); } + crate::relay_invite::revoke_restricted_agent_invites( + tx.conn(), + community_id, + agent_pubkey, + owner_pubkey, + ) + .await?; tx.commit().await?; Ok(true) } diff --git a/crates/buzz-relay/src/api/bridge.rs b/crates/buzz-relay/src/api/bridge.rs index 9bc2940a81..ab7d7f5df3 100644 --- a/crates/buzz-relay/src/api/bridge.rs +++ b/crates/buzz-relay/src/api/bridge.rs @@ -8699,6 +8699,7 @@ pub(crate) mod postgres_tests { "CREATE SCHEMA {schema}; \ CREATE TABLE {schema}.users (LIKE public.users INCLUDING ALL); \ CREATE TABLE {schema}.community_bans (LIKE public.community_bans INCLUDING ALL); \ + CREATE TABLE {schema}.relay_invites (LIKE public.relay_invites INCLUDING ALL); \ CREATE TABLE {schema}.relay_members (LIKE public.relay_members INCLUDING ALL); \ CREATE TABLE {schema}.join_policy_acceptances \ (LIKE public.join_policy_acceptances INCLUDING ALL); \ @@ -8718,6 +8719,15 @@ pub(crate) mod postgres_tests { ) .await .expect("schema pool"); + for sql in [ + include_str!("../../../../schema/functions/community_deletion_lock_key.sql"), + include_str!("../../../../schema/functions/invite_admission_lock.sql"), + ] { + sqlx::raw_sql(sql) + .execute(&pool) + .await + .expect("writer lock functions"); + } Arc::get_mut(&mut state).expect("unique state").db = buzz_db::Db::from_pool(pool); let tenant = fresh_tenant("late-owner.test"); @@ -8803,12 +8813,6 @@ pub(crate) mod postgres_tests { "{action}: the HTTP request recorded the owner" ); - sqlx::raw_sql(sqlx::AssertSqlSafe(format!( - "ALTER TABLE {schema}.users RENAME TO users_unavailable" - ))) - .execute(&admin) - .await - .expect("break the owner-to-agent lookup"); let owner_hex = owner.public_key().to_hex(); match action { "ban" => state @@ -8841,6 +8845,12 @@ pub(crate) mod postgres_tests { .expect("removal commits"); } } + sqlx::raw_sql(sqlx::AssertSqlSafe(format!( + "ALTER TABLE {schema}.users RENAME TO users_unavailable" + ))) + .execute(&admin) + .await + .expect("break the owner-to-agent lookup"); let revoked = state .revoke_live_access( &tenant, diff --git a/crates/buzz-relay/src/handlers/ingest.rs b/crates/buzz-relay/src/handlers/ingest.rs index de4a19217d..b6483518ca 100644 --- a/crates/buzz-relay/src/handlers/ingest.rs +++ b/crates/buzz-relay/src/handlers/ingest.rs @@ -7325,9 +7325,8 @@ mod postgres_tests { use sqlx::postgres::PgConnectOptions; use tokio_util::sync::CancellationToken; - // A schema with bans but no `users` table: the ban commits, and only - // the owned-agent lookup fails. It carries `communities` and the - // deletion lock key so the ban passes community write admission. + // A supported ban writer commits before the users table is taken away: + // only the subsequent owned-agent lookup fails. let db_url = crate::test_support::database_url(); let admin = sqlx::PgPool::connect(&db_url) .await @@ -7335,6 +7334,8 @@ mod postgres_tests { let schema = format!("revoke_owner_{}", Uuid::new_v4().simple()); sqlx::raw_sql(sqlx::AssertSqlSafe(format!( "CREATE SCHEMA {schema}; \ + CREATE TABLE {schema}.users (LIKE public.users INCLUDING ALL); \ + CREATE TABLE {schema}.relay_invites (LIKE public.relay_invites INCLUDING ALL); \ CREATE TABLE {schema}.community_bans (LIKE public.community_bans INCLUDING ALL); \ CREATE TABLE {schema}.communities (LIKE public.communities INCLUDING ALL); \ CREATE FUNCTION {schema}.community_deletion_lock_key(target UUID) RETURNS BIGINT \ @@ -7350,8 +7351,22 @@ mod postgres_tests { let pool = sqlx::PgPool::connect_with(options) .await .expect("schema pool"); + for sql in [ + include_str!("../../../../schema/functions/community_deletion_lock_key.sql"), + include_str!("../../../../schema/functions/invite_admission_lock.sql"), + ] { + sqlx::raw_sql(sql) + .execute(&pool) + .await + .expect("writer lock functions"); + } let state = build_canvas_ingest_state(&db_url, &pool).await; let community = buzz_core::tenant::CommunityId::from_uuid(Uuid::new_v4()); + sqlx::query("INSERT INTO communities(id, host) VALUES($1,'revoke-owner.test')") + .bind(community.as_uuid()) + .execute(&pool) + .await + .expect("writer community"); let tenant = TenantContext::resolved(community, "revoke-owner.test".to_string()); sqlx::query(sqlx::AssertSqlSafe(format!( "INSERT INTO {schema}.communities (id, host) VALUES ($1, 'revoke-owner.test')" @@ -7416,6 +7431,10 @@ mod postgres_tests { ) .await .expect("ban commits"); + sqlx::raw_sql(sqlx::AssertSqlSafe(format!("DROP TABLE {schema}.users"))) + .execute(&admin) + .await + .expect("break only the post-commit owner lookup"); let revoked = state .revoke_live_access( &tenant, diff --git a/migrations/0061_invite_revocation.sql b/migrations/0061_invite_revocation.sql index 6555200622..41eb0702f8 100644 --- a/migrations/0061_invite_revocation.sql +++ b/migrations/0061_invite_revocation.sql @@ -6,57 +6,11 @@ LANGUAGE sql AS $$ SELECT pg_advisory_xact_lock(hashtextextended('invite-admission:' || community::text, 0)); $$; -CREATE FUNCTION lock_invite_restrictions() RETURNS TRIGGER -LANGUAGE plpgsql AS $$ -BEGIN - PERFORM invite_admission_lock(NEW.community_id); - RETURN NEW; -END -$$; - --- Revocation is durable: neither unban nor expiry restores an issued bearer. -CREATE FUNCTION revoke_banned_issuer_invites() RETURNS TRIGGER -LANGUAGE plpgsql AS $$ -BEGIN - IF NEW.banned AND (NEW.ban_expires_at IS NULL OR NEW.ban_expires_at > clock_timestamp()) THEN - UPDATE relay_invites SET revoked_at = clock_timestamp() - WHERE community_id = NEW.community_id AND revoked_at IS NULL - AND (created_by = encode(NEW.pubkey, 'hex') OR created_by IN ( - SELECT encode(pubkey, 'hex') FROM users - WHERE community_id = NEW.community_id AND agent_owner_pubkey = NEW.pubkey - )); - END IF; - RETURN NEW; -END -$$; - --- Learning a verified owner must not revive invites issued by its restricted agent. -CREATE FUNCTION revoke_restricted_agent_invites() RETURNS TRIGGER -LANGUAGE plpgsql AS $$ -BEGIN - IF NEW.agent_owner_pubkey IS NOT NULL AND EXISTS ( - SELECT 1 FROM community_bans WHERE community_id = NEW.community_id - AND pubkey = NEW.agent_owner_pubkey AND banned - AND (ban_expires_at IS NULL OR ban_expires_at > clock_timestamp()) - ) THEN - UPDATE relay_invites SET revoked_at = clock_timestamp() - WHERE community_id = NEW.community_id AND created_by = encode(NEW.pubkey, 'hex') - AND revoked_at IS NULL; - END IF; - RETURN NEW; -END -$$; - -CREATE TRIGGER invite_restriction_lock BEFORE INSERT OR UPDATE ON community_bans -FOR EACH ROW EXECUTE FUNCTION lock_invite_restrictions(); -CREATE TRIGGER invite_issuer_revocation AFTER INSERT OR UPDATE ON community_bans -FOR EACH ROW EXECUTE FUNCTION revoke_banned_issuer_invites(); - -CREATE TRIGGER invite_owner_lock BEFORE INSERT OR UPDATE OF agent_owner_pubkey ON users -FOR EACH ROW EXECUTE FUNCTION lock_invite_restrictions(); -CREATE TRIGGER invite_owner_revocation AFTER INSERT OR UPDATE OF agent_owner_pubkey ON users -FOR EACH ROW EXECUTE FUNCTION revoke_restricted_agent_invites(); - +-- Live revocation is application-owned: supported restriction and owner writers +-- take invite_admission_lock before row locks and revoke in the same commit. +-- Rollout gate: drain all old writer pods before lifting bans or reopening +-- invitation admission, then rerun backfill_invite_revocations() under the +-- schema-destruction maintenance lock to repair bans committed during rollout. -- Include active bans and recorded prior bans, so lifting a ban before this -- migration cannot restore an invite issued before that ban. Scope every owner -- and audit lookup to the invitation's community. diff --git a/schema/functions/backfill_invite_revocations.sql b/schema/functions/backfill_invite_revocations.sql index abe8118b0b..e434de5990 100644 --- a/schema/functions/backfill_invite_revocations.sql +++ b/schema/functions/backfill_invite_revocations.sql @@ -1,3 +1,8 @@ +-- Live revocation is application-owned: supported restriction and owner writers +-- take invite_admission_lock before row locks and revoke in the same commit. +-- Rollout gate: drain all old writer pods before lifting bans or reopening +-- invitation admission, then rerun backfill_invite_revocations() under the +-- schema-destruction maintenance lock to repair bans committed during rollout. -- Include active bans and recorded prior bans, so lifting a ban before this -- migration cannot restore an invite issued before that ban. Scope every owner -- and audit lookup to the invitation's community. diff --git a/schema/functions/lock_invite_restrictions.sql b/schema/functions/lock_invite_restrictions.sql deleted file mode 100644 index c8aec1f2c6..0000000000 --- a/schema/functions/lock_invite_restrictions.sql +++ /dev/null @@ -1,7 +0,0 @@ -CREATE FUNCTION lock_invite_restrictions() RETURNS TRIGGER -LANGUAGE plpgsql AS $$ -BEGIN - PERFORM invite_admission_lock(NEW.community_id); - RETURN NEW; -END -$$; diff --git a/schema/functions/revoke_banned_issuer_invites.sql b/schema/functions/revoke_banned_issuer_invites.sql deleted file mode 100644 index beb40f1ca4..0000000000 --- a/schema/functions/revoke_banned_issuer_invites.sql +++ /dev/null @@ -1,15 +0,0 @@ --- Revocation is durable: neither unban nor expiry restores an issued bearer. -CREATE FUNCTION revoke_banned_issuer_invites() RETURNS TRIGGER -LANGUAGE plpgsql AS $$ -BEGIN - IF NEW.banned AND (NEW.ban_expires_at IS NULL OR NEW.ban_expires_at > clock_timestamp()) THEN - UPDATE relay_invites SET revoked_at = clock_timestamp() - WHERE community_id = NEW.community_id AND revoked_at IS NULL - AND (created_by = encode(NEW.pubkey, 'hex') OR created_by IN ( - SELECT encode(pubkey, 'hex') FROM users - WHERE community_id = NEW.community_id AND agent_owner_pubkey = NEW.pubkey - )); - END IF; - RETURN NEW; -END -$$; diff --git a/schema/functions/revoke_restricted_agent_invites.sql b/schema/functions/revoke_restricted_agent_invites.sql deleted file mode 100644 index 3a6d2359b7..0000000000 --- a/schema/functions/revoke_restricted_agent_invites.sql +++ /dev/null @@ -1,16 +0,0 @@ --- Learning a verified owner must not revive invites issued by its restricted agent. -CREATE FUNCTION revoke_restricted_agent_invites() RETURNS TRIGGER -LANGUAGE plpgsql AS $$ -BEGIN - IF NEW.agent_owner_pubkey IS NOT NULL AND EXISTS ( - SELECT 1 FROM community_bans WHERE community_id = NEW.community_id - AND pubkey = NEW.agent_owner_pubkey AND banned - AND (ban_expires_at IS NULL OR ban_expires_at > clock_timestamp()) - ) THEN - UPDATE relay_invites SET revoked_at = clock_timestamp() - WHERE community_id = NEW.community_id AND created_by = encode(NEW.pubkey, 'hex') - AND revoked_at IS NULL; - END IF; - RETURN NEW; -END -$$; diff --git a/schema/schema.sql b/schema/schema.sql index d8ed4f9019..93f56d23c4 100644 --- a/schema/schema.sql +++ b/schema/schema.sql @@ -79,9 +79,6 @@ CREATE EXTENSION IF NOT EXISTS pgcrypto; \i functions/profile_name_fields.sql \i functions/invite_admission_lock.sql -\i functions/lock_invite_restrictions.sql -\i functions/revoke_banned_issuer_invites.sql -\i functions/revoke_restricted_agent_invites.sql \i functions/backfill_invite_revocations.sql -- tables diff --git a/schema/triggers/community_bans.sql b/schema/triggers/community_bans.sql index 27c66ee1a2..063e3ab456 100644 --- a/schema/triggers/community_bans.sql +++ b/schema/triggers/community_bans.sql @@ -1,6 +1 @@ SELECT attach_community_write_fence('community_bans'); - -CREATE TRIGGER invite_restriction_lock BEFORE INSERT OR UPDATE ON community_bans -FOR EACH ROW EXECUTE FUNCTION lock_invite_restrictions(); -CREATE TRIGGER invite_issuer_revocation AFTER INSERT OR UPDATE ON community_bans -FOR EACH ROW EXECUTE FUNCTION revoke_banned_issuer_invites(); diff --git a/schema/triggers/users.sql b/schema/triggers/users.sql index 60bd2c5c76..5f65f3c763 100644 --- a/schema/triggers/users.sql +++ b/schema/triggers/users.sql @@ -1,6 +1 @@ SELECT attach_community_write_fence('users'); - -CREATE TRIGGER invite_owner_lock BEFORE INSERT OR UPDATE OF agent_owner_pubkey ON users -FOR EACH ROW EXECUTE FUNCTION lock_invite_restrictions(); -CREATE TRIGGER invite_owner_revocation AFTER INSERT OR UPDATE OF agent_owner_pubkey ON users -FOR EACH ROW EXECUTE FUNCTION revoke_restricted_agent_invites(); diff --git a/scripts/reconcile-schema-after-pgschema.sql b/scripts/reconcile-schema-after-pgschema.sql index c673c1a779..f3f46f37da 100644 --- a/scripts/reconcile-schema-after-pgschema.sql +++ b/scripts/reconcile-schema-after-pgschema.sql @@ -243,8 +243,8 @@ BEGIN END IF; IF (SELECT count(*) FROM pg_trigger WHERE NOT tgisinternal AND tgname IN ('invite_restriction_lock', 'invite_issuer_revocation', - 'invite_owner_lock', 'invite_owner_revocation')) <> 4 THEN - RAISE EXCEPTION 'invitation revocation triggers missing from live catalog'; + 'invite_owner_lock', 'invite_owner_revocation')) <> 0 THEN + RAISE EXCEPTION 'invitation revocation must use supported application writers, not triggers'; END IF; END $$;