From a1ff595d46ddf98831c58517ce9166e1e156f051 Mon Sep 17 00:00:00 2001 From: Krish Ray Date: Mon, 16 Nov 2026 13:33:52 -0500 Subject: [PATCH 1/7] fix(db): prepare deletion catalogs for mention groups Co-authored-by: Sigil <06114f072cf21e50fcd4133ab21346cdb1f74ee16d853a9729995fa6c03a251c@buzz.block.builderlab.xyz> Signed-off-by: Krish Ray Signed-off-by: kray --- crates/buzz-db/src/store/deletion.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/buzz-db/src/store/deletion.rs b/crates/buzz-db/src/store/deletion.rs index 490d53cf6ad..932a360e308 100644 --- a/crates/buzz-db/src/store/deletion.rs +++ b/crates/buzz-db/src/store/deletion.rs @@ -141,6 +141,8 @@ pub const PENDING_SCOPED_TABLES: &[&str] = &[ "identity_retirement_actions", "identity_retirement_holds", "identity_retirement_workflows", + "mention_group_commands", + "mention_groups", ]; /// Tenant tables an expand migration may add between a deletion's approval @@ -157,6 +159,8 @@ pub const APPROVAL_FORWARD_TABLES: &[&str] = &[ "identity_retirement_actions", "identity_retirement_holds", "identity_retirement_workflows", + "mention_group_commands", + "mention_groups", ]; /// Control-plane tables with community provenance that the tenant purge does From b212c2186d4cd8b642f3e5dda3eb128d1630e6a7 Mon Sep 17 00:00:00 2001 From: Krish Ray Date: Mon, 16 Nov 2026 14:33:58 -0500 Subject: [PATCH 2/7] feat(relay): add shared mention groups with durable CAS commands Store relay-owned groups and management policy with atomic signed heads, accepted-command receipts and default-channel joins. Expose NIP-MG discovery and conflict responses, with persistence, admission and live transport coverage. Co-authored-by: Sigil <06114f072cf21e50fcd4133ab21346cdb1f74ee16d853a9729995fa6c03a251c@buzz.block.builderlab.xyz> Signed-off-by: Krish Ray Signed-off-by: kray --- crates/buzz-core/src/channel.rs | 58 ++ crates/buzz-core/src/kind.rs | 19 +- crates/buzz-core/src/lib.rs | 2 + crates/buzz-core/src/mention_group.rs | 580 ++++++++++++++++ crates/buzz-db/src/lib.rs | 2 +- crates/buzz-db/src/runtime/migration.rs | 21 +- crates/buzz-db/src/store/channel_members.rs | 165 +++++ crates/buzz-db/src/store/deletion.rs | 112 +++- crates/buzz-db/src/store/mention_group.rs | 561 ++++++++++++++++ .../src/store/mention_group_postgres_tests.rs | 619 ++++++++++++++++++ crates/buzz-db/src/store/mod.rs | 6 + crates/buzz-relay/src/api/bridge.rs | 8 + crates/buzz-relay/src/conformance/mod.rs | 2 +- .../buzz-relay/src/handlers/channel_authz.rs | 18 +- .../src/handlers/command_executor.rs | 4 +- crates/buzz-relay/src/handlers/event.rs | 11 +- crates/buzz-relay/src/handlers/ingest.rs | 16 + .../buzz-relay/src/handlers/mention_groups.rs | 207 ++++++ .../handlers/mention_groups_postgres_tests.rs | 448 +++++++++++++ crates/buzz-relay/src/handlers/mod.rs | 4 + .../buzz-relay/src/handlers/side_effects.rs | 37 +- crates/buzz-relay/src/nip11.rs | 18 + .../tests/e2e_mention_groups.rs | 448 +++++++++++++ docs/nips/NIP-MG.md | 291 ++++++++ migrations/0097_mention_groups.sql | 42 ++ schema/schema.sql | 3 + schema/tables/public/communities.sql | 3 + .../tables/public/mention_group_commands.sql | 15 + schema/tables/public/mention_groups.sql | 17 + 29 files changed, 3707 insertions(+), 30 deletions(-) create mode 100644 crates/buzz-core/src/mention_group.rs create mode 100644 crates/buzz-db/src/store/mention_group.rs create mode 100644 crates/buzz-db/src/store/mention_group_postgres_tests.rs create mode 100644 crates/buzz-relay/src/handlers/mention_groups.rs create mode 100644 crates/buzz-relay/src/handlers/mention_groups_postgres_tests.rs create mode 100644 crates/buzz-test-client/tests/e2e_mention_groups.rs create mode 100644 docs/nips/NIP-MG.md create mode 100644 migrations/0097_mention_groups.sql create mode 100644 schema/tables/public/mention_group_commands.sql create mode 100644 schema/tables/public/mention_groups.sql diff --git a/crates/buzz-core/src/channel.rs b/crates/buzz-core/src/channel.rs index 36ee3f43c2e..1a5e7e0969f 100644 --- a/crates/buzz-core/src/channel.rs +++ b/crates/buzz-core/src/channel.rs @@ -259,6 +259,41 @@ impl FromStr for ChannelJoinRole { } } +/// Why an agent's channel-add policy refused a third-party add. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ChannelAddPolicyDenied { + /// Owner-only admission was requested but no owner is recorded. + OwnerMissing, + /// The actor differs from the recorded owner. + OwnerOnly, + /// The target refuses all third-party channel additions. + Nobody, +} + +/// Evaluate an agent's channel-add policy for a third-party add. +/// +/// Callers bypass this check for self-adds and targets without a policy row. +/// Unknown values preserve the existing allow behavior; the database enum +/// constrains stored values. Both relay validation and admitted mutations use +/// this decision so their policy rules cannot diverge. +pub fn decide_channel_add_policy( + policy: &str, + owner: Option<&[u8]>, + actor: &[u8], +) -> Result<(), ChannelAddPolicyDenied> { + match policy { + "owner_only" => { + let owner = owner.ok_or(ChannelAddPolicyDenied::OwnerMissing)?; + if actor != owner { + return Err(ChannelAddPolicyDenied::OwnerOnly); + } + Ok(()) + } + "nobody" => Err(ChannelAddPolicyDenied::Nobody), + _ => Ok(()), + } +} + /// The facts a kind:9000 add or role change is decided on, for /// [`decide_member_put`]. Every field must come from one consistent read: the /// relay validator reads them for a fast, client-visible answer, and @@ -561,6 +596,29 @@ impl FromStr for MemberRole { #[cfg(test)] mod tests { + #[test] + fn third_party_add_policy_requires_the_recorded_owner_only_when_requested() { + use super::{decide_channel_add_policy, ChannelAddPolicyDenied::*}; + let actor = [1; 32]; + let other = [2; 32]; + for (policy, owner, expected) in [ + ("owner_only", None, Err(OwnerMissing)), + ("owner_only", Some(other.as_slice()), Err(OwnerOnly)), + ("owner_only", Some(actor.as_slice()), Ok(())), + ("nobody", None, Err(Nobody)), + ("nobody", Some(actor.as_slice()), Err(Nobody)), + ("everyone", None, Ok(())), + ("everyone", Some(other.as_slice()), Ok(())), + ("unknown", None, Ok(())), + ] { + assert_eq!( + decide_channel_add_policy(policy, owner, &actor), + expected, + "{policy}" + ); + } + } + use super::{ canonical_channel_name, channel_name_error, channel_type_from_group_state_tags, decide_member_put, group_state_identity_tags, parse_channel_labels, ChannelJoinRole, diff --git a/crates/buzz-core/src/kind.rs b/crates/buzz-core/src/kind.rs index 7428c75cfee..ac6e9ff89d1 100644 --- a/crates/buzz-core/src/kind.rs +++ b/crates/buzz-core/src/kind.rs @@ -445,6 +445,12 @@ pub const RELAY_ADMIN_REMOVE_MEMBER: u32 = 9031; pub const RELAY_ADMIN_CHANGE_ROLE: u32 = 9032; /// Buzz: Set the workspace profile (icon). Admin/owner-signed command. pub const RELAY_ADMIN_SET_WORKSPACE_PROFILE: u32 = 9033; +/// NIP-MG: Set the community mention-group management policy. +pub const RELAY_ADMIN_SET_MENTION_GROUP_POLICY: u32 = 47002; +/// NIP-MG: Create or replace a community mention group using a version precondition. +pub const RELAY_ADMIN_PUT_MENTION_GROUP: u32 = 47000; +/// NIP-MG: Delete a community mention group using a version precondition. +pub const RELAY_ADMIN_DELETE_MENTION_GROUP: u32 = 47001; // NIP-43 relay membership announcement events (relay-signed) /// NIP-43: Relay membership list snapshot (relay-signed, replaceable by convention). pub const KIND_NIP43_MEMBERSHIP_LIST: u32 = 13534; @@ -498,6 +504,9 @@ pub const KIND_MEMBERSHIP_SNAPSHOT: u32 = 39008; /// NIP-CL: request-bound public membership overlay; query-time only, never stored. pub const KIND_MEMBERSHIP_PUBLIC: u32 = 39009; +/// NIP-MG: Relay-signed community mention-group state or management settings. +pub const KIND_MENTION_GROUP_STATE: u32 = 39010; + /// Workflow definition (parameterized replaceable, d=workflow_uuid). pub const KIND_WORKFLOW_DEF: u32 = 30620; @@ -747,6 +756,9 @@ pub const ALL_KINDS: &[u32] = &[ RELAY_ADMIN_REMOVE_MEMBER, RELAY_ADMIN_CHANGE_ROLE, RELAY_ADMIN_SET_WORKSPACE_PROFILE, + RELAY_ADMIN_SET_MENTION_GROUP_POLICY, + RELAY_ADMIN_PUT_MENTION_GROUP, + RELAY_ADMIN_DELETE_MENTION_GROUP, KIND_NIP43_MEMBERSHIP_LIST, KIND_NIP43_MEMBER_ADDED, KIND_NIP43_MEMBER_REMOVED, @@ -765,6 +777,7 @@ pub const ALL_KINDS: &[u32] = &[ KIND_THREAD_WINDOW_BOUNDS, KIND_MEMBERSHIP_SNAPSHOT, KIND_MEMBERSHIP_PUBLIC, + KIND_MENTION_GROUP_STATE, KIND_PRESENCE_UPDATE, KIND_TYPING_INDICATOR, KIND_AGENT_PRESENCE, @@ -881,7 +894,7 @@ pub const fn is_workflow_execution_kind(kind: u32) -> bool { } /// Returns `true` if `kind` is a NIP-43 relay membership admin command (9030–9032) -/// or the Buzz workspace-profile admin command (9033). +/// or a Buzz workspace-profile or mention-group command. pub const fn is_relay_admin_kind(kind: u32) -> bool { matches!( kind, @@ -889,6 +902,9 @@ pub const fn is_relay_admin_kind(kind: u32) -> bool { | RELAY_ADMIN_REMOVE_MEMBER | RELAY_ADMIN_CHANGE_ROLE | RELAY_ADMIN_SET_WORKSPACE_PROFILE + | RELAY_ADMIN_SET_MENTION_GROUP_POLICY + | RELAY_ADMIN_PUT_MENTION_GROUP + | RELAY_ADMIN_DELETE_MENTION_GROUP ) } @@ -935,6 +951,7 @@ pub const fn is_relay_only_kind(kind: u32) -> bool { | KIND_THREAD_WINDOW_BOUNDS | KIND_MEMBERSHIP_SNAPSHOT | KIND_MEMBERSHIP_PUBLIC + | KIND_MENTION_GROUP_STATE ) } diff --git a/crates/buzz-core/src/lib.rs b/crates/buzz-core/src/lib.rs index f1330a65655..b196300380f 100644 --- a/crates/buzz-core/src/lib.rs +++ b/crates/buzz-core/src/lib.rs @@ -24,6 +24,8 @@ pub mod git_perms; pub mod invite; /// Buzz kind number registry — custom event type constants. pub mod kind; +/// NIP-MG community mention-group command validation and normalized values. +pub mod mention_group; /// Network utilities — SSRF-safe IP classification. pub mod network; /// NIP-10 thread-marker parsing — shared `root`/`reply` marker resolver. diff --git a/crates/buzz-core/src/mention_group.rs b/crates/buzz-core/src/mention_group.rs new file mode 100644 index 00000000000..48f2681d688 --- /dev/null +++ b/crates/buzz-core/src/mention_group.rs @@ -0,0 +1,580 @@ +//! NIP-MG wire validation, independent of transport admission and persistence. +//! +//! These parsers do not verify signatures, actor roles, freshness, the relay's +//! configured message-size limit, or version preconditions against stored state. +//! Those checks belong to the relay and its admitted mutation transaction. + +use std::collections::BTreeSet; +use std::fmt; +use std::str::FromStr; + +use nostr::{Event, PublicKey}; +use uuid::Uuid; + +use crate::kind::{ + event_kind_u32, RELAY_ADMIN_DELETE_MENTION_GROUP, RELAY_ADMIN_PUT_MENTION_GROUP, + RELAY_ADMIN_SET_MENTION_GROUP_POLICY, +}; + +/// Reserved addressable-state coordinate for community management settings. +pub const SETTINGS_D_TAG: &str = "settings"; +/// Maximum number of Unicode scalar values in a normalized group name. +pub const MAX_NAME_CHARS: usize = 120; +/// Maximum distinct default channels in a group replacement. +pub const MAX_DEFAULT_CHANNELS: usize = 32; +const MAX_CLIENT_ID_UTF16: usize = 128; +const MAX_AUTH_CONDITIONS_BYTES: usize = 4096; + +/// Validated complete replacement or deletion request. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Command { + /// Canonical, non-nil community-local group identity. + pub id: Uuid, + /// Expected current version; zero requests creation at an unused identity. + pub prev: i64, + /// Requested transition. Empty membership remains a live put. + pub operation: Operation, +} + +/// Group mutation carried by a command kind. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Operation { + /// Replace the entire name and explicit member set. + Put { + /// Trimmed display name, preserving case, spelling and internal spaces. + name: String, + /// Lowercase hex public keys, sorted and deduplicated, including self. + members: Vec, + /// Canonical default-channel UUIDs, sorted and deduplicated. + channels: Vec, + }, + /// Retire this identity permanently; the store publishes a tombstone. + Delete, +} + +/// Community mention-group management setting. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Manage { + /// Management is restricted according to the community's admin policy. + Admins, + /// Management is available according to the community's everyone policy. + Everyone, +} + +impl Manage { + /// Stable value used in command and settings-state tags. + pub const fn as_str(self) -> &'static str { + match self { + Self::Admins => "admins", + Self::Everyone => "everyone", + } + } +} + +impl fmt::Display for Manage { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(self.as_str()) + } +} + +impl FromStr for Manage { + type Err = String; + + fn from_str(value: &str) -> Result { + match value { + "admins" => Ok(Self::Admins), + "everyone" => Ok(Self::Everyone), + _ => Err("manage must be admins or everyone".into()), + } + } +} + +/// Validated request to replace the community management setting. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PolicyCommand { + /// Expected settings revision; zero identifies the implicit initial state. + pub prev: i64, + /// Requested stable policy value; authorization is a relay concern. + pub manage: Manage, +} + +/// Parse a put/delete command and normalize its display name and member set. +/// +/// The parser accepts only this operation's semantic tags and bounded existing +/// `auth`, `client-id`, and `ms` transport annotations. It never infers a member +/// from the signer: self-membership must be explicitly present as a `p` tag. +pub fn parse_command(event: &Event) -> Result { + let put = match event_kind_u32(event) { + RELAY_ADMIN_PUT_MENTION_GROUP => true, + RELAY_ADMIN_DELETE_MENTION_GROUP => false, + _ => return Err("not a mention group put/delete command".into()), + }; + empty_content(event)?; + let mut id = None; + let mut prev = None; + let mut name = None; + let mut members = BTreeSet::new(); + let mut channels = BTreeSet::new(); + let mut annotations = Annotations::default(); + for tag in event.tags.iter() { + let parts = tag.as_slice(); + match parts.first().map(String::as_str) { + Some("d") => singleton(&mut id, parts)?, + Some("prev") => singleton(&mut prev, parts)?, + Some("name") if put => singleton(&mut name, parts)?, + Some("p") if put => { + let value = pair(parts)?; + let key = PublicKey::from_hex(value) + .map_err(|_| "member must be a 64-character hex public key")?; + members.insert(key.to_hex()); + } + Some("channel") if put => { + let id = crate::artifact::canonical_uuid(pair(parts)?).map_err(str::to_owned)?; + channels.insert(id); + if channels.len() > MAX_DEFAULT_CHANNELS { + return Err("at most 32 distinct default channels are allowed".into()); + } + } + _ => annotations.accept(parts)?, + } + } + let id = crate::artifact::canonical_uuid(required(id, "d")?).map_err(str::to_owned)?; + let prev = version(required(prev, "prev")?)?; + let operation = if put { + let name = required(name, "name")?.trim(); + if name.is_empty() + || name.chars().count() > MAX_NAME_CHARS + || name + .chars() + .any(|c| c.is_control() || matches!(c, '\u{2028}' | '\u{2029}')) + { + return Err( + "name must be 1..120 Unicode characters of single-line text without controls" + .into(), + ); + } + Operation::Put { + name: name.into(), + members: members.into_iter().collect(), + channels: channels.into_iter().collect(), + } + } else { + Operation::Delete + }; + Ok(Command { + id, + prev, + operation, + }) +} + +/// Parse a settings command containing exactly one `manage` and one `prev` tag. +/// +/// The reserved `d=settings` coordinate belongs to the relay-signed projection; +/// commands contain no `d` tag. Actor authorization is deliberately separate. +pub fn parse_policy_command(event: &Event) -> Result { + if event_kind_u32(event) != RELAY_ADMIN_SET_MENTION_GROUP_POLICY { + return Err("not a mention group policy command".into()); + } + empty_content(event)?; + let mut prev = None; + let mut manage = None; + let mut annotations = Annotations::default(); + for tag in event.tags.iter() { + let parts = tag.as_slice(); + match parts.first().map(String::as_str) { + Some("prev") => singleton(&mut prev, parts)?, + Some("manage") => singleton(&mut manage, parts)?, + _ => annotations.accept(parts)?, + } + } + Ok(PolicyCommand { + prev: version(required(prev, "prev")?)?, + manage: required(manage, "manage")?.parse()?, + }) +} + +fn empty_content(event: &Event) -> Result<(), String> { + if !event.content.is_empty() { + return Err("mention group commands require empty content".into()); + } + Ok(()) +} + +fn pair(parts: &[String]) -> Result<&str, String> { + if parts.len() != 2 { + return Err("command fields require exactly two tag elements".into()); + } + Ok(&parts[1]) +} + +fn singleton<'a>(field: &mut Option<&'a str>, parts: &'a [String]) -> Result<(), String> { + if field.replace(pair(parts)?).is_some() { + return Err("duplicate command field".into()); + } + Ok(()) +} + +fn required<'a>(field: Option<&'a str>, label: &str) -> Result<&'a str, String> { + field.ok_or_else(|| format!("missing {label} tag")) +} + +fn version(value: &str) -> Result { + let parsed = value + .parse::() + .map_err(|_| "prev must be a canonical nonnegative signed-64-bit decimal")?; + if parsed < 0 || parsed.to_string() != value { + return Err("prev must be a canonical nonnegative signed-64-bit decimal".into()); + } + Ok(parsed) +} + +#[derive(Default)] +struct Annotations { + auth: bool, + client_id: bool, + ms: bool, +} + +impl Annotations { + fn accept(&mut self, parts: &[String]) -> Result<(), String> { + let seen = match parts.first().map(String::as_str) { + Some("auth") => { + // NIP-OA verification and condition semantics stay with the + // authenticated transport. Only bound the envelope here. + if parts.len() != 4 + || parts[1].len() != 64 + || !parts[1].bytes().all(|b| b.is_ascii_hexdigit()) + || parts[2].len() > MAX_AUTH_CONDITIONS_BYTES + || parts[3].len() != 128 + || !parts[3].bytes().all(|b| b.is_ascii_hexdigit()) + { + return Err("invalid auth annotation".into()); + } + &mut self.auth + } + Some("client-id") => { + let value = pair(parts)?; + if value.is_empty() + || value.encode_utf16().count() > MAX_CLIENT_ID_UTF16 + || value.chars().any(char::is_control) + { + return Err("invalid client-id annotation".into()); + } + &mut self.client_id + } + Some("ms") => { + let value = pair(parts)?; + let parsed = version(value).map_err(|_| "invalid ms annotation")?; + if parsed > 999 { + return Err("invalid ms annotation".into()); + } + &mut self.ms + } + _ => return Err("unexpected command tag".into()), + }; + if std::mem::replace(seen, true) { + return Err("duplicate transport annotation".into()); + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use nostr::{EventBuilder, Keys, Kind, Tag}; + + const ID: &str = "0659678f-fddb-40df-a285-35f6b41db019"; + + fn fields(values: &[&[&str]]) -> Vec> { + values + .iter() + .map(|v| v.iter().map(|s| (*s).into()).collect()) + .collect() + } + + fn put_tags() -> Vec> { + fields(&[&["d", ID], &["prev", "0"], &["name", "Support team"]]) + } + + fn signed(keys: &Keys, kind: u32, tags: Vec>, content: &str) -> Event { + EventBuilder::new(Kind::Custom(kind as u16), content) + .allow_self_tagging() + .tags(tags.into_iter().map(|parts| Tag::parse(parts).unwrap())) + .sign_with_keys(keys) + .unwrap() + } + + fn event(kind: u32, tags: Vec>) -> Event { + signed(&Keys::generate(), kind, tags, "") + } + + #[test] + fn put_normalizes_the_explicit_set_without_dropping_the_signer() { + let keys = Keys::generate(); + let self_key = keys.public_key().to_hex(); + let other = Keys::generate().public_key().to_hex(); + let mut tags = put_tags(); + tags[2][1] = " SRE — 夜間 ".into(); + tags.extend(fields(&[ + &["p", &other.to_uppercase()], + &["p", &self_key], + &["p", &other], + ])); + let command = signed(&keys, RELAY_ADMIN_PUT_MENTION_GROUP, tags, ""); + let mut expected = vec![self_key, other]; + expected.sort(); + assert_eq!( + parse_command(&command).unwrap(), + Command { + id: Uuid::parse_str(ID).unwrap(), + prev: 0, + operation: Operation::Put { + name: "SRE — 夜間".into(), + members: expected, + channels: vec![] + }, + } + ); + } + + #[test] + fn empty_put_update_and_delete_have_distinct_public_operations() { + let empty = event(RELAY_ADMIN_PUT_MENTION_GROUP, put_tags()); + assert!(matches!(parse_command(&empty).unwrap().operation, + Operation::Put { members, .. } if members.is_empty())); + let mut update = put_tags(); + update[1][1] = i64::MAX.to_string(); + assert_eq!( + parse_command(&event(RELAY_ADMIN_PUT_MENTION_GROUP, update)) + .unwrap() + .prev, + i64::MAX + ); + let delete = event( + RELAY_ADMIN_DELETE_MENTION_GROUP, + fields(&[&["d", ID], &["prev", "3"]]), + ); + assert_eq!(parse_command(&delete).unwrap().operation, Operation::Delete); + for extra in [ + vec!["name".into(), "Hidden".into()], + vec!["p".into(), "ab".repeat(32)], + ] { + let mut tags = fields(&[&["d", ID], &["prev", "3"]]); + tags.push(extra); + assert!(parse_command(&event(RELAY_ADMIN_DELETE_MENTION_GROUP, tags)).is_err()); + } + } + + #[test] + fn ambiguous_or_malformed_command_fields_are_rejected() { + for field in 0..3 { + let mut duplicate = put_tags(); + duplicate.push(duplicate[field].clone()); + assert!(parse_command(&event(RELAY_ADMIN_PUT_MENTION_GROUP, duplicate)).is_err()); + let mut missing = put_tags(); + missing.remove(field); + assert!(parse_command(&event(RELAY_ADMIN_PUT_MENTION_GROUP, missing)).is_err()); + let mut extra_value = put_tags(); + extra_value[field].push("extra".into()); + assert!(parse_command(&event(RELAY_ADMIN_PUT_MENTION_GROUP, extra_value)).is_err()); + } + for id in [ + ID.to_uppercase(), + ID.replace('-', ""), + Uuid::nil().to_string(), + "settings".into(), + ] { + let mut tags = put_tags(); + tags[0][1] = id; + assert!(parse_command(&event(RELAY_ADMIN_PUT_MENTION_GROUP, tags)).is_err()); + } + for prev in [ + "", + "-1", + "+1", + "01", + " 1", + "1 ", + "1.0", + "9223372036854775808", + ] { + let mut tags = put_tags(); + tags[1][1] = prev.into(); + assert!( + parse_command(&event(RELAY_ADMIN_PUT_MENTION_GROUP, tags)).is_err(), + "{prev}" + ); + } + for extra in fields(&[ + &["h", ID], + &["version", "1"], + &["deleted", "true"], + &["name"], + &["p", "npub1bad"], + &["p", "ab", "relay"], + ]) { + let mut tags = put_tags(); + tags.push(extra); + assert!(parse_command(&event(RELAY_ADMIN_PUT_MENTION_GROUP, tags)).is_err()); + } + assert!(parse_command(&signed( + &Keys::generate(), + RELAY_ADMIN_PUT_MENTION_GROUP, + put_tags(), + "hidden" + )) + .is_err()); + assert!(parse_command(&event(crate::kind::KIND_MENTION_GROUP_STATE, put_tags())).is_err()); + } + + #[test] + fn names_use_unicode_scalar_limits_and_groups_can_exceed_send_recipient_limits() { + for (name, accepted) in [ + ("夜".repeat(120), true), + ("夜".repeat(121), false), + (" ".into(), false), + ("a\nb".into(), false), + ("a\tb".into(), false), + ("a\u{7f}b".into(), false), + ("a\u{2028}b".into(), false), + ("a\u{2029}b".into(), false), + ] { + let mut tags = put_tags(); + tags[2][1] = name; + assert_eq!( + parse_command(&event(RELAY_ADMIN_PUT_MENTION_GROUP, tags)).is_ok(), + accepted + ); + } + let mut tags = put_tags(); + for _ in 0..40 { + tags.push(vec!["p".into(), Keys::generate().public_key().to_hex()]); + } + assert!( + matches!(parse_command(&event(RELAY_ADMIN_PUT_MENTION_GROUP, tags)).unwrap().operation, + Operation::Put { members, .. } if members.len() == 40) + ); + } + + #[test] + fn default_channels_are_a_bounded_canonical_set() { + let mut tags = put_tags(); + for value in (1..=32).rev().chain([1, 32]) { + tags.push(vec!["channel".into(), Uuid::from_u128(value).to_string()]); + } + let parsed = parse_command(&event(RELAY_ADMIN_PUT_MENTION_GROUP, tags.clone())).unwrap(); + assert!(matches!(parsed.operation, Operation::Put { channels, .. } + if channels == (1..=32).map(Uuid::from_u128).collect::>())); + tags.push(vec!["channel".into(), Uuid::from_u128(33).to_string()]); + assert!(parse_command(&event(RELAY_ADMIN_PUT_MENTION_GROUP, tags)).is_err()); + for channel in [ + ID.to_uppercase(), + Uuid::nil().to_string(), + "private-room".into(), + ] { + let mut tags = put_tags(); + tags.push(vec!["channel".into(), channel]); + assert!(parse_command(&event(RELAY_ADMIN_PUT_MENTION_GROUP, tags)).is_err()); + } + let mut tags = fields(&[&["d", ID], &["prev", "1"]]); + tags.push(vec!["channel".into(), ID.into()]); + assert!(parse_command(&event(RELAY_ADMIN_DELETE_MENTION_GROUP, tags)).is_err()); + } + + #[test] + fn only_bounded_singleton_transport_annotations_are_accepted() { + let auth = vec!["auth".into(), "ab".repeat(32), "".into(), "cd".repeat(64)]; + let annotations = vec![ + auth, + vec!["client-id".into(), "x".repeat(128)], + vec!["ms".into(), "999".into()], + ]; + let mut tags = put_tags(); + tags.extend(annotations.clone()); + assert!(parse_command(&event(RELAY_ADMIN_PUT_MENTION_GROUP, tags)).is_ok()); + for annotation in annotations { + let mut tags = put_tags(); + tags.extend([annotation.clone(), annotation]); + assert!(parse_command(&event(RELAY_ADMIN_PUT_MENTION_GROUP, tags)).is_err()); + } + let mut invalid = fields(&[ + &["client-id", ""], + &["client-id", "a", "extra"], + &["ms", "1000"], + &["ms", "00"], + &["ms", "-1"], + &["auth", "ab"], + &["unknown", "value"], + &["-"], + ]); + invalid.push(vec!["client-id".into(), "😀".repeat(65)]); + invalid.push(vec![ + "auth".into(), + "ab".repeat(32), + "x".repeat(4097), + "cd".repeat(64), + ]); + for annotation in invalid { + let mut tags = put_tags(); + tags.push(annotation); + assert!(parse_command(&event(RELAY_ADMIN_PUT_MENTION_GROUP, tags)).is_err()); + } + } + + #[test] + fn policy_wire_values_are_exact_and_do_not_accept_group_fields() { + for (wire, expected) in [("admins", Manage::Admins), ("everyone", Manage::Everyone)] { + let policy = event( + RELAY_ADMIN_SET_MENTION_GROUP_POLICY, + fields(&[&["manage", wire], &["prev", "0"]]), + ); + assert_eq!( + parse_policy_command(&policy).unwrap(), + PolicyCommand { + prev: 0, + manage: expected + } + ); + assert_eq!(expected.to_string(), wire); + } + for wire in ["Admins", " everyone", "", "members"] { + let policy = event( + RELAY_ADMIN_SET_MENTION_GROUP_POLICY, + fields(&[&["manage", wire], &["prev", "0"]]), + ); + assert!(parse_policy_command(&policy).is_err()); + } + for extra in fields(&[ + &["manage", "admins"], + &["prev", "0"], + &["d", SETTINGS_D_TAG], + &["name", "Team"], + &["p", "ab"], + ]) { + let mut tags = fields(&[&["manage", "admins"], &["prev", "0"]]); + tags.push(extra); + assert!( + parse_policy_command(&event(RELAY_ADMIN_SET_MENTION_GROUP_POLICY, tags)).is_err() + ); + } + for tags in [ + fields(&[&["prev", "0"]]), + fields(&[&["manage", "admins"]]), + fields(&[&["manage", "admins"], &["prev", "01"]]), + ] { + assert!( + parse_policy_command(&event(RELAY_ADMIN_SET_MENTION_GROUP_POLICY, tags)).is_err() + ); + } + assert!(parse_policy_command(&signed( + &Keys::generate(), + RELAY_ADMIN_SET_MENTION_GROUP_POLICY, + fields(&[&["manage", "admins"], &["prev", "0"]]), + "hidden" + )) + .is_err()); + assert!(parse_policy_command(&event(RELAY_ADMIN_PUT_MENTION_GROUP, put_tags())).is_err()); + } +} diff --git a/crates/buzz-db/src/lib.rs b/crates/buzz-db/src/lib.rs index 106b46eda36..877d9c150c9 100644 --- a/crates/buzz-db/src/lib.rs +++ b/crates/buzz-db/src/lib.rs @@ -96,7 +96,7 @@ pub(crate) use runtime::{ pub use store::{ admin_moderation, allowlist, api_token, archived_identities, artifact, artifact_sync, channel, channel_members, community, community_auth, deletion, dm, entity_deletion, event, feed, - git_repo, leader_lock, media, membership_snapshot, moderation, nip_fi_binding, + git_repo, leader_lock, media, membership_snapshot, mention_group, moderation, nip_fi_binding, operator_listener, partition, personal_read, product_feedback, push, reaction, read_state, relay_admin_actions, relay_invite, relay_members, relay_operators, reminder, replaceable, storage_accounting, thread, thread_window, user, user_deletion, user_deletion_fences, workflow, diff --git a/crates/buzz-db/src/runtime/migration.rs b/crates/buzz-db/src/runtime/migration.rs index bf2e65361ec..7714214a47f 100644 --- a/crates/buzz-db/src/runtime/migration.rs +++ b/crates/buzz-db/src/runtime/migration.rs @@ -879,7 +879,7 @@ mod postgres_tests { let mut migrations: Vec<_> = MIGRATOR.iter().collect(); migrations.sort_by_key(|migration| migration.version); - assert_eq!(migrations.len(), 96); + assert_eq!(migrations.len(), 97); assert_eq!(migrations[89].version, 90); assert!(migrations[89] .sql @@ -1520,6 +1520,8 @@ mod postgres_tests { "nip_fi_profile_heads", "media_uploaders", "media_publications", + "mention_groups", + "mention_group_commands", ]; for table in crate::deletion::EXPECTED_SCOPED_TABLES .iter() @@ -3101,6 +3103,8 @@ mod postgres_tests { .expect("apply migrations for schema parity"); for table in [ + "mention_groups", + "mention_group_commands", "media_uploaders", "audit_log", "media_publications", @@ -3176,6 +3180,8 @@ mod postgres_tests { ); for table in [ + "mention_groups", + "mention_group_commands", "communities", "community_auth_upgrades", "entity_deletion_requests", @@ -3921,6 +3927,8 @@ mod postgres_tests { let sql = migration_sql(); let tables = create_tables(sql.as_str()); for table in [ + "mention_groups", + "mention_group_commands", "communities", "events", "channels", @@ -3981,10 +3989,17 @@ mod postgres_tests { .validate_serving_catalog() .await .expect("new runtime must accept pre-retirement catalog"); - store + // Serving accepts the historical fence shape, while destructive + // operations still require the new feature's expanded tenant catalog. + let error = store .validate_catalog() .await - .expect("deletion must accept pre-retirement catalog"); + .expect_err("feature deletion requires its expanded tenant catalog"); + assert!( + matches!(&error, crate::DbError::DeletionSafety(reason) + if reason == "community deletion catalog drift (missing=mention_group_commands,mention_groups, unknown=)"), + "{error}" + ); run_migrations(&pool).await.expect("apply all migrations"); let fence_triggers: i64 = sqlx::query_scalar( "SELECT count(*) FROM pg_trigger WHERE NOT tgisinternal AND tgname LIKE 'community_write_fence_%'", diff --git a/crates/buzz-db/src/store/channel_members.rs b/crates/buzz-db/src/store/channel_members.rs index 82b66a7acae..0315043724e 100644 --- a/crates/buzz-db/src/store/channel_members.rs +++ b/crates/buzz-db/src/store/channel_members.rs @@ -900,6 +900,171 @@ fn check_distinct_targets(targets: &[MemberPut<'_>]) -> Result<()> { } } +/// Add only new group members to configured public channels on the group's +/// admitted transaction. Missing/deleted channels remain inert references; +/// present nonpublic channels are invalid configuration. Closed public channels +/// are retained but skipped. Existing active memberships never change role. +/// +/// All channel membership locks precede TTL and row locks, in canonical order. +/// Policy refusals are bounded accounting, while database failures abort the +/// entire group write. The caller publishes returned channel rosters after commit. +pub(crate) async fn put_group_default_members_in_transaction( + tx: &mut AdmittedTx, + channels: &[Uuid], + targets: &[Vec], + actor: &[u8], + membership_enforced: bool, +) -> Result<( + Vec, + Vec<(Uuid, Vec)>, + crate::mention_group::JoinSummary, +)> { + use buzz_core::channel::{decide_channel_add_policy, ChannelAddPolicyDenied}; + let community = tx.community(); + let mut channels = channels.to_vec(); + channels.sort_unstable(); + channels.dedup(); + for channel in &channels { + acquire_channel_membership_lock(tx.conn(), community, *channel).await?; + } + let mut summary = crate::mention_group::JoinSummary::default(); + let policy_rows = if targets.is_empty() { + Vec::new() + } else { + sqlx::query( + "SELECT pubkey, channel_add_policy::text AS policy, agent_owner_pubkey FROM users \ + WHERE community_id=$1 AND pubkey=ANY($2) ORDER BY pubkey FOR SHARE", + ) + .bind(community.as_uuid()) + .bind(targets) + .fetch_all(tx.conn()) + .await? + }; + let mut policies = std::collections::HashMap::new(); + for row in policy_rows { + policies.insert( + row.try_get::, _>("pubkey")?, + ( + row.try_get::("policy")?, + row.try_get::>, _>("agent_owner_pubkey")?, + ), + ); + } + // Group membership is recipient data, not community admission. Hold the + // effective target/owner roster rows through commit so a concurrent removal + // either wins first and is skipped, or waits for this join to commit. + let admitted_targets: std::collections::HashSet> = if membership_enforced { + let mut keys: Vec = targets.iter().map(hex::encode).collect(); + keys.extend( + policies + .values() + .filter_map(|(_, owner)| owner.as_ref().map(hex::encode)), + ); + keys.sort_unstable(); + keys.dedup(); + let admitted: Vec = sqlx::query_scalar( + "SELECT pubkey FROM relay_members WHERE community_id=$1 AND pubkey=ANY($2) ORDER BY pubkey FOR SHARE", + ).bind(community.as_uuid()).bind(&keys).fetch_all(tx.conn()).await?; + let admitted: std::collections::HashSet = admitted.into_iter().collect(); + targets + .iter() + .filter(|target| { + admitted.contains(&hex::encode(target)) + || policies + .get(*target) + .and_then(|(_, owner)| owner.as_ref()) + .is_some_and(|owner| admitted.contains(&hex::encode(owner))) + }) + .cloned() + .collect() + } else { + targets.iter().cloned().collect() + }; + let mut changed = Vec::new(); + let mut joined_members = Vec::new(); + for channel in channels { + lock_channel_ttl_shared_in_transaction(tx, channel).await?; + let row = sqlx::query( + "SELECT visibility::text AS visibility, channel_type::text AS channel_type, unlisted, archived_at \ + FROM channels WHERE community_id=$1 AND id=$2 AND deleted_at IS NULL FOR NO KEY UPDATE", + ).bind(community.as_uuid()).bind(channel).fetch_optional(tx.conn()).await?; + let Some(row) = row else { + summary.skip("channel_unavailable", targets.len()); + continue; + }; + if row.try_get::("visibility")? != "open" + || !matches!( + row.try_get::("channel_type")?.as_str(), + "stream" | "forum" + ) + || row.try_get::("unlisted")? + { + return Err(DbError::InvalidData( + "mention group default channel must be a listed public stream or forum".into(), + )); + } + if row + .try_get::>, _>("archived_at")? + .is_some() + { + summary.skip("channel_closed", targets.len()); + continue; + } + let existing: Vec> = sqlx::query_scalar( + "SELECT pubkey FROM channel_members WHERE community_id=$1 AND channel_id=$2 AND pubkey=ANY($3) AND removed_at IS NULL", + ).bind(community.as_uuid()).bind(channel).bind(targets).fetch_all(tx.conn()).await?; + let existing: std::collections::HashSet> = existing.into_iter().collect(); + let mut allowed = Vec::new(); + for target in targets { + if !admitted_targets.contains(target) { + summary.skip("target_not_admitted", 1); + continue; + } + if existing.contains(target) { + summary.skip("already_member", 1); + continue; + } + if target != actor { + if let Some((policy, owner)) = policies.get(target) { + if let Err(denial) = decide_channel_add_policy(policy, owner.as_deref(), actor) + { + summary.skip( + match denial { + ChannelAddPolicyDenied::OwnerMissing => "target_owner_missing", + ChannelAddPolicyDenied::OwnerOnly => "target_owner_only", + ChannelAddPolicyDenied::Nobody => "target_policy_nobody", + }, + 1, + ); + continue; + } + } + } + allowed.push(MemberPut { + pubkey: target, + requested: None, + }); + } + let results = put_members_on(tx, channel, &allowed, Some(actor)).await?; + let mut did_change = false; + for result in results { + match result { + Ok(put) => { + joined_members.push((channel, put.member.pubkey)); + summary.joined += 1; + did_change = true; + } + Err(DbError::AccessDenied(_)) => summary.skip("membership_denied", 1), + Err(error) => return Err(error), + } + } + if did_change { + changed.push(channel); + } + } + Ok((changed, joined_members, summary)) +} + /// The decisions and upsert of [`put_members`], on a transaction that holds /// `channel_id`'s [`lock_channel_for_member_put`] locks. The caller owns the /// commit. diff --git a/crates/buzz-db/src/store/deletion.rs b/crates/buzz-db/src/store/deletion.rs index 932a360e308..8af60b4ded8 100644 --- a/crates/buzz-db/src/store/deletion.rs +++ b/crates/buzz-db/src/store/deletion.rs @@ -90,6 +90,8 @@ pub const RELAY_ADMIN_TABLES: &[(&str, &str)] = &[ /// approval and again before PostgreSQL purge. A new tenant table therefore /// blocks deletion until this manifest is intentionally updated. pub const EXPECTED_SCOPED_TABLES: &[&str] = &[ + "mention_group_commands", + "mention_groups", "nip_fi_profile_heads", "api_tokens", "archived_identities", @@ -141,8 +143,6 @@ pub const PENDING_SCOPED_TABLES: &[&str] = &[ "identity_retirement_actions", "identity_retirement_holds", "identity_retirement_workflows", - "mention_group_commands", - "mention_groups", ]; /// Tenant tables an expand migration may add between a deletion's approval @@ -180,6 +180,8 @@ const EXCLUDED_SCOPED_TABLES: &[&str] = &[ /// not matter, but the list must stay complete ([`EXPECTED_SCOPED_TABLES`] /// gates it). pub const PURGE_SCOPED_TABLES: &[&str] = &[ + "mention_group_commands", + "mention_groups", "nip_fi_profile_heads", "personal_read_frontiers", "personal_read_accounts", @@ -4823,11 +4825,20 @@ pub(crate) mod postgres_tests { }) .await .expect("connect isolated migration DB"); - // Stop just before the retirement migration so every current table - // exists and the universal fence objects are still present. + // Stop before retirement so the legacy universal fence objects remain + // available for both states of this test. crate::migration::run_migrations_through(&db.pool, 89) .await .expect("migrate with fence objects present"); + // Add the feature schema without running retirement: these tables + // never had universal fence objects, but current destruction requires + // them. This isolated fixture does not rerun the embedded migrator. + sqlx::raw_sql(include_str!( + "../../../../migrations/0093_mention_groups.sql" + )) + .execute(&db.pool) + .await + .expect("expand current feature schema while preserving legacy fences"); let store = db.deletion_store(); let community = db .ensure_configured_community("optional-fences.example") @@ -9480,6 +9491,99 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); .expect("count relay admin rows") } + /// The feature tables use real admitted writers and are purged only for + /// the deleted tenant; a bystander's identical command and UUID survive. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn mention_groups_refuse_fenced_writes_and_purge_tenant_rows() { + use buzz_core::mention_group::parse_command; + use nostr::{EventBuilder, Keys, Kind, Tag}; + let (db, store) = store().await; + let (request, inventory) = inventoried_request(&db, &store).await; + let bystander = db + .ensure_configured_community(&format!( + "mention-bystander-{}.example", + Uuid::new_v4().simple() + )) + .await + .expect("create bystander") + .id; + let actor = Keys::generate(); + let relay = Keys::generate(); + let group = Uuid::new_v4(); + let event = EventBuilder::new( + Kind::Custom(buzz_core::kind::RELAY_ADMIN_PUT_MENTION_GROUP as u16), + "", + ) + .tags([ + Tag::parse(["d", &group.to_string()]).expect("d tag"), + Tag::parse(["prev", "0"]).expect("prev tag"), + Tag::parse(["name", "Same group"]).expect("name tag"), + ]) + .sign_with_keys(&actor) + .expect("sign command"); + let command = parse_command(&event).expect("parse command"); + for community in [request.community_id, bystander] { + db.accept_mention_group(community, &event, &command, &relay, 1_000_000, false) + .await + .expect("admitted group write"); + } + store + .approve(request.id, "approver", None) + .await + .expect("approve"); + let claim = store + .claim_specific(request.id, "executor", DEFAULT_LEASE_DURATION) + .await + .expect("claim") + .expect("won claim"); + store.begin_quiescing(&claim.lease).await.expect("quiesce"); + assert!( + db.accept_mention_group( + request.community_id, + &event, + &command, + &relay, + 1_000_000, + false + ) + .await + .is_err(), + "even accepted receipts do not bypass the deletion fence" + ); + let generation = store.fence(&claim.lease).await.expect("fence"); + let token = LeaseToken { + fence_generation: Some(generation), + ..claim.lease + }; + store + .freeze_destructive_storage_manifest(&token, &inventory.storage) + .await + .expect("storage manifest"); + store.mark_drained(&token).await.expect("drain"); + store + .mark_bindings_removed(&token, serde_json::json!({"keys": 0})) + .await + .expect("bindings"); + let deleted = store.purge_postgres(&token).await.expect("purge"); + assert_eq!(deleted.get("mention_groups"), Some(&1)); + assert_eq!(deleted.get("mention_group_commands"), Some(&1)); + store + .mark_cache_purged(&token, serde_json::json!({"keys": 0})) + .await + .expect("cache"); + store + .verify_postgres_logically_deleted(&token) + .await + .expect("verify"); + let kept: (i64, i64, i64) = sqlx::query_as( + "SELECT (SELECT count(*) FROM mention_groups WHERE community_id=$1), \ + (SELECT count(*) FROM mention_group_commands WHERE community_id=$1), \ + (SELECT count(*) FROM events WHERE community_id=$1 AND kind=39010 AND deleted_at IS NULL)", + ).bind(bystander.as_uuid()).fetch_one(&db.pool).await.expect("bystander rows"); + assert_eq!(kept, (1, 1, 1)); + } + /// A deletion inventoried before a later release's expand migration and /// executed after it: each pending table is accepted absent and present, /// purged for the target community only, and proven empty, while a table diff --git a/crates/buzz-db/src/store/mention_group.rs b/crates/buzz-db/src/store/mention_group.rs new file mode 100644 index 00000000000..e4aef6f52e5 --- /dev/null +++ b/crates/buzz-db/src/store/mention_group.rs @@ -0,0 +1,561 @@ +//! Atomic community Mention Group and management-policy acceptance. +//! +//! Unused IDs become live at version one; live IDs advance by exact CAS; +//! deleted IDs stay retired. Accepted command receipts survive every later +//! revision, so an uncertain retry never becomes another logical write. + +use buzz_core::mention_group::{ + parse_command, parse_policy_command, Command, Manage, Operation, PolicyCommand, +}; +use buzz_core::{CommunityId, StoredEvent}; +use chrono::{DateTime, Utc}; +use nostr::{Event, EventBuilder, Keys, Kind, Tag, Timestamp}; +use serde::{Deserialize, Serialize}; +use sqlx::Row; +use std::collections::{BTreeMap, HashSet}; +use uuid::Uuid; + +use crate::{AdmittedTx, Db, DbError, Result}; + +/// Result of a group or management-policy command. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum GroupOutcome { + /// Row, receipt and signed state were committed together. + Applied, + /// This exact signed command was already committed; no new state is emitted. + Duplicate, + /// The expected version does not match a live group or current policy. + Conflict, + /// Another live group already owns this name in the community. + NameTaken, + /// Current community authority does not permit this command. + Forbidden, +} + +/// Bounded accounting of default-channel joins, retained in the command receipt. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct JoinSummary { + /// Membership rows newly inserted or reactivated. + pub joined: usize, + /// Number of skipped target/channel pairs, keyed by stable public reason. + pub skipped: BTreeMap, +} + +impl JoinSummary { + pub(crate) fn skip(&mut self, reason: &str, count: usize) { + if count > 0 { + *self.skipped.entry(reason.into()).or_default() += count; + } + } +} + +/// Committed command result; only a fresh acceptance returns a fanout snapshot. +#[derive(Debug)] +pub struct GroupWrite { + /// Durable outcome. + pub outcome: GroupOutcome, + /// Already committed relay-signed state, safe to fan out after returning. + pub snapshot: Option, + /// Channels whose real membership rows changed in the committed transaction. + pub joined_channels: Vec, + /// Newly inserted/reactivated target keys by channel, for postcommit notices. + pub joined_members: Vec<(Uuid, Vec)>, + /// Original join accounting, also returned for a durable identical retry. + pub joins: JoinSummary, +} + +impl GroupWrite { + fn without_snapshot(outcome: GroupOutcome) -> Self { + Self { + outcome, + snapshot: None, + joined_channels: Vec::new(), + joined_members: Vec::new(), + joins: JoinSummary::default(), + } + } +} + +impl Db { + /// Look up durable acceptance before transport freshness checks. + /// + /// This read grants no permission to execute an unrecognized command. + pub async fn mention_group_command_accepted( + &self, + community: CommunityId, + event_id: &[u8], + ) -> Result { + let mut conn = crate::observability::acquire_writer( + &self.pool, + crate::observability::WriterOperation::EventWrite, + ) + .await?; + receipt_exists(&mut conn, community, event_id).await + } + + /// Compare and atomically commit a normalized group command and signed head. + /// + /// `command` must be parsed from `event` by the shared protocol validator. + /// Every non-applied outcome leaves both canonical state and receipts intact. + pub async fn accept_mention_group( + &self, + community: CommunityId, + event: &Event, + command: &Command, + relay_keys: &Keys, + max_message_length: usize, + membership_enforced: bool, + ) -> Result { + let parsed = parse_command(event).map_err(DbError::InvalidData)?; + if &parsed != command { + return Err(DbError::InvalidData( + "mention group command differs from signed event".into(), + )); + } + let mut tx = self.begin_event_write_transaction(community).await?; + lock_community(&mut tx).await?; + if let Some(joins) = receipt_summary(tx.conn(), community, event.id.as_bytes()).await? { + let mut result = GroupWrite::without_snapshot(GroupOutcome::Duplicate); + result.joins = joins; + return Ok(result); + } + if !authorize_command(&mut tx, event, false, membership_enforced).await? { + return Ok(GroupWrite::without_snapshot(GroupOutcome::Forbidden)); + } + let head = sqlx::query( + "SELECT name, members, version, deleted_at FROM mention_groups \ + WHERE community_id=$1 AND id=$2 FOR UPDATE", + ) + .bind(community.as_uuid()) + .bind(command.id) + .fetch_optional(tx.conn()) + .await?; + let current = head + .as_ref() + .map(|r| r.try_get::("version")) + .transpose()?; + let deleted = head + .as_ref() + .map(|r| r.try_get::>, _>("deleted_at")) + .transpose()? + .flatten() + .is_some(); + if deleted + || current.unwrap_or(0) != command.prev + || (head.is_none() && matches!(command.operation, Operation::Delete)) + { + return Ok(GroupWrite::without_snapshot(GroupOutcome::Conflict)); + } + let version = current + .unwrap_or(0) + .checked_add(1) + .ok_or_else(|| DbError::InvalidData("mention group version exhausted".into()))?; + let (name, members, channels, operation, deleting) = match &command.operation { + Operation::Put { + name, + members, + channels, + } => ( + name.clone(), + members.clone(), + channels.clone(), + "put", + false, + ), + Operation::Delete => ( + head.as_ref() + .ok_or_else(|| DbError::InvalidData("missing group".into()))? + .try_get("name")?, + Vec::new(), + Vec::new(), + "delete", + true, + ), + }; + let mut tags = base_tags(&command.id.to_string(), version, event)?; + if deleting { + tags.push(tag(["deleted", "true"])?); + } else { + tags.push(tag(["name", name.as_str()])?); + for member in &members { + tags.push(tag(["p", member.as_str()])?); + } + } + for channel in &channels { + tags.push(tag(["channel", &channel.to_string()])?); + } + let old_members: Vec = head + .as_ref() + .map(|row| row.try_get("members")) + .transpose()? + .unwrap_or_default(); + let old_members: HashSet<&str> = old_members.iter().map(String::as_str).collect(); + let added: Vec> = members + .iter() + .filter(|key| !old_members.contains(key.as_str())) + .map(|key| { + hex::decode(key).map_err(|_| DbError::InvalidData("invalid member key".into())) + }) + .collect::>()?; + // Build and bound the final signed projection before changing any row. + let state = build_snapshot( + &mut tx, + relay_keys, + &command.id.to_string(), + tags, + max_message_length, + ) + .await?; + let (joined_channels, joined_members, joins) = + crate::channel_members::put_group_default_members_in_transaction( + &mut tx, + &channels, + &added, + &event.pubkey.to_bytes(), + membership_enforced, + ) + .await?; + let result = sqlx::query( + "INSERT INTO mention_groups (community_id,id,name,members,channels,version,deleted_at,state_event_id) \ + VALUES ($1,$2,$3,$4,$5,$6,CASE WHEN $7 THEN clock_timestamp() END,$8) \ + ON CONFLICT (community_id,id) DO UPDATE SET name=EXCLUDED.name,members=EXCLUDED.members,\ + channels=EXCLUDED.channels,version=EXCLUDED.version,deleted_at=EXCLUDED.deleted_at,state_event_id=EXCLUDED.state_event_id,\ + updated_at=clock_timestamp()", + ).bind(community.as_uuid()).bind(command.id).bind(&name).bind(&members).bind(&channels).bind(version) + .bind(deleting).bind(state.id.as_bytes().as_slice()).execute(tx.conn()).await; + if let Err(error) = result { + if matches!(&error, sqlx::Error::Database(db) + if db.code().as_deref() == Some("23505") && db.constraint() == Some("idx_mention_groups_live_name")) + { + // PostgreSQL has aborted this transaction; rollback before reporting a collision. + tx.rollback().await?; + return Ok(GroupWrite::without_snapshot(GroupOutcome::NameTaken)); + } + return Err(error.into()); + } + let snapshot = persist_snapshot(&mut tx, state).await?; + record_receipt( + &mut tx, + event, + Some(command.id), + operation, + version, + &snapshot, + &joins, + ) + .await?; + tx.commit().await?; + Ok(GroupWrite { + outcome: GroupOutcome::Applied, + snapshot: Some(snapshot), + joined_channels, + joined_members, + joins, + }) + } + + /// Compare and atomically commit the community's group-management policy. + /// + /// An untouched community has `everyone`, version zero and no published head; + /// the first policy command uses `prev=0` and publishes settings version one. + pub async fn accept_mention_group_policy( + &self, + community: CommunityId, + event: &Event, + command: &PolicyCommand, + relay_keys: &Keys, + max_message_length: usize, + membership_enforced: bool, + ) -> Result { + let parsed = parse_policy_command(event).map_err(DbError::InvalidData)?; + if &parsed != command { + return Err(DbError::InvalidData( + "mention group policy differs from signed event".into(), + )); + } + let mut tx = self.begin_event_write_transaction(community).await?; + lock_community(&mut tx).await?; + if let Some(joins) = receipt_summary(tx.conn(), community, event.id.as_bytes()).await? { + let mut result = GroupWrite::without_snapshot(GroupOutcome::Duplicate); + result.joins = joins; + return Ok(result); + } + if !authorize_command(&mut tx, event, true, membership_enforced).await? { + return Ok(GroupWrite::without_snapshot(GroupOutcome::Forbidden)); + } + let current: i64 = + sqlx::query_scalar("SELECT mention_groups_version FROM communities WHERE id=$1") + .bind(community.as_uuid()) + .fetch_one(tx.conn()) + .await?; + if current != command.prev { + return Ok(GroupWrite::without_snapshot(GroupOutcome::Conflict)); + } + let version = current + .checked_add(1) + .ok_or_else(|| DbError::InvalidData("mention group policy version exhausted".into()))?; + let manage = match command.manage { + Manage::Admins => "admins", + Manage::Everyone => "everyone", + }; + let mut tags = base_tags("settings", version, event)?; + tags.push(tag(["manage", manage])?); + let state = + build_snapshot(&mut tx, relay_keys, "settings", tags, max_message_length).await?; + sqlx::query("UPDATE communities SET mention_groups_manage=$2,mention_groups_version=$3,mention_groups_state_event_id=$4 WHERE id=$1") + .bind(community.as_uuid()).bind(manage).bind(version).bind(state.id.as_bytes().as_slice()) + .execute(tx.conn()).await?; + let snapshot = persist_snapshot(&mut tx, state).await?; + record_receipt( + &mut tx, + event, + None, + "policy", + version, + &snapshot, + &JoinSummary::default(), + ) + .await?; + tx.commit().await?; + Ok(GroupWrite { + outcome: GroupOutcome::Applied, + snapshot: Some(snapshot), + joined_channels: Vec::new(), + joined_members: Vec::new(), + joins: JoinSummary::default(), + }) + } +} + +async fn lock_community(tx: &mut AdmittedTx) -> Result<()> { + sqlx::query("SET LOCAL statement_timeout='5s'") + .execute(tx.conn()) + .await?; + // The same lock owner transitions use: policy changes and group writes see + // one order, and compatible FK key-share locks cannot create a lock cycle. + sqlx::query("SELECT id FROM communities WHERE id=$1 FOR NO KEY UPDATE") + .bind(tx.community().as_uuid()) + .fetch_one(tx.conn()) + .await?; + Ok(()) +} + +// Every mutable membership decision is held through commit. Agent ownership +// itself is immutable; a stored owner only supplies admission under Everyone, +// never an inherited administrator role. +async fn authorize_command( + tx: &mut AdmittedTx, + event: &Event, + policy_change: bool, + membership_enforced: bool, +) -> Result { + let community = tx.community(); + let actor = event.pubkey.to_hex(); + let own_role: Option = sqlx::query_scalar( + "SELECT role FROM relay_members WHERE community_id=$1 AND pubkey=$2 FOR SHARE", + ) + .bind(community.as_uuid()) + .bind(&actor) + .fetch_optional(tx.conn()) + .await?; + let steward = matches!(own_role.as_deref(), Some("owner" | "admin")); + if steward { + return Ok(true); + } + if policy_change { + let stewards = sqlx::query( + "SELECT pubkey FROM relay_members WHERE community_id=$1 AND role IN ('owner','admin') ORDER BY pubkey FOR SHARE", + ).bind(community.as_uuid()).fetch_all(tx.conn()).await?; + if !stewards.is_empty() { + return Ok(false); + } + } else { + let manage: String = + sqlx::query_scalar("SELECT mention_groups_manage FROM communities WHERE id=$1") + .bind(community.as_uuid()) + .fetch_one(tx.conn()) + .await?; + match manage.as_str() { + "admins" => return Ok(false), + "everyone" => {} + _ => { + return Err(DbError::InvalidData( + "unknown mention group management policy".into(), + )) + } + } + } + if !membership_enforced || own_role.is_some() { + return Ok(true); + } + let owner: Option> = sqlx::query_scalar( + "SELECT agent_owner_pubkey FROM users WHERE community_id=$1 AND pubkey=$2", + ) + .bind(community.as_uuid()) + .bind(event.pubkey.to_bytes().as_slice()) + .fetch_optional(tx.conn()) + .await? + .flatten(); + let Some(owner) = owner else { + return Ok(false); + }; + let owner_role: Option = sqlx::query_scalar( + "SELECT role FROM relay_members WHERE community_id=$1 AND pubkey=$2 FOR SHARE", + ) + .bind(community.as_uuid()) + .bind(hex::encode(owner)) + .fetch_optional(tx.conn()) + .await?; + Ok(owner_role.is_some()) +} + +async fn receipt_exists( + conn: &mut sqlx::PgConnection, + community: CommunityId, + id: &[u8], +) -> Result { + Ok(sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM mention_group_commands WHERE community_id=$1 AND event_id=$2)", + ) + .bind(community.as_uuid()) + .bind(id) + .fetch_one(conn) + .await?) +} + +async fn receipt_summary( + conn: &mut sqlx::PgConnection, + community: CommunityId, + id: &[u8], +) -> Result> { + let summary: Option = sqlx::query_scalar( + "SELECT join_summary FROM mention_group_commands WHERE community_id=$1 AND event_id=$2", + ) + .bind(community.as_uuid()) + .bind(id) + .fetch_optional(conn) + .await?; + summary + .map(serde_json::from_value) + .transpose() + .map_err(Into::into) +} + +fn tag(values: [&str; N]) -> Result { + Tag::parse(values).map_err(|e| DbError::InvalidData(format!("invalid mention group tag: {e}"))) +} + +fn base_tags(coordinate: &str, version: i64, command: &Event) -> Result> { + Ok(vec![ + tag(["-"])?, + tag(["d", coordinate])?, + tag(["version", &version.to_string()])?, + tag(["command", &command.id.to_hex()])?, + ]) +} + +async fn build_snapshot( + tx: &mut AdmittedTx, + keys: &Keys, + coordinate: &str, + tags: Vec, + max_message_length: usize, +) -> Result { + let community = tx.community(); + let kind = buzz_core::kind::KIND_MENTION_GROUP_STATE as i32; + let pubkey = keys.public_key().to_bytes(); + let key = crate::replaceable::event_replacement_lock_key( + community, + kind, + &pubkey, + Some(coordinate.as_bytes()), + ); + sqlx::query("SELECT pg_advisory_xact_lock($1)") + .bind(key) + .execute(tx.conn()) + .await?; + // Retired heads count: same-second commands must still replace correctly. + let latest: Option> = sqlx::query_scalar( + "SELECT max(created_at) FROM events WHERE community_id=$1 AND kind=$2 AND pubkey=$3 AND d_tag=$4", + ).bind(community.as_uuid()).bind(kind).bind(pubkey.as_slice()).bind(coordinate) + .fetch_one(tx.conn()).await?; + let now = i64::try_from(Timestamp::now().as_secs()) + .map_err(|_| DbError::InvalidTimestamp(i64::MAX))?; + let seconds = latest + .map(|value| { + value + .timestamp() + .checked_add(1) + .ok_or(DbError::InvalidTimestamp(i64::MAX)) + }) + .transpose()? + .unwrap_or(now) + .max(now); + let event = EventBuilder::new(Kind::Custom(kind as u16), "") + .tags(tags) + .allow_self_tagging() + .custom_created_at(Timestamp::from(seconds as u64)) + .sign_with_keys(keys) + .map_err(|e| DbError::InvalidData(format!("mention group signing failed: {e}")))?; + if serde_json::to_vec(&serde_json::json!(["EVENT", &event]))?.len() > max_message_length { + return Err(DbError::InvalidData( + "mention group state exceeds maximum message length".into(), + )); + } + Ok(event) +} + +async fn persist_snapshot(tx: &mut AdmittedTx, event: Event) -> Result { + let community = tx.community(); + let kind = buzz_core::kind::KIND_MENTION_GROUP_STATE as i32; + let pubkey = event.pubkey.to_bytes(); + let coordinate = crate::event::extract_d_tag(&event) + .ok_or_else(|| DbError::InvalidData("mention group state missing coordinate".into()))?; + let seconds = i64::try_from(event.created_at.as_secs()) + .map_err(|_| DbError::InvalidTimestamp(i64::MAX))?; + let created_at = + DateTime::from_timestamp(seconds, 0).ok_or(DbError::InvalidTimestamp(seconds))?; + let received_at = Utc::now(); + sqlx::query(superseded_with_mentions_sql!( + "UPDATE events SET deleted_at=NOW() WHERE community_id=$1 AND kind=$2 AND pubkey=$3 AND d_tag=$4 AND deleted_at IS NULL" + )).bind(community.as_uuid()).bind(kind).bind(pubkey.as_slice()).bind(&coordinate).execute(tx.conn()).await?; + sqlx::query( + "INSERT INTO events (community_id,id,pubkey,created_at,kind,tags,content,sig,received_at,channel_id,d_tag) \ + VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,NULL,$10)", + ).bind(community.as_uuid()).bind(event.id.as_bytes().as_slice()).bind(pubkey.as_slice()) + .bind(created_at).bind(kind).bind(serde_json::to_value(&event.tags)?).bind(&event.content) + .bind(event.sig.serialize().as_slice()).bind(received_at).bind(&coordinate).execute(tx.conn()).await?; + crate::insert_mentions_in_transaction(tx, &event, None).await?; + crate::store::event_follow_up::after_admitted_insert( + tx, + event.id.as_bytes(), + created_at, + kind, + None, + ) + .await?; + Ok(StoredEvent::with_received_at( + event, + received_at, + None, + true, + )) +} + +async fn record_receipt( + tx: &mut AdmittedTx, + event: &Event, + group: Option, + operation: &str, + version: i64, + snapshot: &StoredEvent, + joins: &JoinSummary, +) -> Result<()> { + sqlx::query( + "INSERT INTO mention_group_commands (community_id,event_id,signer,group_id,operation,version,state_event_id,command,join_summary) \ + VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)", + ).bind(tx.community().as_uuid()).bind(event.id.as_bytes().as_slice()).bind(event.pubkey.to_hex()) + .bind(group).bind(operation).bind(version).bind(snapshot.event.id.as_bytes().as_slice()) + .bind(serde_json::to_value(event)?).bind(serde_json::to_value(joins)?).execute(tx.conn()).await?; + Ok(()) +} diff --git a/crates/buzz-db/src/store/mention_group_postgres_tests.rs b/crates/buzz-db/src/store/mention_group_postgres_tests.rs new file mode 100644 index 00000000000..45a33cf266d --- /dev/null +++ b/crates/buzz-db/src/store/mention_group_postgres_tests.rs @@ -0,0 +1,619 @@ +//! Storage-boundary journeys: CAS, durable retry, atomic failure and isolation. + +use super::mention_group::GroupOutcome; +use crate::Db; +use buzz_core::mention_group::{parse_command, parse_policy_command}; +use buzz_core::{CommunityId, StoredEvent}; +use nostr::{Event, EventBuilder, Keys, Kind, Tag}; +use sqlx::{PgPool, Row}; +use uuid::Uuid; + +struct Fixture { + db: Db, + community: CommunityId, + actor: Keys, + relay: Keys, +} + +impl Fixture { + async fn new() -> Self { + let pool = PgPool::connect(&crate::test_support::database_url()) + .await + .unwrap(); + if std::env::var("BUZZ_TEST_SCHEMA_MODE").as_deref() != Ok("desired") { + crate::migration::run_migrations(&pool).await.unwrap(); + } + let community = CommunityId::from_uuid(Uuid::new_v4()); + let actor = Keys::generate(); + sqlx::query("INSERT INTO communities (id,host) VALUES ($1,$2)") + .bind(community.as_uuid()) + .bind(format!( + "mention-groups-{}.example.org", + community.as_uuid() + )) + .execute(&pool) + .await + .unwrap(); + sqlx::query("INSERT INTO relay_members (community_id,pubkey,role) VALUES ($1,$2,'owner')") + .bind(community.as_uuid()) + .bind(actor.public_key().to_hex()) + .execute(&pool) + .await + .unwrap(); + Self { + db: Db::from_pool(pool), + community, + actor, + relay: Keys::generate(), + } + } + + fn put(&self, id: Uuid, prev: i64, name: &str, members: &[String]) -> Event { + let mut tags = vec![ + vec!["d".into(), id.to_string()], + vec!["prev".into(), prev.to_string()], + vec!["name".into(), name.into()], + ]; + tags.extend( + members + .iter() + .map(|member| vec!["p".into(), member.clone()]), + ); + self.event(buzz_core::kind::RELAY_ADMIN_PUT_MENTION_GROUP, tags) + } + + fn delete(&self, id: Uuid, prev: i64) -> Event { + self.event( + buzz_core::kind::RELAY_ADMIN_DELETE_MENTION_GROUP, + vec![ + vec!["d".into(), id.to_string()], + vec!["prev".into(), prev.to_string()], + ], + ) + } + + fn event(&self, kind: u32, tags: Vec>) -> Event { + EventBuilder::new(Kind::Custom(kind as u16), "") + .tags(tags.into_iter().map(|tag| Tag::parse(tag).unwrap())) + .allow_self_tagging() + .sign_with_keys(&self.actor) + .unwrap() + } + + async fn apply(&self, event: &Event) -> crate::Result { + self.db + .accept_mention_group( + self.community, + event, + &parse_command(event).unwrap(), + &self.relay, + 1_000_000, + true, + ) + .await + } + + async fn state(&self, id: Uuid) -> (i64, bool, Vec) { + let row = sqlx::query("SELECT version,deleted_at IS NOT NULL AS deleted,state_event_id FROM mention_groups WHERE community_id=$1 AND id=$2") + .bind(self.community.as_uuid()).bind(id).fetch_one(self.db.pool()).await.unwrap(); + ( + row.get("version"), + row.get("deleted"), + row.get("state_event_id"), + ) + } + + async fn live_heads(&self, id: Uuid) -> i64 { + sqlx::query_scalar("SELECT count(*) FROM events WHERE community_id=$1 AND kind=39010 AND d_tag=$2 AND deleted_at IS NULL") + .bind(self.community.as_uuid()).bind(id.to_string()).fetch_one(self.db.pool()).await.unwrap() + } +} + +fn applied(write: super::mention_group::GroupWrite) -> StoredEvent { + assert_eq!(write.outcome, GroupOutcome::Applied); + let snapshot = write.snapshot.unwrap(); + snapshot.event.verify().unwrap(); + assert!(snapshot.channel_id.is_none()); + snapshot +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn mention_group_lifecycle_keeps_receipts_and_live_tombstones() { + let f = Fixture::new().await; + let id = Uuid::new_v4(); + let mut members: Vec = (0..40) + .map(|_| Keys::generate().public_key().to_hex()) + .collect(); + members.push(f.relay.public_key().to_hex()); + members.push(members[0].clone()); + let create = f.put(id, 0, " On call ", &members); + let first = applied(f.apply(&create).await.unwrap()); + let row = + sqlx::query("SELECT name,members FROM mention_groups WHERE community_id=$1 AND id=$2") + .bind(f.community.as_uuid()) + .bind(id) + .fetch_one(f.db.pool()) + .await + .unwrap(); + assert_eq!(row.get::("name"), "On call"); + let stored: Vec = row.get("members"); + members.sort(); + members.dedup(); + assert_eq!(stored, members); + let published: Vec = first + .event + .tags + .iter() + .filter_map(|tag| { + let fields = tag.as_slice(); + (fields.first().map(String::as_str) == Some("p")).then(|| fields[1].clone()) + }) + .collect(); + assert_eq!( + published, members, + "relay-key membership must survive signing" + ); + let edit = f.put(id, 1, "Night shift", &[]); + let second = applied(f.apply(&edit).await.unwrap()); + assert!(second.event.created_at > first.event.created_at); + assert_eq!( + f.apply(&create).await.unwrap().outcome, + GroupOutcome::Duplicate + ); + assert_eq!( + f.apply(&f.delete(id, 1)).await.unwrap().outcome, + GroupOutcome::Conflict + ); + assert_eq!(f.state(id).await.0, 2); + let tombstone = applied(f.apply(&f.delete(id, 2)).await.unwrap()); + assert!(tombstone.event.created_at > second.event.created_at); + assert!(tombstone + .event + .tags + .iter() + .any(|tag| tag.as_slice() == ["deleted", "true"])); + assert!(!tombstone + .event + .tags + .iter() + .any(|tag| matches!(tag.as_slice()[0].as_str(), "name" | "p"))); + assert_eq!( + f.state(id).await, + (3, true, tombstone.event.id.to_bytes().to_vec()) + ); + assert_eq!(f.live_heads(id).await, 1); + assert_eq!( + f.apply(&f.put(id, 3, "Revive", &[])).await.unwrap().outcome, + GroupOutcome::Conflict + ); + assert_eq!( + f.apply(&edit).await.unwrap().outcome, + GroupOutcome::Duplicate + ); + applied( + f.apply(&f.put(Uuid::new_v4(), 0, "NIGHT SHIFT", &[])) + .await + .unwrap(), + ); + assert!(f + .db + .mention_group_command_accepted(f.community, create.id.as_bytes()) + .await + .unwrap()); + let old_mentions: i64 = sqlx::query_scalar( + "SELECT count(*) FROM event_mentions WHERE community_id=$1 AND event_id=$2", + ) + .bind(f.community.as_uuid()) + .bind(first.event.id.as_bytes().as_slice()) + .fetch_one(f.db.pool()) + .await + .unwrap(); + assert_eq!( + old_mentions, 0, + "retirement removes stale mention index entries" + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn mention_group_concurrent_cas_names_and_identical_retries_commit_once() { + let f = Fixture::new().await; + let id = Uuid::new_v4(); + let a = f.put(id, 0, "A", &[]); + let b = f.put(id, 0, "B", &[]); + let (a, b) = tokio::join!(f.apply(&a), f.apply(&b)); + let outcomes = [a.unwrap().outcome, b.unwrap().outcome]; + assert_eq!( + outcomes + .iter() + .filter(|v| **v == GroupOutcome::Applied) + .count(), + 1 + ); + assert!(outcomes.contains(&GroupOutcome::Conflict)); + let a = f.put(id, 1, "C", &[]); + let b = f.put(id, 1, "D", &[]); + let (a, b) = tokio::join!(f.apply(&a), f.apply(&b)); + let outcomes = [a.unwrap().outcome, b.unwrap().outcome]; + assert_eq!( + outcomes + .iter() + .filter(|v| **v == GroupOutcome::Applied) + .count(), + 1 + ); + assert!(outcomes.contains(&GroupOutcome::Conflict)); + let first_id = Uuid::new_v4(); + let second_id = Uuid::new_v4(); + let a = f.put(first_id, 0, "Shared", &[]); + let b = f.put(second_id, 0, "SHARED", &[]); + let (a, b) = tokio::join!(f.apply(&a), f.apply(&b)); + let outcomes = [a.unwrap().outcome, b.unwrap().outcome]; + assert_eq!( + outcomes + .iter() + .filter(|v| **v == GroupOutcome::Applied) + .count(), + 1 + ); + assert!(outcomes.contains(&GroupOutcome::NameTaken)); + let before = f.state(id).await; + assert_eq!( + f.apply(&f.put(id, 2, "shared", &[])).await.unwrap().outcome, + GroupOutcome::NameTaken + ); + assert_eq!(f.state(id).await, before, "rename collision must roll back"); + let retry = f.put(id, 2, "Final", &[]); + let (a, b) = tokio::join!(f.apply(&retry), f.apply(&retry)); + let outcomes = [a.unwrap().outcome, b.unwrap().outcome]; + assert!(outcomes.contains(&GroupOutcome::Applied)); + assert!(outcomes.contains(&GroupOutcome::Duplicate)); + assert_eq!(f.state(id).await.0, 3); + assert_eq!(f.live_heads(id).await, 1); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn mention_group_failures_roll_back_rows_receipts_and_retirement() { + let f = Fixture::new().await; + let id = Uuid::new_v4(); + let create = f.put(id, 0, "Stable", &[]); + let command = parse_command(&create).unwrap(); + assert!(f + .db + .accept_mention_group(f.community, &create, &command, &f.relay, 1, true) + .await + .is_err()); + assert_eq!(f.live_heads(id).await, 0); + assert!(!f + .db + .mention_group_command_accepted(f.community, create.id.as_bytes()) + .await + .unwrap()); + applied(f.apply(&create).await.unwrap()); + let before = f.state(id).await; + // A real database boundary failure after group/head writes must roll back + // canonical data, the previous-head retirement and the acceptance receipt. + sqlx::query("ALTER TABLE mention_group_commands ADD CONSTRAINT reject_second_revision CHECK (version < 2)") + .execute(f.db.pool()).await.unwrap(); + let update = f.put(id, 1, "Uncommitted", &[]); + assert!(f.apply(&update).await.is_err()); + assert_eq!(f.state(id).await, before); + assert_eq!(f.live_heads(id).await, 1); + assert!(!f + .db + .mention_group_command_accepted(f.community, update.id.as_bytes()) + .await + .unwrap()); + sqlx::query("ALTER TABLE mention_group_commands DROP CONSTRAINT reject_second_revision") + .execute(f.db.pool()) + .await + .unwrap(); + applied(f.apply(&update).await.unwrap()); + // Deferred uniqueness reaches COMMIT rather than the earlier INSERT. + sqlx::query("ALTER TABLE mention_group_commands ADD CONSTRAINT commit_failure UNIQUE (community_id,operation,version) DEFERRABLE INITIALLY DEFERRED") + .execute(f.db.pool()).await.unwrap(); + let other = Uuid::new_v4(); + let other_create = f.put(other, 0, "Commit failure", &[]); + assert!(f.apply(&other_create).await.is_err()); + assert_eq!(f.live_heads(other).await, 0); + let count: i64 = + sqlx::query_scalar("SELECT count(*) FROM mention_groups WHERE community_id=$1 AND id=$2") + .bind(f.community.as_uuid()) + .bind(other) + .fetch_one(f.db.pool()) + .await + .unwrap(); + assert_eq!(count, 0); + assert!(!f + .db + .mention_group_command_accepted(f.community, other_create.id.as_bytes()) + .await + .unwrap()); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn mention_group_policy_cas_uses_settings_coordinate_and_shared_receipts() { + let f = Fixture::new().await; + let defaults: (String,i64,Option>) = sqlx::query_as("SELECT mention_groups_manage,mention_groups_version,mention_groups_state_event_id FROM communities WHERE id=$1") + .bind(f.community.as_uuid()).fetch_one(f.db.pool()).await.unwrap(); + assert_eq!(defaults, ("everyone".into(), 0, None)); + let event = f.event( + buzz_core::kind::RELAY_ADMIN_SET_MENTION_GROUP_POLICY, + vec![ + vec!["manage".into(), "admins".into()], + vec!["prev".into(), "0".into()], + ], + ); + let command = parse_policy_command(&event).unwrap(); + let state = applied( + f.db.accept_mention_group_policy(f.community, &event, &command, &f.relay, 1_000_000, true) + .await + .unwrap(), + ); + assert!(state + .event + .tags + .iter() + .any(|tag| tag.as_slice() == ["d", "settings"])); + assert_eq!( + f.db.accept_mention_group_policy(f.community, &event, &command, &f.relay, 1_000_000, true) + .await + .unwrap() + .outcome, + GroupOutcome::Duplicate + ); + let stale = f.event( + buzz_core::kind::RELAY_ADMIN_SET_MENTION_GROUP_POLICY, + vec![ + vec!["manage".into(), "everyone".into()], + vec!["prev".into(), "0".into()], + ], + ); + assert_eq!( + f.db.accept_mention_group_policy( + f.community, + &stale, + &parse_policy_command(&stale).unwrap(), + &f.relay, + 1_000_000, + true, + ) + .await + .unwrap() + .outcome, + GroupOutcome::Conflict + ); + let groups: i64 = + sqlx::query_scalar("SELECT count(*) FROM mention_groups WHERE community_id=$1") + .bind(f.community.as_uuid()) + .fetch_one(f.db.pool()) + .await + .unwrap(); + assert_eq!(groups, 0, "settings must not create a fake group"); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn mention_group_default_joins_are_atomic_report_skips_and_never_replay() { + use buzz_core::channel::{ChannelType, ChannelVisibility}; + let f = Fixture::new().await; + let public = + f.db.create_channel( + f.community, + "Public", + ChannelType::Stream, + ChannelVisibility::Open, + None, + &f.actor.public_key().to_bytes(), + None, + ) + .await + .unwrap() + .id; + let archived = + f.db.create_channel( + f.community, + "Archived", + ChannelType::Forum, + ChannelVisibility::Open, + None, + &f.actor.public_key().to_bytes(), + None, + ) + .await + .unwrap() + .id; + f.db.archive_channel(f.community, archived).await.unwrap(); + let private = + f.db.create_channel( + f.community, + "Private", + ChannelType::Stream, + ChannelVisibility::Private, + None, + &f.actor.public_key().to_bytes(), + None, + ) + .await + .unwrap() + .id; + let gone = Uuid::new_v4(); + let target = Keys::generate(); + let blocked = Keys::generate(); + let removed = Keys::generate(); + let agent = Keys::generate(); + for key in [&target, &blocked, &removed] { + let _ = + f.db.add_relay_member( + f.community, + &key.public_key().to_hex(), + "member", + None, + &f.relay, + ) + .await + .unwrap(); + } + let _ = + f.db.remove_relay_member(f.community, &removed.public_key().to_hex(), &f.relay) + .await + .unwrap(); + f.db.ensure_user(f.community, &f.actor.public_key().to_bytes()) + .await + .unwrap(); + f.db.ensure_user(f.community, &agent.public_key().to_bytes()) + .await + .unwrap(); + f.db.set_agent_owner( + f.community, + &agent.public_key().to_bytes(), + &f.actor.public_key().to_bytes(), + ) + .await + .unwrap(); + f.db.ensure_user(f.community, &blocked.public_key().to_bytes()) + .await + .unwrap(); + f.db.set_channel_add_policy(f.community, &blocked.public_key().to_bytes(), "nobody") + .await + .unwrap(); + let id = Uuid::new_v4(); + let event = |prev: i64, name: &str, members: &[String], channels: &[Uuid]| { + let mut tags = vec![ + vec!["d".into(), id.to_string()], + vec!["prev".into(), prev.to_string()], + vec!["name".into(), name.into()], + ]; + tags.extend(members.iter().map(|key| vec!["p".into(), key.clone()])); + tags.extend( + channels + .iter() + .map(|channel| vec!["channel".into(), channel.to_string()]), + ); + f.event(buzz_core::kind::RELAY_ADMIN_PUT_MENTION_GROUP, tags) + }; + let members = vec![ + target.public_key().to_hex(), + blocked.public_key().to_hex(), + f.actor.public_key().to_hex(), + removed.public_key().to_hex(), + agent.public_key().to_hex(), + ]; + // A present private channel invalidates the configuration and commits no + // earlier join, even when a valid channel appears in the same command. + let invalid = event(0, "Invalid", &members, &[public, private]); + assert!(f.apply(&invalid).await.is_err()); + assert!(f + .db + .get_member_role(f.community, public, &target.public_key().to_bytes()) + .await + .unwrap() + .is_none()); + assert!(!f + .db + .mention_group_command_accepted(f.community, invalid.id.as_bytes()) + .await + .unwrap()); + let create = event(0, "Configured", &members, &[public, archived, gone]); + let accepted = f.apply(&create).await.unwrap(); + assert_eq!(accepted.outcome, GroupOutcome::Applied); + assert_eq!(accepted.joins.joined, 2); + assert!( + accepted + .joined_members + .contains(&(public, agent.public_key().to_bytes().to_vec())), + "an agent is admitted through its current owner without its own roster row" + ); + assert!(f + .db + .get_member_role(f.community, public, &removed.public_key().to_bytes()) + .await + .unwrap() + .is_none()); + assert_eq!(accepted.joins.skipped.get("target_not_admitted"), Some(&1)); + assert_eq!(accepted.joined_channels, vec![public]); + assert_eq!(accepted.joins.skipped.get("target_policy_nobody"), Some(&1)); + assert_eq!(accepted.joins.skipped.get("already_member"), Some(&1)); + assert_eq!(accepted.joins.skipped.get("channel_closed"), Some(&5)); + assert_eq!(accepted.joins.skipped.get("channel_unavailable"), Some(&5)); + assert_eq!( + f.db.get_member_role(f.community, public, &f.actor.public_key().to_bytes()) + .await + .unwrap() + .as_deref(), + Some("owner") + ); + f.db.remove_member( + f.community, + public, + &target.public_key().to_bytes(), + &f.actor.public_key().to_bytes(), + ) + .await + .unwrap(); + let replay = f.apply(&create).await.unwrap(); + assert_eq!(replay.outcome, GroupOutcome::Duplicate); + assert_eq!( + replay.joins, accepted.joins, + "retry retains original skip report" + ); + assert!(replay.joined_channels.is_empty()); + assert!( + f.db.get_member_role(f.community, public, &target.public_key().to_bytes()) + .await + .unwrap() + .is_none(), + "retry cannot undo a later leave" + ); + // Changing only group metadata/defaults does not re-add unchanged members. + let edit = event(1, "Renamed", &members, &[public, gone]); + let edited = f.apply(&edit).await.unwrap(); + assert_eq!(edited.outcome, GroupOutcome::Applied); + assert_eq!(edited.joins.joined, 0); + assert!(f + .db + .get_member_role(f.community, public, &target.public_key().to_bytes()) + .await + .unwrap() + .is_none()); + let retained: Vec = + sqlx::query_scalar("SELECT channels FROM mention_groups WHERE community_id=$1 AND id=$2") + .bind(f.community.as_uuid()) + .bind(id) + .fetch_one(f.db.pool()) + .await + .unwrap(); + assert!( + retained.contains(&gone), + "gone defaults remain inert saved references" + ); + let outsider = Keys::generate(); + let mut open_members = members.clone(); + open_members.push(outsider.public_key().to_hex()); + let open = event(2, "Open mode", &open_members, &[public]); + let open_result = + f.db.accept_mention_group( + f.community, + &open, + &parse_command(&open).unwrap(), + &f.relay, + 1_000_000, + false, + ) + .await + .unwrap(); + assert_eq!(open_result.outcome, GroupOutcome::Applied); + assert_eq!( + open_result.joins.joined, 1, + "open mode permits authenticated outside recipients" + ); + assert!(f + .db + .get_member_role(f.community, public, &outsider.public_key().to_bytes()) + .await + .unwrap() + .is_some()); +} diff --git a/crates/buzz-db/src/store/mod.rs b/crates/buzz-db/src/store/mod.rs index e9c2e0d72bb..ea0bcbce5a7 100644 --- a/crates/buzz-db/src/store/mod.rs +++ b/crates/buzz-db/src/store/mod.rs @@ -129,3 +129,9 @@ pub mod media; mod media_postgres_tests; #[cfg(test)] mod message_edit_state_postgres_tests; + +/// Relay-owned community Mention Groups and policy acceptance. +pub mod mention_group; + +#[cfg(test)] +mod mention_group_postgres_tests; diff --git a/crates/buzz-relay/src/api/bridge.rs b/crates/buzz-relay/src/api/bridge.rs index 3357dbf32b8..3bfcb959f03 100644 --- a/crates/buzz-relay/src/api/bridge.rs +++ b/crates/buzz-relay/src/api/bridge.rs @@ -1561,6 +1561,14 @@ async fn submit_event_authed( response: api_error(StatusCode::BAD_REQUEST, &msg), } } + Err(IngestError::GroupConflict(msg)) => { + crate::handlers::ingest::reject_with_transport("http", "invalid"); + SubmitOutcome::Rejected { + kind: kind_u32, + reason: "mention_group_conflict", + response: api_error(StatusCode::CONFLICT, &msg), + } + } Err(IngestError::CanvasConflict(msg)) => { // Canvas CAS precondition failures are a distinct HTTP 409 so the // CLI's reconciliation branch (which gates on `status == 409`) is diff --git a/crates/buzz-relay/src/conformance/mod.rs b/crates/buzz-relay/src/conformance/mod.rs index 0abeb15218b..f7bd340fc14 100644 --- a/crates/buzz-relay/src/conformance/mod.rs +++ b/crates/buzz-relay/src/conformance/mod.rs @@ -433,7 +433,7 @@ pub fn sanitized_reason_for(err: &crate::handlers::ingest::IngestError) -> Sanit use crate::handlers::ingest::IngestError as E; match err { E::Rejected(_) => SanitizedReason::Invalid, - E::CanvasConflict(_) => SanitizedReason::Invalid, + E::CanvasConflict(_) | E::GroupConflict(_) => SanitizedReason::Invalid, E::AuthFailed(_) => SanitizedReason::Restricted, E::Internal(_) => SanitizedReason::ServerError, // A ban refusal is sanitized as the error every transport sees. diff --git a/crates/buzz-relay/src/handlers/channel_authz.rs b/crates/buzz-relay/src/handlers/channel_authz.rs index 83f43b0464c..404cbece727 100644 --- a/crates/buzz-relay/src/handlers/channel_authz.rs +++ b/crates/buzz-relay/src/handlers/channel_authz.rs @@ -191,17 +191,17 @@ pub fn decide_channel_add_policy( owner: Option<&[u8]>, actor: &[u8], ) -> Result<(), ChannelAuthzError> { - match policy { - "owner_only" => { - let owner = owner.ok_or(ChannelAuthzError::PolicyOwnerOnlyNoOwner)?; - if actor != owner { - return Err(ChannelAuthzError::PolicyOwnerOnlyDenied); + buzz_core::channel::decide_channel_add_policy(policy, owner, actor).map_err(|denied| { + match denied { + buzz_core::channel::ChannelAddPolicyDenied::OwnerMissing => { + ChannelAuthzError::PolicyOwnerOnlyNoOwner } - Ok(()) + buzz_core::channel::ChannelAddPolicyDenied::OwnerOnly => { + ChannelAuthzError::PolicyOwnerOnlyDenied + } + buzz_core::channel::ChannelAddPolicyDenied::Nobody => ChannelAuthzError::PolicyNobody, } - "nobody" => Err(ChannelAuthzError::PolicyNobody), - _ => Ok(()), - } + }) } /// What authority `actor` holds to remove *somebody else* (kind:9001). diff --git a/crates/buzz-relay/src/handlers/command_executor.rs b/crates/buzz-relay/src/handlers/command_executor.rs index 750301ae7d5..ead63d66f24 100644 --- a/crates/buzz-relay/src/handlers/command_executor.rs +++ b/crates/buzz-relay/src/handlers/command_executor.rs @@ -1717,8 +1717,8 @@ mod postgres_tests { fn rejection_message(result: Result>, IngestError>) -> String { match result { Err(IngestError::Rejected(message)) => message, - Err(IngestError::CanvasConflict(message)) => { - panic!("unexpected canvas conflict: {message}") + Err(IngestError::CanvasConflict(message) | IngestError::GroupConflict(message)) => { + panic!("unexpected state conflict: {message}") } Err(IngestError::AuthFailed(message)) => panic!("unexpected auth failure: {message}"), Err(IngestError::Internal(message)) => panic!("unexpected internal failure: {message}"), diff --git a/crates/buzz-relay/src/handlers/event.rs b/crates/buzz-relay/src/handlers/event.rs index 781b3541c01..c83cc8758cd 100644 --- a/crates/buzz-relay/src/handlers/event.rs +++ b/crates/buzz-relay/src/handlers/event.rs @@ -781,7 +781,8 @@ pub async fn handle_event(event: Event, conn: Arc, state: Arc (m, "auth"), + | IngestError::CanvasConflict(m) + | IngestError::GroupConflict(m) => (m, "auth"), }; reject(reason); write.ok(&conn, &event_id_hex, false, &message); @@ -913,7 +914,9 @@ pub async fn handle_event(event: Event, conn: Arc, state: Arc (message, "invalid"), - IngestError::CanvasConflict(message) => (message, "invalid"), + IngestError::CanvasConflict(message) | IngestError::GroupConflict(message) => { + (message, "invalid") + } IngestError::AuthFailed(message) => (message, "auth"), IngestError::Internal(message) => (message, "error"), // `into_legacy` never returns `Ban`; it would fail closed here. @@ -986,7 +989,9 @@ pub async fn handle_event(event: Event, conn: Arc, state: Arc (m.clone(), "invalid"), - IngestError::CanvasConflict(m) => (m.clone(), "invalid"), + IngestError::CanvasConflict(m) | IngestError::GroupConflict(m) => { + (m.clone(), "invalid") + } IngestError::AuthFailed(m) => (m.clone(), "auth"), // `into_legacy` never returns `Ban`; it would fail closed here. IngestError::Internal(_) | IngestError::Ban { .. } => { diff --git a/crates/buzz-relay/src/handlers/ingest.rs b/crates/buzz-relay/src/handlers/ingest.rs index 2f2ce7257c9..9ee03ff5fca 100644 --- a/crates/buzz-relay/src/handlers/ingest.rs +++ b/crates/buzz-relay/src/handlers/ingest.rs @@ -492,6 +492,8 @@ pub enum IngestError { /// [`IngestError::Rejected`] so the HTTP bridge can map it to /// `409 CONFLICT` while generic client mistakes remain `400 BAD_REQUEST`. CanvasConflict(String), + /// Mention Group CAS or name collision — WS: OK false, HTTP: 409. + GroupConflict(String), /// Auth/scope error — WS: OK false, HTTP: 401/403. AuthFailed(String), /// Server error — WS: OK false, HTTP: 500. @@ -596,6 +598,7 @@ fn map_push_accept_error(error: super::push_lease::AcceptError) -> IngestError { /// Returns `Err` for unknown kinds — the relay rejects them. fn required_scope_for_kind(kind: u32, event: &Event) -> Result { match kind { + kind if super::mention_groups::is_command(kind) => Ok(Scope::UsersWrite), KIND_PROFILE => Ok(Scope::UsersWrite), KIND_TEXT_NOTE | KIND_LONG_FORM | buzz_core::kind::KIND_ARTIFACT => Ok(Scope::MessagesWrite), KIND_CONTACT_LIST | KIND_READ_STATE | KIND_USER_STATUS | KIND_AGENT_ENGRAM @@ -2640,6 +2643,19 @@ async fn ingest_event_inner( } let event = std::sync::Arc::try_unwrap(event).unwrap_or_else(|arc| (*arc).clone()); + if super::mention_groups::is_command(kind_u32) { + let result = super::mention_groups::accept(state, tenant, &event, &auth).await?; + emit( + tracer, + TraceAction::WriteInsertGlobal { + msg_id: msg_id_label(event.id.as_bytes()), + claimed_community: claimed_community_from_event(&event), + }, + state_for_request(tenant, auth.pubkey()), + ); + return Ok(result); + } + if kind_u32 == buzz_core::kind::KIND_ARTIFACT && event.pubkey == *auth.pubkey() && state diff --git a/crates/buzz-relay/src/handlers/mention_groups.rs b/crates/buzz-relay/src/handlers/mention_groups.rs new file mode 100644 index 00000000000..2619baa2c41 --- /dev/null +++ b/crates/buzz-relay/src/handlers/mention_groups.rs @@ -0,0 +1,207 @@ +//! NIP-MG commands: admission, atomic persistence and committed-state delivery. + +use std::sync::Arc; + +use buzz_auth::Scope; +use buzz_core::kind::{ + event_kind_u32, RELAY_ADMIN_DELETE_MENTION_GROUP, RELAY_ADMIN_PUT_MENTION_GROUP, + RELAY_ADMIN_SET_MENTION_GROUP_POLICY, +}; +use buzz_core::mention_group::{parse_command, parse_policy_command}; +use buzz_core::TenantContext; +use buzz_db::mention_group::{GroupOutcome, GroupWrite}; +use nostr::Event; + +use super::ingest::{IngestAuth, IngestError, IngestResult}; +use crate::state::AppState; + +/// Whether this kind is a direct community Mention Groups command. +pub(crate) fn is_command(kind: u32) -> bool { + matches!( + kind, + RELAY_ADMIN_PUT_MENTION_GROUP + | RELAY_ADMIN_DELETE_MENTION_GROUP + | RELAY_ADMIN_SET_MENTION_GROUP_POLICY + ) +} + +/// Accept a verified signature before generic freshness rejection, so a durable +/// receipt can settle an old exact retry without granting another mutation. +pub(crate) async fn accept( + state: &Arc, + tenant: &TenantContext, + event: &Event, + auth: &IngestAuth, +) -> Result { + if event.pubkey != *auth.pubkey() { + return Err(IngestError::AuthFailed( + "invalid: event pubkey does not match authenticated identity".into(), + )); + } + if auth.channel_ids().is_some() { + return Err(IngestError::AuthFailed( + "restricted: mention group commands require a global token".into(), + )); + } + if !auth.scopes().contains(&Scope::UsersWrite) { + return Err(IngestError::AuthFailed( + "restricted: insufficient scope (need users:write)".into(), + )); + } + super::ingest::enforce_write_restriction(state, tenant, event_kind_u32(event), auth.pubkey()) + .await?; + + let now = chrono::Utc::now().timestamp(); + if now.abs_diff(event.created_at.as_secs() as i64) > 120 + && !state + .db + .mention_group_command_accepted(tenant.community(), event.id.as_bytes()) + .await + .map_err(storage_error)? + { + return Err(IngestError::Rejected( + "invalid: mention group command timestamp out of range".into(), + )); + } + + let write = if event_kind_u32(event) == RELAY_ADMIN_SET_MENTION_GROUP_POLICY { + let command = parse_policy_command(event).map_err(invalid)?; + state + .db + .accept_mention_group_policy( + tenant.community(), + event, + &command, + &state.relay_keypair, + state.config.max_frame_bytes, + state.config.require_relay_membership, + ) + .await + } else { + let command = parse_command(event).map_err(invalid)?; + state + .db + .accept_mention_group( + tenant.community(), + event, + &command, + &state.relay_keypair, + state.config.max_frame_bytes, + state.config.require_relay_membership, + ) + .await + } + .map_err(storage_error)?; + finish(state, tenant, event, write).await +} + +fn invalid(reason: String) -> IngestError { + IngestError::Rejected(format!("invalid: {reason}")) +} + +fn storage_error(error: buzz_db::DbError) -> IngestError { + match error { + buzz_db::DbError::InvalidData(reason) => invalid(reason), + buzz_db::DbError::AccessDenied(reason) => { + IngestError::AuthFailed(format!("restricted: {reason}")) + } + error => IngestError::Internal(format!("error: mention group storage: {error}")), + } +} + +async fn finish( + state: &Arc, + tenant: &TenantContext, + event: &Event, + write: GroupWrite, +) -> Result { + match write.outcome { + GroupOutcome::Conflict => { + return Err(IngestError::GroupConflict( + "conflict: mention group version changed".into(), + )); + } + GroupOutcome::NameTaken => { + return Err(IngestError::GroupConflict( + "duplicate: mention group name already exists".into(), + )); + } + GroupOutcome::Forbidden => { + return Err(IngestError::AuthFailed( + "restricted: community policy does not permit this mention group command".into(), + )); + } + GroupOutcome::Applied | GroupOutcome::Duplicate => {} + } + let mut message = if write.outcome == GroupOutcome::Duplicate { + "duplicate:".to_owned() + } else { + String::new() + }; + if !write.joins.skipped.is_empty() { + let summary = serde_json::to_string(&write.joins) + .map_err(|error| IngestError::Internal(format!("error: join summary: {error}")))?; + if !message.is_empty() { + message.push(' '); + } + message.push_str("joins: "); + message.push_str(&summary); + } + if let Some(snapshot) = write.snapshot { + super::side_effects::fan_out_mention_group_state(tenant, state, &snapshot).await; + } + for (channel, target) in write.joined_members { + state.invalidate_membership(tenant, channel, &target); + if let Err(error) = super::side_effects::emit_system_message( + tenant, + state, + channel, + serde_json::json!({ + "type": "member_joined", + "actor": event.pubkey.to_hex(), + "target": hex::encode(&target), + }), + chrono::Utc::now(), + ) + .await + { + tracing::warn!(%channel, %error, "default-channel join notice delivery failed"); + } + match state.db.channel_type_of(tenant.community(), channel).await { + Ok(Some(channel_type)) => { + if let Err(error) = super::side_effects::emit_typed_membership_notification( + tenant, + state, + channel, + &channel_type, + &target, + event.pubkey.as_bytes(), + buzz_core::kind::KIND_MEMBER_ADDED_NOTIFICATION, + &[], + ) + .await + { + tracing::warn!(%channel, %error, "default-channel membership notification failed"); + } + } + Ok(None) => {} + Err(error) => { + tracing::warn!(%channel, %error, "default-channel membership type lookup failed"); + } + } + } + // Membership rows already committed. Reuse ordinary channel discovery + // publication; it also has the existing periodic reconciliation owner. + for channel in write.joined_channels { + if let Err(error) = + super::side_effects::emit_group_discovery_events(tenant, state, channel).await + { + tracing::warn!(%channel, %error, "default-channel discovery delivery failed"); + } + } + Ok(IngestResult { + event_id: event.id.to_hex(), + accepted: true, + message, + }) +} diff --git a/crates/buzz-relay/src/handlers/mention_groups_postgres_tests.rs b/crates/buzz-relay/src/handlers/mention_groups_postgres_tests.rs new file mode 100644 index 00000000000..c7e0c8e3c9e --- /dev/null +++ b/crates/buzz-relay/src/handlers/mention_groups_postgres_tests.rs @@ -0,0 +1,448 @@ +//! NIP-MG admission regressions through the production ingest and REQ seams. +//! Run against the feature schema with BUZZ_TEST_DATABASE_URL set. + +use std::sync::Arc; +use std::time::Duration; + +use buzz_auth::Scope; +use buzz_core::kind::{ + KIND_MENTION_GROUP_STATE, RELAY_ADMIN_PUT_MENTION_GROUP, RELAY_ADMIN_SET_MENTION_GROUP_POLICY, +}; +use buzz_core::TenantContext; +use buzz_db::event::EventQuery; +use nostr::{Event, EventBuilder, Keys, Kind, Tag, Timestamp}; +use serde_json::json; +use uuid::Uuid; + +use super::group_state_postgres_tests::{community, req_event_ids, state}; +use super::ingest::{ingest_event, HttpAuthMethod, IngestAuth, IngestError}; +use crate::state::AppState; + +fn auth(keys: &Keys) -> IngestAuth { + IngestAuth::Http { + pubkey: keys.public_key(), + scopes: vec![Scope::UsersWrite], + auth_method: HttpAuthMethod::Nip98, + } +} + +fn put_at(keys: &Keys, id: Uuid, prev: i64, name: &str, timestamp: u64) -> Event { + EventBuilder::new(Kind::Custom(RELAY_ADMIN_PUT_MENTION_GROUP as u16), "") + .custom_created_at(Timestamp::from(timestamp)) + .allow_self_tagging() + .tags([ + Tag::parse(["d", &id.to_string()]).unwrap(), + Tag::parse(["prev", &prev.to_string()]).unwrap(), + Tag::parse(["name", name]).unwrap(), + Tag::public_key(keys.public_key()), + ]) + .sign_with_keys(keys) + .unwrap() +} + +fn put(keys: &Keys, id: Uuid, prev: i64, name: &str) -> Event { + put_at(keys, id, prev, name, Timestamp::now().as_secs()) +} + +async fn head(state: &AppState, tenant: &TenantContext, id: Uuid) -> Option { + let events = state + .db + .query_events(&EventQuery { + kinds: Some(vec![KIND_MENTION_GROUP_STATE as i32]), + d_tag: Some(id.to_string()), + limit: Some(1), + ..EventQuery::for_community(tenant.community()) + }) + .await + .unwrap(); + events.into_iter().next().map(|stored| stored.event) +} + +async fn receipt(state: &AppState, tenant: &TenantContext, event: &Event) -> bool { + state + .db + .mention_group_command_accepted(tenant.community(), event.id.as_bytes()) + .await + .unwrap() +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn signed_actor_global_token_and_users_write_scope_are_required_even_for_retries() { + let state = state().await; + let tenant = community(&state, "mg-admission").await; + let actor = Keys::generate(); + let other = Keys::generate(); + let id = Uuid::new_v4(); + let command = put(&actor, id, 0, "Support"); + let scoped = IngestAuth::Nip42 { + pubkey: actor.public_key(), + scopes: vec![Scope::UsersWrite], + channel_ids: Some(vec![Uuid::new_v4()]), + conn_id: Uuid::new_v4(), + }; + let no_users_write = IngestAuth::Http { + pubkey: actor.public_key(), + scopes: vec![Scope::MessagesWrite, Scope::AdminUsers], + auth_method: HttpAuthMethod::Nip98, + }; + for accepted in [false, true] { + for (context, reason) in [ + (auth(&other), "authenticated identity"), + (scoped.clone(), "global token"), + (no_users_write.clone(), "users:write"), + ] { + let error = ingest_event(&state, &tenant, command.clone(), context) + .await + .err() + .expect("expected refusal"); + assert!( + matches!(error, IngestError::AuthFailed(ref message) if message.contains(reason)), + "{error:?}" + ); + assert_eq!(receipt(&state, &tenant, &command).await, accepted); + } + if !accepted { + assert!(head(&state, &tenant, id).await.is_none()); + assert!( + ingest_event(&state, &tenant, command.clone(), auth(&actor)) + .await + .unwrap() + .accepted + ); + } + } + let current = head(&state, &tenant, id).await.unwrap(); + assert_eq!( + current + .tags + .iter() + .find(|tag| tag.as_slice()[0] == "version") + .unwrap() + .content(), + Some("1") + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn command_signature_is_verified_before_execution_or_receipt_acknowledgement() { + let state = state().await; + let tenant = community(&state, "mg-signature").await; + let actor = Keys::generate(); + let id = Uuid::new_v4(); + let command = put(&actor, id, 0, "Support"); + let mut forged = command.clone(); + forged.sig = put(&Keys::generate(), id, 0, "Support").sig; + for accepted in [false, true] { + let error = ingest_event(&state, &tenant, forged.clone(), auth(&actor)) + .await + .err() + .expect("expected refusal"); + assert!( + matches!(error, IngestError::Rejected(ref message) if message.contains("signature")), + "{error:?}" + ); + assert_eq!(receipt(&state, &tenant, &command).await, accepted); + if !accepted { + assert!(head(&state, &tenant, id).await.is_none()); + ingest_event(&state, &tenant, command.clone(), auth(&actor)) + .await + .unwrap(); + } + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn ban_and_current_group_policy_refusals_leave_no_receipt_and_have_valid_controls() { + let state = state().await; + let tenant = community(&state, "mg-authority").await; + let owner = Keys::generate(); + let member = Keys::generate(); + let _ = state + .db + .add_relay_member( + tenant.community(), + &owner.public_key().to_hex(), + "owner", + None, + &state.relay_keypair, + ) + .await + .unwrap(); + let _ = state + .db + .add_relay_member( + tenant.community(), + &member.public_key().to_hex(), + "member", + None, + &state.relay_keypair, + ) + .await + .unwrap(); + let policy = |manage: &str, prev: &str| { + EventBuilder::new( + Kind::Custom(RELAY_ADMIN_SET_MENTION_GROUP_POLICY as u16), + "", + ) + .tags([ + Tag::parse(["manage", manage]).unwrap(), + Tag::parse(["prev", prev]).unwrap(), + ]) + .sign_with_keys(&owner) + .unwrap() + }; + ingest_event(&state, &tenant, policy("admins", "0"), auth(&owner)) + .await + .unwrap(); + let command = put(&member, Uuid::new_v4(), 0, "Support"); + let error = ingest_event(&state, &tenant, command.clone(), auth(&member)) + .await + .err() + .expect("expected refusal"); + assert!( + matches!(error, IngestError::AuthFailed(ref message) if message.starts_with("restricted:")), + "{error:?}" + ); + assert!(!receipt(&state, &tenant, &command).await); + ingest_event(&state, &tenant, policy("everyone", "1"), auth(&owner)) + .await + .unwrap(); + state + .db + .ban_community_member( + tenant.community(), + member.public_key().as_bytes(), + owner.public_key().as_bytes(), + None, + None, + ) + .await + .unwrap(); + state.invalidate_restrictions_local(tenant.community()); + let error = ingest_event(&state, &tenant, command.clone(), auth(&member)) + .await + .err() + .expect("expected refusal") + .into_legacy(); + assert!( + matches!(error, IngestError::AuthFailed(ref message) if message.starts_with("blocked:")), + "{error:?}" + ); + assert!(!receipt(&state, &tenant, &command).await); + state + .db + .unban_community_member( + tenant.community(), + member.public_key().as_bytes(), + owner.public_key().as_bytes(), + ) + .await + .unwrap(); + state.invalidate_restrictions_local(tenant.community()); + assert!( + ingest_event(&state, &tenant, command.clone(), auth(&member)) + .await + .unwrap() + .accepted + ); + assert!(receipt(&state, &tenant, &command).await); +} + +#[tokio::test] +#[ignore = "requires Postgres; exercises one real command-expiry transition"] +async fn expired_exact_receipt_retry_survives_a_later_edit_but_unknown_expired_commands_fail() { + let state = state().await; + let tenant = community(&state, "mg-expiry").await; + let actor = Keys::generate(); + let id = Uuid::new_v4(); + let timestamp = Timestamp::now().as_secs() - 105; + let original = put_at(&actor, id, 0, "Original", timestamp); + ingest_event(&state, &tenant, original.clone(), auth(&actor)) + .await + .unwrap(); + let edit = put(&actor, id, 1, "Current"); + ingest_event(&state, &tenant, edit, auth(&actor)) + .await + .unwrap(); + let current = head(&state, &tenant, id).await.unwrap(); + let wait = (timestamp + 121).saturating_sub(Timestamp::now().as_secs()); + assert!(wait <= 16, "expiry wait unexpectedly exceeded its bound"); + tokio::time::sleep(Duration::from_secs(wait)).await; + assert!(Timestamp::now().as_secs() > timestamp + 120); + let replay = ingest_event(&state, &tenant, original.clone(), auth(&actor)) + .await + .unwrap(); + assert!( + replay.accepted && replay.message.starts_with("duplicate:"), + "retry refused: {}", + replay.message + ); + assert_eq!(replay.event_id, original.id.to_hex()); + let unknown = put_at(&actor, id, 2, "Expired overwrite", timestamp); + let error = ingest_event(&state, &tenant, unknown.clone(), auth(&actor)) + .await + .err() + .expect("expected refusal"); + assert!( + matches!(error, IngestError::Rejected(ref message) if message.contains("timestamp")), + "{error:?}" + ); + assert!(!receipt(&state, &tenant, &unknown).await); + let future = put_at( + &actor, + id, + 2, + "Future overwrite", + Timestamp::now().as_secs() + 300, + ); + let error = ingest_event(&state, &tenant, future.clone(), auth(&actor)) + .await + .err() + .expect("expected refusal"); + assert!( + matches!(error, IngestError::Rejected(ref message) if message.contains("mention group command timestamp")), + "{error:?}" + ); + assert!(!receipt(&state, &tenant, &future).await); + assert_eq!(head(&state, &tenant, id).await.unwrap().id, current.id); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn recipient_cannot_delete_relay_group_state_by_event_or_address() { + let state = state().await; + let tenant = community(&state, "mg-head-deletion").await; + let recipient = Keys::generate(); + let id = Uuid::new_v4(); + ingest_event( + &state, + &tenant, + put(&recipient, id, 0, "Support"), + auth(&recipient), + ) + .await + .unwrap(); + let current = head(&state, &tenant, id).await.unwrap(); + let deletion_auth = || IngestAuth::Http { + pubkey: recipient.public_key(), + scopes: vec![Scope::MessagesWrite, Scope::UsersWrite], + auth_method: HttpAuthMethod::Nip98, + }; + let deletion = |tag: Tag| { + EventBuilder::new(Kind::EventDeletion, "") + .tags([tag]) + .sign_with_keys(&recipient) + .unwrap() + }; + for tag in [ + Tag::parse(["e", ¤t.id.to_hex()]).unwrap(), + Tag::parse(["a", &format!("39010:{}:{id}", current.pubkey.to_hex())]).unwrap(), + // Relay-only state also cannot be targeted using the recipient as the + // coordinate author: it must not store an accepted deletion of this kind. + Tag::parse([ + "a", + &format!("39010:{}:{id}", recipient.public_key().to_hex()), + ]) + .unwrap(), + ] { + let request = deletion(tag); + let error = ingest_event(&state, &tenant, request.clone(), deletion_auth()) + .await + .err() + .expect("relay-owned group state deletion must be refused"); + assert!( + matches!(error, IngestError::Rejected(ref message) + if message == "invalid: deletion target not found or not deletable by you"), + "{error:?}" + ); + assert!(state + .db + .get_event_by_id(tenant.community(), request.id.as_bytes()) + .await + .unwrap() + .is_none()); + assert_eq!(head(&state, &tenant, id).await.unwrap().id, current.id); + assert_eq!( + req_event_ids( + &state, + &tenant, + &recipient, + json!({"kinds":[39010], "#d":[id.to_string()]}) + ) + .await, + vec![current.id.to_hex()] + ); + } + let note = EventBuilder::new(Kind::TextNote, "Ordinary deletable note") + .sign_with_keys(&recipient) + .unwrap(); + ingest_event(&state, &tenant, note.clone(), deletion_auth()) + .await + .unwrap(); + assert!( + ingest_event( + &state, + &tenant, + deletion(Tag::parse(["e", ¬e.id.to_hex()]).unwrap()), + deletion_auth() + ) + .await + .unwrap() + .accepted + ); + assert_eq!(head(&state, &tenant, id).await.unwrap().id, current.id); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn relay_signed_state_is_visible_to_nonrecipient_members_and_cannot_be_forged() { + let state = state().await; + let tenant = community(&state, "mg-state").await; + let actor = Keys::generate(); + let reader = Keys::generate(); + for keys in [&actor, &reader] { + let _ = state + .db + .add_relay_member( + tenant.community(), + &keys.public_key().to_hex(), + "member", + None, + &state.relay_keypair, + ) + .await + .unwrap(); + } + let mut configured = (*state).clone(); + let mut config = (*state.config).clone(); + config.require_relay_membership = true; + configured.config = Arc::new(config); + let state = Arc::new(configured); + let id = Uuid::new_v4(); + ingest_event(&state, &tenant, put(&actor, id, 0, "Support"), auth(&actor)) + .await + .unwrap(); + let current = head(&state, &tenant, id).await.unwrap(); + assert!(current.verify_signature()); + assert_eq!(current.pubkey, state.relay_keypair.public_key()); + assert!(!current.tags.iter().any(|tag| tag.as_slice()[0] == "p" + && tag.content() == Some(reader.public_key().to_hex().as_str()))); + let ids = req_event_ids(&state, &tenant, &reader, json!({"kinds":[39010], "authors":[state.relay_keypair.public_key().to_hex()], "#d":[id.to_string()]})).await; + assert_eq!(ids, vec![current.id.to_hex()]); + let forged = EventBuilder::new(Kind::Custom(KIND_MENTION_GROUP_STATE as u16), "") + .tags(current.tags.iter().cloned()) + .sign_with_keys(&actor) + .unwrap(); + let error = ingest_event(&state, &tenant, forged, auth(&actor)) + .await + .err() + .expect("expected refusal"); + assert!( + matches!(error, IngestError::Rejected(ref message) if message.contains("relay-only")), + "{error:?}" + ); + assert_eq!(head(&state, &tenant, id).await.unwrap().id, current.id); +} diff --git a/crates/buzz-relay/src/handlers/mod.rs b/crates/buzz-relay/src/handlers/mod.rs index 19d9942e068..bf9f19f85cd 100644 --- a/crates/buzz-relay/src/handlers/mod.rs +++ b/crates/buzz-relay/src/handlers/mod.rs @@ -40,6 +40,10 @@ pub mod ingest; pub mod media_access; #[cfg(test)] mod membership_notice_postgres_tests; +/// Relay-owned community Mention Groups (NIP-MG). +pub(crate) mod mention_groups; +#[cfg(test)] +mod mention_groups_postgres_tests; /// Community moderation authorization seam (capability helper). pub mod moderation_authz; /// Community moderation command handler (kinds 9040–9044). diff --git a/crates/buzz-relay/src/handlers/side_effects.rs b/crates/buzz-relay/src/handlers/side_effects.rs index afa25fd20f2..6e58f94493a 100644 --- a/crates/buzz-relay/src/handlers/side_effects.rs +++ b/crates/buzz-relay/src/handlers/side_effects.rs @@ -10,8 +10,9 @@ use buzz_core::kind::{ event_kind_u32, is_parameterized_replaceable, AUTHOR_ONLY_KINDS, KIND_AGENT_PROFILE, KIND_DM_VISIBILITY, KIND_GIT_REPO_ANNOUNCEMENT, KIND_IA_ARCHIVED, KIND_IA_ARCHIVED_LIST, KIND_IA_UNARCHIVED, KIND_MEMBER_ADDED_NOTIFICATION, KIND_MEMBER_REMOVED_NOTIFICATION, - KIND_NIP29_GROUP_ADMINS, KIND_NIP29_GROUP_MEMBERS, KIND_NIP29_GROUP_METADATA, - KIND_NIP43_MEMBERSHIP_LIST, KIND_REACTION, KIND_THREAD_SUMMARY, KIND_VERIFIED_PROFILE, + KIND_MENTION_GROUP_STATE, KIND_NIP29_GROUP_ADMINS, KIND_NIP29_GROUP_MEMBERS, + KIND_NIP29_GROUP_METADATA, KIND_NIP43_MEMBERSHIP_LIST, KIND_REACTION, KIND_THREAD_SUMMARY, + KIND_VERIFIED_PROFILE, }; use buzz_core::StoredEvent; use buzz_db::channel::{group_members_tags, MemberRecord, MemberRole}; @@ -444,8 +445,12 @@ pub(crate) async fn authorized_standard_deletion_target( else { return Ok(None); }; - // The profile's p tag names its subject, not an author with deletion rights. - if event_kind_u32(&target.event) == KIND_VERIFIED_PROFILE { + // Relay-state p tags name subjects or recipients, not authors with + // deletion rights. Their command handlers own retirement. + if matches!( + event_kind_u32(&target.event), + KIND_VERIFIED_PROFILE | KIND_MENTION_GROUP_STATE + ) { return Ok(None); } let author = effective_message_author(&target.event, &state.relay_keypair.public_key()); @@ -521,7 +526,10 @@ pub async fn validate_standard_deletion_event( return Err(anyhow::anyhow!("invalid a-tag format")); } if let Ok(target_kind) = parts[0].parse() { - if target_kind == KIND_VERIFIED_PROFILE { + if matches!( + target_kind, + KIND_VERIFIED_PROFILE | KIND_MENTION_GROUP_STATE + ) { anyhow::bail!(DELETION_TARGET_DENIED); } check_deletion_privacy_k_tag(event, target_kind)?; @@ -1376,7 +1384,7 @@ pub(crate) async fn emit_membership_notification_tagged( /// [`emit_membership_notification`] for a caller that already read the /// channel's type, such as a kind:9000 notifying several people. #[allow(clippy::too_many_arguments)] -async fn emit_typed_membership_notification( +pub(crate) async fn emit_typed_membership_notification( tenant: &TenantContext, state: &Arc, channel_id: Uuid, @@ -4334,6 +4342,23 @@ pub struct ReconcileSummary { pub failed: usize, } +/// Fan an already committed NIP-MG state out within its community. +pub(crate) async fn fan_out_mention_group_state( + tenant: &TenantContext, + state: &Arc, + stored: &buzz_core::StoredEvent, +) { + dispatch_persistent_event( + tenant, + state, + stored, + buzz_core::kind::KIND_MENTION_GROUP_STATE, + &state.relay_keypair.public_key().to_hex(), + None, + ) + .await; +} + /// Fan a committed NIP-43 membership list (kind:13534) out to live subscribers. /// /// Membership mutations write the list in their own transaction (see diff --git a/crates/buzz-relay/src/nip11.rs b/crates/buzz-relay/src/nip11.rs index e58ec300961..45db9011693 100644 --- a/crates/buzz-relay/src/nip11.rs +++ b/crates/buzz-relay/src/nip11.rs @@ -48,6 +48,9 @@ pub struct RelayInfo { pub buzz_v1: Option, /// NIP-AR artifact query transport and enforced resource limits. pub artifacts: serde_json::Value, + /// NIP-MG community groups, settings commands and effective membership rule. + #[serde(skip_serializing_if = "Option::is_none")] + pub mention_groups: Option, /// Relay operator's public key (hex), if published. pub pubkey: Option, /// Contact address for the relay operator. @@ -293,6 +296,7 @@ impl RelayInfo { name: "Buzz Relay".to_string(), description: "Buzz — private team communication relay".to_string(), icon: icon.filter(|s| !s.is_empty()).map(|s| s.to_string()), + mention_groups: None, read_state_snapshot: None, membership_snapshot: None, membership_public: None, @@ -479,6 +483,20 @@ pub(crate) async fn nip11_document( info.workflow_agent_mentions = state.config.workflow_agent_mentions; info.artifacts["incremental"] = crate::api::artifact_sync::capability(); if let Some(tenant) = tenant.as_ref() { + info.mention_groups = Some(serde_json::json!({ + "version": 1, + "put_kind": buzz_core::kind::RELAY_ADMIN_PUT_MENTION_GROUP, + "delete_kind": buzz_core::kind::RELAY_ADMIN_DELETE_MENTION_GROUP, + "set_manage_kind": buzz_core::kind::RELAY_ADMIN_SET_MENTION_GROUP_POLICY, + "state_kind": buzz_core::kind::KIND_MENTION_GROUP_STATE, + "settings_d": buzz_core::mention_group::SETTINGS_D_TAG, + "default_manage": "everyone", + "membership": if state.config.require_relay_membership { "roster" } else { "open" }, + "max_default_channels": buzz_core::mention_group::MAX_DEFAULT_CHANNELS, + })); + info.supported_extensions + .get_or_insert_default() + .push("nip-mg".to_owned()); if let Some(profile) = crate::verified_profiles::discovery(state, tenant).await { if let Some(fi) = info.federated_identity.as_mut() { fi["public_profile"] = profile; diff --git a/crates/buzz-test-client/tests/e2e_mention_groups.rs b/crates/buzz-test-client/tests/e2e_mention_groups.rs new file mode 100644 index 00000000000..c9033740633 --- /dev/null +++ b/crates/buzz-test-client/tests/e2e_mention_groups.rs @@ -0,0 +1,448 @@ +//! NIP-MG live WS/HTTP journey on an explicitly selected isolated local relay. +//! +//! BUZZ_MG_TEST_RELAY_URL=ws://127.0.0.1:15891 cargo test -p buzz-test-client \ +//! --test e2e_mention_groups -- --ignored --nocapture +//! The relay must use the feature schema, open membership, and a fresh community. + +use std::time::Duration; + +use base64::{engine::general_purpose::STANDARD as BASE64, Engine}; +use buzz_core::kind::{ + KIND_MENTION_GROUP_STATE, RELAY_ADMIN_DELETE_MENTION_GROUP, RELAY_ADMIN_PUT_MENTION_GROUP, + RELAY_ADMIN_SET_MENTION_GROUP_POLICY, +}; +use buzz_test_client::{BuzzTestClient, RelayMessage}; +use nostr::{Event, EventBuilder, Filter, Keys, Kind, PublicKey, Tag}; +use reqwest::StatusCode; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use uuid::Uuid; + +fn local_relay_urls() -> (String, String) { + let ws = std::env::var("BUZZ_MG_TEST_RELAY_URL") + .expect("set BUZZ_MG_TEST_RELAY_URL to an isolated local relay"); + let mut url = url::Url::parse(&ws).unwrap(); + assert!( + matches!( + url.host_str(), + Some("127.0.0.1" | "localhost" | "[::1]" | "::1") + ), + "local relay required" + ); + let scheme = match url.scheme() { + "ws" => "http", + "wss" => "https", + _ => panic!("WebSocket relay URL required"), + }; + url.set_scheme(scheme).unwrap(); + (ws, url.as_str().trim_end_matches('/').to_string()) +} + +fn put(keys: &Keys, id: Uuid, prev: i64, name: &str) -> Event { + put_with_defaults(keys, id, prev, name, &[keys.public_key()], &[]) +} + +fn put_with_defaults( + keys: &Keys, + id: Uuid, + prev: i64, + name: &str, + members: &[PublicKey], + channels: &[Uuid], +) -> Event { + let mut tags = vec![ + Tag::parse(["d", &id.to_string()]).unwrap(), + Tag::parse(["prev", &prev.to_string()]).unwrap(), + Tag::parse(["name", name]).unwrap(), + ]; + tags.extend(members.iter().copied().map(Tag::public_key)); + tags.extend( + channels + .iter() + .map(|id| Tag::parse(["channel", &id.to_string()]).unwrap()), + ); + EventBuilder::new(Kind::Custom(RELAY_ADMIN_PUT_MENTION_GROUP as u16), "") + .allow_self_tagging() + .tags(tags) + .sign_with_keys(keys) + .unwrap() +} + +async fn post(http: &str, keys: &Keys, path: &str, body: &Value) -> (StatusCode, Value) { + let url = format!("{http}{path}"); + let bytes = serde_json::to_vec(body).unwrap(); + let auth = EventBuilder::new(Kind::HttpAuth, "") + .tags([ + Tag::parse(["u", &url]).unwrap(), + Tag::parse(["method", "POST"]).unwrap(), + Tag::parse(["payload", &hex::encode(Sha256::digest(&bytes))]).unwrap(), + Tag::parse(["nonce", &Uuid::new_v4().to_string()]).unwrap(), + ]) + .sign_with_keys(keys) + .unwrap(); + let response = reqwest::Client::builder() + .timeout(Duration::from_secs(10)) + .build() + .unwrap() + .post(&url) + .header("content-type", "application/json") + .header( + "authorization", + format!( + "Nostr {}", + BASE64.encode(serde_json::to_vec(&auth).unwrap()) + ), + ) + .body(bytes) + .send() + .await + .unwrap(); + let status = response.status(); + let body = response.json().await.unwrap(); + (status, body) +} + +async fn query_state( + http: &str, + reader: &Keys, + relay: PublicKey, + kind: u32, + d: &str, +) -> Vec { + let (status, body) = post( + http, + reader, + "/query", + &json!([{ + "kinds":[kind], "authors":[relay.to_hex()], "#d":[d], "consistency":"strong" + }]), + ) + .await; + assert_eq!(status, StatusCode::OK, "{body}"); + serde_json::from_value(body).unwrap() +} + +fn field<'a>(event: &'a Event, name: &str) -> Option<&'a str> { + event + .tags + .iter() + .find(|tag| tag.as_slice()[0] == name) + .and_then(Tag::content) +} + +async fn live_head( + reader: &mut BuzzTestClient, + sub: &str, + relay: PublicKey, + version: &str, +) -> Event { + let deadline = tokio::time::Instant::now() + Duration::from_secs(10); + loop { + let remaining = deadline.saturating_duration_since(tokio::time::Instant::now()); + assert!( + !remaining.is_zero(), + "missing live group revision {version}" + ); + match reader + .recv_event(remaining) + .await + .expect("live group delivery") + { + RelayMessage::Event { + subscription_id, + event, + } if subscription_id == sub => { + assert_eq!(event.kind.as_u16() as u32, KIND_MENTION_GROUP_STATE); + assert_eq!(event.pubkey, relay); + assert!(event.verify_id() && event.verify_signature()); + if field(&event, "version") == Some(version) { + return *event; + } + } + RelayMessage::Closed { message, .. } => panic!("subscription closed: {message}"), + _ => {} + } + } +} + +#[tokio::test] +#[ignore = "requires an isolated open local relay with the feature schema"] +async fn http_commands_ws_live_delivery_and_tombstone_reads_share_one_authoritative_head() { + let (ws, http) = local_relay_urls(); + let info: Value = reqwest::Client::builder() + .timeout(Duration::from_secs(10)) + .build() + .unwrap() + .get(format!("{http}/")) + .header("accept", "application/nostr+json") + .send() + .await + .unwrap() + .error_for_status() + .unwrap() + .json() + .await + .unwrap(); + assert_eq!( + info["mention_groups"]["membership"], "open", + "isolated open relay required" + ); + assert_eq!(info["mention_groups"]["default_manage"], "everyone"); + let relay = PublicKey::from_hex(info["self"].as_str().expect("relay signing key")).unwrap(); + let actor = Keys::generate(); + let outsider = Keys::generate(); + let eligible = Keys::generate(); + let blocked = Keys::generate(); + let id = Uuid::new_v4(); + let name = format!("mg-e2e-{id}"); + let sub = format!("mg-{id}"); + let mut writer = BuzzTestClient::connect(&ws, &actor).await.unwrap(); + let mut reader = BuzzTestClient::connect(&ws, &outsider).await.unwrap(); + assert!( + query_state(&http, &actor, relay, KIND_MENTION_GROUP_STATE, "settings") + .await + .is_empty(), + "fresh community with implicit settings revision zero required" + ); + let channel = Uuid::new_v4(); + let create = EventBuilder::new(Kind::Custom(9007), "") + .tags([ + Tag::parse(["h", &channel.to_string()]).unwrap(), + Tag::parse(["name", &format!("mg-default-{channel}")]).unwrap(), + Tag::parse(["channel_type", "stream"]).unwrap(), + Tag::parse(["visibility", "open"]).unwrap(), + Tag::parse(["unlisted", "false"]).unwrap(), + ]) + .sign_with_keys(&actor) + .unwrap(); + let (status, created) = post(&http, &actor, "/events", &json!(create)).await; + assert_eq!(status, StatusCode::OK, "{created}"); + assert_eq!(created["accepted"], true); + let refuse_adds = EventBuilder::new( + Kind::Custom(10100), + json!({"channel_add_policy":"nobody"}).to_string(), + ) + .sign_with_keys(&blocked) + .unwrap(); + let (status, configured) = post(&http, &blocked, "/events", &json!(refuse_adds)).await; + assert_eq!(status, StatusCode::OK, "{configured}"); + assert_eq!(configured["accepted"], true); + let members = [ + actor.public_key(), + eligible.public_key(), + blocked.public_key(), + ]; + let filter = json!({"kinds":[39010], "authors":[relay.to_hex()], "#d":[id.to_string()]}); + reader + .subscribe( + &sub, + vec![serde_json::from_value::(filter.clone()).unwrap()], + ) + .await + .unwrap(); + assert!(reader + .collect_until_eose(&sub, Duration::from_secs(10)) + .await + .unwrap() + .is_empty()); + + let original = put_with_defaults(&actor, id, 0, &name, &members, &[channel]); + let (status, accepted) = post(&http, &actor, "/events", &json!(original)).await; + assert_eq!(status, StatusCode::OK, "{accepted}"); + assert_eq!(accepted["accepted"], true); + assert_eq!(accepted["event_id"], original.id.to_hex()); + let original_message = accepted["message"].as_str().unwrap().to_owned(); + let joins: Value = serde_json::from_str( + original_message + .strip_prefix("joins: ") + .expect("join accounting in acceptance"), + ) + .unwrap(); + assert_eq!(joins["joined"], 1); + assert_eq!(joins["skipped"]["already_member"], 1); + assert_eq!(joins["skipped"]["target_policy_nobody"], 1); + let initial = live_head(&mut reader, &sub, relay, "1").await; + assert_eq!(field(&initial, "name"), Some(name.as_str())); + for member in members { + assert!( + initial + .tags + .iter() + .any(|tag| tag.as_slice()[0] == "p" + && tag.content() == Some(member.to_hex().as_str())) + ); + } + assert!(!initial.tags.iter().any(|tag| tag.as_slice()[0] == "p" + && tag.content() == Some(outsider.public_key().to_hex().as_str()))); + assert_eq!( + field(&initial, "channel"), + Some(channel.to_string().as_str()) + ); + let rosters = query_state(&http, &actor, relay, 39002, &channel.to_string()).await; + assert_eq!(rosters.len(), 1); + assert!(rosters[0].verify_signature()); + for (member, expected) in [ + (actor.public_key(), true), + (eligible.public_key(), true), + (blocked.public_key(), false), + ] { + assert_eq!( + rosters[0] + .tags + .iter() + .any(|tag| tag.as_slice()[0] == "p" + && tag.content() == Some(member.to_hex().as_str())), + expected + ); + } + + for (event, expected_status, prefix) in [ + ( + put(&actor, id, 0, "Stale overwrite"), + StatusCode::CONFLICT, + "conflict:", + ), + ( + put(&actor, Uuid::new_v4(), 0, &name), + StatusCode::CONFLICT, + "duplicate:", + ), + ( + put(&actor, Uuid::new_v4(), 0, ""), + StatusCode::BAD_REQUEST, + "invalid:", + ), + ] { + let (status, body) = post(&http, &actor, "/events", &json!(event)).await; + assert_eq!(status, expected_status, "{body}"); + assert!( + body["error"].as_str().unwrap().starts_with(prefix), + "{body}" + ); + } + + let edit = put_with_defaults( + &actor, + id, + 1, + &format!("{name} renamed"), + &members, + &[channel], + ); + let ack = writer.send_event(edit.clone()).await.unwrap(); + assert!(ack.accepted, "{ack:?}"); + assert_eq!(ack.event_id, edit.id.to_hex()); + let edited = live_head(&mut reader, &sub, relay, "2").await; + assert!(edited.created_at > initial.created_at); + let (status, duplicate) = post(&http, &actor, "/events", &json!(original)).await; + assert_eq!(status, StatusCode::OK, "{duplicate}"); + assert_eq!(duplicate["accepted"], true); + assert_eq!( + duplicate["message"], + format!("duplicate: {original_message}") + ); + + let policy = |manage: &str, prev: &str| { + EventBuilder::new( + Kind::Custom(RELAY_ADMIN_SET_MENTION_GROUP_POLICY as u16), + "", + ) + .tags([ + Tag::parse(["manage", manage]).unwrap(), + Tag::parse(["prev", prev]).unwrap(), + ]) + .sign_with_keys(&actor) + .unwrap() + }; + let admins = policy("admins", "0"); + let (status, policy_ack) = post(&http, &actor, "/events", &json!(admins)).await; + assert_eq!(status, StatusCode::OK, "{policy_ack}"); + assert_eq!(policy_ack["accepted"], true); + let settings = query_state( + &http, + &outsider, + relay, + KIND_MENTION_GROUP_STATE, + "settings", + ) + .await; + assert_eq!(settings.len(), 1); + assert!(settings[0].verify_id() && settings[0].verify_signature()); + assert_eq!(field(&settings[0], "manage"), Some("admins")); + assert_eq!(field(&settings[0], "version"), Some("1")); + assert_eq!( + field(&settings[0], "command"), + Some(admins.id.to_hex().as_str()) + ); + assert!(settings[0].content.is_empty()); + let outsider_put = put(&outsider, Uuid::new_v4(), 0, "Forbidden group"); + let (status, denied) = post(&http, &outsider, "/events", &json!(outsider_put)).await; + assert_eq!(status, StatusCode::FORBIDDEN, "{denied}"); + assert!( + denied["error"].as_str().unwrap().starts_with("restricted:"), + "{denied}" + ); + // This relay has no owner/admin roster. The same admitted actor can restore + // everyone management through the rosterless settings authority rule. + let everyone = policy("everyone", "1"); + let (status, restored) = post(&http, &actor, "/events", &json!(everyone)).await; + assert_eq!(status, StatusCode::OK, "{restored}"); + assert_eq!(restored["accepted"], true); + let restored = query_state( + &http, + &outsider, + relay, + KIND_MENTION_GROUP_STATE, + "settings", + ) + .await; + assert_eq!(restored.len(), 1); + assert_eq!(field(&restored[0], "manage"), Some("everyone")); + assert_eq!(field(&restored[0], "version"), Some("2")); + assert_eq!( + field(&restored[0], "command"), + Some(everyone.id.to_hex().as_str()) + ); + + let forged = EventBuilder::new(Kind::Custom(KIND_MENTION_GROUP_STATE as u16), "") + .tags(edited.tags.iter().cloned()) + .sign_with_keys(&actor) + .unwrap(); + let ack = writer.send_event(forged.clone()).await.unwrap(); + assert!( + !ack.accepted && ack.message.contains("relay-only"), + "{ack:?}" + ); + let (status, body) = post(&http, &actor, "/events", &json!(forged)).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{body}"); + assert!( + body["error"].as_str().unwrap().contains("relay-only"), + "{body}" + ); + + let delete = EventBuilder::new(Kind::Custom(RELAY_ADMIN_DELETE_MENTION_GROUP as u16), "") + .tags([ + Tag::parse(["d", &id.to_string()]).unwrap(), + Tag::parse(["prev", "2"]).unwrap(), + ]) + .sign_with_keys(&actor) + .unwrap(); + let (status, deleted) = post(&http, &actor, "/events", &json!(delete)).await; + assert_eq!(status, StatusCode::OK, "{deleted}"); + assert_eq!(deleted["accepted"], true); + let tombstone = live_head(&mut reader, &sub, relay, "3").await; + assert!(tombstone.created_at > edited.created_at); + assert_eq!(field(&tombstone, "deleted"), Some("true")); + assert!(field(&tombstone, "name").is_none() && field(&tombstone, "p").is_none()); + + let mut query = filter; + query["consistency"] = json!("strong"); + let (status, heads) = post(&http, &outsider, "/query", &json!([query])).await; + assert_eq!(status, StatusCode::OK, "{heads}"); + let events: Vec = serde_json::from_value(heads).unwrap(); + assert_eq!(events.len(), 1); + assert_eq!(events[0].id, tombstone.id); + reader.close_subscription(&sub).await.unwrap(); + reader.disconnect().await.unwrap(); + writer.disconnect().await.unwrap(); +} diff --git a/docs/nips/NIP-MG.md b/docs/nips/NIP-MG.md new file mode 100644 index 00000000000..658fd645b77 --- /dev/null +++ b/docs/nips/NIP-MG.md @@ -0,0 +1,291 @@ +NIP-MG +====== + +Community Mention Groups +------------------------ + +`draft` `optional` `relay` `Buzz extension` + +**Depends on:** NIP-01 (events and filters), NIP-11 (discovery), NIP-42 +(authentication), NIP-70 (protected relay state). + +## Purpose and scope + +A mention group is a community-owned name and explicit set of recipient public +keys. People and agents share the same representation. The relay executes signed +commands and publishes authoritative state; the client does not own or sign the +authoritative directory. These numbers are Buzz extensions, not global Nostr +allocations. + +A group has no channel, conversation roster, or creator-owned authority. Its +optional default channels identify existing public channels to join when members +are added. Inclusion never grants private-channel access. Saving group state +must not itself create a message, mention notification, unread item, or agent +conversation wake. + +Every command, receipt, group and state event belongs to the server-resolved +community. Clients must bind editors and pending results to that community +session; identical UUIDs on two communities refer to independent groups. + +## Kinds and discovery + +| Kind | Name | Author | Meaning | +| ------- | --------------------- | ---------------- | ---------------------------------------------------- | +| `47000` | Put mention group | Authorized actor | Complete group replacement with version precondition | +| `47001` | Delete mention group | Authorized actor | Permanent retirement with version precondition | +| `47002` | Set management policy | Authorized actor | Replace the community management setting | +| `39010` | Mention-group state | Relay only | Addressable group, tombstone, or settings head | + +A supporting relay advertises `nip-mg` in NIP-11 `supported_extensions` and: + +```json +{ + "mention_groups": { + "version": 1, + "put_kind": 47000, + "delete_kind": 47001, + "set_manage_kind": 47002, + "state_kind": 39010, + "default_manage": "everyone", + "membership": "roster" + } +} +``` + +`version` is the protocol schema version, independent of state revisions. +`membership` is `open` or `roster`: on an open community, any authenticated, +unbanned key is a current member; on a roster community, current membership +requires a community member row or an effectively admitted agent through its +owner. The advertised message-size limit is +`limitation.max_message_length`. A host must advertise its command capability +only when its signing and publishing paths support this contract. + +## Authority and admission + +Management defaults to `everyone`. Under `everyone`, current community members +may put and delete groups. Under `admins`, the signer must hold an actual +community `owner` or `admin` role; an agent does not inherit that role from its +owner. Group inclusion grants no management authority. + +Changing the management policy requires an actual owner/admin role. If the +community has no owner/admin row, any current member may change the setting. +This exception permits stewardship on communities without an initial steward. +It does not grant inherited admin authority to agents in a community that has a +steward. + +Commands use authenticated WS `EVENT` or HTTP `/events`. The signer must equal +the authenticated actor. Existing tenant write fences, credential scope and +ban checks apply. New execution uses the relay-admin freshness window of +plus/minus 120 seconds. The relay evaluates current membership, management policy +and steward authority inside the admitted transaction, ordered against relevant +membership and policy changes. + +## Command format + +All commands have empty `content`. Singleton semantic fields must appear exactly +once with exactly two tag elements. Unknown tags and inappropriate fields are +rejected, including `h`, state-only fields, and `d` on a policy command. + +Put (`47000`) is a complete replacement: + +```json +{ + "kind": 47000, + "content": "", + "tags": [ + ["d", "0659678f-fddb-40df-a285-35f6b41db019"], + ["prev", "0"], + ["name", "Support team"], + ["p", ""], + ["p", ""], + ["channel", "865a455d-914c-4b8b-8295-0b6d75f45730"] + ] +} +``` + +Delete (`47001`) has exactly `d` and `prev` semantic tags; it has no `name`, +`p`, or `channel` tags. Set policy (`47002`) has exactly `manage` and `prev` +semantic tags, for example `[["manage","admins"],["prev","0"]]`. +`manage` accepts exactly `admins` or `everyone`. + +Validation and normalization: + +- `d` is a canonical lowercase, hyphenated, non-nil UUID. The literal `settings` + is reserved for relay state and cannot identify a group. +- `prev` is a canonical decimal string in `0..9223372036854775807`, with no + whitespace, sign or leading zeroes except the value `0` itself. +- Names are trimmed and contain 1–120 Unicode scalar values. Control characters + and embedded Unicode line/paragraph separators are rejected. Spelling, case + and internal spaces are preserved. Active names are unique per community + under the database's `lower(name)` collation, not full Unicode case folding. +- Each `p` has exactly two elements and a 64-character hexadecimal public key. + Normalize keys to lowercase, sorted and deduplicated. Zero members is valid. + The signer is included only when explicitly tagged. Builders that suppress + signer `p` tags must disable that behavior for this protocol. +- Each `channel` has exactly two elements and a canonical non-nil UUID. Sort and + deduplicate them; at most 32 distinct defaults are allowed. The relay validates + channel eligibility within the community. Core wire validation performs no + channel or membership lookup. +- Stored group size is independent of any send-recipient limit. Reject a command + when its resulting signed state exceeds the advertised message-size bound; + never truncate members or channels. + +The only optional transport annotations are one each of: + +- `client-id`: two elements, nonempty text without controls, at most 128 UTF-16 + code units, matching the existing host bound; +- `ms`: two elements with a canonical decimal string in `0..999`; +- `auth`: the four-element NIP-OA envelope, with a 64-character hex owner key, + conditions bounded to 4,096 UTF-8 bytes and 128-character hex signature. + Existing relay NIP-OA verification remains authoritative; the wire parser does + not treat a structurally valid annotation as authorization. + +Duplicate annotations are rejected. Annotations cannot change command meaning. + +## Revisions, transactions and retries + +Each group starts unused. A fresh put with `prev=0` creates live revision 1. +Thereafter, a put or delete must supply the current revision and advances it by +one. Counters never wrap. Even an otherwise identical fresh put advances the +revision. A delete commits a permanent tombstone and releases the live name; +the UUID cannot be reused. An empty live group continues to reserve its name. + +The settings coordinate has an implicit initial revision 0 and value `everyone`. +There is no signed initial head. Reads must not lazily write a default head. The +first accepted policy command uses `prev=0` and publishes settings revision 1. +Subsequent policy changes use the same compare-and-set revision rules. + +Accepted signed command IDs have durable receipts shared by all three command +kinds. An exact retry acknowledges its original acceptance without applying a +second mutation, advancing any revision, repeating default-channel joins, or +publishing another state event. This holds even after a later edit supersedes +the accepted result. A receipt confirms historical acceptance, not currentness. + +Receipt replay still requires signature, authenticated actor, tenant, scope, +write-fence and ban admission. It precedes freshness and new-execution authority +checks. A never-accepted stale command remains rejected. On an uncertain outcome, +clients retain and resend the same signed event. After a version conflict they +read current state and reconcile rather than automatically overwriting it. + +Group/settings mutation, version check, receipt, signed state insertion and +previous-head retirement commit atomically in one admitted transaction. +Coordinate locking includes absent coordinates so concurrent creates cannot +both succeed. Name uniqueness is enforced transactionally across different IDs. +Failures leave no partial group, setting, receipt, head, or joins. + +## Default-channel behavior + +On creation, members are new additions. On an update, only keys newly added to +the stored member set are candidates for joining default channels. Replacing +only the default-channel list does not retroactively join existing members. +The relay uses the accepted replacement's defaults and existing channel-join +policy; it skips identities that have left the community and channels that are +gone or closed. Private-channel access is never acquired through a group. +Group deletion does not remove channel membership. + +Default-channel membership writes commit in the group transaction. When any +target/channel pair is skipped, the success message is `joins:` and a space followed by +JSON, for example `joins: {"joined":2,"skipped":{"channel_closed":1}}`. +`joined` counts new or reactivated memberships; `skipped` maps stable reasons +to pair counts. Reasons are `channel_unavailable`, `channel_closed`, +`target_not_admitted`, `already_member`, `target_owner_missing`, +`target_owner_only`, `target_policy_nobody`, and `membership_denied`. +An exact retry returns the stored report after `duplicate:` and a space, for example +`duplicate: joins: {"joined":2,"skipped":{"channel_closed":1}}`. +Without skips, first acceptance has an empty message and replay has `duplicate:`. + +## Relay state + +The relay publishes kind `39010` under its advertised community signing key. +Each current head has empty content, a protected `["-"]` marker, one `d`, one +positive decimal `version`, and one `command` carrying the accepted command ID. + +- A live group head uses `d=`, its normalized `name`, sorted `p` + members, and sorted `channel` defaults. +- A tombstone uses `d=` and `["deleted","true"]`; it has no name, + member, or default-channel tags. +- A settings head uses `d=settings` and one `manage` tag; it has no name, + member, channel or deleted tags. + +Heads are stored without a channel ID. A tombstone is a discoverable current +event, not a deleted event-store row, and does not expire under ordinary message +retention. Kind-5 deletion cannot remove these relay-owned heads. Users cannot +remove state by deleting their input command. Clients +must reject submitted projections: `39010` is relay-only. + +The new head's timestamp is at least `max(now, prior coordinate timestamps + 1)`, +including retired heads, so addressable-event replacement works within one +second. Clients additionally fold by revision, ignore lower revisions and +duplicate event IDs, and repair conflicting equal revisions by reading the +authoritative head. + +All admitted community readers can read every head, including nonrecipients and +members without channel memberships. State `p` tags are data, never read gates +or notification intent. + +## Reads and convergence + +Use ordinary WS `REQ` for history plus live updates: + +```json +{"kinds":[39010],"authors":[""],"limit":1000} +{"kinds":[39010],"authors":[""],"#d":["settings"],"limit":1} +``` + +The directory includes the reserved settings coordinate; distinguish it from +UUID group coordinates. HTTP `/query` pages heads with the existing composite +`until` plus `before_id` cursor, using the last event's inclusive timestamp and +ID. Do not decrement the second. Request strong consistency for edit readback. +Continue until a short successful page; a partial result does not prove absence. +COUNT uses the same tenant/read admission. + +Keep the live subscription open while loading pages and merge by coordinate and +revision. Reconcile all heads, including tombstones and settings, at startup and +after interrupted continuity. This is a convergent directory, not a multi-page +atomic snapshot. Share the host's reconnect owner and fleet backoff. + +Committed state is durable; normal operation fans out the committed event after +commit. Delivery through publisher failure or process death is not guaranteed by +this protocol's asynchronous dispatch. Reconnect reconciliation and the host's +existing online state-refresh policy repair missed updates. A publish failure +after commit cannot cause a second logical write. + +## Responses + +WS `OK` and HTTP `/events` acknowledge the signed command event ID. + +| Outcome | Accepted | Message prefix | HTTP | +| ------------------------------------------ | -------- | --------------------------- | ---- | +| Committed | true | empty | 200 | +| Exact accepted retry | true | `duplicate:` | 200 | +| Wrong revision, retired ID, unknown delete | false | `conflict:` | 409 | +| Another live group owns name | false | `duplicate:` | 409 | +| Insufficient authority | false | `restricted:` | 403 | +| Banned actor | false | existing `blocked:` refusal | 403 | +| Invalid shape or excessive resulting state | false | `invalid:` | 400 | +| Persistence/admission lookup failure | false | `error:` | 500 | + +Clients must preserve name collision, version conflict, authority denial and +unknown transport outcome as distinct results. + +## Community removal and client projection + +Community removal leaves stored group keys and revisions unchanged. The host +intersects the stored set with authoritative effective community membership for +completion, sending and reader chips, including correctly owner-admitted agents. +The editor hides confirmed removed identities; its next successful replacement +prunes them. Loading, failed or incomplete discovery is not removal evidence. +Current projections do not rewrite recipients captured in historical messages. + +Group expansion still obeys destination admission and send-recipient limits. +The host owns completion aggregation, selected-occurrence provenance, reader +chips and signing/publishing capabilities. Relay support alone does not provide +those client behaviors. + +## Deployment + +Tenant tables and purge catalogs require the repository's compatibility-first +two-release rollout. All serving deletion executors and operator tools must +recognize the future tables before feature schema is installed. Signed heads, +receipts and group identities remain tenant-scoped through deletion and purge. +See [database guidance](../database.md). diff --git a/migrations/0097_mention_groups.sql b/migrations/0097_mention_groups.sql new file mode 100644 index 00000000000..63ac5c4ca7d --- /dev/null +++ b/migrations/0097_mention_groups.sql @@ -0,0 +1,42 @@ +-- Compatibility prerequisite: deploy the pending-table catalog release everywhere first. +SET LOCAL lock_timeout = '5s'; +SET LOCAL statement_timeout = '30s'; + +ALTER TABLE communities + ADD COLUMN mention_groups_manage TEXT NOT NULL DEFAULT 'everyone' CHECK (mention_groups_manage IN ('admins', 'everyone')), + ADD COLUMN mention_groups_version BIGINT NOT NULL DEFAULT 0 CHECK (mention_groups_version >= 0), + ADD COLUMN mention_groups_state_event_id BYTEA CHECK (length(mention_groups_state_event_id) = 32); + +-- Community-owned recipient sets. Deleted IDs remain reserved until community purge. +-- Current signed heads, including tombstones, must survive any future event retention. +CREATE TABLE mention_groups ( + community_id UUID NOT NULL, + id UUID NOT NULL CHECK (id <> '00000000-0000-0000-0000-000000000000'::uuid), + name TEXT NOT NULL, + members TEXT[] NOT NULL, + channels UUID[] NOT NULL DEFAULT '{}' CHECK (cardinality(channels) <= 32), + version BIGINT NOT NULL CHECK (version > 0), + deleted_at TIMESTAMPTZ, + state_event_id BYTEA NOT NULL CHECK (length(state_event_id) = 32), + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + PRIMARY KEY (community_id, id) +); +CREATE UNIQUE INDEX idx_mention_groups_live_name + ON mention_groups (community_id, lower(name)) WHERE deleted_at IS NULL; + +-- Durable accepted commands, independent of event retirement and head changes. +CREATE TABLE mention_group_commands ( + community_id UUID NOT NULL, + event_id BYTEA NOT NULL CHECK (length(event_id) = 32), + signer TEXT NOT NULL, + group_id UUID, + operation TEXT NOT NULL CHECK (operation IN ('put', 'delete', 'policy')), + version BIGINT NOT NULL CHECK (version > 0), + state_event_id BYTEA NOT NULL CHECK (length(state_event_id) = 32), + command JSONB NOT NULL, + join_summary JSONB NOT NULL, + accepted_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + PRIMARY KEY (community_id, event_id), + CHECK ((operation = 'policy') = (group_id IS NULL)) +); diff --git a/schema/schema.sql b/schema/schema.sql index e8e651167f5..b8d6082c0cb 100644 --- a/schema/schema.sql +++ b/schema/schema.sql @@ -171,3 +171,6 @@ CREATE EXTENSION IF NOT EXISTS pgcrypto; \i tables/public/media_uploaders.sql \i tables/public/media_publications.sql + +\i tables/public/mention_groups.sql +\i tables/public/mention_group_commands.sql diff --git a/schema/tables/public/communities.sql b/schema/tables/public/communities.sql index 4c328109f69..6752adb818b 100644 --- a/schema/tables/public/communities.sql +++ b/schema/tables/public/communities.sql @@ -26,6 +26,9 @@ CREATE TABLE communities ( deletion_state TEXT NOT NULL DEFAULT 'active' CHECK (deletion_state IN ('active', 'quiescing', 'fenced', 'tombstone')), deletion_fence_generation BIGINT NOT NULL DEFAULT 0 CHECK (deletion_fence_generation >= 0), deleted_at TIMESTAMPTZ, + mention_groups_manage TEXT NOT NULL DEFAULT 'everyone' CHECK (mention_groups_manage IN ('admins', 'everyone')), + mention_groups_version BIGINT NOT NULL DEFAULT 0 CHECK (mention_groups_version >= 0), + mention_groups_state_event_id BYTEA CHECK (length(mention_groups_state_event_id) = 32), artifact_policy_modified_at TIMESTAMPTZ NOT NULL DEFAULT 'epoch', CONSTRAINT chk_communities_id_not_nil CHECK (id <> '00000000-0000-0000-0000-000000000000'::uuid) ); diff --git a/schema/tables/public/mention_group_commands.sql b/schema/tables/public/mention_group_commands.sql new file mode 100644 index 00000000000..01873f4d680 --- /dev/null +++ b/schema/tables/public/mention_group_commands.sql @@ -0,0 +1,15 @@ +-- Durable accepted commands, independent of event retirement and head changes. +CREATE TABLE mention_group_commands ( + community_id UUID NOT NULL, + event_id BYTEA NOT NULL CHECK (length(event_id) = 32), + signer TEXT NOT NULL, + group_id UUID, + operation TEXT NOT NULL CHECK (operation IN ('put', 'delete', 'policy')), + version BIGINT NOT NULL CHECK (version > 0), + state_event_id BYTEA NOT NULL CHECK (length(state_event_id) = 32), + command JSONB NOT NULL, + join_summary JSONB NOT NULL, + accepted_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + PRIMARY KEY (community_id, event_id), + CHECK ((operation = 'policy') = (group_id IS NULL)) +); diff --git a/schema/tables/public/mention_groups.sql b/schema/tables/public/mention_groups.sql new file mode 100644 index 00000000000..285ff4b58de --- /dev/null +++ b/schema/tables/public/mention_groups.sql @@ -0,0 +1,17 @@ +-- Community-owned recipient sets. Deleted IDs remain reserved until community purge. +-- Current signed heads, including tombstones, must survive any future event retention. +CREATE TABLE mention_groups ( + community_id UUID NOT NULL, + id UUID NOT NULL CHECK (id <> '00000000-0000-0000-0000-000000000000'::uuid), + name TEXT NOT NULL, + members TEXT[] NOT NULL, + channels UUID[] NOT NULL DEFAULT '{}' CHECK (cardinality(channels) <= 32), + version BIGINT NOT NULL CHECK (version > 0), + deleted_at TIMESTAMPTZ, + state_event_id BYTEA NOT NULL CHECK (length(state_event_id) = 32), + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + PRIMARY KEY (community_id, id) +); +CREATE UNIQUE INDEX idx_mention_groups_live_name + ON mention_groups (community_id, lower(name)) WHERE deleted_at IS NULL; From c3c63441a6dbf110790fd3de8aad4b8ab72b98d3 Mon Sep 17 00:00:00 2001 From: Krish Ray Date: Mon, 16 Nov 2026 16:16:25 -0500 Subject: [PATCH 3/7] fix(mention-groups): enforce mobile member limit and admitted writes Use the shared event writer for relay-signed group heads. Limit groups to 20 distinct members, advertise the cap, and derive refusal text from the core constant. Check parity with the mobile push limit and run that check for Dart-only changes. Co-authored-by: Sigil <06114f072cf21e50fcd4133ab21346cdb1f74ee16d853a9729995fa6c03a251c@buzz.block.builderlab.xyz> Signed-off-by: Krish Ray Signed-off-by: kray --- .github/workflows/ci.yml | 2 + crates/buzz-core/src/mention_group.rs | 51 +++++++++++++++++-- crates/buzz-db/src/store/mention_group.rs | 32 +++--------- .../src/store/mention_group_postgres_tests.rs | 2 +- crates/buzz-relay/src/nip11.rs | 1 + .../tests/e2e_mention_groups.rs | 41 +++++++++++++++ docs/nips/NIP-MG.md | 15 ++++-- lefthook.yml | 2 +- scripts/ci-selection.test.mjs | 5 ++ 9 files changed, 115 insertions(+), 36 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 77e51db63c0..c199dc0ef01 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -51,6 +51,8 @@ jobs: filters: | rust: - 'crates/**' + # The core mention-group limit is coupled to the mobile push gate. + - 'mobile/lib/shared/push/push_subscription.dart' - 'migrations/**' - 'schema/**' - 'Cargo.toml' diff --git a/crates/buzz-core/src/mention_group.rs b/crates/buzz-core/src/mention_group.rs index 48f2681d688..dda96ad24f5 100644 --- a/crates/buzz-core/src/mention_group.rs +++ b/crates/buzz-core/src/mention_group.rs @@ -20,6 +20,11 @@ use crate::kind::{ pub const SETTINGS_D_TAG: &str = "settings"; /// Maximum number of Unicode scalar values in a normalized group name. pub const MAX_NAME_CHARS: usize = 120; +/// Maximum distinct members in a group replacement. Keep in sync with +/// `buzzPushHellthreadParticipantLimit` in +/// `mobile/lib/shared/push/push_subscription.dart` so one group fits the mobile +/// push recipient gate. Clients discover this value through NIP-11. +pub const MAX_MEMBERS: usize = 20; /// Maximum distinct default channels in a group replacement. pub const MAX_DEFAULT_CHANNELS: usize = 32; const MAX_CLIENT_ID_UTF16: usize = 128; @@ -127,6 +132,9 @@ pub fn parse_command(event: &Event) -> Result { let key = PublicKey::from_hex(value) .map_err(|_| "member must be a 64-character hex public key")?; members.insert(key.to_hex()); + if members.len() > MAX_MEMBERS { + return Err(format!("a group can have at most {MAX_MEMBERS} members")); + } } Some("channel") if put => { let id = crate::artifact::canonical_uuid(pair(parts)?).map_err(str::to_owned)?; @@ -430,7 +438,7 @@ mod tests { } #[test] - fn names_use_unicode_scalar_limits_and_groups_can_exceed_send_recipient_limits() { + fn names_use_unicode_scalar_limits_and_groups_bound_distinct_members() { for (name, accepted) in [ ("夜".repeat(120), true), ("夜".repeat(121), false), @@ -449,12 +457,47 @@ mod tests { ); } let mut tags = put_tags(); - for _ in 0..40 { + for _ in 0..20 { tags.push(vec!["p".into(), Keys::generate().public_key().to_hex()]); } + tags.push(vec!["p".into(), tags[3][1].to_uppercase()]); assert!( - matches!(parse_command(&event(RELAY_ADMIN_PUT_MENTION_GROUP, tags)).unwrap().operation, - Operation::Put { members, .. } if members.len() == 40) + matches!(parse_command(&event(RELAY_ADMIN_PUT_MENTION_GROUP, tags.clone())).unwrap().operation, + Operation::Put { members, .. } if members.len() == 20) + ); + tags.push(vec!["p".into(), Keys::generate().public_key().to_hex()]); + assert_eq!( + parse_command(&event(RELAY_ADMIN_PUT_MENTION_GROUP, tags)).unwrap_err(), + "a group can have at most 20 members" + ); + } + + #[test] + fn group_member_limit_matches_mobile_push_gate() { + let source = std::fs::read_to_string(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../mobile/lib/shared/push/push_subscription.dart" + )) + .expect("read the mobile push contract"); + let initializer = source + .lines() + .filter_map(|line| line.trim().strip_prefix("const ")) + .filter_map(|declaration| declaration.split_once('=')) + .find_map(|(name, value)| { + (name.split_whitespace().last() == Some("buzzPushHellthreadParticipantLimit")) + .then_some(value) + }) + .expect("mobile push participant limit must be declared"); + let mobile_limit: usize = initializer + .split_once(';') + .expect("mobile push participant limit must end with a semicolon") + .0 + .trim() + .parse() + .expect("mobile push participant limit must be an integer"); + assert_eq!( + MAX_MEMBERS, mobile_limit, + "group members and the mobile push recipient gate must have the same limit" ); } diff --git a/crates/buzz-db/src/store/mention_group.rs b/crates/buzz-db/src/store/mention_group.rs index e4aef6f52e5..97adbfefd3c 100644 --- a/crates/buzz-db/src/store/mention_group.rs +++ b/crates/buzz-db/src/store/mention_group.rs @@ -511,35 +511,17 @@ async fn persist_snapshot(tx: &mut AdmittedTx, event: Event) -> Result StoredEvent { async fn mention_group_lifecycle_keeps_receipts_and_live_tombstones() { let f = Fixture::new().await; let id = Uuid::new_v4(); - let mut members: Vec = (0..40) + let mut members: Vec = (0..19) .map(|_| Keys::generate().public_key().to_hex()) .collect(); members.push(f.relay.public_key().to_hex()); diff --git a/crates/buzz-relay/src/nip11.rs b/crates/buzz-relay/src/nip11.rs index 45db9011693..79edab5d818 100644 --- a/crates/buzz-relay/src/nip11.rs +++ b/crates/buzz-relay/src/nip11.rs @@ -492,6 +492,7 @@ pub(crate) async fn nip11_document( "settings_d": buzz_core::mention_group::SETTINGS_D_TAG, "default_manage": "everyone", "membership": if state.config.require_relay_membership { "roster" } else { "open" }, + "max_members": buzz_core::mention_group::MAX_MEMBERS, "max_default_channels": buzz_core::mention_group::MAX_DEFAULT_CHANNELS, })); info.supported_extensions diff --git a/crates/buzz-test-client/tests/e2e_mention_groups.rs b/crates/buzz-test-client/tests/e2e_mention_groups.rs index c9033740633..b6b8134508f 100644 --- a/crates/buzz-test-client/tests/e2e_mention_groups.rs +++ b/crates/buzz-test-client/tests/e2e_mention_groups.rs @@ -188,6 +188,8 @@ async fn http_commands_ws_live_delivery_and_tombstone_reads_share_one_authoritat "isolated open relay required" ); assert_eq!(info["mention_groups"]["default_manage"], "everyone"); + assert_eq!(info["mention_groups"]["version"], 1); + assert_eq!(info["mention_groups"]["max_members"], 20); let relay = PublicKey::from_hex(info["self"].as_str().expect("relay signing key")).unwrap(); let actor = Keys::generate(); let outsider = Keys::generate(); @@ -198,6 +200,45 @@ async fn http_commands_ws_live_delivery_and_tombstone_reads_share_one_authoritat let sub = format!("mg-{id}"); let mut writer = BuzzTestClient::connect(&ws, &actor).await.unwrap(); let mut reader = BuzzTestClient::connect(&ws, &outsider).await.unwrap(); + let bounded_id = Uuid::new_v4(); + let bounded_name = format!("mg-limit-{bounded_id}"); + let bounded_members: Vec<_> = (0..21).map(|_| Keys::generate().public_key()).collect(); + let oversized = put_with_defaults(&actor, bounded_id, 0, &bounded_name, &bounded_members, &[]); + let refusal = "invalid: a group can have at most 20 members"; + let (status, body) = post(&http, &actor, "/events", &json!(oversized)).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{body}"); + assert_eq!(body["error"], refusal); + let ack = writer.send_event(oversized).await.unwrap(); + assert!(!ack.accepted, "{ack:?}"); + assert_eq!(ack.message, refusal); + let boundary = put_with_defaults( + &actor, + bounded_id, + 0, + &bounded_name, + &bounded_members[..20], + &[], + ); + let (status, body) = post(&http, &actor, "/events", &json!(boundary)).await; + assert_eq!(status, StatusCode::OK, "{body}"); + assert_eq!(body["accepted"], true); + let heads = query_state( + &http, + &actor, + relay, + KIND_MENTION_GROUP_STATE, + &bounded_id.to_string(), + ) + .await; + assert_eq!(heads.len(), 1); + assert_eq!( + heads[0] + .tags + .iter() + .filter(|tag| tag.as_slice()[0] == "p") + .count(), + 20 + ); assert!( query_state(&http, &actor, relay, KIND_MENTION_GROUP_STATE, "settings") .await diff --git a/docs/nips/NIP-MG.md b/docs/nips/NIP-MG.md index 658fd645b77..a39bf2d9b43 100644 --- a/docs/nips/NIP-MG.md +++ b/docs/nips/NIP-MG.md @@ -47,7 +47,8 @@ A supporting relay advertises `nip-mg` in NIP-11 `supported_extensions` and: "set_manage_kind": 47002, "state_kind": 39010, "default_manage": "everyone", - "membership": "roster" + "membership": "roster", + "max_members": 20 } } ``` @@ -119,16 +120,20 @@ Validation and normalization: and internal spaces are preserved. Active names are unique per community under the database's `lower(name)` collation, not full Unicode case folding. - Each `p` has exactly two elements and a 64-character hexadecimal public key. - Normalize keys to lowercase, sorted and deduplicated. Zero members is valid. + Normalize keys to lowercase, sorted and deduplicated. Zero members is valid; + at most 20 distinct members are allowed, advertised as `max_members` in NIP-11. The signer is included only when explicitly tagged. Builders that suppress signer `p` tags must disable that behavior for this protocol. - Each `channel` has exactly two elements and a canonical non-nil UUID. Sort and deduplicate them; at most 32 distinct defaults are allowed. The relay validates channel eligibility within the community. Core wire validation performs no channel or membership lookup. -- Stored group size is independent of any send-recipient limit. Reject a command - when its resulting signed state exceeds the advertised message-size bound; - never truncate members or channels. +- The member limit matches the mobile push recipient gate. Larger audiences + should use a channel. A put over the limit is refused with + `invalid: a group can have at most 20 members`. A message combining groups or + other mentions remains subject to the push recipient gate for the whole + message. Also reject a command when its resulting signed state exceeds the + advertised message-size bound; never truncate members or channels. The only optional transport annotations are one each of: diff --git a/lefthook.yml b/lefthook.yml index d4fbe25c6d3..4ded7fd3607 100644 --- a/lefthook.yml +++ b/lefthook.yml @@ -100,7 +100,7 @@ pre-push: run: ./scripts/without-git-env.sh just file-size-check rust-tests: files: git diff --name-only origin/main...HEAD - glob: ["crates/**", "migrations/**", "schema/**", "Cargo.toml", "Cargo.lock", "rust-toolchain.toml", "deny.toml", "scripts/run-tests.sh", "Justfile"] + glob: ["crates/**", "mobile/lib/shared/push/push_subscription.dart", "migrations/**", "schema/**", "Cargo.toml", "Cargo.lock", "rust-toolchain.toml", "deny.toml", "scripts/run-tests.sh", "Justfile"] env: # Lanes run under a pty; with agent shells' TERM=dumb, nextest's # progress bar swallows every FAIL line, panic, and summary. diff --git a/scripts/ci-selection.test.mjs b/scripts/ci-selection.test.mjs index 821d4f08844..ad78b65b0e0 100644 --- a/scripts/ci-selection.test.mjs +++ b/scripts/ci-selection.test.mjs @@ -217,6 +217,11 @@ const scenarios = [ ["mobile"], ], ["mobile lockfile", ["mobile/pubspec.lock"], ["mobile"]], + [ + "mobile push gate shared with mention groups", + ["mobile/lib/shared/push/push_subscription.dart"], + ["mobile", "rust"], + ], [ "mobile release source helper", ["scripts/mobile-release-source.sh"], From be07b8b8e7528c44f9fb2622d6c1e504d2944571 Mon Sep 17 00:00:00 2001 From: Krish Ray Date: Mon, 16 Nov 2026 17:22:10 -0500 Subject: [PATCH 4/7] fix(mention-groups): keep stale default channels from blocking edits Retain saved defaults that become private or unlisted as inactive references, without granting channel access. Refuse newly selected nonpublic defaults. Clarify policy authority for open communities without stewards. Co-authored-by: Sigil <06114f072cf21e50fcd4133ab21346cdb1f74ee16d853a9729995fa6c03a251c@buzz.block.builderlab.xyz> Signed-off-by: Krish Ray Signed-off-by: kray Co-authored-by: Codex Signed-off-by: kray --- crates/buzz-db/src/runtime/migration.rs | 11 ++++- crates/buzz-db/src/store/channel_members.rs | 10 ++++- crates/buzz-db/src/store/deletion.rs | 20 +++++----- crates/buzz-db/src/store/mention_group.rs | 10 ++++- .../src/store/mention_group_postgres_tests.rs | 40 +++++++++++++++++++ crates/buzz-db/tests/observability_source.rs | 1 + docs/nips/NIP-MG.md | 12 ++++-- 7 files changed, 84 insertions(+), 20 deletions(-) diff --git a/crates/buzz-db/src/runtime/migration.rs b/crates/buzz-db/src/runtime/migration.rs index 7714214a47f..417697b5ee2 100644 --- a/crates/buzz-db/src/runtime/migration.rs +++ b/crates/buzz-db/src/runtime/migration.rs @@ -4072,10 +4072,17 @@ mod postgres_tests { .validate_serving_catalog() .await .expect("new code must boot before the drop"); - store + // Serving accepts the historical catalog, while destruction requires + // the current feature's expanded tenant catalog. + let error = store .validate_catalog() .await - .expect("deletion must accept the catalog before the drop"); + .expect_err("feature deletion requires its expanded tenant catalog"); + assert!( + matches!(&error, crate::DbError::DeletionSafety(reason) + if reason == "community deletion catalog drift (missing=mention_group_commands,mention_groups, unknown=)"), + "{error}" + ); run_migrations(&pool).await.expect("apply all migrations"); assert_eq!(present(&pool).await, (false, false)); store diff --git a/crates/buzz-db/src/store/channel_members.rs b/crates/buzz-db/src/store/channel_members.rs index 0315043724e..85a2b16246b 100644 --- a/crates/buzz-db/src/store/channel_members.rs +++ b/crates/buzz-db/src/store/channel_members.rs @@ -902,8 +902,9 @@ fn check_distinct_targets(targets: &[MemberPut<'_>]) -> Result<()> { /// Add only new group members to configured public channels on the group's /// admitted transaction. Missing/deleted channels remain inert references; -/// present nonpublic channels are invalid configuration. Closed public channels -/// are retained but skipped. Existing active memberships never change role. +/// newly configured nonpublic channels are invalid configuration. Saved defaults +/// that have become nonpublic or closed are retained but skipped. Existing active +/// memberships never change role. /// /// All channel membership locks precede TTL and row locks, in canonical order. /// Policy refusals are bounded accounting, while database failures abort the @@ -911,6 +912,7 @@ fn check_distinct_targets(targets: &[MemberPut<'_>]) -> Result<()> { pub(crate) async fn put_group_default_members_in_transaction( tx: &mut AdmittedTx, channels: &[Uuid], + old_channels: &[Uuid], targets: &[Vec], actor: &[u8], membership_enforced: bool, @@ -999,6 +1001,10 @@ pub(crate) async fn put_group_default_members_in_transaction( ) || row.try_get::("unlisted")? { + if old_channels.contains(&channel) { + summary.skip("channel_closed", targets.len()); + continue; + } return Err(DbError::InvalidData( "mention group default channel must be a listed public stream or forum".into(), )); diff --git a/crates/buzz-db/src/store/deletion.rs b/crates/buzz-db/src/store/deletion.rs index 8af60b4ded8..e20fae5576c 100644 --- a/crates/buzz-db/src/store/deletion.rs +++ b/crates/buzz-db/src/store/deletion.rs @@ -4834,7 +4834,7 @@ pub(crate) mod postgres_tests { // never had universal fence objects, but current destruction requires // them. This isolated fixture does not rerun the embedded migrator. sqlx::raw_sql(include_str!( - "../../../../migrations/0093_mention_groups.sql" + "../../../../migrations/0097_mention_groups.sql" )) .execute(&db.pool) .await @@ -4979,6 +4979,12 @@ DROP FUNCTION community_deletion_lock_key(UUID); crate::migration::run_migrations_through(&db.pool, 86) .await .expect("phase-one schema"); + sqlx::raw_sql(include_str!( + "../../../../migrations/0097_mention_groups.sql" + )) + .execute(&db.pool) + .await + .expect("expand feature schema while preserving single-table guards"); let community = db .ensure_configured_community("optional-guards.example") .await @@ -5833,9 +5839,7 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); } async fn contender_db(application_name: &str) -> Db { - let database_url = std::env::var("BUZZ_TEST_DATABASE_URL") - .or_else(|_| std::env::var("DATABASE_URL")) - .unwrap_or_else(|_| "postgres://buzz:buzz_dev@localhost:5432/buzz".to_string()); // sadscan:disable np.postgres.1 -- local test-only credentials + let database_url = crate::test_support::database_url(); let options = PgConnectOptions::from_str(&database_url) .expect("parse test database URL") .application_name(application_name); @@ -8337,9 +8341,7 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); /// disturb the shared test database. Returns the admin pool and the /// scratch database guard, which drops the database. async fn scratch_desired_state_database(prefix: &str) -> (PgPool, ScratchDb) { - let base_url = std::env::var("BUZZ_TEST_DATABASE_URL") - .or_else(|_| std::env::var("DATABASE_URL")) - .unwrap_or_else(|_| "postgres://buzz:buzz_dev@localhost:5432/buzz".to_string()); + let base_url = crate::test_support::database_url(); let admin = PgPool::connect(&base_url) .await .expect("connect admin database"); @@ -9287,9 +9289,7 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); // scenario in a dedicated database so concurrent purge/verify tests // never observe the drifted surface; advisory locks are also // per-database, so the parked migration lock cannot stall them. - let base_url = std::env::var("BUZZ_TEST_DATABASE_URL") - .or_else(|_| std::env::var("DATABASE_URL")) - .unwrap_or_else(|_| "postgres://buzz:buzz_dev@localhost:5432/buzz".to_string()); + let base_url = crate::test_support::database_url(); let probe_db = ScratchDb::create(&base_url, "buzz_lock_probe").await; let db = Db::new(&DbConfig { database_url: probe_db.url().to_owned(), diff --git a/crates/buzz-db/src/store/mention_group.rs b/crates/buzz-db/src/store/mention_group.rs index 97adbfefd3c..551e91d2612 100644 --- a/crates/buzz-db/src/store/mention_group.rs +++ b/crates/buzz-db/src/store/mention_group.rs @@ -123,7 +123,7 @@ impl Db { return Ok(GroupWrite::without_snapshot(GroupOutcome::Forbidden)); } let head = sqlx::query( - "SELECT name, members, version, deleted_at FROM mention_groups \ + "SELECT name, members, channels, version, deleted_at FROM mention_groups \ WHERE community_id=$1 AND id=$2 FOR UPDATE", ) .bind(community.as_uuid()) @@ -197,6 +197,11 @@ impl Db { hex::decode(key).map_err(|_| DbError::InvalidData("invalid member key".into())) }) .collect::>()?; + let old_channels: Vec = head + .as_ref() + .map(|row| row.try_get("channels")) + .transpose()? + .unwrap_or_default(); // Build and bound the final signed projection before changing any row. let state = build_snapshot( &mut tx, @@ -210,6 +215,7 @@ impl Db { crate::channel_members::put_group_default_members_in_transaction( &mut tx, &channels, + &old_channels, &added, &event.pubkey.to_bytes(), membership_enforced, @@ -302,7 +308,7 @@ impl Db { tags.push(tag(["manage", manage])?); let state = build_snapshot(&mut tx, relay_keys, "settings", tags, max_message_length).await?; - sqlx::query("UPDATE communities SET mention_groups_manage=$2,mention_groups_version=$3,mention_groups_state_event_id=$4 WHERE id=$1") + sqlx::query("UPDATE communities SET mention_groups_manage=$2,mention_groups_version=$3,mention_groups_state_event_id=$4 WHERE id=$1 AND deletion_state = 'active'") .bind(community.as_uuid()).bind(manage).bind(version).bind(state.id.as_bytes().as_slice()) .execute(tx.conn()).await?; let snapshot = persist_snapshot(&mut tx, state).await?; diff --git a/crates/buzz-db/src/store/mention_group_postgres_tests.rs b/crates/buzz-db/src/store/mention_group_postgres_tests.rs index 5194de1fd9b..191cbee9cec 100644 --- a/crates/buzz-db/src/store/mention_group_postgres_tests.rs +++ b/crates/buzz-db/src/store/mention_group_postgres_tests.rs @@ -616,4 +616,44 @@ async fn mention_group_default_joins_are_atomic_report_skips_and_never_replay() .await .unwrap() .is_some()); + + // A saved default can become nonpublic. It must not prevent a rename or + // member removal, and re-adding a group member must not grant access. + let without_target: Vec<_> = open_members + .iter() + .filter(|key| **key != target.public_key().to_hex()) + .cloned() + .collect(); + let mut version = 3; + for (visibility, unlisted) in [("open", true), ("private", false)] { + f.db.update_channel( + f.community, + public, + crate::channel::ChannelUpdate { + visibility: Some(visibility.into()), + unlisted: Some(unlisted), + ..Default::default() + }, + &f.actor.public_key().to_bytes(), + ) + .await + .unwrap(); + let rename = event(version, "Still editable", &without_target, &[public]); + let renamed = f.apply(&rename).await.unwrap(); + assert_eq!(renamed.outcome, GroupOutcome::Applied); + assert_eq!(renamed.joins.joined, 0); + version += 1; + let add = event(version, "Still editable", &open_members, &[public]); + let added = f.apply(&add).await.unwrap(); + assert_eq!(added.outcome, GroupOutcome::Applied); + assert_eq!(added.joins.skipped.get("channel_closed"), Some(&1)); + assert_eq!(added.joins.joined, 0); + assert!(f + .db + .get_member_role(f.community, public, &target.public_key().to_bytes()) + .await + .unwrap() + .is_none()); + version += 1; + } } diff --git a/crates/buzz-db/tests/observability_source.rs b/crates/buzz-db/tests/observability_source.rs index f85af28be13..bd601f78a70 100644 --- a/crates/buzz-db/tests/observability_source.rs +++ b/crates/buzz-db/tests/observability_source.rs @@ -4064,6 +4064,7 @@ fn every_production_single_table_guard_writer_preserves_its_invariants() { "mark_logically_verified", ], vec![ + "accept_mention_group_policy", "archive_community_owned_by", "ensure_configured_community_with_operation", "set_community_icon", diff --git a/docs/nips/NIP-MG.md b/docs/nips/NIP-MG.md index a39bf2d9b43..9a44eafaefe 100644 --- a/docs/nips/NIP-MG.md +++ b/docs/nips/NIP-MG.md @@ -72,7 +72,8 @@ Changing the management policy requires an actual owner/admin role. If the community has no owner/admin row, any current member may change the setting. This exception permits stewardship on communities without an initial steward. It does not grant inherited admin authority to agents in a community that has a -steward. +steward. On an open community without a steward, any authenticated, unbanned key +may therefore change the management policy. Commands use authenticated WS `EVENT` or HTTP `/events`. The signer must equal the authenticated actor. Existing tenant write fences, credential scope and @@ -126,8 +127,10 @@ Validation and normalization: signer `p` tags must disable that behavior for this protocol. - Each `channel` has exactly two elements and a canonical non-nil UUID. Sort and deduplicate them; at most 32 distinct defaults are allowed. The relay validates - channel eligibility within the community. Core wire validation performs no - channel or membership lookup. + newly selected channels' eligibility within the community. A saved default + that later becomes private or unlisted remains an inert reference and does + not prevent other group edits. Core wire validation performs no channel or + membership lookup. - The member limit matches the mobile push recipient gate. Larger audiences should use a channel. A put over the limit is refused with `invalid: a group can have at most 20 members`. A message combining groups or @@ -185,7 +188,8 @@ the stored member set are candidates for joining default channels. Replacing only the default-channel list does not retroactively join existing members. The relay uses the accepted replacement's defaults and existing channel-join policy; it skips identities that have left the community and channels that are -gone or closed. Private-channel access is never acquired through a group. +gone or closed, including saved defaults that became private or unlisted (counted +as `channel_closed`). Private-channel access is never acquired through a group. Group deletion does not remove channel membership. Default-channel membership writes commit in the group transaction. When any From f7d5de2ac1114a3946d9330b5b52d12c29642d07 Mon Sep 17 00:00:00 2001 From: Krish Ray Date: Tue, 17 Nov 2026 23:22:57 +0000 Subject: [PATCH 5/7] fix(db): order mention group channel locks before community writes Signed-off-by: Krish Ray Co-authored-by: Sigil <06114f072cf21e50fcd4133ab21346cdb1f74ee16d853a9729995fa6c03a251c@buzz.block.builderlab.xyz> Co-authored-by: Codex --- crates/buzz-db/src/store/channel_members.rs | 38 +++- crates/buzz-db/src/store/mention_group.rs | 15 +- .../src/store/mention_group_postgres_tests.rs | 174 ++++++++++++++++++ 3 files changed, 216 insertions(+), 11 deletions(-) diff --git a/crates/buzz-db/src/store/channel_members.rs b/crates/buzz-db/src/store/channel_members.rs index 85a2b16246b..5795ae4bc06 100644 --- a/crates/buzz-db/src/store/channel_members.rs +++ b/crates/buzz-db/src/store/channel_members.rs @@ -900,13 +900,38 @@ fn check_distinct_targets(targets: &[MemberPut<'_>]) -> Result<()> { } } +/// Lock all normalized group defaults before taking the community row. +/// +/// Membership locks all precede per-channel TTL and row locks. This phase +/// makes no eligibility decision: an accepted receipt must replay even when +/// a default has since disappeared or become nonpublic. +pub(crate) async fn lock_group_default_channels_in_transaction( + tx: &mut AdmittedTx, + channels: &[Uuid], +) -> Result<()> { + let community = tx.community(); + for channel in channels { + acquire_channel_membership_lock(tx.conn(), community, *channel).await?; + } + for channel in channels { + lock_channel_ttl_shared_in_transaction(tx, *channel).await?; + sqlx::query("SELECT id FROM channels WHERE community_id=$1 AND id=$2 FOR NO KEY UPDATE") + .bind(community.as_uuid()) + .bind(channel) + .fetch_optional(tx.conn()) + .await?; + } + Ok(()) +} + /// Add only new group members to configured public channels on the group's /// admitted transaction. Missing/deleted channels remain inert references; /// newly configured nonpublic channels are invalid configuration. Saved defaults /// that have become nonpublic or closed are retained but skipped. Existing active /// memberships never change role. /// -/// All channel membership locks precede TTL and row locks, in canonical order. +/// The caller holds [`lock_group_default_channels_in_transaction`]'s locks +/// for the normalized, sorted/deduplicated `channels` from the signed command. /// Policy refusals are bounded accounting, while database failures abort the /// entire group write. The caller publishes returned channel rosters after commit. pub(crate) async fn put_group_default_members_in_transaction( @@ -923,12 +948,6 @@ pub(crate) async fn put_group_default_members_in_transaction( )> { use buzz_core::channel::{decide_channel_add_policy, ChannelAddPolicyDenied}; let community = tx.community(); - let mut channels = channels.to_vec(); - channels.sort_unstable(); - channels.dedup(); - for channel in &channels { - acquire_channel_membership_lock(tx.conn(), community, *channel).await?; - } let mut summary = crate::mention_group::JoinSummary::default(); let policy_rows = if targets.is_empty() { Vec::new() @@ -984,11 +1003,10 @@ pub(crate) async fn put_group_default_members_in_transaction( }; let mut changed = Vec::new(); let mut joined_members = Vec::new(); - for channel in channels { - lock_channel_ttl_shared_in_transaction(tx, channel).await?; + for &channel in channels { let row = sqlx::query( "SELECT visibility::text AS visibility, channel_type::text AS channel_type, unlisted, archived_at \ - FROM channels WHERE community_id=$1 AND id=$2 AND deleted_at IS NULL FOR NO KEY UPDATE", + FROM channels WHERE community_id=$1 AND id=$2 AND deleted_at IS NULL", ).bind(community.as_uuid()).bind(channel).fetch_optional(tx.conn()).await?; let Some(row) = row else { summary.skip("channel_unavailable", targets.len()); diff --git a/crates/buzz-db/src/store/mention_group.rs b/crates/buzz-db/src/store/mention_group.rs index 551e91d2612..e17ebca43e0 100644 --- a/crates/buzz-db/src/store/mention_group.rs +++ b/crates/buzz-db/src/store/mention_group.rs @@ -113,6 +113,14 @@ impl Db { )); } let mut tx = self.begin_event_write_transaction(community).await?; + set_statement_budget(&mut tx).await?; + // Channel writers lock channels before invalidating the community. + // Match that order using the full normalized put set, locks only: + // mutable eligibility and authorization stay after the receipt check. + if let Operation::Put { channels, .. } = &command.operation { + crate::channel_members::lock_group_default_channels_in_transaction(&mut tx, channels) + .await?; + } lock_community(&mut tx).await?; if let Some(joins) = receipt_summary(tx.conn(), community, event.id.as_bytes()).await? { let mut result = GroupWrite::without_snapshot(GroupOutcome::Duplicate); @@ -280,6 +288,7 @@ impl Db { )); } let mut tx = self.begin_event_write_transaction(community).await?; + set_statement_budget(&mut tx).await?; lock_community(&mut tx).await?; if let Some(joins) = receipt_summary(tx.conn(), community, event.id.as_bytes()).await? { let mut result = GroupWrite::without_snapshot(GroupOutcome::Duplicate); @@ -333,10 +342,14 @@ impl Db { } } -async fn lock_community(tx: &mut AdmittedTx) -> Result<()> { +async fn set_statement_budget(tx: &mut AdmittedTx) -> Result<()> { sqlx::query("SET LOCAL statement_timeout='5s'") .execute(tx.conn()) .await?; + Ok(()) +} + +async fn lock_community(tx: &mut AdmittedTx) -> Result<()> { // The same lock owner transitions use: policy changes and group writes see // one order, and compatible FK key-share locks cannot create a lock cycle. sqlx::query("SELECT id FROM communities WHERE id=$1 FOR NO KEY UPDATE") diff --git a/crates/buzz-db/src/store/mention_group_postgres_tests.rs b/crates/buzz-db/src/store/mention_group_postgres_tests.rs index 191cbee9cec..4f8b57959a7 100644 --- a/crates/buzz-db/src/store/mention_group_postgres_tests.rs +++ b/crates/buzz-db/src/store/mention_group_postgres_tests.rs @@ -273,6 +273,160 @@ async fn mention_group_concurrent_cas_names_and_identical_retries_commit_once() assert_eq!(f.live_heads(id).await, 1); } +// A settings writer already holding a channel lock must be able to finish +// its community invalidation while a group put waits for that channel. +async fn assert_channel_writer_precedes_group_put(updates: crate::channel::ChannelUpdate) { + use buzz_core::channel::{ChannelType, ChannelVisibility}; + use std::time::Duration; + + let f = Fixture::new().await; + let channel = + f.db.create_channel( + f.community, + "Lock order", + ChannelType::Stream, + ChannelVisibility::Open, + None, + &f.actor.public_key().to_bytes(), + None, + ) + .await + .unwrap() + .id; + let id = Uuid::new_v4(); + let event = f.event( + buzz_core::kind::RELAY_ADMIN_PUT_MENTION_GROUP, + vec![ + vec!["d".into(), id.to_string()], + vec!["prev".into(), "0".into()], + vec!["name".into(), "Ordered".into()], + vec!["p".into(), f.actor.public_key().to_hex()], + vec!["channel".into(), channel.to_string()], + ], + ); + // One connection identifies the real acceptance backend without a + // test-only production seam or matching unrelated cluster sessions. + let put_pool = sqlx::postgres::PgPoolOptions::new() + .max_connections(1) + .connect(&crate::test_support::database_url()) + .await + .unwrap(); + let put_pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(&put_pool) + .await + .unwrap(); + let mut holder = + f.db.begin_event_write_transaction(f.community) + .await + .unwrap(); + sqlx::query("SET LOCAL statement_timeout='2s'") + .execute(holder.conn()) + .await + .unwrap(); + let holder_pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(holder.conn()) + .await + .unwrap(); + let mut writer = + crate::channel::lock_channel_for_settings_write(&mut holder, channel, &updates) + .await + .unwrap(); + let community = f.community; + let relay = f.relay.clone(); + let put = tokio::spawn(async move { + Db::from_pool(put_pool) + .accept_mention_group( + community, + &event, + &parse_command(&event).unwrap(), + &relay, + 1_000_000, + true, + ) + .await + }); + // Observe PostgreSQL's actual lock dependency, with a bounded deadline. + // No scheduling delay can stand in for proof that acceptance is blocked. + tokio::time::timeout(Duration::from_secs(3), async { + loop { + let blocked: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE pid=$1 \ + AND wait_event_type='Lock' AND $2=ANY(pg_blocking_pids(pid)))", + ) + .bind(put_pid) + .bind(holder_pid) + .fetch_one(f.db.pool()) + .await + .unwrap(); + if blocked { + break; + } + assert!( + !put.is_finished(), + "put finished without waiting for channel writer" + ); + tokio::task::yield_now().await; + } + }) + .await + .expect("put never waited for the production channel lock"); + let invalidated: chrono::DateTime = sqlx::query_scalar( + "UPDATE communities SET artifact_policy_modified_at=clock_timestamp() \ + WHERE id=$1 RETURNING artifact_policy_modified_at", + ) + .bind(community.as_uuid()) + .fetch_one(writer.tx().conn()) + .await + .expect("channel writer must update community while group put waits"); + holder.commit().await.unwrap(); + let accepted = tokio::time::timeout(Duration::from_secs(6), put) + .await + .unwrap() + .unwrap() + .expect("group put must also commit; neither writer may abort"); + assert_eq!(accepted.outcome, GroupOutcome::Applied); + assert_eq!(accepted.joins.skipped.get("already_member"), Some(&1)); + assert_eq!(f.state(id).await.0, 1); + assert_eq!(f.live_heads(id).await, 1); + let actual: chrono::DateTime = + sqlx::query_scalar("SELECT artifact_policy_modified_at FROM communities WHERE id=$1") + .bind(community.as_uuid()) + .fetch_one(f.db.pool()) + .await + .unwrap(); + assert_eq!(actual, invalidated); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn cluster_global_mention_group_put_waits_before_community_for_membership_writer() { + assert_channel_writer_precedes_group_put(crate::channel::ChannelUpdate { + visibility: Some("private".into()), + ..Default::default() + }) + .await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn cluster_global_mention_group_put_waits_before_community_for_exclusive_ttl_writer() { + assert_channel_writer_precedes_group_put(crate::channel::ChannelUpdate { + ttl_seconds: Some(Some(3600)), + ..Default::default() + }) + .await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn cluster_global_mention_group_put_waits_before_community_for_row_writer() { + assert_channel_writer_precedes_group_put(crate::channel::ChannelUpdate { + unlisted: Some(true), + ..Default::default() + }) + .await; +} + #[tokio::test] #[ignore = "requires Postgres"] async fn mention_group_failures_roll_back_rows_receipts_and_retirement() { @@ -638,6 +792,9 @@ async fn mention_group_default_joins_are_atomic_report_skips_and_never_replay() ) .await .unwrap(); + let replay = f.apply(&create).await.unwrap(); + assert_eq!(replay.outcome, GroupOutcome::Duplicate); + assert_eq!(replay.joins, accepted.joins); let rename = event(version, "Still editable", &without_target, &[public]); let renamed = f.apply(&rename).await.unwrap(); assert_eq!(renamed.outcome, GroupOutcome::Applied); @@ -656,4 +813,21 @@ async fn mention_group_default_joins_are_atomic_report_skips_and_never_replay() .is_none()); version += 1; } + f.db.soft_delete_channel(f.community, public).await.unwrap(); + let replay = f.apply(&create).await.unwrap(); + assert_eq!(replay.outcome, GroupOutcome::Duplicate); + assert_eq!(replay.joins, accepted.joins); + // Even a physically absent default must not turn an accepted receipt + // into a new eligibility decision in the prelock phase. + sqlx::query("DELETE FROM channels WHERE community_id=$1 AND id=$2") + .bind(f.community.as_uuid()) + .bind(public) + .execute(f.db.pool()) + .await + .unwrap(); + let replay = f.apply(&create).await.unwrap(); + assert_eq!(replay.outcome, GroupOutcome::Duplicate); + assert_eq!(replay.joins, accepted.joins); + assert_eq!(f.state(id).await.0, version); + assert_eq!(f.live_heads(id).await, 1); } From 266ab6245b3bd0c8c5f54678f1c327eaf27d5c82 Mon Sep 17 00:00:00 2001 From: Krish Ray Date: Tue, 17 Nov 2026 23:23:15 +0000 Subject: [PATCH 6/7] test(relay): seed historical mention group receipt without sleeping Signed-off-by: Krish Ray Co-authored-by: Sigil <06114f072cf21e50fcd4133ab21346cdb1f74ee16d853a9729995fa6c03a251c@buzz.block.builderlab.xyz> Co-authored-by: Codex --- .../handlers/mention_groups_postgres_tests.rs | 26 ++++++++++++++----- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/crates/buzz-relay/src/handlers/mention_groups_postgres_tests.rs b/crates/buzz-relay/src/handlers/mention_groups_postgres_tests.rs index c7e0c8e3c9e..fba096c773c 100644 --- a/crates/buzz-relay/src/handlers/mention_groups_postgres_tests.rs +++ b/crates/buzz-relay/src/handlers/mention_groups_postgres_tests.rs @@ -2,7 +2,6 @@ //! Run against the feature schema with BUZZ_TEST_DATABASE_URL set. use std::sync::Arc; -use std::time::Duration; use buzz_auth::Scope; use buzz_core::kind::{ @@ -252,25 +251,38 @@ async fn ban_and_current_group_policy_refusals_leave_no_receipt_and_have_valid_c } #[tokio::test] -#[ignore = "requires Postgres; exercises one real command-expiry transition"] +#[ignore = "requires Postgres"] async fn expired_exact_receipt_retry_survives_a_later_edit_but_unknown_expired_commands_fail() { let state = state().await; let tenant = community(&state, "mg-expiry").await; let actor = Keys::generate(); let id = Uuid::new_v4(); - let timestamp = Timestamp::now().as_secs() - 105; + let timestamp = Timestamp::now().as_secs() - 3600; let original = put_at(&actor, id, 0, "Original", timestamp); - ingest_event(&state, &tenant, original.clone(), auth(&actor)) + // Seed historical acceptance through the same storage API and parsed + // signed command as the handler, without a near-expiry setup or clock wait. + let seeded = state + .db + .accept_mention_group( + tenant.community(), + &original, + &buzz_core::mention_group::parse_command(&original).unwrap(), + &state.relay_keypair, + state.config.max_frame_bytes, + state.config.require_relay_membership, + ) .await .unwrap(); + assert_eq!( + seeded.outcome, + buzz_db::mention_group::GroupOutcome::Applied + ); + assert!(receipt(&state, &tenant, &original).await); let edit = put(&actor, id, 1, "Current"); ingest_event(&state, &tenant, edit, auth(&actor)) .await .unwrap(); let current = head(&state, &tenant, id).await.unwrap(); - let wait = (timestamp + 121).saturating_sub(Timestamp::now().as_secs()); - assert!(wait <= 16, "expiry wait unexpectedly exceeded its bound"); - tokio::time::sleep(Duration::from_secs(wait)).await; assert!(Timestamp::now().as_secs() > timestamp + 120); let replay = ingest_event(&state, &tenant, original.clone(), auth(&actor)) .await From 3df54db74f01ebd8f47cc0ecdba50745b17cfefb Mon Sep 17 00:00:00 2001 From: Krish Ray Date: Tue, 17 Nov 2026 23:23:31 +0000 Subject: [PATCH 7/7] fix(ci): scope Rust push parity to the mobile contract Signed-off-by: Krish Ray Co-authored-by: Sigil <06114f072cf21e50fcd4133ab21346cdb1f74ee16d853a9729995fa6c03a251c@buzz.block.builderlab.xyz> Co-authored-by: Codex --- .github/workflows/ci.yml | 2 +- crates/buzz-core/src/mention_group.rs | 4 ++-- lefthook.yml | 2 +- mobile/lib/shared/push/push_contract.dart | 3 +++ mobile/lib/shared/push/push_subscription.dart | 5 ++++- scripts/ci-selection.test.mjs | 9 +++++++-- 6 files changed, 18 insertions(+), 7 deletions(-) create mode 100644 mobile/lib/shared/push/push_contract.dart diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c199dc0ef01..841b79d0371 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -52,7 +52,7 @@ jobs: rust: - 'crates/**' # The core mention-group limit is coupled to the mobile push gate. - - 'mobile/lib/shared/push/push_subscription.dart' + - 'mobile/lib/shared/push/push_contract.dart' - 'migrations/**' - 'schema/**' - 'Cargo.toml' diff --git a/crates/buzz-core/src/mention_group.rs b/crates/buzz-core/src/mention_group.rs index dda96ad24f5..3dc2002f38e 100644 --- a/crates/buzz-core/src/mention_group.rs +++ b/crates/buzz-core/src/mention_group.rs @@ -22,7 +22,7 @@ pub const SETTINGS_D_TAG: &str = "settings"; pub const MAX_NAME_CHARS: usize = 120; /// Maximum distinct members in a group replacement. Keep in sync with /// `buzzPushHellthreadParticipantLimit` in -/// `mobile/lib/shared/push/push_subscription.dart` so one group fits the mobile +/// `mobile/lib/shared/push/push_contract.dart` so one group fits the mobile /// push recipient gate. Clients discover this value through NIP-11. pub const MAX_MEMBERS: usize = 20; /// Maximum distinct default channels in a group replacement. @@ -476,7 +476,7 @@ mod tests { fn group_member_limit_matches_mobile_push_gate() { let source = std::fs::read_to_string(concat!( env!("CARGO_MANIFEST_DIR"), - "/../../mobile/lib/shared/push/push_subscription.dart" + "/../../mobile/lib/shared/push/push_contract.dart" )) .expect("read the mobile push contract"); let initializer = source diff --git a/lefthook.yml b/lefthook.yml index 4ded7fd3607..204d11e0198 100644 --- a/lefthook.yml +++ b/lefthook.yml @@ -100,7 +100,7 @@ pre-push: run: ./scripts/without-git-env.sh just file-size-check rust-tests: files: git diff --name-only origin/main...HEAD - glob: ["crates/**", "mobile/lib/shared/push/push_subscription.dart", "migrations/**", "schema/**", "Cargo.toml", "Cargo.lock", "rust-toolchain.toml", "deny.toml", "scripts/run-tests.sh", "Justfile"] + glob: ["crates/**", "mobile/lib/shared/push/push_contract.dart", "migrations/**", "schema/**", "Cargo.toml", "Cargo.lock", "rust-toolchain.toml", "deny.toml", "scripts/run-tests.sh", "Justfile"] env: # Lanes run under a pty; with agent shells' TERM=dumb, nextest's # progress bar swallows every FAIL line, panic, and summary. diff --git a/mobile/lib/shared/push/push_contract.dart b/mobile/lib/shared/push/push_contract.dart new file mode 100644 index 00000000000..2df4c8208c3 --- /dev/null +++ b/mobile/lib/shared/push/push_contract.dart @@ -0,0 +1,3 @@ +/// Maximum p-tag recipients before mobile push suppresses a hellthread. +/// Kept in sync with the relay Mention Group member limit. +const buzzPushHellthreadParticipantLimit = 20; diff --git a/mobile/lib/shared/push/push_subscription.dart b/mobile/lib/shared/push/push_subscription.dart index 788a1d3ab20..36f2b1441bd 100644 --- a/mobile/lib/shared/push/push_subscription.dart +++ b/mobile/lib/shared/push/push_subscription.dart @@ -1,5 +1,9 @@ import 'dart:convert'; +import 'push_contract.dart'; + +export 'push_contract.dart' show buzzPushHellthreadParticipantLimit; + /// User-visible Buzz message kinds. This mirrors /// `EventKind.channelMessageEventKinds` without importing feature code into /// the shared push layer. @@ -10,7 +14,6 @@ const buzzPushChannelKinds = [9]; const buzzPushChannelChunkSize = 50; const buzzPushMaxSubscriptions = 16; const buzzPushMaxIgnoreFilters = 8; -const buzzPushHellthreadParticipantLimit = 20; const _supportedNotificationClasses = {'default'}; const _filterKeys = {'kinds', 'authors', '#p', '#h', '#e'}; diff --git a/scripts/ci-selection.test.mjs b/scripts/ci-selection.test.mjs index ad78b65b0e0..3acb1033d8b 100644 --- a/scripts/ci-selection.test.mjs +++ b/scripts/ci-selection.test.mjs @@ -218,10 +218,15 @@ const scenarios = [ ], ["mobile lockfile", ["mobile/pubspec.lock"], ["mobile"]], [ - "mobile push gate shared with mention groups", - ["mobile/lib/shared/push/push_subscription.dart"], + "mobile push contract shared with mention groups", + ["mobile/lib/shared/push/push_contract.dart"], ["mobile", "rust"], ], + [ + "mobile push implementation", + ["mobile/lib/shared/push/push_subscription.dart"], + ["mobile"], + ], [ "mobile release source helper", ["scripts/mobile-release-source.sh"],