From 59097c94ca0fcb615988facc6877cdc467449c7d Mon Sep 17 00:00:00 2001 From: Ravneet Arora Date: Wed, 28 Oct 2026 17:06:26 -0400 Subject: [PATCH] BUZZ-413: Fence new message writes Signed-off-by: Ravneet Arora Signed-off-by: presentyourlove --- crates/buzz-db/src/error.rs | 4 + crates/buzz-db/src/runtime/admitted_tx.rs | 19 + crates/buzz-db/src/store/event.rs | 2 + crates/buzz-db/src/store/mod.rs | 4 + crates/buzz-db/src/store/user.rs | 2 + .../buzz-db/src/store/user_deletion_fences.rs | 18 +- .../src/store/user_deletion_write_guard.rs | 108 +++++ ...ser_deletion_write_guard_postgres_tests.rs | 434 ++++++++++++++++++ crates/buzz-relay/src/handlers/ingest.rs | 6 + crates/buzz-relay/src/handlers/mod.rs | 2 + .../user_deletion_message_postgres_tests.rs | 235 ++++++++++ docs/user-deletion-message-fencing.md | 44 ++ 12 files changed, 870 insertions(+), 8 deletions(-) create mode 100644 crates/buzz-db/src/store/user_deletion_write_guard.rs create mode 100644 crates/buzz-db/src/store/user_deletion_write_guard_postgres_tests.rs create mode 100644 crates/buzz-relay/src/handlers/user_deletion_message_postgres_tests.rs create mode 100644 docs/user-deletion-message-fencing.md diff --git a/crates/buzz-db/src/error.rs b/crates/buzz-db/src/error.rs index 10c8487bb87..913f78facb0 100644 --- a/crates/buzz-db/src/error.rs +++ b/crates/buzz-db/src/error.rs @@ -45,6 +45,10 @@ pub enum DbError { #[error("invitation owner does not match the recorded owner")] InviteOwnerMismatch, + /// A permanent user-deletion restriction refuses this serving write. + #[error("identity is restricted for user deletion")] + UserDeletionRestricted, + /// JSON serialization or deserialization failed. #[error("serialization error: {0}")] Serde(#[from] serde_json::Error), diff --git a/crates/buzz-db/src/runtime/admitted_tx.rs b/crates/buzz-db/src/runtime/admitted_tx.rs index 2e4ce60a758..b3598f6184b 100644 --- a/crates/buzz-db/src/runtime/admitted_tx.rs +++ b/crates/buzz-db/src/runtime/admitted_tx.rs @@ -145,6 +145,25 @@ impl AdmittedTx { &mut self.tx } + pub(crate) async fn guard_message_author(&mut self, event: &nostr::Event) -> Result<()> { + crate::store::user_deletion_write_guard::guard_message(&mut self.tx, self.community, event) + .await + } + + pub(crate) async fn guard_agent_owner_assignment( + &mut self, + agent: &[u8], + owner: &[u8], + ) -> Result<()> { + crate::store::user_deletion_write_guard::guard_owner_assignment( + &mut self.tx, + self.community, + agent, + owner, + ) + .await + } + /// Record that an event committed with this transaction belongs to /// `channel_id`, so [`AdmittedTx::commit`] refreshes the channel's TTL. pub(crate) fn record_channel_event(&mut self, channel_id: Option, kind: i32) { diff --git a/crates/buzz-db/src/store/event.rs b/crates/buzz-db/src/store/event.rs index c279e4831d0..4e30b11dbee 100644 --- a/crates/buzz-db/src/store/event.rs +++ b/crates/buzz-db/src/store/event.rs @@ -477,6 +477,7 @@ async fn insert_event_on( return Err(DbError::EphemeralEventRejected(kind_u16)); } + tx.guard_message_author(event).await?; let id_bytes = event.id.as_bytes(); let pubkey_bytes = event.pubkey.to_bytes(); let sig_bytes = event.sig.serialize(); @@ -1865,6 +1866,7 @@ pub(crate) async fn insert_event_with_thread_metadata_tx( return Err(DbError::EphemeralEventRejected(kind_u16)); } + tx.guard_message_author(event).await?; let id_bytes = event.id.as_bytes(); let pubkey_bytes = event.pubkey.to_bytes(); let sig_bytes = event.sig.serialize(); diff --git a/crates/buzz-db/src/store/mod.rs b/crates/buzz-db/src/store/mod.rs index d36fa4d0894..39e3ddfd82c 100644 --- a/crates/buzz-db/src/store/mod.rs +++ b/crates/buzz-db/src/store/mod.rs @@ -30,6 +30,10 @@ pub mod nip_fi_binding; pub mod user_deletion; /// Operator-global user restrictions and identity-lock primitives. pub mod user_deletion_fences; +pub(crate) mod user_deletion_write_guard; + +#[cfg(test)] +mod user_deletion_write_guard_postgres_tests; #[cfg(test)] mod event_follow_up_postgres_tests; diff --git a/crates/buzz-db/src/store/user.rs b/crates/buzz-db/src/store/user.rs index 19f80799d77..6a648356ce7 100644 --- a/crates/buzz-db/src/store/user.rs +++ b/crates/buzz-db/src/store/user.rs @@ -376,6 +376,8 @@ async fn set_agent_owner_with_operation( 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?; + tx.guard_agent_owner_assignment(agent_pubkey, owner_pubkey) + .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( diff --git a/crates/buzz-db/src/store/user_deletion_fences.rs b/crates/buzz-db/src/store/user_deletion_fences.rs index 2d437fff094..3be9955f759 100644 --- a/crates/buzz-db/src/store/user_deletion_fences.rs +++ b/crates/buzz-db/src/store/user_deletion_fences.rs @@ -1,5 +1,6 @@ -//! Operator-global restriction storage and identity locks; no serving or worker -//! path calls these helpers yet. Installing fences does not itself enforce them. +//! Operator-global restriction storage and identity locks. New stream/forum +//! messages and agent-owner assignment consult these through the write guard. +//! Other serving paths and the real fencing worker are not integrated yet. //! //! Callers use a writer-pool READ COMMITTED transaction. Acquire existing //! community guards first, then `lock_request` for the worker, then all human @@ -150,19 +151,20 @@ async fn lock( /// For multiple identities, acquire the full shared set first. The caller must /// refuse a restricted operation and retain this transaction through any write. /// An agent lookup is scoped; it does not resolve or check the human owner. -/// The planned agent-write path locks the verified owner and agent together, -/// then reads the agent restriction only. This requires the gate to install the +/// The message-write path locks the verified owner and agent together, then +/// reads the signer's restrictions, not the owner's. This requires the gate to install the /// human and all owned-agent restrictions atomically, and creation/assignment -/// paths to reject restricted owners. These callers are not wired in yet. +/// paths to reject restricted owners. The real gate is not wired in yet. pub async fn find( tx: &mut Transaction<'_, Postgres>, identity: FenceIdentity, ) -> Result> { lock_shared(tx, &[identity]).await?; - read(tx, identity).await + read_locked(tx, identity).await } -async fn read( +/// Read one exact restriction after the caller has locked its identity. +pub(super) async fn read_locked( tx: &mut Transaction<'_, Postgres>, identity: FenceIdentity, ) -> Result> { @@ -226,7 +228,7 @@ pub async fn insert( ) .bind(identity.pubkey.to_hex()).bind(identity.scope_id()).bind(request_id).bind(&owner) .execute(&mut **tx).await?; - let saved = read(tx, identity) + let saved = read_locked(tx, identity) .await? .ok_or_else(|| DbError::DeletionSafety("fence insertion returned no row".into()))?; if saved.request_id != request_id || saved.source_owner_pubkey != owner { diff --git a/crates/buzz-db/src/store/user_deletion_write_guard.rs b/crates/buzz-db/src/store/user_deletion_write_guard.rs new file mode 100644 index 00000000000..b16b415c93b --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion_write_guard.rs @@ -0,0 +1,108 @@ +//! First serving integration: new stream/forum messages and agent ownership. +//! Other writes are not fenced here; real deletion must remain disabled until +//! every serving path and external-work drain has been integrated. + +use buzz_core::{kind, CommunityId}; +use nostr::{Event, PublicKey}; +use sqlx::{Postgres, Transaction}; + +use super::user_deletion_fences::{lock_exclusive, lock_shared, read_locked, FenceIdentity}; +use crate::{DbError, Result}; + +pub(crate) async fn guard_message( + tx: &mut Transaction<'_, Postgres>, + community: CommunityId, + event: &Event, +) -> Result<()> { + if !matches!( + u32::from(event.kind.as_u16()), + kind::KIND_STREAM_MESSAGE + | kind::KIND_STREAM_MESSAGE_V2 + | kind::KIND_FORUM_POST + | kind::KIND_FORUM_COMMENT + ) { + return Ok(()); + } + + let signer = event.pubkey; + let owner = owner(tx, community, signer).await?; + let mut identities = vec![ + FenceIdentity::user(signer), + FenceIdentity::agent(community, signer), + ]; + if let Some(owner) = owner { + identities.push(FenceIdentity::user(owner)); + } + // Global signer lock also coordinates the first assignment of an owner. + // Never derive the owner from a cached session or an event tag. + lock_shared(tx, &identities).await?; + if owner != self::owner(tx, community, signer).await? { + // Restart in a new transaction: adding another owner lock now could + // invert the global-before-scoped ordering. No write has occurred. + return Err(DbError::AccessDenied( + "agent ownership changed; retry the write".into(), + )); + } + check_signer(tx, community, signer).await +} + +pub(crate) async fn guard_owner_assignment( + tx: &mut Transaction<'_, Postgres>, + community: CommunityId, + agent: &[u8], + owner: &[u8], +) -> Result<()> { + let agent = parse_key(agent)?; + let owner = parse_key(owner)?; + lock_shared( + tx, + &[FenceIdentity::user(agent), FenceIdentity::user(owner)], + ) + .await?; + // Ownership must not change while a message holds the scoped shared lock. + lock_exclusive(tx, &[FenceIdentity::agent(community, agent)]).await?; + if read_locked(tx, FenceIdentity::user(owner)).await?.is_some() { + return Err(DbError::UserDeletionRestricted); + } + check_signer(tx, community, agent).await +} + +async fn owner( + tx: &mut Transaction<'_, Postgres>, + community: CommunityId, + signer: PublicKey, +) -> Result> { + let owner: Option>> = sqlx::query_scalar( + "SELECT agent_owner_pubkey FROM users WHERE community_id = $1 AND pubkey = $2", + ) + .bind(community.as_uuid()) + .bind(signer.to_bytes().as_slice()) + .fetch_optional(&mut **tx) + .await?; + owner.flatten().map(|key| parse_key(&key)).transpose() +} + +fn parse_key(key: &[u8]) -> Result { + PublicKey::from_slice(key) + .map_err(|_| DbError::InvalidData("invalid user-deletion identity key".into())) +} + +async fn check_signer( + tx: &mut Transaction<'_, Postgres>, + community: CommunityId, + signer: PublicKey, +) -> Result<()> { + // Read the signer's restrictions, not the owner's. Check both possible + // scopes even if the profile/ownership row is absent: those mutable rows + // must not determine whether a permanent restriction still applies. + if read_locked(tx, FenceIdentity::user(signer)) + .await? + .is_some() + || read_locked(tx, FenceIdentity::agent(community, signer)) + .await? + .is_some() + { + return Err(DbError::UserDeletionRestricted); + } + Ok(()) +} diff --git a/crates/buzz-db/src/store/user_deletion_write_guard_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion_write_guard_postgres_tests.rs new file mode 100644 index 00000000000..10f0459a7f0 --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion_write_guard_postgres_tests.rs @@ -0,0 +1,434 @@ +use super::user_deletion_fences::{self as fences, FenceIdentity}; +use crate::{event, Db, DbError}; +use buzz_core::CommunityId; +use nostr::{Event, EventBuilder, Keys, Kind}; +use sqlx::{PgPool, Postgres, Transaction}; +use std::time::Duration; +use uuid::Uuid; + +struct Fixture { + pool: PgPool, + db: Db, + community: CommunityId, + lease: crate::entity_deletion::EntityLease, +} + +impl Fixture { + async fn new() -> Self { + let pool = PgPool::connect(&crate::test_support::database_url()) + .await + .unwrap(); + let db = Db::from_pool(pool.clone()); + let community = db + .ensure_configured_community(&format!("message-fences-{}.test", Uuid::new_v4())) + .await + .unwrap() + .id; + let request = db + .user_deletion_store() + .submit(&format!("demo:{}", Uuid::new_v4()), "operator", None) + .await + .unwrap(); + let store = db.entity_deletion_store(); + store + .approve( + request.id, + "reviewer", + request.inventory_digest.as_deref().unwrap(), + ) + .await + .unwrap(); + let lease = store + .claim(request.id, "worker", Duration::from_secs(300)) + .await + .unwrap() + .unwrap(); + Self { + pool, + db, + community, + lease, + } + } + + async fn fence(&self, keys: &Keys, owner: Option<&Keys>) { + let mut tx = self.pool.begin().await.unwrap(); + self.fence_in(&mut tx, keys, owner).await; + tx.commit().await.unwrap(); + } + + async fn fence_in( + &self, + tx: &mut Transaction<'_, Postgres>, + keys: &Keys, + owner: Option<&Keys>, + ) { + let identity = if owner.is_some() { + FenceIdentity::agent(self.community, keys.public_key()) + } else { + FenceIdentity::user(keys.public_key()) + }; + fences::insert(tx, identity, &self.lease, owner.map(Keys::public_key)) + .await + .unwrap(); + } + + async fn agent(&self, owner: &Keys) -> Keys { + self.db + .ensure_user(self.community, owner.public_key().as_bytes()) + .await + .unwrap(); + let agent = Keys::generate(); + self.db + .ensure_user(self.community, agent.public_key().as_bytes()) + .await + .unwrap(); + self.db + .set_agent_owner( + self.community, + agent.public_key().as_bytes(), + owner.public_key().as_bytes(), + ) + .await + .unwrap(); + agent + } +} + +fn message(keys: &Keys, kind: u16) -> Event { + EventBuilder::new(Kind::Custom(kind), Uuid::new_v4().to_string()) + .sign_with_keys(keys) + .unwrap() +} + +fn restricted(result: crate::Result<(buzz_core::StoredEvent, bool)>) { + assert!( + matches!(result, Err(DbError::UserDeletionRestricted)), + "{result:?}" + ); +} + +async fn wait_for_waiter(pool: &PgPool, pid: i32) { + tokio::time::timeout(Duration::from_secs(4), async { + loop { + let waiting: bool = sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM pg_locks WHERE pid = $1 AND locktype = 'advisory' AND NOT granted)").bind(pid).fetch_one(pool).await.unwrap(); + if waiting { break; } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }).await.expect("production writer must wait for the identity lock"); +} + +async fn writer( + f: &Fixture, + event: Event, +) -> ( + i32, + tokio::task::JoinHandle>, +) { + let mut tx = crate::begin_community_event_write_transaction( + &f.pool, + f.community, + crate::observability::WriterOperation::EventWrite, + ) + .await + .unwrap(); + let pid = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(tx.conn()) + .await + .unwrap(); + let task = tokio::spawn(async move { + let result = event::insert_event_in_transaction(&mut tx, &event, None).await; + if result.is_ok() { + tx.commit().await.unwrap(); + } else { + tx.rollback().await.unwrap(); + } + result + }); + (pid, task) +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn message_writers_enforce_global_and_scoped_fences_even_without_profiles() { + let f = Fixture::new().await; + let user = Keys::generate(); + let agent = f.agent(&user).await; + let other = Keys::generate(); + let other_community = + f.db.ensure_configured_community(&format!("unrestricted-{}.test", Uuid::new_v4())) + .await + .unwrap() + .id; + for keys in [&user, &agent, &other] { + f.db.insert_event_with_thread_metadata(f.community, &message(keys, 9), None, None) + .await + .unwrap(); + } + f.fence(&user, None).await; + f.fence(&agent, Some(&user)).await; + for kind in [9, 40002, 45001, 45003] { + for keys in [&user, &agent] { + restricted( + f.db.insert_event(f.community, &message(keys, kind), None) + .await, + ); + restricted( + f.db.insert_event_with_thread_metadata( + f.community, + &message(keys, kind), + None, + None, + ) + .await, + ); + } + f.db.insert_event(f.community, &message(&other, kind), None) + .await + .unwrap(); + f.db.insert_event(other_community, &message(&agent, kind), None) + .await + .unwrap(); + restricted( + f.db.insert_event(other_community, &message(&user, kind), None) + .await, + ); + } + sqlx::query("DELETE FROM users WHERE community_id = $1 AND pubkey = $2") + .bind(f.community.as_uuid()) + .bind(agent.public_key().to_bytes().as_slice()) + .execute(&f.pool) + .await + .unwrap(); + restricted( + f.db.insert_event(f.community, &message(&agent, 9), None) + .await, + ); + f.db.ensure_user(f.community, agent.public_key().as_bytes()) + .await + .unwrap(); + restricted( + f.db.insert_event_with_thread_metadata(f.community, &message(&agent, 9), None, None) + .await, + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn already_started_message_commits_before_fence_then_new_message_is_rejected() { + let f = Fixture::new().await; + let user = Keys::generate(); + let event = message(&user, 9); + let mut tx = crate::begin_community_event_write_transaction( + &f.pool, + f.community, + crate::observability::WriterOperation::EventWrite, + ) + .await + .unwrap(); + event::insert_event_in_transaction(&mut tx, &event, None) + .await + .unwrap(); + let mut gate = f.pool.begin().await.unwrap(); + let pid = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(&mut *gate) + .await + .unwrap(); + let lease = f.lease.clone(); + let identity = FenceIdentity::user(user.public_key()); + let gating = tokio::spawn(async move { + fences::insert(&mut gate, identity, &lease, None) + .await + .unwrap(); + gate.commit().await.unwrap(); + }); + wait_for_waiter(&f.pool, pid).await; + assert!(f + .db + .get_event_by_id(f.community, event.id.as_bytes()) + .await + .unwrap() + .is_none()); + tx.commit().await.unwrap(); + tokio::time::timeout(Duration::from_secs(5), gating) + .await + .unwrap() + .unwrap(); + assert!(f + .db + .get_event_by_id(f.community, event.id.as_bytes()) + .await + .unwrap() + .is_some()); + restricted( + f.db.insert_event(f.community, &message(&user, 9), None) + .await, + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn message_waits_for_human_or_agent_owner_fence_and_reads_after_commit() { + let f = Fixture::new().await; + for is_agent in [false, true] { + let user = Keys::generate(); + let sender = if is_agent { + f.agent(&user).await + } else { + user.clone() + }; + let event = message(&sender, 9); + let mut gate = f.pool.begin().await.unwrap(); + fences::lock_request(&mut gate, &f.lease).await.unwrap(); + fences::lock_exclusive(&mut gate, &[FenceIdentity::user(user.public_key())]) + .await + .unwrap(); + let (pid, sending) = writer(&f, event.clone()).await; + wait_for_waiter(&f.pool, pid).await; + f.fence_in(&mut gate, &user, None).await; + if is_agent { + f.fence_in(&mut gate, &sender, Some(&user)).await; + } + gate.commit().await.unwrap(); + restricted( + tokio::time::timeout(Duration::from_secs(5), sending) + .await + .unwrap() + .unwrap(), + ); + assert!(f + .db + .get_event_by_id(f.community, event.id.as_bytes()) + .await + .unwrap() + .is_none()); + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn ownership_change_while_waiting_rejects_and_retry_uses_current_owner() { + let f = Fixture::new().await; + let agent = Keys::generate(); + let owner = Keys::generate(); + f.db.ensure_user(f.community, owner.public_key().as_bytes()) + .await + .unwrap(); + f.db.ensure_user(f.community, agent.public_key().as_bytes()) + .await + .unwrap(); + let mut assignment = f.pool.begin().await.unwrap(); + fences::lock_shared( + &mut assignment, + &[ + FenceIdentity::user(agent.public_key()), + FenceIdentity::user(owner.public_key()), + ], + ) + .await + .unwrap(); + fences::lock_exclusive( + &mut assignment, + &[FenceIdentity::agent(f.community, agent.public_key())], + ) + .await + .unwrap(); + let event = message(&agent, 9); + let (pid, sending) = writer(&f, event.clone()).await; + wait_for_waiter(&f.pool, pid).await; + sqlx::query("UPDATE users SET agent_owner_pubkey = $1 WHERE community_id = $2 AND pubkey = $3") + .bind(owner.public_key().to_bytes().as_slice()) + .bind(f.community.as_uuid()) + .bind(agent.public_key().to_bytes().as_slice()) + .execute(&mut *assignment) + .await + .unwrap(); + assignment.commit().await.unwrap(); + assert!( + matches!(sending.await.unwrap(), Err(DbError::AccessDenied(reason)) if reason.contains("ownership changed")) + ); + assert!(f + .db + .get_event_by_id(f.community, event.id.as_bytes()) + .await + .unwrap() + .is_none()); + f.db.insert_event(f.community, &event, None).await.unwrap(); + f.fence(&agent, Some(&owner)).await; + restricted( + f.db.insert_event(f.community, &message(&agent, 9), None) + .await, + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn first_owner_assignment_waits_for_messages_and_rejects_restricted_owners() { + let f = Fixture::new().await; + let agent = Keys::generate(); + let owner = Keys::generate(); + f.db.ensure_user(f.community, owner.public_key().as_bytes()) + .await + .unwrap(); + f.db.ensure_user(f.community, agent.public_key().as_bytes()) + .await + .unwrap(); + let mut tx = crate::begin_community_event_write_transaction( + &f.pool, + f.community, + crate::observability::WriterOperation::EventWrite, + ) + .await + .unwrap(); + event::insert_event_in_transaction(&mut tx, &message(&agent, 9), None) + .await + .unwrap(); + // A dedicated single-connection pool exposes the actual setter's backend. + let assign_pool = sqlx::postgres::PgPoolOptions::new() + .max_connections(1) + .connect(&crate::test_support::database_url()) + .await + .unwrap(); + let pid = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(&assign_pool) + .await + .unwrap(); + let assignment = tokio::spawn({ + let (agent, owner, community) = (agent.public_key(), owner.public_key(), f.community); + async move { + super::user::set_agent_owner( + &assign_pool, + community, + agent.as_bytes(), + owner.as_bytes(), + ) + .await + } + }); + wait_for_waiter(&f.pool, pid).await; + tx.commit().await.unwrap(); + assert!(assignment.await.unwrap().unwrap()); + f.fence(&owner, None).await; + let another = Keys::generate(); + f.db.ensure_user(f.community, another.public_key().as_bytes()) + .await + .unwrap(); + assert!(matches!( + f.db.set_agent_owner( + f.community, + another.public_key().as_bytes(), + owner.public_key().as_bytes() + ) + .await, + Err(DbError::UserDeletionRestricted) + )); + let saved: Option> = sqlx::query_scalar( + "SELECT agent_owner_pubkey FROM users WHERE community_id = $1 AND pubkey = $2", + ) + .bind(f.community.as_uuid()) + .bind(another.public_key().to_bytes().as_slice()) + .fetch_one(&f.pool) + .await + .unwrap(); + assert!(saved.is_none()); +} diff --git a/crates/buzz-relay/src/handlers/ingest.rs b/crates/buzz-relay/src/handlers/ingest.rs index 9c6d6f206e7..cd0295ec60e 100644 --- a/crates/buzz-relay/src/handlers/ingest.rs +++ b/crates/buzz-relay/src/handlers/ingest.rs @@ -3703,6 +3703,12 @@ async fn ingest_event_inner( buzz_db::DbError::AuthEventRejected => { IngestError::Rejected("invalid: AUTH events cannot be stored".into()) } + buzz_db::DbError::UserDeletionRestricted => IngestError::Rejected( + "restricted: identity is restricted for user deletion".into(), + ), + buzz_db::DbError::AccessDenied(reason) => { + IngestError::Rejected(format!("restricted: {reason}")) + } other => IngestError::Internal(format!("error: database error: {other}")), }); } diff --git a/crates/buzz-relay/src/handlers/mod.rs b/crates/buzz-relay/src/handlers/mod.rs index cd610668906..a887bd60dba 100644 --- a/crates/buzz-relay/src/handlers/mod.rs +++ b/crates/buzz-relay/src/handlers/mod.rs @@ -54,6 +54,8 @@ pub mod side_effects; mod system_channel_postgres_tests; /// Per-filter query scope for system channels. pub(crate) mod system_channels; +#[cfg(test)] +mod user_deletion_message_postgres_tests; /// Extract an optional TTL (in seconds) from a Nostr event's `ttl` tag, /// applying the server-side override when configured. diff --git a/crates/buzz-relay/src/handlers/user_deletion_message_postgres_tests.rs b/crates/buzz-relay/src/handlers/user_deletion_message_postgres_tests.rs new file mode 100644 index 00000000000..e6627646148 --- /dev/null +++ b/crates/buzz-relay/src/handlers/user_deletion_message_postgres_tests.rs @@ -0,0 +1,235 @@ +//! Exercise both transport entry points and the real message transaction. + +use std::{sync::Arc, time::Duration}; + +use buzz_core::TenantContext; +use buzz_db::user_deletion_fences::{self as fences, FenceIdentity}; +use nostr::{Event, EventBuilder, Keys, Kind, Tag}; +use serde_json::Value; +use uuid::Uuid; + +use super::group_state_postgres_tests::{community, create_channel, test_conn}; +use crate::state::AppState; + +struct Fixture { + state: Arc, + pool: sqlx::PgPool, + tenant: TenantContext, + channel: Uuid, + user: Keys, + agent: Keys, + peer: Keys, + url: String, + server: tokio::task::JoinHandle<()>, +} + +impl Fixture { + async fn new() -> Self { + let state = crate::api::bridge::postgres_tests::bridge_handler_test_state() + .await + .expect("Postgres and Redis"); + let pool = sqlx::PgPool::connect(&crate::test_support::database_url()) + .await + .unwrap(); + let tenant = community(&state, "message-deletion").await; + let (user, agent, peer) = (Keys::generate(), Keys::generate(), Keys::generate()); + state + .db + .ensure_user(tenant.community(), user.public_key().as_bytes()) + .await + .unwrap(); + state + .db + .ensure_user(tenant.community(), agent.public_key().as_bytes()) + .await + .unwrap(); + state + .db + .set_agent_owner( + tenant.community(), + agent.public_key().as_bytes(), + user.public_key().as_bytes(), + ) + .await + .unwrap(); + let channel = create_channel( + &state, + &tenant, + &peer, + &[ + &["p", &user.public_key().to_hex()], + &["p", &agent.public_key().to_hex()], + ], + ) + .await; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let router = crate::router::build_router(state.clone()); + let server = tokio::spawn(async move { + axum::serve( + listener, + router.into_make_service_with_connect_info::(), + ) + .await + .unwrap(); + }); + Self { + url, + server, + state, + pool, + tenant, + channel, + user, + agent, + peer, + } + } + + fn message(&self, key: &Keys, kind: u16, root: Option<&Event>) -> Event { + let mut tags = vec![Tag::parse(["h", &self.channel.to_string()]).unwrap()]; + if let Some(root) = root { + tags.push(Tag::parse(["e", &root.id.to_hex(), "", "root"]).unwrap()); + tags.push(Tag::parse(["e", &root.id.to_hex(), "", "reply"]).unwrap()); + } + EventBuilder::new(Kind::Custom(kind), Uuid::new_v4().to_string()) + .tags(tags) + .sign_with_keys(key) + .unwrap() + } + + async fn fence(&self) { + let request = self + .state + .db + .user_deletion_store() + .submit(&format!("demo:{}", Uuid::new_v4()), "operator", None) + .await + .unwrap(); + let store = self.state.db.entity_deletion_store(); + store + .approve( + request.id, + "reviewer", + request.inventory_digest.as_deref().unwrap(), + ) + .await + .unwrap(); + let lease = store + .claim(request.id, "worker", Duration::from_secs(300)) + .await + .unwrap() + .unwrap(); + let mut tx = self.pool.begin().await.unwrap(); + let user = FenceIdentity::user(self.user.public_key()); + let agent = FenceIdentity::agent(self.tenant.community(), self.agent.public_key()); + fences::lock_request(&mut tx, &lease).await.unwrap(); + fences::lock_exclusive(&mut tx, &[user, agent]) + .await + .unwrap(); + fences::insert(&mut tx, user, &lease, None).await.unwrap(); + fences::insert(&mut tx, agent, &lease, Some(self.user.public_key())) + .await + .unwrap(); + tx.commit().await.unwrap(); + } + + async fn send(&self, key: &Keys, event: &Event, websocket: bool) -> (bool, String) { + if websocket { + let (conn, mut rx) = test_conn(&self.tenant, key); + if let crate::connection::AuthState::Authenticated(ctx) = + &mut *conn.auth_state.lock().unwrap() + { + ctx.scopes = vec![buzz_auth::Scope::MessagesWrite]; + // Intentionally no cached owner: the write must use PostgreSQL. + ctx.agent_owner_pubkey = None; + } + super::event::handle_event(event.clone(), conn, self.state.clone()).await; + let axum::extract::ws::Message::Text(text) = rx.try_recv().unwrap() else { + panic!("expected OK"); + }; + let frame: Value = serde_json::from_str(&text).unwrap(); + assert_eq!(frame[0], "OK", "{frame}"); + assert_eq!(frame[1], event.id.to_hex()); + ( + frame[2].as_bool().unwrap(), + frame[3].as_str().unwrap().to_string(), + ) + } else { + let response = reqwest::Client::new() + .post(format!("{}/events", self.url)) + .header("host", self.tenant.host()) + .header("x-pubkey", key.public_key().to_hex()) + .json(event) + .send() + .await + .unwrap(); + let status = response.status(); + let body: Value = response.json().await.unwrap(); + if status.is_success() { + ( + body["accepted"].as_bool().unwrap(), + body["message"].as_str().unwrap_or("").to_owned(), + ) + } else { + assert_eq!(status, axum::http::StatusCode::BAD_REQUEST, "{body}"); + (false, body["error"].as_str().unwrap().to_owned()) + } + } + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + self.server.abort(); + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn http_and_websocket_messages_honor_user_and_agent_fences() { + let f = Fixture::new().await; + let root = f.message(&f.peer, 9, None); + assert!(f.send(&f.peer, &root, false).await.0); + for websocket in [false, true] { + for key in [&f.user, &f.agent, &f.peer] { + assert!( + f.send(key, &f.message(key, 9, Some(&root)), websocket) + .await + .0 + ); + } + } + let counters: (i64, i64) = sqlx::query_as("SELECT reply_count::bigint, descendant_count::bigint FROM thread_metadata WHERE community_id = $1 AND event_id = $2").bind(f.tenant.community().as_uuid()).bind(root.id.as_bytes().as_slice()).fetch_one(&f.pool).await.unwrap(); + assert_eq!(counters, (6, 6), "fixture must create real replies"); + f.fence().await; + for websocket in [false, true] { + for key in [&f.user, &f.agent] { + for kind in [9, 40002, 45001, 45003] { + let event = f.message(key, kind, Some(&root)); + let (accepted, reason) = f.send(key, &event, websocket).await; + assert!(!accepted, "fenced event accepted"); + assert_eq!( + reason, + "restricted: identity is restricted for user deletion" + ); + assert!(f + .state + .db + .get_event_by_id(f.tenant.community(), event.id.as_bytes()) + .await + .unwrap() + .is_none()); + } + } + } + let after: (i64, i64) = sqlx::query_as("SELECT reply_count::bigint, descendant_count::bigint FROM thread_metadata WHERE community_id = $1 AND event_id = $2").bind(f.tenant.community().as_uuid()).bind(root.id.as_bytes().as_slice()).fetch_one(&f.pool).await.unwrap(); + assert_eq!(after, counters, "rejected replies must not update counters"); + for websocket in [false, true] { + assert!( + f.send(&f.peer, &f.message(&f.peer, 9, Some(&root)), websocket) + .await + .0 + ); + } +} diff --git a/docs/user-deletion-message-fencing.md b/docs/user-deletion-message-fencing.md new file mode 100644 index 00000000000..b9c3d2f47e3 --- /dev/null +++ b/docs/user-deletion-message-fencing.md @@ -0,0 +1,44 @@ +# User-deletion fencing: message integration + +This is the first serving integration after fence storage (PR #8632). It does not enable the real user-deletion worker. Do not install production fences until all required serving paths, fencing inventory, and external-work draining are integrated and deployed on every writer. + +## Coverage + +| Operation | This change | +| --- | --- | +| New stream messages and replies, kinds 9 and 40002 | Guarded inside event persistence | +| New forum posts and comments, kinds 45001 and 45003 | Guarded inside event persistence | +| HTTP `/events` and WebSocket `EVENT` for these kinds | Same guard and fixed rejection | +| Agent's first owner assignment through `set_agent_owner` | Coordinates with message locks; refuses restricted owners and identities | +| Other kinds, including edits, reactions, profiles, commands, ephemeral typing, and gift wraps | Follow-up work | +| Uploads, git operations, agent execution, and already-started external work | Follow-up work | + +The guard is called by both event insertion implementations in `buzz-db/src/store/event.rs`. It runs before the event INSERT, thread metadata, counters, mentions, and post-commit publication. It only applies to the four kinds above. Shared locks remain held until the caller's transaction commits or rolls back. There is no restriction cache and no separate transaction holding the message's identity locks. + +## A normal message + +1. The transports authenticate and validate the event through their existing paths. The shared ingest path requires the event signer to equal the authenticated identity for these message kinds. +2. The database writer starts its existing transaction and acquires the shared community deletion lock. +3. Read `users.agent_owner_pubkey` for the signer in this community. Do not trust an owner in a session cache or event tag. +4. Acquire shared identity locks in the existing canonical order: the global signer key, the verified owner's global key when present, and the signer's scoped community key. +5. Read ownership again. If it changed while waiting, reject with a retry message; release the transaction instead of acquiring more locks out of order. +6. Read the signer's global and community-scoped restriction rows. Neither lookup reads the owner's restriction. Refuse with `restricted: identity is restricted for user deletion` if either exists. A missing profile does not remove a restriction. +7. Persist the message and its transactional derived records, then commit and release all locks. Continue the existing post-commit publication. + +A global signer lock and lookup are retained even for agents because role/profile rows are mutable. The scoped signer lookup is retained even without an ownership row because permanent restrictions must survive profile deletion. This is two exact indexed lookups, not a new batch-read API. The guard reuses the internal locked-read helper after acquiring the full lock set once. + +## Ownership assignment + +`set_agent_owner_with_operation` remains the first-owner-wins conditional update. Before that update, its existing transaction acquires shared locks for the prospective owner and global agent key, then the agent's scoped exclusive lock. It checks the prospective owner's global restriction and the agent's own restrictions. The exclusive agent lock prevents assignment from changing ownership while a message uses the old relationship. This covers both existing public setter entry points, including authorization callers; it is not a claim that every agent lifecycle operation is now fenced. + +## Fencing and in-flight work + +The future fencing worker must lock the request, take the user's exclusive identity lock, discover owned agents under that lock, acquire their exclusive scoped locks, and commit all restrictions and the checkpoint together. If a message owns a shared lock first, the worker waits until that message transaction ends. If the worker owns its exclusive lock first, the message waits and then sees the committed restriction. + +This transaction only protects message persistence. It does not drain uploads or promise that all post-commit delivery has finished when a fence commits. Those are separate later stages. + +## Validation + +Database regressions cover both insertion APIs, all four message kinds, human restrictions across communities, agent restrictions within one community, removal/recreation of profiles, both fencing race directions, owner changes while a sender waits, and assignment blocked by an active message or restricted owner. They observe PostgreSQL lock waiters before releasing a lock rather than depending on a sleep to manufacture the race. + +The relay regression starts a local listening relay, sends HTTP requests over TCP, and exercises the WebSocket EVENT handler, checks the fixed rejection, verifies no rejected event exists, and confirms rejected replies leave thread counters unchanged. The peer remains able to send after the requested user and agent are fenced.