diff --git a/NOSTR.md b/NOSTR.md index 0cdfe929ae8..3ee50488bbe 100644 --- a/NOSTR.md +++ b/NOSTR.md @@ -52,7 +52,7 @@ PGPASSWORD=buzz_dev psql -h localhost -U buzz -d buzz -c \ | **User profiles (kind:0)** | ✅ | NIP-01 metadata; synced to users table (display_name, avatar, about, NIP-05). NIP-05 handles must canonicalize to this relay's domain — off-domain or invalid handles are silently cleared. If a NIP-05 handle collides with another user's (UNIQUE constraint), the handle is skipped but other profile fields (display_name, avatar, about) are still synced. | | **Group creation (kind:9007)** | ✅ | NIP-29; include an `h` tag with the new channel id and a `name` tag, optional `visibility`, `channel_type`, label `t` and `unlisted` tags. The relay refuses a 9007 without `h`. It refuses a listed channel (open, not unlisted, stream or forum) whose name another listed channel already has, ignoring case and including archived ones: `invalid: an open channel named "" already exists`. | | **Add user (kind:9000)** | ✅ | Open: any user, subject to target's `channel_add_policy` (`owner_only`/`nobody` can block). Private: owner/admin only. Self-add bypasses agent policy but not private-channel auth. A guest cannot add anyone. A new member with no role tag gets the channel's `join_role`; a non-member adding themselves may ask for `join_role` or a lower role. One event may name up to 100 people: one `p` tag each, with an optional role as the `p` tag's third element (NIP-29), falling back to the event's `role` tag. Each person is checked and added on their own. When the event names several people, the OK message is `members: ` followed by JSON listing the non-empty `added`, `updated` (role changed), `already_member` and `rejected` (`[{"reason", "pubkeys"}]`) results. The event is refused only when it is malformed or nobody it names may be added; then one person keeps the single-add error, and several get `invalid: members: {…}`. The event and its membership changes are stored together, so an `error:` rejection stores nothing and the same event can be resent; a resent stored event returns `duplicate:` without results. Re-adding someone at their current role posts no second `member_joined` notice. | -| **Remove user (kind:9001)** | ✅ | Self-remove allowed (with last-owner guard). Removing others: owner/admin only. | +| **Remove user (kind:9001)** | ✅ | Self-remove allowed (with last-owner guard). Removing others: owner/admin, or an active member removing their own agent. Only a channel owner may remove another channel owner. | | **Edit group metadata (kind:9002)** | ✅ | `name`/`about`/label `t`/`visibility`/`ttl`/`archived`/`join_role`/`unlisted` tags: owner/admin. `topic`/`purpose` tags: any member except a guest. `auto_join` tag: relay owner/admin (see [Default channels](#default-channels)). A relay operator may also send a 9002 that changes only `name` on a listed channel, archived ones included, whatever its channel role, so that duplicate names can be repaired; the channel stays archived. The relay refuses a `name`, `visibility` or `unlisted` change that leaves a listed channel with a name another listed channel already has: `invalid: an open channel named "" already exists`. The relay refuses a private-to-open `visibility` change while the channel has, or once had, a member who is neither the sender nor an agent the sender owns (NIP-OA); removed members count, because their posts stay in its history: `invalid: a private channel with other members cannot be made open; create a new open channel instead`. Buzz applies 9002 as a partial update: an absent tag leaves that setting unchanged. | | **Admin delete event (kind:9005)** | ✅ | Event author can always delete own. Otherwise owner/admin required. Target must be in same channel. | | **Group deletion (kind:9008)** | ✅ | Owner only. | @@ -121,7 +121,7 @@ What each role can do: | Read, leave | Yes | Yes | Yes | | Post, reply, edit, delete own, react, artifacts, canvas, forum, pins, typing, workflow messages, huddles | No | Yes | Yes | | Topic, purpose (kind:9002) | No | Yes | Yes | -| Add people (kind:9000) | No | Yes, as member, guest or bot | Yes, any role | +| Add people (kind:9000) | No | Yes, as member, guest or bot | Yes; only owners can grant owner | | Push to the channel's git repositories | No | Yes | Yes | | Name, about, visibility, TTL, `join_role`, `unlisted` | No | No | Yes | @@ -135,7 +135,11 @@ Other rules: lower role. A higher role is refused. - Any member who can write (member, bot, owner or admin) can make a guest a member with kind:9000 (`role` `member`). This is the same for a person and - an agent. Only owners and admins can make any other role change. + an agent. Owners and admins can make other role changes, except that only + owners may grant ownership or change an owner's role. Admins cannot promote + themselves or anyone else to owner. Only owners may remove other owners; + owning an agent does not override its channel-owner role. The last-owner + guard still applies to owner demotion and departure. - The human owner of an agent can edit (kind:40003) and delete (kind:9005) that agent's messages, also as a guest or a non-member. This is existing behavior. It lets a person correct or remove what their agent posted; it diff --git a/crates/buzz-core/src/channel.rs b/crates/buzz-core/src/channel.rs index 3e3a7b10904..36ee3f43c2e 100644 --- a/crates/buzz-core/src/channel.rs +++ b/crates/buzz-core/src/channel.rs @@ -288,6 +288,8 @@ pub enum MemberPutDenial { NotAMember, /// A non-elevated actor asked for owner or admin. ElevatedRoleGrant, + /// Only an owner may grant ownership or change an owner's role. + OwnershipChange, /// A guest, or a non-member where joining does not give `member`, tried /// to add someone else. Adding people is a write. GuestCannotAdd, @@ -302,7 +304,8 @@ pub enum MemberPutDenial { /// This is the one definition of the admission rules: a guest never adds /// anyone; a non-member adds others only where joining gives `member`; a /// joiner gets `join_role` or a lower role it asks for; only owners and admins -/// grant elevated roles; and an active role changes only as +/// grant admin, only owners grant ownership or change an owner's role; +/// and an active role changes only as /// [`MemberRole::may_change_role`] allows. With no `role` tag, an active member /// keeps their role and a new member gets `join_role`. /// @@ -340,6 +343,15 @@ pub fn decide_member_put(put: MemberPut<'_>) -> Result {requested}" + ); } } } @@ -804,6 +823,60 @@ mod tests { } } + #[test] + fn admins_cannot_acquire_or_change_ownership_through_member_put() { + use MemberRole::*; + // New members, existing members (including self), and unknown stored + // roles must all use the same ownership boundary. Unchanged roles are + // still idempotent, and omitting the role still preserves it. + for target_role in [None, Some("member"), Some("admin"), Some("future_role")] { + for target_is_actor in [false, true] { + let put = MemberPut { + private: true, + join_role: ChannelJoinRole::Member, + actor_role: Some(Admin), + target_is_actor, + target_role, + requested: Some(Owner), + }; + assert_eq!( + decide_member_put(put), + Err(MemberPutDenial::OwnershipChange) + ); + assert_eq!( + decide_member_put(MemberPut { + actor_role: Some(Owner), + ..put + }), + Ok(Owner) + ); + } + } + for requested in [ + Some(Admin), + Some(Member), + Some(Bot), + Some(Guest), + Some(Owner), + None, + ] { + let result = decide_member_put(MemberPut { + private: true, + join_role: ChannelJoinRole::Member, + actor_role: Some(Admin), + target_is_actor: false, + target_role: Some("owner"), + requested, + }); + let expected = if requested.is_none() || requested == Some(Owner) { + Ok(Owner) + } else { + Err(MemberPutDenial::OwnershipChange) + }; + assert_eq!(result, expected, "requested {requested:?}"); + } + } + #[test] fn channel_names_trim_whitespace_and_drop_all_leading_hashes() { assert_eq!(canonical_channel_name("channel"), "channel"); diff --git a/crates/buzz-db/src/store/channel_members.rs b/crates/buzz-db/src/store/channel_members.rs index 0d0286c7841..f543c6ed2ef 100644 --- a/crates/buzz-db/src/store/channel_members.rs +++ b/crates/buzz-db/src/store/channel_members.rs @@ -1097,6 +1097,7 @@ fn member_put_denial_message(denial: buzz_core::channel::MemberPutDenial) -> &'s match denial { D::NotAMember => "private channel requires an invite from an active member", D::ElevatedRoleGrant => "only owners/admins may grant elevated roles", + D::OwnershipChange => "only owners may grant ownership or change an owner's role", D::GuestCannotAdd => "only members can add people in this channel", D::SelfJoinAboveJoinRole => { "joining this channel gives the guest role; ask a member to make you a member" @@ -1108,7 +1109,8 @@ fn member_put_denial_message(denial: buzz_core::channel::MemberPutDenial) -> &'s /// Remove a member from a channel (soft delete). /// /// `actor_pubkey` must be an active owner/admin, the agent's owner, or the member -/// removing themselves. +/// removing themselves. Only a channel owner may remove another channel owner, +/// even when the target is their own agent. /// /// Returns `Err(DbError::MemberNotFound)` if the target is not an active member. /// @@ -1154,6 +1156,29 @@ pub async fn remove_member( // as `add_member`). acquire_channel_membership_lock(tx.conn(), community_id, channel_id).await?; + remove_member_on( + &mut tx, + channel_id, + pubkey, + actor_pubkey, + actor_is_agent_owner, + ) + .await?; + tx.commit().await?; + Ok(()) +} + +/// Apply a removal on an admitted transaction holding the membership lock. +async fn remove_member_on( + tx: &mut AdmittedTx, + channel_id: Uuid, + pubkey: &[u8], + actor_pubkey: &[u8], + actor_is_agent_owner: bool, +) -> Result<()> { + let community_id = tx.community(); + let is_self_remove = pubkey == actor_pubkey; + let target_role = get_active_role_tx(tx.conn(), community_id, channel_id, pubkey).await?; if !is_self_remove { let actor_role_str = get_active_role_tx(tx.conn(), community_id, channel_id, actor_pubkey) .await? @@ -1161,6 +1186,11 @@ pub async fn remove_member( let actor_role: MemberRole = actor_role_str.parse().map_err(|_| { DbError::InvalidData(format!("invalid role in database: {actor_role_str}")) })?; + if target_role.as_deref() == Some("owner") && actor_role != MemberRole::Owner { + return Err(DbError::AccessDenied( + "only owners may remove another owner".to_string(), + )); + } if !actor_role.is_elevated() && !actor_is_agent_owner { return Err(DbError::AccessDenied( "only owners/admins or the agent's owner may remove other members".to_string(), @@ -1171,7 +1201,6 @@ pub async fn remove_member( // Defense-in-depth: prevent removing the last owner regardless of caller. // Callers (REST handlers, NIP-29 handlers) also check this, but the DB // layer enforces it as the final safety net. - let target_role = get_active_role_tx(tx.conn(), community_id, channel_id, pubkey).await?; if target_role.as_deref() == Some("owner") { let row = sqlx::query( "SELECT COUNT(*) as cnt FROM channel_members \ @@ -1207,7 +1236,6 @@ pub async fn remove_member( return Err(DbError::MemberNotFound(channel_id)); } - tx.commit().await?; Ok(()) } @@ -2444,6 +2472,46 @@ impl Db { remove_member(&self.pool, community_id, channel_id, pubkey, actor_pubkey).await } + /// Store a kind:9001 command and its removal together. A locked refusal + /// rolls back the event; a duplicate never removes a rejoined member. + #[datastore_span(name = "remove_member_with_event", system = "postgresql")] + pub async fn remove_member_with_event( + &self, + community_id: CommunityId, + channel_id: Uuid, + pubkey: &[u8], + event: &nostr::Event, + thread_meta: Option>, + ) -> Result<(buzz_core::StoredEvent, bool)> { + let actor = event.pubkey.to_bytes(); + // Immutable ownership lookup, before taking a pooled transaction. + let actor_is_agent_owner = pubkey != actor.as_slice() + && crate::user::is_agent_owner(&self.pool, community_id, pubkey, &actor).await?; + let mut tx = crate::begin_community_event_write_transaction( + &self.pool, + community_id, + crate::observability::WriterOperation::EventWrite, + ) + .await?; + tx.set_push_enqueue(self.push_enqueue.clone()); + acquire_channel_membership_lock(tx.conn(), community_id, channel_id).await?; + let (stored, inserted) = crate::event::insert_event_with_thread_metadata_tx( + &mut tx, + event, + Some(channel_id), + thread_meta, + ) + .await?; + if !inserted { + tx.rollback().await?; + return Ok((stored, false)); + } + crate::insert_mentions_in_transaction(&mut tx, event, Some(channel_id)).await?; + remove_member_on(&mut tx, channel_id, pubkey, &actor, actor_is_agent_owner).await?; + tx.commit().await?; + Ok((stored, true)) + } + /// Returns `true` if the pubkey is an active member. #[datastore_span(name = "is_member", system = "postgresql")] pub async fn is_member( @@ -4888,6 +4956,105 @@ mod postgres_tests { ); } + #[tokio::test] + #[ignore = "requires Postgres"] + async fn admins_cannot_change_ownership_or_remove_owners() { + let pool = setup_pool().await; + let (community, channel_id, owner, co_owner) = + channel_with_two_owners(&pool, "owner-precedence").await; + let admin = random_pubkey(); + let member = random_pubkey(); + let newcomer = random_pubkey(); + for pk in [&admin, &member, &newcomer] { + ensure_user(&pool, community, pk) + .await + .expect("ensure user"); + } + add_member( + &pool, + community, + channel_id, + &admin, + MemberRole::Admin, + Some(&owner), + ) + .await + .expect("owner grants admin"); + add_member( + &pool, + community, + channel_id, + &member, + MemberRole::Member, + Some(&admin), + ) + .await + .expect("admin adds member"); + + // Granting owner to self, another member, or a new member must fail. + // So must demoting/removing a co-owner even while another owner remains. + for (target, requested) in [ + (&admin, MemberRole::Owner), + (&member, MemberRole::Owner), + (&newcomer, MemberRole::Owner), + (&co_owner, MemberRole::Admin), + ] { + let err = add_member( + &pool, + community, + channel_id, + target, + requested, + Some(&admin), + ) + .await + .expect_err("admin must not change ownership"); + assert!(matches!(err, DbError::AccessDenied(_)), "{err:?}"); + } + // Owning the agent is not a way around its channel-owner role. + set_agent_owner(&pool, community, &co_owner, &admin) + .await + .expect("set immutable agent ownership"); + let err = remove_member(&pool, community, channel_id, &co_owner, &admin) + .await + .expect_err("admin must not remove an owner, even its own agent"); + assert!(matches!(err, DbError::AccessDenied(_)), "{err:?}"); + let members = get_members(&pool, community, channel_id) + .await + .expect("members"); + for (pk, role) in [ + (&owner, "owner"), + (&co_owner, "owner"), + (&admin, "admin"), + (&member, "member"), + ] { + assert!(members.iter().any(|m| &m.pubkey == pk && m.role == role)); + } + assert!(!members.iter().any(|m| m.pubkey == newcomer)); + + // Admins keep ordinary role management and removal authority. + add_member( + &pool, + community, + channel_id, + &member, + MemberRole::Admin, + Some(&admin), + ) + .await + .expect("admin promotes another admin"); + remove_member(&pool, community, channel_id, &member, &admin) + .await + .expect("admin removes another admin"); + // Owners can remove co-owners; the last-owner guard still applies. + remove_member(&pool, community, channel_id, &co_owner, &owner) + .await + .expect("owner removes co-owner"); + remove_member(&pool, community, channel_id, &owner, &owner) + .await + .expect_err("last-owner guard remains in force"); + } + /// Sets up an open channel with exactly two owners, returning /// `(community, channel_id, owner_a, owner_b)`. async fn channel_with_two_owners( diff --git a/crates/buzz-relay/src/handlers/channel_authz.rs b/crates/buzz-relay/src/handlers/channel_authz.rs index 1c1c6649924..83f43b0464c 100644 --- a/crates/buzz-relay/src/handlers/channel_authz.rs +++ b/crates/buzz-relay/src/handlers/channel_authz.rs @@ -30,6 +30,9 @@ pub enum ChannelAuthzError { /// Actor tried to grant `owner`/`admin` without holding it. #[error("only owners/admins may grant elevated roles")] ElevatedRoleGrantDenied, + /// Actor tried to grant ownership or change an owner's role without being an owner. + #[error("only owners may grant ownership or change an owner's role")] + OwnershipChangeDenied, /// Actor tried to change an active member's role without being elevated. #[error("only owners/admins may change an active member's role")] RoleChangeDenied, @@ -69,6 +72,7 @@ impl From for ChannelAuthzError { match denial { MemberPutDenial::NotAMember => Self::ActorNotAuthorized, MemberPutDenial::ElevatedRoleGrant => Self::ElevatedRoleGrantDenied, + MemberPutDenial::OwnershipChange => Self::OwnershipChangeDenied, MemberPutDenial::GuestCannotAdd => Self::GuestCannotAdd, MemberPutDenial::SelfJoinAboveJoinRole => Self::SelfJoinAboveJoinRole, MemberPutDenial::RoleChange => Self::RoleChangeDenied, @@ -80,7 +84,7 @@ impl From for ChannelAuthzError { /// /// This is the single definition of last-owner protection. Every call site /// that once restated it — kind:9000 demotion, kind:9001 self-removal, -/// kind:9022 leave, and the `handle_remove_user` / `handle_leave_request` +/// kind:9022 leave, and the `handle_leave_request` /// appliers — asks this one question and supplies its own wording. /// /// `members` must already be filtered to *active* membership; both @@ -203,19 +207,31 @@ pub fn decide_channel_add_policy( /// What authority `actor` holds to remove *somebody else* (kind:9001). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum RemoveOtherDecision { - /// Channel owner or admin — authorized for any target. + /// Channel owner, or an admin removing a non-owner. Allow, /// An active non-elevated member. Authorized only if they own the target /// agent, which the caller must confirm with a database read. CheckAgentOwner, - /// Not an active member. Denied without any further read — you must be in - /// the channel to remove anyone, even your own bot. + /// Not an active member, or a non-owner removing an owner. Denied even + /// when the actor owns the target agent. Deny, } /// Classify `actor`'s authority to remove another member (NIP-29 kind:9001). -pub fn classify_remove_other(members: &[MemberRecord], actor: &[u8]) -> RemoveOtherDecision { +pub fn classify_remove_other( + members: &[MemberRecord], + actor: &[u8], + target: &[u8], +) -> RemoveOtherDecision { match members.iter().find(|m| m.pubkey == actor) { + Some(m) + if m.role != "owner" + && members + .iter() + .any(|m| m.pubkey == target && m.role == "owner") => + { + RemoveOtherDecision::Deny + } Some(m) if m.role == "owner" || m.role == "admin" => RemoveOtherDecision::Allow, Some(_) => RemoveOtherDecision::CheckAgentOwner, None => RemoveOtherDecision::Deny, @@ -254,8 +270,8 @@ mod tests { type SoleOwnerCase<'a> = (Roster<'a>, u8, bool); /// `(roster, actor, expected_error)`. type DepartureCase<'a> = (Roster<'a>, u8, Option); - /// `(roster, actor, expected_decision)`. - type RemoveOtherCase<'a> = (Roster<'a>, u8, RemoveOtherDecision); + /// `(roster, actor, target, expected_decision)`. + type RemoveOtherCase<'a> = (Roster<'a>, u8, u8, RemoveOtherDecision); /// `(policy, owner_tag, actor, expected_error)`. type AddPolicyCase<'a> = (&'a str, Option, u8, Option); @@ -488,16 +504,16 @@ mod tests { Some(Member), Err(E::LastOwnerDemotion), ), - // Another owner demoting the sole owner is impossible (they'd be an - // owner too), but an admin demoting the sole owner is not. + // An admin cannot demote even one of multiple owners; the + // ownership boundary applies before the last-owner guard. ( "open", - &[(1, "owner"), (2, "admin")], + &[(1, "owner"), (2, "admin"), (3, "owner")], 2, Some(Admin), 1, Some(Member), - Err(E::LastOwnerDemotion), + Err(E::OwnershipChangeDenied), ), // With a co-owner present the demotion is allowed. ( @@ -811,25 +827,32 @@ mod tests { use RemoveOtherDecision::{Allow, CheckAgentOwner, Deny}; let cases: &[RemoveOtherCase] = &[ - // Owners and admins may remove anyone. - (&[(1, "owner"), (2, "member")], 1, Allow), - (&[(1, "owner"), (2, "admin")], 2, Allow), + // Owners manage any target; admins manage non-owners. + (&[(1, "owner"), (2, "owner")], 1, 2, Allow), + (&[(1, "owner"), (2, "admin")], 1, 2, Allow), + (&[(1, "admin"), (2, "member")], 1, 2, Allow), + (&[(1, "admin"), (2, "admin")], 1, 2, Allow), + // Owner targets never fall through to the agent-owner exception. + (&[(1, "admin"), (2, "owner"), (3, "owner")], 1, 2, Deny), + (&[(1, "member"), (2, "owner")], 1, 2, Deny), + (&[(1, "guest"), (2, "owner")], 1, 2, Deny), + (&[(1, "bot"), (2, "owner")], 1, 2, Deny), // A plain member, guest, or bot may only remove an agent they own. - (&[(1, "owner"), (2, "member")], 2, CheckAgentOwner), - (&[(1, "owner"), (2, "guest")], 2, CheckAgentOwner), - (&[(1, "owner"), (2, "bot")], 2, CheckAgentOwner), + (&[(1, "member"), (2, "bot")], 1, 2, CheckAgentOwner), + (&[(1, "guest"), (2, "bot")], 1, 2, CheckAgentOwner), + (&[(1, "bot"), (2, "bot")], 1, 2, CheckAgentOwner), // Non-members are denied without an agent-owner read: you must be // in the channel to remove anyone, even your own bot. - (&[(1, "owner")], 9, Deny), - (&[], 9, Deny), + (&[(1, "owner")], 9, 1, Deny), + (&[], 9, 1, Deny), ]; - for (entries, actor, expected) in cases { + for (entries, actor, target, expected) in cases { let members = roster(entries); assert_eq!( - classify_remove_other(&members, &pk(*actor)), + classify_remove_other(&members, &pk(*actor), &pk(*target)), *expected, - "roster {entries:?} actor {actor}" + "roster {entries:?} actor {actor} target {target}" ); } } @@ -851,6 +874,10 @@ mod tests { ChannelAuthzError::RoleChangeDenied, "only owners/admins may change an active member's role", ), + ( + ChannelAuthzError::OwnershipChangeDenied, + "only owners may grant ownership or change an owner's role", + ), ( ChannelAuthzError::LastOwnerDemotion, "cannot demote the last owner — transfer ownership first", diff --git a/crates/buzz-relay/src/handlers/ingest.rs b/crates/buzz-relay/src/handlers/ingest.rs index 46a1c81f282..99ac76628bb 100644 --- a/crates/buzz-relay/src/handlers/ingest.rs +++ b/crates/buzz-relay/src/handlers/ingest.rs @@ -3674,6 +3674,19 @@ async fn ingest_event_inner( })?; message = ok_message; (stored, inserted) + } else if kind_u32 == KIND_NIP29_REMOVE_USER { + let thread_params = thread_meta.as_ref().map(|m| m.as_params()); + crate::handlers::side_effects::persist_remove_user(tenant, &event, state, thread_params) + .await + .map_err(|e| match e.downcast_ref::() { + Some(buzz_db::DbError::AccessDenied(reason)) => { + IngestError::Rejected(format!("invalid: {reason}")) + } + Some(missing @ buzz_db::DbError::MemberNotFound(_)) => { + IngestError::Rejected(format!("invalid: {missing}")) + } + _ => IngestError::Internal(format!("error: membership removal failed: {e}")), + })? } else if kind_u32 == KIND_NIP29_EDIT_METADATA { // One commit stores the event and applies its channel changes. A // failure stores nothing, so the client is told and can resend it. @@ -3783,11 +3796,12 @@ async fn ingest_event_inner( }); } - // Workflow deletion, kind 5 / 9005 deletions of `e` targets, kind:9000 and - // kind:9002 applied their changes in the insert's own transaction above. + // Workflow deletion, kind 5 / 9005 deletions of `e` targets, and kinds + // 9000–9002 applied their changes in the insert's own transaction above. let persisted_atomically = workflow_deletion || atomic_deletion || kind_u32 == KIND_NIP29_PUT_USER + || kind_u32 == KIND_NIP29_REMOVE_USER || kind_u32 == KIND_NIP29_EDIT_METADATA; if !persisted_atomically && crate::handlers::side_effects::is_side_effect_kind(kind_u32) { if let Err(e) = diff --git a/crates/buzz-relay/src/handlers/mod.rs b/crates/buzz-relay/src/handlers/mod.rs index d1384b9ff3c..566a06a2256 100644 --- a/crates/buzz-relay/src/handlers/mod.rs +++ b/crates/buzz-relay/src/handlers/mod.rs @@ -54,6 +54,8 @@ pub mod push_lease; mod put_user_postgres_tests; /// NIP-43 relay membership admin command handler (kinds 9030–9032). pub mod relay_admin; +#[cfg(test)] +mod remove_user_postgres_tests; /// NIP-56 report (kind:1984) validation + moderation queue persistence. pub mod report; /// HTTP report-resolution orchestrations for the deployment admin API (Phase 2). diff --git a/crates/buzz-relay/src/handlers/remove_user_postgres_tests.rs b/crates/buzz-relay/src/handlers/remove_user_postgres_tests.rs new file mode 100644 index 00000000000..d400913d306 --- /dev/null +++ b/crates/buzz-relay/src/handlers/remove_user_postgres_tests.rs @@ -0,0 +1,207 @@ +//! A removal's receipt, membership write and publication must agree. + +use std::sync::atomic::Ordering; +use std::sync::Arc; +use std::time::Duration; + +use buzz_db::channel::MemberRole; +use nostr::{EventBuilder, Keys, Kind, Tag}; + +use super::group_state_postgres_tests::{community, create_channel, http_auth}; +use super::ingest::{ingest_event, IngestError}; +use crate::nip_fi_test_hooks::event_publish_counter; + +/// Hold the membership lock until ingest has passed admission, then promote +/// its target. Refusal must roll back the command and never reach dispatch. +/// The same command can subsequently remove a member, but its replay cannot +/// remove someone who rejoined. Restoring the old post-insert path fails here. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn removal_receipt_tracks_the_locked_membership_write() { + let state = crate::api::bridge::postgres_tests::bridge_handler_test_state() + .await + .expect("local Postgres and Redis"); + let tenant = community(&state, "remove-user-locked-refusal").await; + let (owner, admin, target) = (Keys::generate(), Keys::generate(), Keys::generate()); + let owner_key = owner.public_key().to_bytes(); + let admin_key = admin.public_key().to_bytes(); + let target_key = target.public_key().to_bytes(); + let channel = create_channel( + &state, + &tenant, + &owner, + &[ + &["visibility", "private"], + &["p", &admin.public_key().to_hex()], + &["p", &target.public_key().to_hex()], + ], + ) + .await; + let community = tenant.community(); + state + .db + .add_member( + community, + channel, + &admin_key, + MemberRole::Admin, + Some(&owner_key), + ) + .await + .expect("promote admin"); + let removal = EventBuilder::new(Kind::Custom(9001), "") + .tags([ + Tag::parse(["h", &channel.to_string()]).unwrap(), + Tag::parse(["p", &target.public_key().to_hex()]).unwrap(), + ]) + .sign_with_keys(&admin) + .expect("sign removal"); + let published = event_publish_counter::register(community); + let lock_key = format!("buzz_channel_membership:{}:{channel}", community.as_uuid()); + let pool = state.db.pool(); + let mut holder = pool.begin().await.expect("begin promotion"); + sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))") + .bind(&lock_key) + .execute(&mut *holder) + .await + .expect("hold membership lock"); + let task = tokio::spawn({ + let state = Arc::clone(&state); + let tenant = tenant.clone(); + let event = removal.clone(); + let auth = http_auth(&admin); + async move { ingest_event(&state, &tenant, event, auth).await } + }); + tokio::time::timeout(Duration::from_secs(10), async { + loop { + let waiting: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM pg_locks WHERE locktype = 'advisory' AND NOT granted \ + AND database = (SELECT oid FROM pg_database WHERE datname = current_database()) \ + AND ((classid::bigint << 32) | objid::bigint) = hashtextextended($1, 0))", + ) + .bind(&lock_key) + .fetch_one(pool) + .await + .expect("observe removal waiting after admission"); + if waiting { + break; + } + assert!( + !task.is_finished(), + "removal never waited on the membership lock" + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("removal reaches membership lock"); + sqlx::query("UPDATE channel_members SET role = 'owner' WHERE community_id = $1 AND channel_id = $2 AND pubkey = $3") + .bind(community.as_uuid()) + .bind(channel) + .bind(target_key.as_slice()) + .execute(&mut *holder) + .await + .expect("promote target after admission"); + holder.commit().await.expect("commit promotion"); + let result = tokio::time::timeout(Duration::from_secs(10), task) + .await + .expect("removal returns") + .expect("removal task"); + match result { + Err(IngestError::Rejected(reason)) => { + assert_eq!(reason, "invalid: only owners may remove another owner") + } + Err(error) => panic!("expected locked refusal, got {error:?}"), + Ok(result) => panic!( + "locked refusal reported accepted:{} {}", + result.accepted, result.message + ), + } + assert_eq!( + state + .db + .get_member_role(community, channel, &target_key) + .await + .unwrap() + .as_deref(), + Some("owner") + ); + assert!(state + .db + .get_event_by_id(community, &removal.id.to_bytes()) + .await + .unwrap() + .is_none()); + assert_eq!( + published.load(Ordering::Relaxed), + 0, + "refusal must never reach publication" + ); + + // A refused command was not stored: it can succeed once authorized. + state + .db + .add_member( + community, + channel, + &target_key, + MemberRole::Member, + Some(&owner_key), + ) + .await + .unwrap(); + let accepted = ingest_event(&state, &tenant, removal.clone(), http_auth(&admin)) + .await + .unwrap(); + assert!(accepted.accepted); + assert!(state + .db + .get_member_role(community, channel, &target_key) + .await + .unwrap() + .is_none()); + assert!(state + .db + .get_event_by_id(community, &removal.id.to_bytes()) + .await + .unwrap() + .is_some()); + let after_removal = published.load(Ordering::Relaxed); + assert!( + after_removal > 0, + "a committed removal must reach publication" + ); + + // A recorded command remains complete even after its target rejoins. + state + .db + .add_member( + community, + channel, + &target_key, + MemberRole::Member, + Some(&owner_key), + ) + .await + .unwrap(); + let duplicate = ingest_event(&state, &tenant, removal, http_auth(&admin)) + .await + .unwrap(); + assert!(duplicate.accepted); + assert_eq!(duplicate.message, "duplicate:"); + assert_eq!( + state + .db + .get_member_role(community, channel, &target_key) + .await + .unwrap() + .as_deref(), + Some("member") + ); + assert_eq!( + published.load(Ordering::Relaxed), + after_removal, + "duplicate must not publish again" + ); + event_publish_counter::deregister(community); +} diff --git a/crates/buzz-relay/src/handlers/side_effects.rs b/crates/buzz-relay/src/handlers/side_effects.rs index cc0c10ca3c7..55293b0b8d9 100644 --- a/crates/buzz-relay/src/handlers/side_effects.rs +++ b/crates/buzz-relay/src/handlers/side_effects.rs @@ -54,7 +54,7 @@ pub fn is_side_effect_kind(kind: u32) -> bool { /// 3. `disable_departed_member_workflows` — durably disables any workflows the /// kicked user owned in this channel (SEC-006). /// -/// These are identical to what `handle_remove_user` (kind 9001 path) fires after +/// These are identical to what `persist_remove_user` (kind 9001 path) fires after /// removing a member. Without them a kicked user's live WebSocket session retains /// full channel access: the `channel_members.removed_at` write is invisible to /// the running subscription and the membership cache until natural expiry, which @@ -399,7 +399,7 @@ pub async fn handle_side_effects( // kind:9000 belongs to the atomic put-user path in ingest, which // reports each person's result. 9000 => Err(anyhow::anyhow!("kind:9000 requires persist_put_user")), - 9001 => handle_remove_user(tenant, event, state).await, + 9001 => Err(anyhow::anyhow!("kind:9001 requires persist_remove_user")), // kind:9002 belongs to the atomic persistence path in ingest. 9002 => Err(anyhow::anyhow!("kind:9002 requires atomic persistence")), // kind:9005 belongs to the atomic deletion path in ingest. @@ -698,7 +698,7 @@ pub async fn validate_admin_event( channel_authz::decide_self_departure(&members, &actor_bytes)?; Ok(()) } else { - match channel_authz::classify_remove_other(&members, &actor_bytes) { + match channel_authz::classify_remove_other(&members, &actor_bytes, &target_pubkey) { RemoveOtherDecision::Allow => Ok(()), RemoveOtherDecision::CheckAgentOwner => { if state @@ -2249,31 +2249,32 @@ fn put_refusal_reason(error: buzz_db::DbError) -> String { } } -async fn handle_remove_user( +/// Commit a kind:9001 and its removal before running live effects. A locked +/// refusal stores nothing; a duplicate runs no removal or notifications. +pub(crate) async fn persist_remove_user( tenant: &TenantContext, event: &Event, state: &Arc, -) -> anyhow::Result<()> { + thread_meta: Option>, +) -> anyhow::Result<(buzz_core::StoredEvent, bool)> { let channel_id = extract_h_tag_channel(event).ok_or_else(|| anyhow::anyhow!("missing h tag"))?; let target_pubkey = extract_p_tag(event).ok_or_else(|| anyhow::anyhow!("missing p tag"))?; let actor_bytes = event.pubkey.to_bytes().to_vec(); - // Guard: prevent last-owner orphaning on self-removal (kind 9001). - if target_pubkey == actor_bytes { - let members = state - .db - .get_members_for_event_write(tenant.community(), channel_id) - .await?; - if channel_authz::is_sole_owner(&members, &actor_bytes) { - return Err(ChannelAuthzError::LastOwnerRemovalTransferFirst.into()); - } - } - - state + let (stored, inserted) = state .db - .remove_member(tenant.community(), channel_id, &target_pubkey, &actor_bytes) + .remove_member_with_event( + tenant.community(), + channel_id, + &target_pubkey, + event, + thread_meta, + ) .await?; + if !inserted { + return Ok((stored, false)); + } state.invalidate_membership(tenant, channel_id, &target_pubkey); evict_live_channel_subscriptions(tenant, state, channel_id, &target_pubkey).await; disable_departed_member_workflows(tenant, state, channel_id, &target_pubkey).await; @@ -2285,7 +2286,7 @@ async fn handle_remove_user( } else { "member_removed" }; - emit_system_message( + if let Err(e) = emit_system_message( tenant, state, channel_id, @@ -2296,7 +2297,10 @@ async fn handle_remove_user( }), chrono::Utc::now(), ) - .await?; + .await + { + warn!(channel = %channel_id, error = %e, "removal system message failed"); + } if let Err(e) = emit_group_discovery_events(tenant, state, channel_id).await { warn!(channel = %channel_id, error = %e, "NIP-29 group discovery emission failed"); @@ -2315,7 +2319,7 @@ async fn handle_remove_user( warn!(channel = %channel_id, error = %e, "membership notification emission failed"); } - Ok(()) + Ok((stored, true)) } /// Persist an authorized kind:9002 event and the channel changes it names.