diff --git a/crates/buzz-core/src/kind.rs b/crates/buzz-core/src/kind.rs index 4f77f1dc69f..4870a5ab563 100644 --- a/crates/buzz-core/src/kind.rs +++ b/crates/buzz-core/src/kind.rs @@ -402,6 +402,9 @@ pub const KIND_NIP29_JOIN_REQUEST: u32 = 9021; /// NIP-29: Request to leave a group. pub const KIND_NIP29_LEAVE_REQUEST: u32 = 9022; +/// Buzz: Conditionally change the role of an existing Solo member. +pub const KIND_SOLO_MEMBER_ROLE: u32 = 9050; + // Buzz community moderation commands (mod-signed, processed like 9030-series: // validated + executed directly, never stored as regular events; every // accepted command writes a `moderation_actions` audit row). @@ -740,6 +743,7 @@ pub const ALL_KINDS: &[u32] = &[ KIND_NIP29_CREATE_INVITE, KIND_NIP29_JOIN_REQUEST, KIND_NIP29_LEAVE_REQUEST, + KIND_SOLO_MEMBER_ROLE, KIND_MODERATION_BAN, KIND_MODERATION_UNBAN, KIND_MODERATION_TIMEOUT, diff --git a/crates/buzz-db/src/store/channel.rs b/crates/buzz-db/src/store/channel.rs index e691bb01994..233660c9d61 100644 --- a/crates/buzz-db/src/store/channel.rs +++ b/crates/buzz-db/src/store/channel.rs @@ -857,6 +857,40 @@ pub fn group_members_tags( Ok(tags) } +/// Sign and replace one group-state event while the caller holds its +/// replacement lock. The caller commits or rolls back the replacement. +pub(crate) async fn replace_signed_group_state_under_lock( + tx: &mut crate::AdmittedTx, + channel_id: Uuid, + kind: i32, + tags: Vec, + signer: &nostr::Keys, +) -> Result<(StoredEvent, bool)> { + let relay_pubkey = signer.public_key().to_bytes(); + let latest: Option> = sqlx::query_scalar( + "SELECT created_at FROM events WHERE community_id = $1 AND kind = $2 AND pubkey = $3 \ + AND channel_id = $4 AND deleted_at IS NULL ORDER BY created_at DESC, id ASC LIMIT 1", + ) + .bind(tx.community().as_uuid()) + .bind(kind) + .bind(relay_pubkey.as_slice()) + .bind(channel_id) + .fetch_optional(tx.conn()) + .await?; + let now = nostr::Timestamp::now().as_secs(); + let timestamp = latest + .map(|timestamp| (timestamp.timestamp() as u64).saturating_add(1)) + .unwrap_or(now) + .max(now); + let event = nostr::EventBuilder::new(nostr::Kind::Custom(kind as u16), "") + .tags(tags) + .allow_self_tagging() + .custom_created_at(nostr::Timestamp::from(timestamp)) + .sign_with_keys(signer) + .map_err(|error| DbError::InvalidData(error.to_string()))?; + crate::replaceable::replace_addressable_event_under_lock(tx, &event, Some(channel_id)).await +} + fn group_list_identity_tags( group_id: &str, identity: Option<&ChannelIdentity>, diff --git a/crates/buzz-db/src/store/channel_members.rs b/crates/buzz-db/src/store/channel_members.rs index 82b66a7acae..1764014e4b5 100644 --- a/crates/buzz-db/src/store/channel_members.rs +++ b/crates/buzz-db/src/store/channel_members.rs @@ -10,7 +10,10 @@ use uuid::Uuid; use crate::channel::{row_to_channel_record, ChannelRecord}; use crate::error::{DbError, Result}; use crate::{AdmittedTx, Db, ReadAt}; -use buzz_core::CommunityId; +use buzz_core::{ + kind::{KIND_NIP29_GROUP_ADMINS, KIND_NIP29_GROUP_MEMBERS}, + CommunityId, StoredEvent, +}; use buzz_datastore_tracing::datastore_span; pub use buzz_core::channel::MemberRole; @@ -35,6 +38,16 @@ pub struct MemberRecord { pub removed_at: Option>, } +/// A conditional role change for an existing Solo member. +pub struct SoloMemberRoleChange { + /// The member whose role is being edited. + pub target: nostr::PublicKey, + /// The active role the signer saw when confirming. + pub expected_role: MemberRole, + /// The requested access (admin, participating, or viewing only). + pub role: MemberRole, +} + /// Namespace for the per-channel membership advisory lock. Serializes the /// role-authorization + last-owner-count + write sequences in [`add_member`] /// and [`remove_member`] against each other. @@ -2437,6 +2450,164 @@ impl Db { .await } + /// Store a signed Solo role command, its membership change, and both + /// relay-signed membership lists in one transaction. A duplicate returns + /// the stored command with no new lists. + #[datastore_span(name = "change_solo_member_role_with_event", system = "postgresql")] + pub async fn change_solo_member_role_with_event( + &self, + community: CommunityId, + channel_id: Uuid, + change: SoloMemberRoleChange, + event: &nostr::Event, + relay_signer: &nostr::Keys, + ) -> Result<(StoredEvent, Vec)> { + let actor = event.pubkey.to_bytes(); + let target = change.target.to_bytes(); + let denied = |reason: &str| DbError::AccessDenied(reason.to_owned()); + if actor == target || change.expected_role == MemberRole::Owner { + return Err(denied("cannot change a Solo owner's role")); + } + let read_agent_owner = match (change.expected_role, change.role) { + (MemberRole::Admin | MemberRole::Member | MemberRole::Bot, MemberRole::Guest) => false, + (MemberRole::Admin | MemberRole::Guest, MemberRole::Member) + | (MemberRole::Member | MemberRole::Bot | MemberRole::Guest, MemberRole::Admin) => true, + _ => return Err(denied("unsupported Solo member role transition")), + }; + + let mut tx = crate::begin_community_event_write_transaction( + &self.pool, + community, + crate::observability::WriterOperation::EventWrite, + ) + .await?; + tx.set_push_enqueue(self.push_enqueue.clone()); + // Roster replacement takes its coordinate lock before the membership + // lock. Account cleanup takes both list locks in this same order. + let relay_pubkey = relay_signer.public_key().to_bytes(); + let admins_kind = KIND_NIP29_GROUP_ADMINS as i32; + let members_kind = KIND_NIP29_GROUP_MEMBERS as i32; + for kind in [admins_kind, members_kind] { + crate::replaceable::take_replacement_lock( + &mut tx, + kind, + &relay_pubkey, + Some(channel_id), + ) + .await?; + } + lock_channel_for_member_put(&mut tx, channel_id).await?; + let (stored, inserted) = crate::event::insert_event_with_thread_metadata_tx( + &mut tx, + event, + Some(channel_id), + None, + ) + .await?; + if !inserted { + tx.rollback().await?; + return Ok((stored, Vec::new())); + } + + let channel = get_channel_tx(tx.conn(), community, channel_id).await?; + if channel.channel_type != "stream" + || channel.visibility != "private" + || !channel.labels.iter().any(|label| label == "buzz.solo") + { + return Err(denied("channel is not a Solo chat")); + } + if channel.archived_at.is_some() { + return Err(denied("channel is archived")); + } + let actor_role = get_active_role_tx(tx.conn(), community, channel_id, &actor).await?; + if actor_role.as_deref() != Some(MemberRole::Owner.as_str()) { + return Err(denied("only a Solo chat owner may change member roles")); + } + + // Only the relay's verified ownership record establishes agent identity. + let agent_owner: Option> = if read_agent_owner { + sqlx::query_scalar( + "SELECT agent_owner_pubkey FROM users \ + WHERE community_id = $1 AND pubkey = $2 AND agent_owner_pubkey IS NOT NULL", + ) + .bind(community.as_uuid()) + .bind(target.as_slice()) + .fetch_optional(tx.conn()) + .await? + } else { + None + }; + let role = match change.role { + MemberRole::Admin if agent_owner.as_deref() != Some(actor.as_slice()) => { + return Err(denied( + "only an agent's owner may grant it Admin in a Solo chat", + )) + } + MemberRole::Member if agent_owner.is_some() => MemberRole::Bot, + MemberRole::Member if change.expected_role == MemberRole::Guest => { + return Err(denied( + "only a verified agent may move from Viewing only to Participating", + )) + } + role => role, + }; + + // Update the active row in place. The same channel lock serializes + // removal and role writes, and a mismatch never inserts a membership. + let affected = sqlx::query( + "UPDATE channel_members SET role = $4::member_role \ + WHERE community_id = $1 AND channel_id = $2 AND pubkey = $3 \ + AND removed_at IS NULL AND role = $5::member_role", + ) + .bind(community.as_uuid()) + .bind(channel_id) + .bind(target.as_slice()) + .bind(role.as_str()) + .bind(change.expected_role.as_str()) + .execute(tx.conn()) + .await? + .rows_affected(); + if affected != 1 { + return Err(denied( + "membership or role changed; refresh before trying again", + )); + } + crate::insert_mentions_in_transaction(&mut tx, event, Some(channel_id)).await?; + + let members = select_active_members(tx.conn(), community, channel_id).await?; + let group_id = channel_id.to_string(); + let identity = channel.identity(); + let mut group_state = Vec::with_capacity(2); + for (kind, tags) in [ + ( + admins_kind, + crate::channel::group_admins_tags(&group_id, &identity, &members), + ), + ( + members_kind, + crate::channel::group_members_tags(&group_id, Some(&identity), &members), + ), + ] { + let tags = tags.map_err(|error| DbError::InvalidData(error.to_string()))?; + let (snapshot, inserted) = crate::channel::replace_signed_group_state_under_lock( + &mut tx, + channel_id, + kind, + tags, + relay_signer, + ) + .await?; + if !inserted { + return Err(DbError::InvalidData( + "Solo group state replacement failed".into(), + )); + } + group_state.push(snapshot); + } + tx.commit().await?; + Ok((stored, group_state)) + } + /// Removes a member from a channel. #[datastore_span(name = "remove_member", system = "postgresql")] pub async fn remove_member( diff --git a/crates/buzz-db/src/store/user_deletion/account_batches/memberships.rs b/crates/buzz-db/src/store/user_deletion/account_batches/memberships.rs index 0b620d6a314..70dee50dc78 100644 --- a/crates/buzz-db/src/store/user_deletion/account_batches/memberships.rs +++ b/crates/buzz-db/src/store/user_deletion/account_batches/memberships.rs @@ -1,7 +1,7 @@ //! Membership removal and the three signed discovery lists share one commit. use super::*; use buzz_core::CommunityId; -use nostr::{EventBuilder, Kind, Tag, Timestamp}; +use nostr::Tag; impl UserDeletionStore { pub(super) async fn preflight_memberships( @@ -171,22 +171,10 @@ pub(super) async fn rebuild( ) .map_err(|e| invalid(e.to_string()))? }; - let latest: Option> = sqlx::query_scalar("SELECT max(created_at) FROM events WHERE community_id=$1 AND channel_id=$2 AND kind=$3 AND pubkey=$4 AND deleted_at IS NULL") - .bind(community.as_uuid()).bind(channel_id).bind(kind).bind(signer.public_key().to_bytes().as_slice()).fetch_one(tx.conn()).await?; - let now = Timestamp::now().as_secs(); - let timestamp = latest - .map(|t| (t.timestamp() as u64).saturating_add(1)) - .unwrap_or(now) - .max(now); - let event = EventBuilder::new(Kind::Custom(kind as u16), "") - .tags(tags) - .allow_self_tagging() - .custom_created_at(Timestamp::from(timestamp)) - .sign_with_keys(signer) - .map_err(|e| invalid(e.to_string()))?; - let (_, inserted) = - crate::replaceable::replace_addressable_event_under_lock(tx, &event, Some(channel_id)) - .await?; + let (_, inserted) = crate::channel::replace_signed_group_state_under_lock( + tx, channel_id, kind, tags, signer, + ) + .await?; if !inserted { return Err(invalid( "channel list replacement failed; membership removal rolled back", diff --git a/crates/buzz-relay/src/handlers/event.rs b/crates/buzz-relay/src/handlers/event.rs index 407adbb3313..75f03a48c66 100644 --- a/crates/buzz-relay/src/handlers/event.rs +++ b/crates/buzz-relay/src/handlers/event.rs @@ -8,7 +8,8 @@ use tracing::{debug, error, info, warn}; use buzz_core::event::StoredEvent; use buzz_core::kind::{ event_kind_u32, is_ephemeral, is_unshared_gated_event, KIND_AGENT_OBSERVER_FRAME, - KIND_AGENT_PRESENCE, KIND_GIFT_WRAP, KIND_PRESENCE_UPDATE, KIND_TYPING_INDICATOR, + KIND_AGENT_PRESENCE, KIND_GIFT_WRAP, KIND_PRESENCE_UPDATE, KIND_SOLO_MEMBER_ROLE, + KIND_TYPING_INDICATOR, }; use buzz_core::observer::{ content_looks_like_nip44, OBSERVER_AGENT_TAG, OBSERVER_FRAME_CONTROL, OBSERVER_FRAME_TAG, @@ -35,6 +36,7 @@ pub(crate) fn bounded_kind_label(kind: u32) -> String { match kind { 0..=9 | 1059 | 1063 => kind.to_string(), 8000..=8003 | 9000..=9022 | 9030..=9036 => kind.to_string(), + KIND_SOLO_MEMBER_ROLE => kind.to_string(), 13534..=13535 => kind.to_string(), 20000..=29999 => kind.to_string(), 30023 | 30315 | 39000..=39003 => kind.to_string(), diff --git a/crates/buzz-relay/src/handlers/ingest.rs b/crates/buzz-relay/src/handlers/ingest.rs index cf37111d005..e33d0aafadf 100644 --- a/crates/buzz-relay/src/handlers/ingest.rs +++ b/crates/buzz-relay/src/handlers/ingest.rs @@ -29,12 +29,12 @@ use buzz_core::kind::{ KIND_NIP29_LEAVE_REQUEST, KIND_NIP29_PUT_USER, KIND_NIP29_REMOVE_USER, KIND_NIP43_LEAVE_REQUEST, KIND_NIP65_RELAY_LIST_METADATA, KIND_PERSONA, KIND_PIN_LIST, KIND_PRESENCE_UPDATE, KIND_PRIVATE_MANAGED_AGENT, KIND_PRODUCT_FEEDBACK, KIND_PROFILE, - KIND_PROJECT, KIND_REACTION, KIND_READ_STATE, KIND_REPORT, KIND_STREAM_MESSAGE, - KIND_STREAM_MESSAGE_BOOKMARKED, KIND_STREAM_MESSAGE_DIFF, KIND_STREAM_MESSAGE_EDIT, - KIND_STREAM_MESSAGE_PINNED, KIND_STREAM_MESSAGE_SCHEDULED, KIND_STREAM_MESSAGE_V2, - KIND_STREAM_REMINDER, KIND_TEAM, KIND_TEAM_CATALOG, KIND_TEXT_NOTE, KIND_USER_STATUS, - KIND_WORKFLOW_DEF, KIND_WORKFLOW_TRIGGER, RELAY_ADMIN_ADD_MEMBER, RELAY_ADMIN_CHANGE_ROLE, - RELAY_ADMIN_REMOVE_MEMBER, RELAY_ADMIN_SET_ARTIFACT_TYPE_POLICY, + KIND_PROJECT, KIND_REACTION, KIND_READ_STATE, KIND_REPORT, KIND_SOLO_MEMBER_ROLE, + KIND_STREAM_MESSAGE, KIND_STREAM_MESSAGE_BOOKMARKED, KIND_STREAM_MESSAGE_DIFF, + KIND_STREAM_MESSAGE_EDIT, KIND_STREAM_MESSAGE_PINNED, KIND_STREAM_MESSAGE_SCHEDULED, + KIND_STREAM_MESSAGE_V2, KIND_STREAM_REMINDER, KIND_TEAM, KIND_TEAM_CATALOG, KIND_TEXT_NOTE, + KIND_USER_STATUS, KIND_WORKFLOW_DEF, KIND_WORKFLOW_TRIGGER, RELAY_ADMIN_ADD_MEMBER, + RELAY_ADMIN_CHANGE_ROLE, RELAY_ADMIN_REMOVE_MEMBER, RELAY_ADMIN_SET_ARTIFACT_TYPE_POLICY, RELAY_ADMIN_SET_WORKSPACE_PROFILE, }; use buzz_core::tenant::TenantContext; @@ -709,7 +709,8 @@ fn required_scope_for_kind(kind: u32, event: &Event) -> Result Ok(Scope::MessagesWrite), - KIND_NIP29_PUT_USER | KIND_NIP29_REMOVE_USER | KIND_NIP29_DELETE_GROUP => { + KIND_NIP29_PUT_USER | KIND_NIP29_REMOVE_USER | KIND_NIP29_DELETE_GROUP + | KIND_SOLO_MEMBER_ROLE => { Ok(Scope::AdminChannels) } // NIP-43: relay membership admin commands (9030–9032) + Buzz @@ -968,6 +969,7 @@ pub(crate) fn requires_h_channel_scope(kind: u32) -> bool { | KIND_NIP29_DELETE_EVENT | KIND_NIP29_DELETE_GROUP | KIND_NIP29_LEAVE_REQUEST + | KIND_SOLO_MEMBER_ROLE // Huddle lifecycle events + guidelines | KIND_HUDDLE_STARTED | KIND_HUDDLE_PARTICIPANT_JOINED @@ -985,7 +987,7 @@ pub(crate) enum ChannelWrite { /// post ([`buzz_db::channel::MemberRole::can_post`]), never guests; and /// non-members only in an open channel with `join_role = member`. Post, - /// Membership changes (kind:9000 put-user, 9001 remove-user, 9022 leave). + /// Membership changes (put-user, remove-user, leave, Solo member role). /// Members, or anyone in an open channel. The role table does not apply /// here: a guest must still be able to leave, and `decide_put_user` owns /// who may add whom. @@ -996,9 +998,10 @@ impl ChannelWrite { /// The rule for an event kind that passes the generic channel gate. pub(crate) fn for_kind(kind: u32) -> Self { match kind { - KIND_NIP29_PUT_USER | KIND_NIP29_REMOVE_USER | KIND_NIP29_LEAVE_REQUEST => { - Self::Membership - } + KIND_NIP29_PUT_USER + | KIND_NIP29_REMOVE_USER + | KIND_NIP29_LEAVE_REQUEST + | KIND_SOLO_MEMBER_ROLE => Self::Membership, _ => Self::Post, } } @@ -3213,15 +3216,16 @@ async fn ingest_event_inner( } if channel_id.is_some() { - // kind:9002 is not checked here: its atomic write decides the + // Metadata edits and Solo member role changes decide the // archive state under the channel row lock, after its duplicate // check, so a resend that races the first commit is a duplicate. - let is_edit_metadata = kind_u32 == KIND_NIP29_EDIT_METADATA; + let checks_archive_in_write = + matches!(kind_u32, KIND_NIP29_EDIT_METADATA | KIND_SOLO_MEMBER_ROLE); // A member may still leave an archived channel by themselves. let is_self_departure = crate::handlers::side_effects::is_self_departure(&event); - if !is_edit_metadata && !is_self_departure { + if !checks_archive_in_write && !is_self_departure { if let Some(channel) = &channel_row { if channel.archived_at.is_some() { return Err(match target_denial { @@ -3520,7 +3524,7 @@ async fn ingest_event_inner( validate_event_imeta(tenant, state, &event, &tenant_media_base).await?; - let thread_meta = if requires_h_channel_scope(kind_u32) { + let thread_meta = if kind_u32 != KIND_SOLO_MEMBER_ROLE && requires_h_channel_scope(kind_u32) { if let Some(ch_id) = channel_id { resolve_nip10_thread_meta(tenant.community(), &event, ch_id, state) .await @@ -3770,6 +3774,8 @@ async fn ingest_event_inner( })?; message = ok_message; (stored, inserted) + } else if kind_u32 == KIND_SOLO_MEMBER_ROLE { + super::solo_member_role::persist(tenant, state, &event).await? } 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) @@ -3892,13 +3898,13 @@ async fn ingest_event_inner( }); } - // Workflow deletion, kind 5 / 9005 deletions of `e` targets, and kinds - // 9000–9002 applied their changes in the insert's own transaction above. + // These commands applied their changes in the insert's own transaction. 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; + || kind_u32 == KIND_NIP29_EDIT_METADATA + || kind_u32 == KIND_SOLO_MEMBER_ROLE; if !persisted_atomically && crate::handlers::side_effects::is_side_effect_kind(kind_u32) { if let Err(e) = crate::handlers::side_effects::handle_side_effects(tenant, kind_u32, &event, state) diff --git a/crates/buzz-relay/src/handlers/mod.rs b/crates/buzz-relay/src/handlers/mod.rs index 0abe40a6fd7..c6849df635d 100644 --- a/crates/buzz-relay/src/handlers/mod.rs +++ b/crates/buzz-relay/src/handlers/mod.rs @@ -68,6 +68,9 @@ pub mod report_resolution; pub mod req; /// NIP-29 and NIP-25 side-effect handlers. pub mod side_effects; +mod solo_member_role; +#[cfg(test)] +mod solo_member_role_postgres_tests; #[cfg(test)] mod system_channel_postgres_tests; /// Per-filter query scope for system channels. diff --git a/crates/buzz-relay/src/handlers/solo_member_role.rs b/crates/buzz-relay/src/handlers/solo_member_role.rs new file mode 100644 index 00000000000..a57b418ee51 --- /dev/null +++ b/crates/buzz-relay/src/handlers/solo_member_role.rs @@ -0,0 +1,89 @@ +//! Transport-neutral ingest for the Solo member role command. + +use std::sync::Arc; + +use buzz_core::{kind::event_kind_u32, StoredEvent, TenantContext}; +use buzz_db::{channel::MemberRole, channel_members::SoloMemberRoleChange, DbError}; +use nostr::{Event, PublicKey, Tag}; +use uuid::Uuid; + +use crate::state::AppState; + +use super::{event::dispatch_persistent_event, ingest::IngestError}; + +fn required_tag<'a>(event: &'a Event, name: &str) -> Result<&'a str, IngestError> { + let mut tags = event + .tags + .iter() + .filter(|tag| tag.as_slice().first().is_some_and(|key| key == name)); + if let (Some([_, value]), None) = (tags.next().map(Tag::as_slice), tags.next()) { + return Ok(value); + } + Err(IngestError::Rejected(format!( + "invalid: Solo member role command requires exactly one {name} tag with a value" + ))) +} + +pub(super) async fn persist( + tenant: &TenantContext, + state: &Arc, + event: &Event, +) -> Result<(StoredEvent, bool), IngestError> { + if !event.content.is_empty() { + return Err(IngestError::Rejected( + "invalid: Solo member role command content must be empty".into(), + )); + } + let channel_id = required_tag(event, "h")? + .parse::() + .map_err(|_| IngestError::Rejected("invalid: h tag must be a channel UUID".into()))?; + let target = PublicKey::from_hex(required_tag(event, "p")?) + .map_err(|_| IngestError::Rejected("invalid: p tag must be a hex pubkey".into()))?; + let parse_role = |tag| { + required_tag(event, tag)? + .parse::() + .map_err(|_| IngestError::Rejected(format!("invalid: unknown {tag} value"))) + }; + let change = SoloMemberRoleChange { + target, + expected_role: parse_role("expected_role")?, + role: parse_role("role")?, + }; + let (stored, group_state) = state + .db + .change_solo_member_role_with_event( + tenant.community(), + channel_id, + change, + event, + &state.relay_keypair, + ) + .await + .map_err(|error| match error { + DbError::AccessDenied(reason) => IngestError::Rejected(format!("invalid: {reason}")), + DbError::ChannelNotFound(_) => { + IngestError::Rejected("invalid: channel not found".into()) + } + error => { + IngestError::Internal(format!("error: Solo member role write failed: {error}")) + } + })?; + + let inserted = !group_state.is_empty(); + if inserted { + state.invalidate_membership(tenant, channel_id, &target.to_bytes()); + let relay_pubkey_hex = state.relay_keypair.public_key().to_hex(); + for snapshot in group_state { + dispatch_persistent_event( + tenant, + state, + &snapshot, + event_kind_u32(&snapshot.event), + &relay_pubkey_hex, + None, + ) + .await; + } + } + Ok((stored, inserted)) +} diff --git a/crates/buzz-relay/src/handlers/solo_member_role_postgres_tests.rs b/crates/buzz-relay/src/handlers/solo_member_role_postgres_tests.rs new file mode 100644 index 00000000000..8fdfbd21f5a --- /dev/null +++ b/crates/buzz-relay/src/handlers/solo_member_role_postgres_tests.rs @@ -0,0 +1,382 @@ +//! Signed Solo role commands through the production ingest path. + +use buzz_core::{ + kind::{ + KIND_MEMBER_ADDED_NOTIFICATION, KIND_NIP29_GROUP_ADMINS, KIND_NIP29_GROUP_MEMBERS, + KIND_NIP29_REMOVE_USER, KIND_SOLO_MEMBER_ROLE, KIND_SYSTEM_MESSAGE, + }, + TenantContext, +}; +use buzz_db::{channel::MemberRole, event::EventQuery}; +use nostr::{Event, EventBuilder, Keys, Kind, Tag}; +use uuid::Uuid; + +use super::{ + group_state_postgres_tests::{community, create_channel, group_state_tags, http_auth, state}, + ingest::{ingest_event, IngestError}, +}; +use crate::state::AppState; + +fn role_change(owner: &Keys, channel_id: Uuid, target: &Keys, expected: &str, next: &str) -> Event { + EventBuilder::new(Kind::Custom(KIND_SOLO_MEMBER_ROLE as u16), "") + .tags([ + Tag::parse(["h", &channel_id.to_string()]).unwrap(), + Tag::parse(["p", &target.public_key().to_hex()]).unwrap(), + Tag::parse(["expected_role", expected]).unwrap(), + Tag::parse(["role", next]).unwrap(), + ]) + .sign_with_keys(owner) + .expect("sign Solo member role command") +} + +async fn record_agent_owner(state: &AppState, tenant: &TenantContext, agent: &Keys, owner: &Keys) { + let agent = agent.public_key().to_bytes(); + let owner = owner.public_key().to_bytes(); + for pubkey in [&agent, &owner] { + state + .db + .ensure_user(tenant.community(), pubkey) + .await + .expect("user"); + } + assert!(state + .db + .set_agent_owner(tenant.community(), &agent, &owner) + .await + .expect("owner link")); +} + +async fn notice_count(state: &AppState, tenant: &TenantContext, channel_id: Uuid) -> usize { + state + .db + .query_events(&EventQuery { + kinds: Some(vec![ + KIND_SYSTEM_MESSAGE as i32, + KIND_MEMBER_ADDED_NOTIFICATION as i32, + ]), + custom_tag: Some(("h".into(), channel_id.to_string())), + ..EventQuery::for_community(tenant.community()) + }) + .await + .expect("membership notices") + .len() +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn solo_owner_edits_active_members_and_publishes_the_new_roster() { + let state = state().await; + let tenant = community(&state, "solo-agent-role").await; + let [owner, other_owner, own_agent, other_agent, person] = + std::array::from_fn(|_| Keys::generate()); + record_agent_owner(&state, &tenant, &own_agent, &owner).await; + record_agent_owner(&state, &tenant, &other_agent, &other_owner).await; + let channel_id = create_channel( + &state, + &tenant, + &owner, + &[ + &["visibility", "private"], + &["t", "buzz.solo"], + &["p", &own_agent.public_key().to_hex()], + &["p", &person.public_key().to_hex()], + ], + ) + .await; + for admin in [&other_agent, &person] { + state + .db + .add_member( + tenant.community(), + channel_id, + &admin.public_key().to_bytes(), + MemberRole::Admin, + Some(&owner.public_key().to_bytes()), + ) + .await + .expect("existing admin"); + } + state + .db + .set_channel_add_policy( + tenant.community(), + &other_agent.public_key().to_bytes(), + "nobody", + ) + .await + .expect("change invitation policy"); + let initial_notices = notice_count(&state, &tenant, channel_id).await; + + let downgrade = role_change(&owner, channel_id, &other_agent, "admin", "guest"); + let own_promotion = role_change(&owner, channel_id, &own_agent, "member", "admin"); + let participating = role_change(&owner, channel_id, &other_agent, "guest", "member"); + for (command, target, role) in [ + (downgrade.clone(), &other_agent, "guest"), + (own_promotion, &own_agent, "admin"), + (participating, &other_agent, "bot"), + ( + role_change(&owner, channel_id, &person, "admin", "member"), + &person, + "member", + ), + ( + role_change(&owner, channel_id, &person, "member", "guest"), + &person, + "guest", + ), + ] { + let command_id = command.id; + let result = ingest_event(&state, &tenant, command, http_auth(&owner)) + .await + .expect("accepted role change"); + assert!(result.accepted, "{}", result.message); + assert!(state + .db + .get_event_by_id(tenant.community(), command_id.as_bytes()) + .await + .expect("stored command") + .is_some()); + let active_role = state + .db + .get_member_role( + tenant.community(), + channel_id, + &target.public_key().to_bytes(), + ) + .await + .expect("active role"); + assert_eq!(active_role.as_deref(), Some(role)); + } + let result = ingest_event(&state, &tenant, downgrade, http_auth(&owner)) + .await + .expect("confirm an already applied command"); + assert_eq!(result.message, "duplicate:"); + + for (actor, target, expected, role, reason) in [ + ( + &owner, + &other_agent, + "member", + "guest", + "membership or role changed", + ), + ( + &owner, + &other_agent, + "bot", + "admin", + "only an agent's owner", + ), + (&owner, &person, "guest", "member", "only a verified agent"), + ( + &own_agent, + &other_agent, + "bot", + "guest", + "only a Solo chat owner", + ), + ] { + let command = role_change(actor, channel_id, target, expected, role); + let refused = ingest_event(&state, &tenant, command.clone(), http_auth(actor)) + .await + .err(); + assert!( + matches!(refused, Some(IngestError::Rejected(ref message)) if message.contains(reason)), + "{refused:?}" + ); + assert!(state + .db + .get_event_by_id(tenant.community(), command.id.as_bytes()) + .await + .expect("query declined command") + .is_none()); + } + + let roster = + group_state_tags(&state, &tenant, channel_id, KIND_NIP29_GROUP_MEMBERS as i32).await; + for (target, role) in [ + (&own_agent, "admin"), + (&other_agent, "bot"), + (&person, "guest"), + ] { + assert!(roster.contains(&vec![ + "p".into(), + target.public_key().to_hex(), + "".into(), + role.into() + ])); + } + assert_eq!( + notice_count(&state, &tenant, channel_id).await, + initial_notices + ); + + let removal = EventBuilder::new(Kind::Custom(KIND_NIP29_REMOVE_USER as u16), "") + .tags([ + Tag::parse(["h", &channel_id.to_string()]).unwrap(), + Tag::parse(["p", &other_agent.public_key().to_hex()]).unwrap(), + ]) + .sign_with_keys(&owner) + .expect("sign removal"); + let result = ingest_event(&state, &tenant, removal, http_auth(&owner)) + .await + .expect("remove agent"); + assert!(result.accepted, "{}", result.message); + + let command = role_change(&owner, channel_id, &other_agent, "bot", "guest"); + let command_id = command.id; + let refused = ingest_event(&state, &tenant, command, http_auth(&owner)) + .await + .err(); + assert!( + matches!(refused, Some(IngestError::Rejected(ref message)) if message.contains("membership or role changed")), + "{refused:?}" + ); + let roster = + group_state_tags(&state, &tenant, channel_id, KIND_NIP29_GROUP_MEMBERS as i32).await; + let removed_key = other_agent.public_key().to_hex(); + assert!(!roster + .iter() + .any(|tag| tag[0] == "p" && tag[1] == removed_key)); + assert!(state + .db + .get_event_by_id(tenant.community(), command_id.as_bytes()) + .await + .expect("query declined command") + .is_none()); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn solo_role_change_is_refused_on_an_open_channel() { + let state = state().await; + let tenant = community(&state, "solo-role-open-channel").await; + let [owner, own_agent] = std::array::from_fn(|_| Keys::generate()); + record_agent_owner(&state, &tenant, &own_agent, &owner).await; + let channel_id = create_channel( + &state, + &tenant, + &owner, + &[ + &["visibility", "open"], + &["t", "buzz.solo"], + &["p", &own_agent.public_key().to_hex()], + ], + ) + .await; + + let command = role_change(&owner, channel_id, &own_agent, "member", "guest"); + let command_id = command.id; + let refused = ingest_event(&state, &tenant, command, http_auth(&owner)) + .await + .err(); + assert!( + matches!(refused, Some(IngestError::Rejected(ref message)) if message.contains("channel is not a Solo chat")), + "{refused:?}" + ); + assert!(state + .db + .get_event_by_id(tenant.community(), command_id.as_bytes()) + .await + .expect("query declined command") + .is_none()); + let active_role = state + .db + .get_member_role( + tenant.community(), + channel_id, + &own_agent.public_key().to_bytes(), + ) + .await + .expect("active role"); + assert_eq!(active_role.as_deref(), Some("member")); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn solo_role_change_rolls_back_if_signed_roster_write_fails() { + let state = state().await; + let tenant = community(&state, "solo-role-roster-failure").await; + let [owner, agent] = std::array::from_fn(|_| Keys::generate()); + record_agent_owner(&state, &tenant, &agent, &owner).await; + let channel_id = create_channel( + &state, + &tenant, + &owner, + &[ + &["visibility", "private"], + &["t", "buzz.solo"], + &["p", &agent.public_key().to_hex()], + ], + ) + .await; + let admins_kind = KIND_NIP29_GROUP_ADMINS as i32; + let members_kind = KIND_NIP29_GROUP_MEMBERS as i32; + let before_admins = group_state_tags(&state, &tenant, channel_id, admins_kind).await; + let before_members = group_state_tags(&state, &tenant, channel_id, members_kind).await; + + // The PostgreSQL runner isolates this trigger to the test's database. + for statement in [ + "CREATE FUNCTION solo_roster_fail() RETURNS trigger LANGUAGE plpgsql AS \ + $$ BEGIN RAISE EXCEPTION 'injected roster write failure'; END $$", + "CREATE TRIGGER solo_roster_fail BEFORE INSERT ON events FOR EACH ROW \ + WHEN (NEW.kind = 39002) EXECUTE FUNCTION solo_roster_fail()", + ] { + sqlx::query(statement) + .execute(state.db.pool()) + .await + .expect("install roster failure trigger"); + } + + let command = role_change(&owner, channel_id, &agent, "member", "admin"); + let command_id = command.id; + let error = ingest_event(&state, &tenant, command.clone(), http_auth(&owner)) + .await + .err(); + assert!( + matches!(error, Some(IngestError::Internal(ref message)) if message.contains("injected roster write failure")), + "{error:?}" + ); + assert!(state + .db + .get_event_by_id(tenant.community(), command_id.as_bytes()) + .await + .expect("query failed command") + .is_none()); + let active_role = state + .db + .get_member_role( + tenant.community(), + channel_id, + &agent.public_key().to_bytes(), + ) + .await + .expect("active role after rollback"); + assert_eq!(active_role.as_deref(), Some("member")); + assert_eq!( + group_state_tags(&state, &tenant, channel_id, admins_kind).await, + before_admins + ); + assert_eq!( + group_state_tags(&state, &tenant, channel_id, members_kind).await, + before_members + ); + + sqlx::query("DROP TRIGGER solo_roster_fail ON events") + .execute(state.db.pool()) + .await + .expect("remove roster failure trigger"); + let retry = ingest_event(&state, &tenant, command, http_auth(&owner)) + .await + .expect("retry the same signed command"); + assert!( + retry.accepted && retry.message != "duplicate:", + "{}", + retry.message + ); + let agent_hex = agent.public_key().to_hex(); + let admins = group_state_tags(&state, &tenant, channel_id, admins_kind).await; + assert!(admins.contains(&vec!["p".into(), agent_hex.clone(), "admin".into()])); + let members = group_state_tags(&state, &tenant, channel_id, members_kind).await; + assert!(members.contains(&vec!["p".into(), agent_hex, "".into(), "admin".into()])); +} diff --git a/crates/buzz-relay/src/nip11.rs b/crates/buzz-relay/src/nip11.rs index b3bed55df2d..c4f61f018a6 100644 --- a/crates/buzz-relay/src/nip11.rs +++ b/crates/buzz-relay/src/nip11.rs @@ -265,6 +265,8 @@ impl RelayInfo { // without it ignores the tag beside `visibility`, so a client // checks this before opening a channel as unlisted. "buzz-unlisted-channels".to_string(), + // kind:9050 edits an existing Solo member's access. + "buzz-solo-member-role".to_string(), ]; let gif = gif_provider.map(|provider| { supported_extensions.push("buzz-gif".to_string()); @@ -825,10 +827,10 @@ mod tests { } /// Clients refuse NIP-CL labels and system channels, newest-first - /// search, and unlisted channels unless the relay says it supports them, - /// so every document must advertise all three. + /// search, unlisted channels, and Solo role edits unless the relay says it + /// supports them, so every document must advertise these extensions. #[test] - fn advertises_nip_cl_search_sort_and_unlisted_extensions() { + fn advertises_channel_and_search_extensions() { let info = RelayInfo::build( None, None, @@ -842,6 +844,7 @@ mod tests { assert!(extensions.contains(&"nip-cl".to_string())); assert!(extensions.contains(&"buzz-search-sort".to_string())); assert!(extensions.contains(&"buzz-unlisted-channels".to_string())); + assert!(extensions.contains(&"buzz-solo-member-role".to_string())); } /// NIP-WP → NIP-11 mirror: a set workspace icon is served in the standard diff --git a/docs/solo-mobile-contract.md b/docs/solo-mobile-contract.md index e7b17ea5f49..b548b668ffd 100644 --- a/docs/solo-mobile-contract.md +++ b/docs/solo-mobile-contract.md @@ -40,3 +40,34 @@ placement and shared-chat ordinary sending. These are compositional contract tests, not a live desktop/relay/device E2E run. Physical-device installation and launch alone do not prove that journey. + +## Changing an existing member's access + +A Solo chat owner changes an existing member's access with a signed Buzz +kind:9050 event with `admin:channels` scope. The content is empty. Each +required tag appears once. + +Relays advertise `buzz-solo-member-role` in NIP-11 `supported_extensions`. +Clients offer role changes only when the relay advertises this extension. + +| Tag | Value | +| --- | --- | +| `h` | Solo channel UUID | +| `p` | Target member's hex public key | +| `expected_role` | Exact active role from the relay-signed roster: `admin`, `bot`, `member`, or `guest` | +| `role` | `admin`, `member` (Participating), or `guest` (Viewing only) | + +A chat owner may lower any active non-owner to Viewing only, or lower an +Admin to Participating. A move from Viewing only to Participating requires +a verified agent. An Admin grant requires a verified agent owned by the +signer. The relay stores Participating as `bot` for verified agents and +`member` for people. Role changes bypass invitation policy. + +The relay requires a private Solo stream and checks the current chat and +membership under the membership lock. It commits the command, role, signed +admin list, and signed member roster together. It emits no admission notices. + +Refresh the roster after a role mismatch. Resending the same accepted event +confirms its receipt without applying another change. Relays that lack +kind:9050 support reject it. Clients must never fall back to kind:9000 for +this action.