From 82f5edb6182faedcd9cfc0c6b17f098b3075f18d Mon Sep 17 00:00:00 2001 From: kenny lopez Date: Tue, 15 Sep 2026 15:49:10 -0400 Subject: [PATCH] feat(relay): add channel-backed work sessions with inherited access Signed-off-by: kenny lopez --- crates/buzz-acp/src/relay.rs | 4 +- crates/buzz-core/src/kind.rs | 3 + crates/buzz-db/src/lib.rs | 2 +- crates/buzz-db/src/runtime/migration.rs | 20 +- crates/buzz-db/src/store/channel_members.rs | 52 +- crates/buzz-db/src/store/mod.rs | 2 + .../buzz-db/src/store/relay_admin_actions.rs | 11 +- crates/buzz-db/src/store/sessions.rs | 644 ++++++++++++++++++ crates/buzz-db/src/store/thread.rs | 34 +- crates/buzz-relay/src/api/bridge.rs | 40 +- crates/buzz-relay/src/config.rs | 6 + .../src/handlers/admin_outbox_worker.rs | 38 ++ crates/buzz-relay/src/handlers/ingest.rs | 40 +- crates/buzz-relay/src/handlers/mod.rs | 3 + crates/buzz-relay/src/handlers/sessions.rs | 156 +++++ .../src/handlers/sessions_postgres_tests.rs | 484 +++++++++++++ .../buzz-relay/src/handlers/side_effects.rs | 94 ++- crates/buzz-relay/src/nip11.rs | 5 + crates/buzz-relay/src/state.rs | 44 +- docs/features/sessions.md | 111 +++ migrations/0045_sessions.sql | 100 +++ schema/schema.sql | 35 +- 22 files changed, 1870 insertions(+), 58 deletions(-) create mode 100644 crates/buzz-db/src/store/sessions.rs create mode 100644 crates/buzz-relay/src/handlers/sessions.rs create mode 100644 crates/buzz-relay/src/handlers/sessions_postgres_tests.rs create mode 100644 docs/features/sessions.md create mode 100644 migrations/0045_sessions.sql diff --git a/crates/buzz-acp/src/relay.rs b/crates/buzz-acp/src/relay.rs index a019e75834..53b3b59e2a 100644 --- a/crates/buzz-acp/src/relay.rs +++ b/crates/buzz-acp/src/relay.rs @@ -154,7 +154,9 @@ pub(crate) fn channel_type_from_tags(tags: &[serde_json::Value]) -> String { } } } - if declared_type == Some("dm") || is_hidden { + if declared_type == Some("session") { + "session".to_string() + } else if declared_type == Some("dm") || is_hidden { "dm".to_string() } else if declared_type == Some("private") || is_private { "private".to_string() diff --git a/crates/buzz-core/src/kind.rs b/crates/buzz-core/src/kind.rs index 4e1ab1c7f5..c5d7e920d7 100644 --- a/crates/buzz-core/src/kind.rs +++ b/crates/buzz-core/src/kind.rs @@ -341,6 +341,8 @@ pub const KIND_NIP29_EDIT_METADATA: u32 = 9002; pub const KIND_NIP29_DELETE_EVENT: u32 = 9005; /// NIP-29: Create a new group. pub const KIND_NIP29_CREATE_GROUP: u32 = 9007; +/// Durable session creation and parent assignment. +pub const KIND_SESSION_COMMAND: u32 = 9050; /// NIP-29: Delete a group. pub const KIND_NIP29_DELETE_GROUP: u32 = 9008; /// NIP-29: Create an invite to a group. @@ -666,6 +668,7 @@ pub const ALL_KINDS: &[u32] = &[ KIND_NIP29_EDIT_METADATA, KIND_NIP29_DELETE_EVENT, KIND_NIP29_CREATE_GROUP, + KIND_SESSION_COMMAND, KIND_NIP29_DELETE_GROUP, KIND_NIP29_CREATE_INVITE, KIND_NIP29_JOIN_REQUEST, diff --git a/crates/buzz-db/src/lib.rs b/crates/buzz-db/src/lib.rs index 6f8d0ffb3d..a16ac409b8 100644 --- a/crates/buzz-db/src/lib.rs +++ b/crates/buzz-db/src/lib.rs @@ -50,7 +50,7 @@ pub use store::{ admin_moderation, allowlist, api_token, archived_identities, channel, channel_members, community, deletion, dm, event, feed, git_repo, moderation, partition, product_feedback, push, reaction, relay_admin_actions, relay_invite, relay_members, relay_operators, reminder, - replaceable, thread, usage, user, workflow, + replaceable, sessions, thread, usage, user, workflow, }; pub use allowlist::AllowlistEntry; diff --git a/crates/buzz-db/src/runtime/migration.rs b/crates/buzz-db/src/runtime/migration.rs index 5901512504..f25db645c9 100644 --- a/crates/buzz-db/src/runtime/migration.rs +++ b/crates/buzz-db/src/runtime/migration.rs @@ -702,7 +702,7 @@ mod postgres_tests { let mut migrations: Vec<_> = MIGRATOR.iter().collect(); migrations.sort_by_key(|migration| migration.version); - assert_eq!(migrations.len(), 44); + assert_eq!(migrations.len(), 45); assert_eq!(migrations[0].version, 1); assert_eq!(&*migrations[0].description, "initial schema"); assert!(migrations[0] @@ -1141,18 +1141,26 @@ mod postgres_tests { assert!(roster_fence.contains("snapshot_members IS DISTINCT FROM canonical_members")); assert!(roster_fence.contains("ERRCODE = '23514'")); - // Fresh desired-state bootstrap must install the identical executable - // fence as migration 0032. CI and isolated relay startup use schema.sql + // Migration 0045 extends the fence to inherited session membership; + // keep 0032 immutable and compare the current executable fence instead. + // CI and isolated relay startup use schema.sql // without running migrations, so drift reopens rolling-deploy races. fn extract_roster_fence(sql: &str) -> &str { let fence_start = "CREATE OR REPLACE FUNCTION guard_channel_roster_snapshot()"; - let fence_end = " FOR EACH ROW EXECUTE FUNCTION guard_channel_roster_snapshot();"; + let fence_end = "$$ LANGUAGE plpgsql;"; let start = sql.find(fence_start).expect("roster fence function"); - let relative_end = sql[start..].find(fence_end).expect("roster fence trigger"); + let relative_end = sql[start..].find(fence_end).expect("roster fence body"); &sql[start..start + relative_end + fence_end.len()] } + assert_eq!(migrations[44].version, 45); + let sessions = migrations[44].sql.as_str(); + assert!(sessions.contains("FROM effective_channel_members cm")); + assert!(sessions.contains("SELECT parent_channel_id INTO parent_id")); + assert!(desired_schema.contains("CREATE TRIGGER trg_events_guard_channel_roster_snapshot")); + assert!(desired_schema + .contains("FOR EACH ROW EXECUTE FUNCTION guard_channel_roster_snapshot();")); assert_eq!( - extract_roster_fence(roster_fence), + extract_roster_fence(sessions), extract_roster_fence(desired_schema) ); diff --git a/crates/buzz-db/src/store/channel_members.rs b/crates/buzz-db/src/store/channel_members.rs index 8280ca01f8..122870da84 100644 --- a/crates/buzz-db/src/store/channel_members.rs +++ b/crates/buzz-db/src/store/channel_members.rs @@ -178,7 +178,7 @@ pub async fn verify_channel_roster_fence_behavior(pool: &sqlx::PgPool) -> Result /// Take the per-channel membership lock. MUST be the first statement in the /// transaction that then reads roles/owner counts and writes membership, so the /// whole check-then-write sequence is atomic against a concurrent one. -async fn acquire_channel_membership_lock( +pub(crate) async fn acquire_channel_membership_lock( tx: &mut Transaction<'_, Postgres>, community_id: CommunityId, channel_id: Uuid, @@ -352,10 +352,24 @@ pub async fn lock_member_snapshot( ) .await?; acquire_channel_membership_lock(&mut tx, community_id, channel_id).await?; + // A move also holds the child lock before its parent's lock, so the parent + // identity cannot change between this read and publication. + let parent: Option = sqlx::query_scalar( + "SELECT parent_channel_id FROM channels WHERE community_id=$1 AND id=$2", + ) + .bind(community_id.as_uuid()) + .bind(channel_id) + .fetch_optional(&mut *tx) + .await? + .flatten(); + if let Some(parent) = parent { + acquire_channel_membership_lock(&mut tx, community_id, parent).await?; + } + let rows = sqlx::query( r#" SELECT cm.channel_id, cm.pubkey, cm.role::text AS role, cm.joined_at, cm.invited_by, cm.removed_at - FROM channel_members cm + FROM effective_channel_members cm JOIN channels c ON cm.community_id = c.community_id AND cm.channel_id = c.id AND c.deleted_at IS NULL WHERE cm.community_id = $1 AND cm.channel_id = $2 AND cm.removed_at IS NULL ORDER BY cm.joined_at ASC @@ -416,6 +430,7 @@ pub async fn add_member( // First statement: serialize the whole role-check / owner-count / upsert // sequence against concurrent membership writes on this channel. acquire_channel_membership_lock(&mut tx, community_id, channel_id).await?; + crate::sessions::require_independent_membership(&mut tx, community_id, channel_id).await?; let channel = get_channel_tx(&mut tx, community_id, channel_id).await?; @@ -504,7 +519,7 @@ pub async fn add_member( // to moderate, edit metadata, or re-grant ownership. if current_role == "owner" && effective_role != MemberRole::Owner { let row = sqlx::query( - "SELECT COUNT(*) as cnt FROM channel_members \ + "SELECT COUNT(*) as cnt FROM effective_channel_members \ WHERE community_id = $1 AND channel_id = $2 AND role = 'owner' AND removed_at IS NULL", ) .bind(community_id.as_uuid()) @@ -541,7 +556,7 @@ pub async fn add_member( let row = sqlx::query( r#" SELECT channel_id, pubkey, role::text AS role, joined_at, invited_by, removed_at - FROM channel_members WHERE community_id = $1 AND channel_id = $2 AND pubkey = $3 + FROM effective_channel_members WHERE community_id = $1 AND channel_id = $2 AND pubkey = $3 "#, ) .bind(community_id.as_uuid()) @@ -603,6 +618,7 @@ pub async fn remove_member( // the UPDATE against concurrent membership writes on this channel (same key // as `add_member`). acquire_channel_membership_lock(&mut tx, community_id, channel_id).await?; + crate::sessions::require_independent_membership(&mut tx, community_id, channel_id).await?; if !is_self_remove { let actor_role_str = get_active_role_tx(&mut tx, community_id, channel_id, actor_pubkey) @@ -624,7 +640,7 @@ pub async fn remove_member( let target_role = get_active_role_tx(&mut tx, community_id, channel_id, pubkey).await?; if target_role.as_deref() == Some("owner") { let row = sqlx::query( - "SELECT COUNT(*) as cnt FROM channel_members \ + "SELECT COUNT(*) as cnt FROM effective_channel_members \ WHERE community_id = $1 AND channel_id = $2 AND role = 'owner' AND removed_at IS NULL", ) .bind(community_id.as_uuid()) @@ -674,7 +690,7 @@ pub async fn is_member( ) .await?; let row = sqlx::query( - "SELECT COUNT(*) as cnt FROM channel_members cm \ + "SELECT COUNT(*) as cnt FROM effective_channel_members cm \ JOIN channels c ON cm.community_id = c.community_id AND cm.channel_id = c.id AND c.deleted_at IS NULL \ WHERE cm.community_id = $1 AND cm.channel_id = $2 AND cm.pubkey = $3 AND cm.removed_at IS NULL", ) @@ -705,7 +721,7 @@ pub async fn membership_pairs( ) .await?; let rows = sqlx::query( - "SELECT cm.channel_id, cm.pubkey FROM channel_members cm \ + "SELECT cm.channel_id, cm.pubkey FROM effective_channel_members cm \ JOIN channels c ON cm.community_id = c.community_id AND cm.channel_id = c.id AND c.deleted_at IS NULL \ WHERE cm.community_id = $1 AND cm.channel_id = ANY($2) AND cm.pubkey = ANY($3) AND cm.removed_at IS NULL", ) @@ -751,7 +767,7 @@ async fn get_members_with_operation( let rows = sqlx::query( r#" SELECT cm.channel_id, cm.pubkey, cm.role::text AS role, cm.joined_at, cm.invited_by, cm.removed_at - FROM channel_members cm + FROM effective_channel_members cm JOIN channels c ON cm.community_id = c.community_id AND cm.channel_id = c.id AND c.deleted_at IS NULL WHERE cm.community_id = $1 AND cm.channel_id = $2 AND cm.removed_at IS NULL ORDER BY cm.joined_at ASC @@ -787,7 +803,7 @@ pub async fn get_members_bulk( let rows = sqlx::query( r#" SELECT cm.channel_id, cm.pubkey, cm.role::text AS role, cm.joined_at, cm.invited_by, cm.removed_at - FROM channel_members cm + FROM effective_channel_members cm JOIN channels c ON cm.community_id = c.community_id AND cm.channel_id = c.id AND c.deleted_at IS NULL WHERE cm.community_id = $1 AND cm.channel_id = ANY($2) AND cm.removed_at IS NULL ORDER BY cm.joined_at ASC @@ -817,7 +833,7 @@ pub async fn get_accessible_channel_ids( let rows = sqlx::query( r#" SELECT cm.channel_id - FROM channel_members cm + FROM effective_channel_members cm JOIN channels c ON cm.community_id = c.community_id AND cm.channel_id = c.id AND c.deleted_at IS NULL WHERE cm.community_id = $1 AND cm.pubkey = $2 AND cm.removed_at IS NULL UNION @@ -871,7 +887,7 @@ pub async fn list_large_channel_rosters_needing_reconciliation( r#" WITH large_rosters AS ( SELECT cm.community_id, cm.channel_id, COUNT(*) AS member_count - FROM channel_members cm + FROM effective_channel_members cm JOIN channels ch ON ch.community_id = cm.community_id AND ch.id = cm.channel_id @@ -927,7 +943,7 @@ async fn get_active_role_tx( pubkey: &[u8], ) -> Result> { let row = sqlx::query( - "SELECT role::text AS role FROM channel_members \ + "SELECT role::text AS role FROM effective_channel_members \ WHERE community_id = $1 AND channel_id = $2 AND pubkey = $3 AND removed_at IS NULL", ) .bind(community_id.as_uuid()) @@ -1051,7 +1067,7 @@ pub async fn get_accessible_channels( c.ttl_seconds, c.ttl_deadline, (cm.channel_id IS NOT NULL) AS is_member FROM channels c - LEFT JOIN channel_members cm + LEFT JOIN effective_channel_members cm ON c.community_id = cm.community_id AND c.id = cm.channel_id AND cm.pubkey = $2 AND cm.removed_at IS NULL WHERE c.community_id = $1 AND c.deleted_at IS NULL {membership_clause} @@ -1102,7 +1118,7 @@ pub async fn get_bot_members( r#" SELECT cm.pubkey, u.display_name, u.agent_type, u.capabilities, COALESCE(json_agg(DISTINCT jsonb_build_object('name', c.name, 'id', c.id::text)), '[]') AS channels_json - FROM channel_members cm + FROM effective_channel_members cm LEFT JOIN users u ON cm.community_id = u.community_id AND cm.pubkey = u.pubkey JOIN channels c ON cm.community_id = c.community_id AND cm.channel_id = c.id AND c.deleted_at IS NULL WHERE cm.community_id = $1 AND cm.role = 'bot' AND cm.removed_at IS NULL @@ -1217,7 +1233,7 @@ pub async fn get_member_count( ) .await?; let row = sqlx::query( - "SELECT COUNT(*) as cnt FROM channel_members WHERE community_id = $1 AND channel_id = $2 AND removed_at IS NULL", + "SELECT COUNT(*) as cnt FROM effective_channel_members WHERE community_id = $1 AND channel_id = $2 AND removed_at IS NULL", ) .bind(community_id.as_uuid()) .bind(channel_id) @@ -1245,7 +1261,7 @@ pub async fn get_member_counts_bulk( .await?; let mut qb: sqlx::QueryBuilder = sqlx::QueryBuilder::new( - "SELECT channel_id, COUNT(*) as cnt FROM channel_members \ + "SELECT channel_id, COUNT(*) as cnt FROM effective_channel_members \ WHERE community_id = ", ); qb.push_bind(community_id.as_uuid()); @@ -1282,7 +1298,7 @@ pub async fn get_member_role( ) .await?; let row = sqlx::query( - "SELECT cm.role::text AS role FROM channel_members cm \ + "SELECT cm.role::text AS role FROM effective_channel_members cm \ JOIN channels c ON cm.community_id = c.community_id AND cm.channel_id = c.id AND c.deleted_at IS NULL \ WHERE cm.community_id = $1 AND cm.channel_id = $2 AND cm.pubkey = $3 AND cm.removed_at IS NULL", ) @@ -2803,7 +2819,7 @@ mod postgres_tests { .expect("an owner may remove another owner"); let stored: String = sqlx::query_scalar( - "SELECT role::text FROM channel_members \ + "SELECT role::text FROM effective_channel_members \ WHERE community_id = $1 AND channel_id = $2 AND pubkey = $3", ) .bind(community.as_uuid()) diff --git a/crates/buzz-db/src/store/mod.rs b/crates/buzz-db/src/store/mod.rs index 1fa1273eb0..5bf6497150 100644 --- a/crates/buzz-db/src/store/mod.rs +++ b/crates/buzz-db/src/store/mod.rs @@ -46,6 +46,8 @@ pub mod relay_operators; pub mod reminder; /// Replaceable-event persistence and coordinate locking. pub mod replaceable; +/// Channel-backed work sessions and inherited access. +pub mod sessions; /// Thread metadata persistence. pub mod thread; /// Per-community usage rollup queries for Prometheus gauges. diff --git a/crates/buzz-db/src/store/relay_admin_actions.rs b/crates/buzz-db/src/store/relay_admin_actions.rs index 7662077911..4ab5c07555 100644 --- a/crates/buzz-db/src/store/relay_admin_actions.rs +++ b/crates/buzz-db/src/store/relay_admin_actions.rs @@ -621,6 +621,9 @@ pub async fn execute_kick_with_marker( actor_pubkey: &[u8], ) -> Result { let mut tx = pool.begin().await?; + crate::channel_members::acquire_channel_membership_lock(&mut tx, community_id, channel_id) + .await?; + crate::sessions::require_independent_membership(&mut tx, community_id, channel_id).await?; let owned: bool = sqlx::query_scalar( r#" @@ -1570,6 +1573,11 @@ pub async fn deploy_kick_member( target_pubkey: &[u8], actor_pubkey: &[u8], ) -> Result { + let mut tx = pool.begin().await?; + crate::channel_members::acquire_channel_membership_lock(&mut tx, community_id, channel_id) + .await?; + crate::sessions::require_independent_membership(&mut tx, community_id, channel_id).await?; + // Use a direct UPDATE to avoid the tenant ownership check in channel::remove_member. // This is the deployment-authority primitive: no actor role check. let result = sqlx::query( @@ -1583,9 +1591,10 @@ pub async fn deploy_kick_member( .bind(community_id.as_uuid()) .bind(channel_id) .bind(target_pubkey) - .execute(pool) + .execute(&mut *tx) .await?; + tx.commit().await?; if result.rows_affected() > 0 { Ok(KickResult::Removed) } else { diff --git a/crates/buzz-db/src/store/sessions.rs b/crates/buzz-db/src/store/sessions.rs new file mode 100644 index 0000000000..638b60714a --- /dev/null +++ b/crates/buzz-db/src/store/sessions.rs @@ -0,0 +1,644 @@ +//! Durable channel-backed sessions. Parent membership is resolved at read time. + +use buzz_core::{CommunityId, StoredEvent}; +use nostr::Event; +use serde::Deserialize; +use sqlx::{Postgres, Row, Transaction}; +use uuid::Uuid; + +use crate::{channel_members::acquire_channel_membership_lock, Db, DbError, Result}; + +/// Session metadata independent of the channel's message storage. +#[derive(Debug, Clone)] +pub struct SessionInfo { + /// A parent supplies the entire current membership and role set. + pub parent_id: Option, +} + +/// Commands are scoped by the signed event's single `h` tag. +#[derive(Debug, Deserialize)] +#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)] +pub enum SessionCommand { + /// Create a private standalone session or a child of an existing channel. + Create { + /// Initial topic, generated from the first prompt by the client. + title: String, + /// Omitted for independent access. + parent_id: Option, + }, + /// Share a standalone session's whole history with a parent channel. + Move { + /// The channel that will control access. + parent_id: Uuid, + /// Explicit acknowledgement of full-history sharing and access changes. + confirm_history: bool, + }, +} + +/// Reject independent roster writes on children while holding their membership lock. +pub(crate) async fn require_independent_membership( + tx: &mut Transaction<'_, Postgres>, + community: CommunityId, + channel: Uuid, +) -> Result<()> { + let parent: Option = sqlx::query_scalar( + "SELECT parent_channel_id FROM channels WHERE community_id=$1 AND id=$2", + ) + .bind(community.as_uuid()) + .bind(channel) + .fetch_optional(&mut **tx) + .await? + .flatten(); + if parent.is_some() { + return Err(DbError::AccessDenied( + "manage members in the parent channel".into(), + )); + } + Ok(()) +} + +impl Db { + /// Read a session's complete conversation, including agent replies, with bounded keyset paging. + pub async fn session_window( + &self, + community: CommunityId, + id: Uuid, + limit: u32, + cursor: Option<(chrono::DateTime, Vec)>, + kinds: Option<&[u32]>, + ) -> Result<(crate::thread::ChannelWindow, crate::ReadSession)> { + if self.session_info(community, id).await?.is_none() { + return Err(DbError::InvalidData( + "session timeline requires a session".into(), + )); + } + let mut conn = self.pool.acquire().await?; + let window = crate::thread::get_conversation_window_on( + &mut conn, community, id, limit, cursor, kinds, true, + ) + .await?; + Ok(( + window, + crate::ReadSession { + inner: crate::ReadSessionInner::Writer(self.pool.clone()), + }, + )) + } + + /// Read a session's parent from the authoritative writer database. + pub async fn session_info( + &self, + community: CommunityId, + id: Uuid, + ) -> Result> { + let row = sqlx::query("SELECT parent_channel_id FROM channels WHERE community_id=$1 AND id=$2 AND is_session AND deleted_at IS NULL") + .bind(community.as_uuid()).bind(id).fetch_optional(&self.pool).await?; + row.map(|row| { + Ok(SessionInfo { + parent_id: row.try_get("parent_channel_id")?, + }) + }) + .transpose() + } + + /// Direct children only; sessions cannot themselves be parents. + pub async fn child_sessions(&self, community: CommunityId, parent: Uuid) -> Result> { + Ok(sqlx::query_scalar("SELECT id FROM channels WHERE community_id=$1 AND parent_channel_id=$2 AND deleted_at IS NULL ORDER BY id") + .bind(community.as_uuid()).bind(parent).fetch_all(&self.pool).await?) + } + + /// Apply an authorized session command and store its signed receipt atomically. + pub async fn apply_session_command( + &self, + community: CommunityId, + id: Uuid, + event: &Event, + command: &SessionCommand, + ) -> Result<(StoredEvent, bool)> { + let actor = event.pubkey.to_bytes(); + let parent = match command { + SessionCommand::Create { parent_id, .. } => *parent_id, + SessionCommand::Move { parent_id, .. } => Some(*parent_id), + }; + if parent == Some(id) { + return Err(DbError::InvalidData( + "a session cannot parent itself".into(), + )); + } + let connection = crate::observability::acquire_writer( + &self.pool, + crate::observability::WriterOperation::EventWrite, + ) + .await?; + let mut tx = sqlx::Transaction::begin(connection, None).await?; + // An ordinary channel cannot become a session. Reject it as the source + // before taking two locks, including malformed create/move commands. + let source_is_session: Option = + sqlx::query_scalar("SELECT is_session FROM channels WHERE community_id=$1 AND id=$2") + .bind(community.as_uuid()) + .bind(id) + .fetch_optional(&mut *tx) + .await?; + if source_is_session == Some(false) { + return Err(DbError::InvalidData( + "session identifier belongs to an ordinary channel".into(), + )); + } + // Session identity is immutable. Reject a session as parent before taking + // two locks, preventing inverse child/parent lock graphs. + if let Some(parent) = parent { + let ordinary: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM channels WHERE community_id=$1 AND id=$2 AND NOT is_session)", + ).bind(community.as_uuid()).bind(parent).fetch_one(&mut *tx).await?; + if !ordinary { + return Err(DbError::AccessDenied( + "choose an active parent channel".into(), + )); + } + } + // Match roster publication: child membership, then parent membership. + let mut locks = vec![id]; + locks.extend(parent); + for channel in &locks { + acquire_channel_membership_lock(&mut tx, community, *channel).await?; + } + // Match TTL updates: TTL advisory lock precedes channel row locks. + sqlx::query("SELECT pg_advisory_xact_lock_shared(hashtextextended($1, 0))") + .bind(format!("buzz_channel_ttl:{}:{}", community.as_uuid(), id)) + .execute(&mut *tx) + .await?; + // Row locks also serialize against archive/delete metadata writes. + sqlx::query( + "SELECT id FROM channels WHERE community_id=$1 AND id=ANY($2) ORDER BY id FOR UPDATE", + ) + .bind(community.as_uuid()) + .bind(&locks) + .fetch_all(&mut *tx) + .await?; + // Retrying an exact accepted command must not repeat a move or create. + let previous: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM events WHERE community_id=$1 AND id=$2)", + ) + .bind(community.as_uuid()) + .bind(event.id.as_bytes().as_slice()) + .fetch_one(&mut *tx) + .await?; + if previous { + let member: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM effective_channel_members m JOIN channels c ON c.community_id=m.community_id AND c.id=m.channel_id WHERE m.community_id=$1 AND m.channel_id=$2 AND m.pubkey=$3 AND m.removed_at IS NULL AND c.deleted_at IS NULL)") + .bind(community.as_uuid()).bind(id).bind(actor.as_slice()).fetch_one(&mut *tx).await?; + if !member { + return Err(DbError::AccessDenied("session access has changed".into())); + } + let result = crate::event::insert_event_with_thread_metadata_tx( + &mut tx, + community, + event, + Some(id), + None, + ) + .await?; + tx.commit().await?; + return Ok(result); + } + if let Some(parent) = parent { + // Locks serialize against both membership changes and a concurrent move. + let allowed: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM channels c JOIN effective_channel_members m ON m.community_id=c.community_id AND m.channel_id=c.id WHERE c.community_id=$1 AND c.id=$2 AND NOT c.is_session AND c.channel_type IN ('stream','forum') AND c.archived_at IS NULL AND c.deleted_at IS NULL AND m.pubkey=$3 AND m.removed_at IS NULL)") + .bind(community.as_uuid()).bind(parent).bind(actor.as_slice()).fetch_one(&mut *tx).await?; + if !allowed { + return Err(DbError::AccessDenied( + "choose an active channel you belong to".into(), + )); + } + } + match command { + SessionCommand::Create { title, .. } => { + if title.trim().is_empty() || title.chars().count() > 120 { + return Err(DbError::InvalidData( + "session title must contain 1 to 120 characters".into(), + )); + } + let exists: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM channels WHERE community_id=$1 AND id=$2)", + ) + .bind(community.as_uuid()) + .bind(id) + .fetch_one(&mut *tx) + .await?; + if exists { + return Err(DbError::InvalidData( + "session identifier already exists".into(), + )); + } + sqlx::query("INSERT INTO channels (community_id,id,name,channel_type,visibility,created_by,is_session,parent_channel_id) VALUES ($1,$2,$3,'stream','private',$4,true,$5)") + .bind(community.as_uuid()).bind(id).bind(title.trim()).bind(actor.as_slice()).bind(parent).execute(&mut *tx).await?; + if parent.is_none() { + sqlx::query("INSERT INTO channel_members (community_id,channel_id,pubkey,role,invited_by) VALUES ($1,$2,$3,'owner',$3)") + .bind(community.as_uuid()).bind(id).bind(actor.as_slice()).execute(&mut *tx).await?; + } + } + SessionCommand::Move { + parent_id, + confirm_history, + } => { + if !confirm_history { + return Err(DbError::InvalidData( + "confirm sharing the entire session history".into(), + )); + } + let owned: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM channels c JOIN channel_members m ON m.community_id=c.community_id AND m.channel_id=c.id WHERE c.community_id=$1 AND c.id=$2 AND c.is_session AND c.parent_channel_id IS NULL AND c.deleted_at IS NULL AND c.archived_at IS NULL AND m.pubkey=$3 AND m.role='owner' AND m.removed_at IS NULL)") + .bind(community.as_uuid()).bind(id).bind(actor.as_slice()).fetch_one(&mut *tx).await?; + if !owned { + return Err(DbError::AccessDenied( + "only a standalone session owner can move it".into(), + )); + } + let missing: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM channel_members s WHERE s.community_id=$1 AND s.channel_id=$2 AND s.removed_at IS NULL AND NOT EXISTS(SELECT 1 FROM effective_channel_members p WHERE p.community_id=s.community_id AND p.channel_id=$3 AND p.pubkey=s.pubkey AND p.removed_at IS NULL))") + .bind(community.as_uuid()).bind(id).bind(parent_id).fetch_one(&mut *tx).await?; + if missing { + return Err(DbError::AccessDenied( + "add every session participant to the destination channel before moving" + .into(), + )); + } + sqlx::query("UPDATE channels SET parent_channel_id=$3,updated_at=NOW() WHERE community_id=$1 AND id=$2") + .bind(community.as_uuid()).bind(id).bind(parent_id).execute(&mut *tx).await?; + } + } + let result = crate::event::insert_event_with_thread_metadata_tx( + &mut tx, + community, + event, + Some(id), + None, + ) + .await?; + tx.commit().await?; + Ok(result) + } +} + +#[cfg(test)] +mod postgres_tests { + use super::*; + use crate::channel::{ChannelType, ChannelVisibility, MemberRole}; + use nostr::{EventBuilder, Keys, Kind, Tag}; + + fn command(keys: &Keys, id: Uuid, body: serde_json::Value) -> Event { + EventBuilder::new(Kind::Custom(9050), body.to_string()) + .tags([Tag::parse(["h", &id.to_string()]).unwrap()]) + .sign_with_keys(keys) + .unwrap() + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn session_creation_move_and_revocation() { + exercise_session_creation_move_and_revocation().await; + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn migration_schema_session_creation_move_and_revocation() { + exercise_session_creation_move_and_revocation().await; + } + + async fn exercise_session_creation_move_and_revocation() { + let url = crate::test_support::database_url(); + let db = Db::new(&crate::DbConfig { + database_url: url, + ..Default::default() + }) + .await + .unwrap(); + if std::env::var("BUZZ_TEST_SCHEMA_MODE").as_deref() != Ok("desired") { + db.migrate().await.unwrap(); + } + let community = CommunityId::from_uuid(Uuid::new_v4()); + sqlx::query("INSERT INTO communities(id,host) VALUES ($1,$2)") + .bind(community.as_uuid()) + .bind(format!("sessions-{}.test", community.as_uuid())) + .execute(&db.pool) + .await + .unwrap(); + let owner = Keys::generate(); + let guest = Keys::generate(); + let owner_key = owner.public_key().to_bytes(); + let guest_key = guest.public_key().to_bytes(); + crate::user::ensure_user(&db.pool, community, &owner_key) + .await + .unwrap(); + crate::user::ensure_user(&db.pool, community, &guest_key) + .await + .unwrap(); + let parent = db + .create_channel( + community, + "Team", + ChannelType::Stream, + ChannelVisibility::Private, + None, + &owner_key, + None, + ) + .await + .unwrap(); + let session = Uuid::new_v4(); + let create = command( + &owner, + session, + serde_json::json!({"action":"create","title":"Review the layout"}), + ); + let parsed = serde_json::from_str(&create.content).unwrap(); + assert!( + db.apply_session_command(community, session, &create, &parsed) + .await + .unwrap() + .1 + ); + assert!( + !db.apply_session_command(community, session, &create, &parsed) + .await + .unwrap() + .1, + "exact retries do not create another session" + ); + assert!(db.is_member(community, session, &owner_key).await.unwrap()); + assert!(!db.is_member(community, session, &guest_key).await.unwrap()); + db.add_member( + community, + session, + &guest_key, + MemberRole::Member, + Some(&owner_key), + ) + .await + .unwrap(); + let unauthorized = command( + &guest, + session, + serde_json::json!({"action":"move","parent_id":parent.id,"confirm_history":true}), + ); + assert!(db + .apply_session_command( + community, + session, + &unauthorized, + &serde_json::from_str(&unauthorized.content).unwrap() + ) + .await + .is_err()); + let foreign_id = Uuid::new_v4(); + let foreign = command( + &owner, + foreign_id, + serde_json::json!({"action":"create","title":"Foreign","parent_id":parent.id}), + ); + assert!(db + .apply_session_command( + CommunityId::from_uuid(Uuid::new_v4()), + foreign_id, + &foreign, + &serde_json::from_str(&foreign.content).unwrap() + ) + .await + .is_err()); + // Session windows retain replies; ordinary channel windows retain roots. + let root = EventBuilder::new(Kind::Custom(9), "Prompt") + .tags([Tag::parse(["h", &session.to_string()]).unwrap()]) + .sign_with_keys(&owner) + .unwrap(); + let reply = EventBuilder::new(Kind::Custom(9), "Agent reply") + .tags([Tag::parse(["h", &session.to_string()]).unwrap()]) + .sign_with_keys(&guest) + .unwrap(); + let root_time = + chrono::DateTime::from_timestamp(root.created_at.as_secs() as i64, 0).unwrap(); + let reply_time = + chrono::DateTime::from_timestamp(reply.created_at.as_secs() as i64, 0).unwrap(); + crate::event::insert_event_with_thread_metadata( + &db.pool, + community, + &root, + Some(session), + None, + ) + .await + .unwrap(); + crate::event::insert_event_with_thread_metadata( + &db.pool, + community, + &reply, + Some(session), + Some(crate::event::ThreadMetadataParams { + event_id: reply.id.as_bytes(), + event_created_at: reply_time, + channel_id: session, + parent_event_id: Some(root.id.as_bytes()), + parent_event_created_at: Some(root_time), + root_event_id: Some(root.id.as_bytes()), + root_event_created_at: Some(root_time), + depth: 1, + broadcast: false, + }), + ) + .await + .unwrap(); + let (timeline, _) = db + .session_window(community, session, 20, None, Some(&[9])) + .await + .unwrap(); + assert_eq!(timeline.rows.len(), 2); + let (page, _) = db + .session_window(community, session, 1, None, Some(&[9])) + .await + .unwrap(); + assert_eq!(page.rows.len(), 1); + assert!(page.has_more); + assert!(db + .session_window(community, parent.id, 20, None, None) + .await + .is_err()); + let move_event = command( + &owner, + session, + serde_json::json!({"action":"move","parent_id":parent.id,"confirm_history":true}), + ); + let movement = serde_json::from_str(&move_event.content).unwrap(); + assert!( + db.apply_session_command(community, session, &move_event, &movement) + .await + .is_err(), + "missing participants prevent history sharing" + ); + assert!(db + .session_info(community, session) + .await + .unwrap() + .unwrap() + .parent_id + .is_none()); + db.add_member( + community, + parent.id, + &guest_key, + MemberRole::Member, + Some(&owner_key), + ) + .await + .unwrap(); + db.apply_session_command(community, session, &move_event, &movement) + .await + .unwrap(); + assert_eq!( + db.session_info(community, session) + .await + .unwrap() + .unwrap() + .parent_id, + Some(parent.id) + ); + assert!( + db.remove_member(community, session, &guest_key, &owner_key) + .await + .is_err(), + "a child cannot override its parent roster" + ); + db.remove_member(community, parent.id, &guest_key, &owner_key) + .await + .unwrap(); + assert!( + !db.is_member(community, session, &guest_key).await.unwrap(), + "old standalone membership never survives parent revocation" + ); + assert!(!db + .get_accessible_channel_ids(community, &guest_key) + .await + .unwrap() + .contains(&session)); + assert!(!db + .get_members(community, session) + .await + .unwrap() + .iter() + .any(|member| member.pubkey == guest_key)); + let child = Uuid::new_v4(); + let child_event = command( + &owner, + child, + serde_json::json!({"action":"create","title":"Child work","parent_id":parent.id}), + ); + db.apply_session_command( + community, + child, + &child_event, + &serde_json::from_str(&child_event.content).unwrap(), + ) + .await + .unwrap(); + // Capture and publish the inherited roster through the production + // replacement guard (including the database INSERT trigger). + let relay = Keys::generate(); + let mut snapshot = db + .lock_member_snapshot(community, child, &relay.public_key().to_bytes()) + .await + .unwrap(); + assert_eq!(snapshot.members.len(), 1); + assert_eq!(snapshot.members[0].pubkey, owner_key); + let roster = EventBuilder::new(Kind::Custom(39002), "") + .tags([ + Tag::parse(["d", &child.to_string()]).unwrap(), + Tag::parse(["p", &hex::encode(owner_key), "", "owner"]).unwrap(), + ]) + .sign_with_keys(&relay) + .unwrap(); + assert!( + snapshot + .replace_member_event(community, child, &roster) + .await + .unwrap() + .1 + ); + let mut contender = db.pool.begin().await.unwrap(); + let unlocked: bool = + sqlx::query_scalar("SELECT pg_try_advisory_xact_lock(hashtextextended($1,0))") + .bind(format!( + "buzz_channel_membership:{}:{}", + community.as_uuid(), + parent.id + )) + .fetch_one(&mut *contender) + .await + .unwrap(); + assert!( + !unlocked, + "parent mutations must wait for child roster publication" + ); + contender.rollback().await.unwrap(); + snapshot.release().await.unwrap(); + // A legacy publisher's empty physical roster is rejected by the trigger. + let stale = EventBuilder::new(Kind::Custom(39002), "") + .tags([Tag::parse(["d", &child.to_string()]).unwrap()]) + .sign_with_keys(&Keys::generate()) + .unwrap(); + assert!(crate::event::insert_event_with_thread_metadata( + &db.pool, + community, + &stale, + Some(child), + None, + ) + .await + .is_err()); + // Administrative removal shares the parent lock and never edits a + // child's unused physical roster. + db.add_member( + community, + parent.id, + &guest_key, + MemberRole::Member, + Some(&owner_key), + ) + .await + .unwrap(); + assert!(db.is_member(community, child, &guest_key).await.unwrap()); + assert!(db + .deploy_kick_member(community, child, &guest_key, &owner_key) + .await + .is_err()); + db.deploy_kick_member(community, parent.id, &guest_key, &owner_key) + .await + .unwrap(); + assert!(!db.is_member(community, child, &guest_key).await.unwrap()); + let nested_id = Uuid::new_v4(); + let nested = command( + &owner, + nested_id, + serde_json::json!({"action":"create","title":"Nested","parent_id":child}), + ); + assert!(db + .apply_session_command( + community, + nested_id, + &nested, + &serde_json::from_str(&nested.content).unwrap() + ) + .await + .is_err()); + db.soft_delete_channel(community, parent.id).await.unwrap(); + assert!( + db.apply_session_command( + community, + child, + &child_event, + &serde_json::from_str(&child_event.content).unwrap() + ) + .await + .is_err(), + "accepted receipts cannot restore revoked access" + ); + assert!( + !db.is_member(community, child, &owner_key).await.unwrap(), + "deleted parents revoke child access" + ); + } +} diff --git a/crates/buzz-db/src/store/thread.rs b/crates/buzz-db/src/store/thread.rs index a38ac2b038..d390ecd9cc 100644 --- a/crates/buzz-db/src/store/thread.rs +++ b/crates/buzz-db/src/store/thread.rs @@ -655,6 +655,28 @@ pub(crate) async fn get_channel_window_on( limit: u32, cursor: Option<(DateTime, Vec)>, kind_filter: Option<&[u32]>, +) -> Result { + get_conversation_window_on( + conn, + community_id, + channel_id, + limit, + cursor, + kind_filter, + false, + ) + .await +} + +/// Shared bounded window, optionally including replies for a session timeline. +pub(crate) async fn get_conversation_window_on( + conn: &mut sqlx::PgConnection, + community_id: CommunityId, + channel_id: Uuid, + limit: u32, + cursor: Option<(DateTime, Vec)>, + kind_filter: Option<&[u32]>, + include_replies: bool, ) -> Result { let mut param_idx = 3u32; // $1 is community_id, $2 is channel_id let mut sql = String::from( @@ -680,14 +702,16 @@ pub(crate) async fn get_channel_window_on( WHERE e.community_id = $1 AND e.channel_id = $2 AND e.deleted_at IS NULL - AND ( - tm.depth IS NULL - OR tm.depth = 0 - OR (tm.depth = 1 AND tm.broadcast = true) - ) + "#, ); + if !include_replies { + sql.push_str( + " AND (tm.depth IS NULL OR tm.depth = 0 OR (tm.depth = 1 AND tm.broadcast = true))", + ); + } + if cursor.is_some() { // Composite keyset: with ORDER BY created_at DESC, id ASC, the page // after (ts, id) is created_at < ts OR (created_at = ts AND id > id). diff --git a/crates/buzz-relay/src/api/bridge.rs b/crates/buzz-relay/src/api/bridge.rs index 37c549610d..5eaa4c43aa 100644 --- a/crates/buzz-relay/src/api/bridge.rs +++ b/crates/buzz-relay/src/api/bridge.rs @@ -566,17 +566,33 @@ async fn handle_channel_window_filter( .as_ref() .map(|ks| ks.iter().map(|k| k.as_u16() as u32).collect()); - let (window, mut session) = state - .db - .get_channel_window_with_session( - tenant.community(), - ch_id, - limit, - cursor.clone(), - kind_filter.as_deref(), - ) - .await - .map_err(|e| internal_error(&format!("channel window error: {e}")))?; + let (window, mut session) = if extension_flag(raw, "session_timeline") { + state + .db + .session_window( + tenant.community(), + ch_id, + limit, + cursor.clone(), + kind_filter.as_deref(), + ) + .await + } else { + state + .db + .get_channel_window_with_session( + tenant.community(), + ch_id, + limit, + cursor.clone(), + kind_filter.as_deref(), + ) + .await + } + .map_err(|e| match e { + buzz_db::DbError::InvalidData(message) => api_error(StatusCode::BAD_REQUEST, &message), + _ => internal_error(&format!("channel window error: {e}")), + })?; // 1. Rows, in keyset order. let mut row_ids_hex = Vec::with_capacity(window.rows.len()); @@ -1188,7 +1204,7 @@ async fn query_events_authed( // Channel-window filters (`top_level: true`) — the GUI read-model surface. // Dispatched first: a window filter is never a feed/thread/catchall query. for (idx, (raw, filter)) in raw_filters.iter().zip(filters.iter()).enumerate() { - if !extension_flag(raw, "top_level") { + if !extension_flag(raw, "top_level") && !extension_flag(raw, "session_timeline") { continue; } handle_channel_window_filter( diff --git a/crates/buzz-relay/src/config.rs b/crates/buzz-relay/src/config.rs index e035752ec3..dbb48ad7aa 100644 --- a/crates/buzz-relay/src/config.rs +++ b/crates/buzz-relay/src/config.rs @@ -116,6 +116,9 @@ pub const MAX_DRAIN_JITTER_MS: u64 = 20_000; /// Relay runtime configuration, loaded from environment variables. #[derive(Debug, Clone)] pub struct Config { + /// Enable session creation/moves only after every serving pod supports inherited access. + /// BUZZ_ENABLE_SESSIONS defaults off for a two-phase fleet rollout. + pub sessions_enabled: bool, /// Address the relay HTTP/WebSocket server binds to. pub bind_addr: SocketAddr, /// Postgres database connection URL. @@ -1201,6 +1204,9 @@ impl Config { } Ok(Self { + sessions_enabled: std::env::var("BUZZ_ENABLE_SESSIONS") + .map(|value| value == "true" || value == "1") + .unwrap_or(false), bind_addr, database_url, read_database_url, diff --git a/crates/buzz-relay/src/handlers/admin_outbox_worker.rs b/crates/buzz-relay/src/handlers/admin_outbox_worker.rs index a71197301e..6a5ee8613a 100644 --- a/crates/buzz-relay/src/handlers/admin_outbox_worker.rs +++ b/crates/buzz-relay/src/handlers/admin_outbox_worker.rs @@ -235,6 +235,44 @@ async fn deliver_system_message(state: &Arc, row: &OutboxRecord) -> Re let community_id = buzz_core::CommunityId::from_uuid(community_uuid); let tenant = resolve_tenant(state, community_id, "system_message").await?; + let target = hex::decode(target_hex).map_err(|_| "system_message: invalid target")?; + if target.len() != 32 { + return Err("system_message: invalid target length".into()); + } + // This outbox row is durable: discovery or notification failures keep the + // row retryable instead of leaving parent/child access snapshots stale. + state.invalidate_membership(&tenant, channel_id, &target); + if !state + .db + .is_member(community_id, channel_id, &target) + .await + .map_err(|e| format!("system_message: membership lookup failed: {e}"))? + { + let action = state + .db + .get_admin_action(row.action_id) + .await + .map_err(|e| format!("system_message: action lookup failed: {e}"))? + .ok_or("system_message: action not found")?; + super::side_effects::evict_live_channel_subscriptions(&tenant, state, channel_id, &target) + .await; + super::side_effects::disable_departed_member_workflows(&tenant, state, channel_id, &target) + .await; + super::side_effects::emit_membership_notification( + &tenant, + state, + channel_id, + &target, + &action.actor_pubkey, + buzz_core::kind::KIND_MEMBER_REMOVED_NOTIFICATION, + ) + .await + .map_err(|e| format!("system_message: membership notification failed: {e}"))?; + } + super::side_effects::emit_group_discovery_events(&tenant, state, channel_id) + .await + .map_err(|e| format!("system_message: discovery failed: {e}"))?; + crate::handlers::side_effects::emit_system_message( &tenant, state, diff --git a/crates/buzz-relay/src/handlers/ingest.rs b/crates/buzz-relay/src/handlers/ingest.rs index ee1d0312be..bb0d17104d 100644 --- a/crates/buzz-relay/src/handlers/ingest.rs +++ b/crates/buzz-relay/src/handlers/ingest.rs @@ -29,12 +29,12 @@ use buzz_core::kind::{ KIND_NIP29_PUT_USER, KIND_NIP29_REMOVE_USER, KIND_NIP43_LEAVE_REQUEST, KIND_NIP65_RELAY_LIST_METADATA, KIND_PERSONA, KIND_PIN_LIST, KIND_PRESENCE_UPDATE, KIND_PRIVATE_MANAGED_AGENT, KIND_PRODUCT_FEEDBACK, KIND_PROFILE, KIND_PROJECT, KIND_REACTION, - KIND_READ_STATE, KIND_REPORT, KIND_STREAM_MESSAGE, KIND_STREAM_MESSAGE_BOOKMARKED, - KIND_STREAM_MESSAGE_DIFF, KIND_STREAM_MESSAGE_EDIT, KIND_STREAM_MESSAGE_PINNED, - KIND_STREAM_MESSAGE_SCHEDULED, KIND_STREAM_MESSAGE_V2, KIND_STREAM_REMINDER, KIND_TEAM, - KIND_TEAM_CATALOG, KIND_TEXT_NOTE, KIND_USER_STATUS, KIND_WORKFLOW_DEF, KIND_WORKFLOW_TRIGGER, - RELAY_ADMIN_ADD_MEMBER, RELAY_ADMIN_CHANGE_ROLE, RELAY_ADMIN_REMOVE_MEMBER, - RELAY_ADMIN_SET_WORKSPACE_PROFILE, + KIND_READ_STATE, KIND_REPORT, KIND_SESSION_COMMAND, KIND_STREAM_MESSAGE, + KIND_STREAM_MESSAGE_BOOKMARKED, KIND_STREAM_MESSAGE_DIFF, KIND_STREAM_MESSAGE_EDIT, + KIND_STREAM_MESSAGE_PINNED, KIND_STREAM_MESSAGE_SCHEDULED, KIND_STREAM_MESSAGE_V2, + KIND_STREAM_REMINDER, KIND_TEAM, KIND_TEAM_CATALOG, KIND_TEXT_NOTE, KIND_USER_STATUS, + KIND_WORKFLOW_DEF, KIND_WORKFLOW_TRIGGER, RELAY_ADMIN_ADD_MEMBER, RELAY_ADMIN_CHANGE_ROLE, + RELAY_ADMIN_REMOVE_MEMBER, RELAY_ADMIN_SET_WORKSPACE_PROFILE, }; use buzz_core::tenant::TenantContext; use buzz_core::verification::verify_event; @@ -515,7 +515,7 @@ fn required_scope_for_kind(kind: u32, event: &Event) -> Result Ok(Scope::ChannelsWrite), + KIND_SESSION_COMMAND | KIND_NIP29_CREATE_GROUP | KIND_CANVAS => Ok(Scope::ChannelsWrite), KIND_NIP29_JOIN_REQUEST | KIND_NIP29_LEAVE_REQUEST | KIND_NIP43_LEAVE_REQUEST => { Ok(Scope::ChannelsRead) } @@ -2529,6 +2529,7 @@ async fn ingest_event_inner( // without being a member (OQ1 decision; see validate_edit_ownership / // validate_admin_event for per-kind enforcement). let skip_membership = kind_u32 == KIND_NIP29_JOIN_REQUEST + || kind_u32 == KIND_SESSION_COMMAND || kind_u32 == KIND_NIP29_CREATE_GROUP || kind_u32 == KIND_STREAM_MESSAGE_EDIT || kind_u32 == KIND_NIP29_EDIT_METADATA @@ -2929,6 +2930,31 @@ async fn ingest_event_inner( } } + if kind_u32 == KIND_SESSION_COMMAND { + if auth.channel_ids().is_some() { + return Err(IngestError::AuthFailed( + "restricted: session commands require an unrestricted account token".into(), + )); + } + let result = super::sessions::accept(tenant, state, &event).await?; + let (id, _) = super::sessions::parse(&event).map_err(IngestError::Rejected)?; + let action = if result.message.starts_with("duplicate:") { + TraceAction::WriteDuplicate { + msg_id: msg_id_label(event.id.as_bytes()), + channel: channel_label(id), + claimed_community: claimed_community_from_event(&event), + } + } else { + TraceAction::WriteInsert { + msg_id: msg_id_label(event.id.as_bytes()), + channel: channel_label(id), + claimed_community: claimed_community_from_event(&event), + } + }; + emit(tracer, action, state_for_request(tenant, auth.pubkey())); + return Ok(result); + } + if kind_u32 == super::push_lease::KIND_PUSH_LEASE { let outcome = super::push_lease::accept(tenant, state, &event, now) .await diff --git a/crates/buzz-relay/src/handlers/mod.rs b/crates/buzz-relay/src/handlers/mod.rs index 2f4aa00b59..1e3b4aaffd 100644 --- a/crates/buzz-relay/src/handlers/mod.rs +++ b/crates/buzz-relay/src/handlers/mod.rs @@ -66,3 +66,6 @@ pub fn resolve_ttl(event: &nostr::Event, ephemeral_ttl_override: Option) -> (ttl, _) => ttl, } } + +/// Durable channel-backed work sessions. +pub mod sessions; diff --git a/crates/buzz-relay/src/handlers/sessions.rs b/crates/buzz-relay/src/handlers/sessions.rs new file mode 100644 index 0000000000..d2c1fc49f1 --- /dev/null +++ b/crates/buzz-relay/src/handlers/sessions.rs @@ -0,0 +1,156 @@ +//! Session commands share normal channel message storage and authorization. +use std::sync::Arc; + +use buzz_core::kind::{KIND_MEMBER_ADDED_NOTIFICATION, KIND_SESSION_COMMAND}; +use buzz_db::sessions::SessionCommand; +use nostr::Event; +use uuid::Uuid; + +use super::ingest::{IngestError, IngestResult}; +use crate::state::AppState; +use buzz_core::tenant::TenantContext; + +/// Validate a bounded command envelope before applying any database writes. +pub fn parse(event: &Event) -> Result<(Uuid, SessionCommand), String> { + if u32::from(event.kind.as_u16()) != KIND_SESSION_COMMAND || event.content.len() > 2048 { + return Err("invalid session command".into()); + } + let mut tags: Vec<_> = event.tags.iter().map(|tag| tag.as_slice()).collect(); + if let Some(client) = tags + .last() + .filter(|tag| tag.first().is_some_and(|name| name == "client-id")) + { + if client.len() != 2 { + return Err("invalid session client identifier".into()); + } + let client_id = + Uuid::parse_str(&client[1]).map_err(|_| "invalid session client identifier")?; + if client_id.to_string() != client[1] { + return Err("invalid session client identifier".into()); + } + tags.pop(); + } + if tags.len() != 1 || tags[0].len() != 2 || tags[0][0] != "h" { + return Err("session commands require exactly one h tag".into()); + } + let id = Uuid::parse_str(&tags[0][1]).map_err(|_| "invalid session identifier")?; + let command = + serde_json::from_str(&event.content).map_err(|_| "invalid session command content")?; + Ok((id, command)) +} + +/// Apply a command transactionally, then refresh discovery for humans and agents. +pub async fn accept( + tenant: &TenantContext, + state: &Arc, + event: &Event, +) -> Result { + if !state.config.sessions_enabled { + return Err(IngestError::Rejected( + "restricted: sessions are not enabled on this relay".into(), + )); + } + let (id, command) = parse(event).map_err(IngestError::Rejected)?; + let (_, inserted) = state + .db + .apply_session_command(tenant.community(), id, event, &command) + .await + .map_err(|error| match error { + buzz_db::DbError::AccessDenied(message) | buzz_db::DbError::InvalidData(message) => { + IngestError::Rejected(message) + } + _ => IngestError::Internal("session could not be saved".into()), + })?; + // Re-run discovery on exact retries as repair after a lost publication. + state.invalidate_channel_deleted(tenant); + super::side_effects::emit_group_discovery_events(tenant, state, id) + .await + .map_err(|_| IngestError::Internal("session saved; retry to finish discovery".into()))?; + let members = state + .db + .get_members(tenant.community(), id) + .await + .map_err(|_| { + IngestError::Internal("session saved; retry to finish member discovery".into()) + })?; + for member in members { + super::side_effects::emit_membership_notification( + tenant, + state, + id, + &member.pubkey, + &event.pubkey.to_bytes(), + KIND_MEMBER_ADDED_NOTIFICATION, + ) + .await + .map_err(|_| IngestError::Internal("session saved; retry to notify participants".into()))?; + } + Ok(IngestResult { + event_id: event.id.to_hex(), + accepted: true, + message: if inserted { + String::new() + } else { + "duplicate:".into() + }, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use nostr::{EventBuilder, Keys, Kind, Tag}; + + fn event(body: serde_json::Value, tags: Vec) -> Event { + EventBuilder::new(Kind::Custom(9050), body.to_string()) + .tags(tags) + .sign_with_keys(&Keys::generate()) + .unwrap() + } + + #[test] + fn session_command_accepts_one_trailing_outbox_identifier() { + let id = Uuid::new_v4().to_string(); + let h = Tag::parse(["h", &id]).unwrap(); + let client = Tag::parse(["client-id", &id]).unwrap(); + let body = serde_json::json!({"action":"create","title":"Work","parent_id":id}); + assert!(parse(&event(body.clone(), vec![h.clone(), client.clone()])).is_ok()); + for tags in [ + vec![h.clone(), client.clone(), client.clone()], + vec![client, h.clone()], + vec![h.clone(), Tag::parse(["client-id", "invalid"]).unwrap()], + vec![h, Tag::parse(["client-id", &id, "extra"]).unwrap()], + ] { + assert!(parse(&event(body.clone(), tags)).is_err()); + } + } + + #[test] + fn session_command_envelope_rejects_ambiguous_authority() { + let id = Uuid::new_v4().to_string(); + let h = Tag::parse(["h", &id]).unwrap(); + assert!(parse(&event( + serde_json::json!({"action":"create","title":"Work"}), + vec![h.clone()] + )) + .is_ok()); + for body in [ + serde_json::json!(null), + serde_json::json!([]), + serde_json::json!({"action":"create","title":"Work","role":"owner"}), + serde_json::json!({"action":"move","parent_id":id}), + serde_json::json!({"action":"create","title":"Work","parent_id":"invalid"}), + ] { + assert!(parse(&event(body, vec![h.clone()])).is_err()); + } + assert!(parse(&event( + serde_json::json!({"action":"create","title":"Work"}), + vec![h.clone(), h] + )) + .is_err()); + } +} + +#[cfg(test)] +#[path = "sessions_postgres_tests.rs"] +mod postgres_tests; diff --git a/crates/buzz-relay/src/handlers/sessions_postgres_tests.rs b/crates/buzz-relay/src/handlers/sessions_postgres_tests.rs new file mode 100644 index 0000000000..86d5543910 --- /dev/null +++ b/crates/buzz-relay/src/handlers/sessions_postgres_tests.rs @@ -0,0 +1,484 @@ +//! Signed session creation and messaging through the shared relay ingest path. +use crate::handlers::ingest::{ingest_event, HttpAuthMethod, IngestAuth}; +use buzz_auth::Scope; +use buzz_core::{tenant::TenantContext, CommunityId}; +use nostr::{Event, EventBuilder, Keys, Kind, Tag}; +use std::sync::Arc; +use uuid::Uuid; + +async fn test_state(sessions_enabled: bool) -> Arc { + let mut config = crate::config::Config::from_env().unwrap(); + config.sessions_enabled = sessions_enabled; + config.database_url = crate::test_support::database_url(); + config.redis_url = + std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379".into()); + config.require_auth_token = false; + config.require_relay_membership = false; + let pool = sqlx::PgPool::connect(&config.database_url).await.unwrap(); + let db = buzz_db::Db::from_pool(pool.clone()); + if std::env::var("BUZZ_TEST_SCHEMA_MODE").as_deref() != Ok("desired") { + db.migrate().await.unwrap(); + } + let redis = deadpool_redis::Config::from_url(&config.redis_url) + .create_pool(Some(deadpool_redis::Runtime::Tokio1)) + .unwrap(); + let pubsub = Arc::new( + buzz_pubsub::PubSubManager::new(&config.redis_url, redis.clone()) + .await + .unwrap(), + ); + let auth = buzz_auth::AuthService::new(config.auth.clone()); + let media = buzz_media::MediaStorage::new(&config.media).unwrap(); + let workflow = Arc::new(buzz_workflow::WorkflowEngine::new( + db.clone(), + Default::default(), + )); + let (state, _) = crate::state::AppState::new( + config, + db, + redis, + buzz_audit::AuditService::new(pool.clone()), + pubsub, + auth, + buzz_search::SearchService::new(pool), + workflow, + Keys::generate(), + media, + ); + Arc::new(state) +} + +fn auth(keys: &Keys) -> IngestAuth { + IngestAuth::Http { + pubkey: keys.public_key(), + scopes: vec![ + Scope::ChannelsWrite, + Scope::AdminChannels, + Scope::ChannelsRead, + Scope::MessagesWrite, + ], + auth_method: HttpAuthMethod::Nip98, + } +} + +fn event(keys: &Keys, kind: u16, channel: Uuid, content: &str, extra: Vec) -> Event { + let mut tags = vec![Tag::parse(["h", &channel.to_string()]).unwrap()]; + tags.extend(extra); + EventBuilder::new(Kind::Custom(kind), content) + .tags(tags) + .sign_with_keys(keys) + .unwrap() +} + +async fn http( + state: Arc, + tenant: &TenantContext, + keys: &Keys, + path: &str, + body: serde_json::Value, +) -> (axum::http::StatusCode, serde_json::Value) { + use base64::Engine; + use sha2::{Digest, Sha256}; + use tower::ServiceExt; + let body = serde_json::to_vec(&body).unwrap(); + let url = crate::api::bridge::nip98_expected_url(&state.config.relay_url, tenant, path); + let proof = EventBuilder::new(Kind::Custom(27235), "") + .tags([ + Tag::parse(["u", &url]).unwrap(), + Tag::parse(["method", "POST"]).unwrap(), + Tag::parse(["payload", &hex::encode(Sha256::digest(&body))]).unwrap(), + Tag::parse(["nonce", &Uuid::new_v4().to_string()]).unwrap(), + ]) + .sign_with_keys(keys) + .unwrap(); + let header = format!( + "Nostr {}", + base64::engine::general_purpose::STANDARD.encode(serde_json::to_vec(&proof).unwrap()) + ); + let response = crate::router::build_router(state) + .oneshot( + axum::http::Request::builder() + .method("POST") + .uri(path) + .header("Host", tenant.host()) + .header("Content-Type", "application/json") + .header("Authorization", header) + .body(axum::body::Body::from(body)) + .unwrap(), + ) + .await + .unwrap(); + let status = response.status(); + let bytes = axum::body::to_bytes(response.into_body(), 4 * 1024 * 1024) + .await + .unwrap(); + (status, serde_json::from_slice(&bytes).unwrap()) +} + +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn child_session_signed_create_send_reply_and_revoke() { + let state = test_state(true).await; + let pool = sqlx::PgPool::connect(&crate::test_support::database_url()) + .await + .unwrap(); + let community = CommunityId::from_uuid(Uuid::new_v4()); + let host = format!("sessions-{}.test", community.as_uuid()); + sqlx::query("INSERT INTO communities(id,host) VALUES ($1,$2)") + .bind(community.as_uuid()) + .bind(&host) + .execute(&pool) + .await + .unwrap(); + let tenant = TenantContext::resolved(community, host); + let owner = Keys::generate(); + let agent = Keys::generate(); + let outsider = Keys::generate(); + for keys in [&owner, &agent, &outsider] { + state + .db + .ensure_user(community, &keys.public_key().to_bytes()) + .await + .unwrap(); + } + let parent = state + .db + .create_channel( + community, + "Session parent", + buzz_db::channel::ChannelType::Stream, + buzz_db::channel::ChannelVisibility::Private, + None, + &owner.public_key().to_bytes(), + None, + ) + .await + .unwrap(); + // This is the normal invitation the frontend sends before creating a child. + let invite = event( + &owner, + 9000, + parent.id, + "", + vec![Tag::parse(["p", &agent.public_key().to_hex()]).unwrap()], + ); + assert!( + ingest_event(&state, &tenant, invite, auth(&owner)) + .await + .unwrap() + .accepted + ); + let child = Uuid::new_v4(); + let body = serde_json::json!({"action":"create", "title":"Real work", "parent_id":parent.id}) + .to_string(); + let create = event( + &owner, + 9050, + child, + &body, + vec![Tag::parse(["client-id", &Uuid::new_v4().to_string()]).unwrap()], + ); + let unauthorized = event(&outsider, 9050, Uuid::new_v4(), &body, vec![]); + assert!(ingest_event(&state, &tenant, unauthorized, auth(&outsider)) + .await + .is_err()); + let mut limited = auth(&owner); + if let IngestAuth::Http { scopes, .. } = &mut limited { + scopes.clear(); + } + assert!(ingest_event(&state, &tenant, create.clone(), limited) + .await + .is_err()); + let (status, response) = http( + state.clone(), + &tenant, + &owner, + "/events", + serde_json::to_value(&create).unwrap(), + ) + .await; + assert!(status.is_success(), "{response}"); + assert_eq!(response["accepted"], true); + + assert!(ingest_event(&state, &tenant, create, auth(&owner)) + .await + .unwrap() + .message + .starts_with("duplicate:")); + let kinds: Vec = sqlx::query_scalar("SELECT DISTINCT kind FROM events WHERE community_id=$1 AND channel_id=$2 AND kind IN (39000,39001,39002) AND deleted_at IS NULL ORDER BY kind") + .bind(community.as_uuid()).bind(child).fetch_all(&pool).await.unwrap(); + assert_eq!(kinds, vec![39000, 39001, 39002]); + assert!(state + .db + .is_member(community, child, &agent.public_key().to_bytes()) + .await + .unwrap()); + let prompt = event( + &owner, + 9, + child, + "Check the layout", + vec![Tag::parse(["p", &agent.public_key().to_hex()]).unwrap()], + ); + assert!( + ingest_event(&state, &tenant, prompt.clone(), auth(&owner)) + .await + .unwrap() + .accepted + ); + let reply = event( + &agent, + 9, + child, + "Layout checked", + vec![Tag::parse(["e", &prompt.id.to_hex(), "", "root"]).unwrap()], + ); + assert!( + ingest_event(&state, &tenant, reply, auth(&agent)) + .await + .unwrap() + .accepted + ); + assert_eq!( + state + .db + .session_window(community, child, 20, None, Some(&[9])) + .await + .unwrap() + .0 + .rows + .len(), + 2 + ); + // An upgraded pod with creation disabled must still serve sessions created + // by an enabled pod during phase two of the rolling deployment. + let reader_pod = test_state(false).await; + let query = serde_json::json!([{"kinds":[9],"#h":[child.to_string()],"session_timeline":true,"include_aux":true,"limit":20}]); + let (status, response) = + http(reader_pod.clone(), &tenant, &agent, "/query", query.clone()).await; + assert!(status.is_success(), "{response}"); + assert_eq!( + response + .as_array() + .unwrap() + .iter() + .filter(|event| event["kind"] == 9) + .count(), + 2 + ); + assert!(response + .as_array() + .unwrap() + .iter() + .any(|event| event["kind"] == 39006)); + assert!(reader_pod + .is_member_cached(community, child, &agent.public_key().to_bytes()) + .await + .unwrap()); + let mut invalidations = reader_pod.pubsub.subscribe_cache_invalidations(); + let pubsub = reader_pod.pubsub.clone(); + let subscriber = tokio::spawn(async move { pubsub.run_cache_invalidation_subscriber().await }); + // Establish readiness via a unique round trip before making the removal. + tokio::time::timeout(std::time::Duration::from_secs(5), async { + loop { + state + .pubsub + .publish_cache_invalidation( + &tenant, + &buzz_pubsub::cache_invalidation::CacheInvalidation::Visibility { + channel_id: child, + }, + ) + .await + .unwrap(); + if let Ok(Ok(scoped)) = + tokio::time::timeout(std::time::Duration::from_millis(50), invalidations.recv()) + .await + { + if scoped.community_id == community { + break; + } + } + } + }) + .await + .unwrap(); + let remove = event( + &owner, + 9001, + parent.id, + "", + vec![Tag::parse(["p", &agent.public_key().to_hex()]).unwrap()], + ); + assert!( + ingest_event(&state, &tenant, remove, auth(&owner)) + .await + .unwrap() + .accepted + ); + assert!(!state + .db + .is_member(community, child, &agent.public_key().to_bytes()) + .await + .unwrap()); + let denied = event(&agent, 9, child, "Must be denied", vec![]); + assert!(ingest_event(&state, &tenant, denied, auth(&agent)) + .await + .is_err()); + tokio::time::timeout(std::time::Duration::from_secs(5), async { + loop { + let scoped = invalidations.recv().await.unwrap(); + let target_removed = scoped.community_id == community && matches!(&scoped.invalidation, + buzz_pubsub::cache_invalidation::CacheInvalidation::Membership { pubkey, .. } if pubkey == &agent.public_key().to_bytes()); + reader_pod.apply_cache_invalidation(scoped.community_id, scoped.invalidation); + if target_removed { break; } + } + }).await.unwrap(); + assert!(!reader_pod + .is_member_cached(community, child, &agent.public_key().to_bytes()) + .await + .unwrap()); + let (status, response) = http(reader_pod.clone(), &tenant, &agent, "/query", query).await; + assert!( + status == axum::http::StatusCode::FORBIDDEN + || (status.is_success() && response.as_array().is_some_and(Vec::is_empty)), + "{status}: {response}" + ); + subscriber.abort(); + // Administrative kicks use the durable outbox and must also invalidate a + // warm child cache and publish the child's removal notification. + let target = outsider.public_key().to_bytes(); + let invite = event( + &owner, + 9000, + parent.id, + "", + vec![Tag::parse(["p", &outsider.public_key().to_hex()]).unwrap()], + ); + assert!( + ingest_event(&state, &tenant, invite, auth(&owner)) + .await + .unwrap() + .accepted + ); + assert!(state + .is_member_cached(community, child, &target) + .await + .unwrap()); + let report: Uuid = sqlx::query_scalar("INSERT INTO moderation_reports (community_id, report_event_id, reporter_pubkey, target_kind, target_pubkey, channel_id, report_type) VALUES ($1,$2,$3,'pubkey',$4,$5,'harassment') RETURNING id") + .bind(community.as_uuid()).bind(prompt.id.as_bytes().as_slice()) + .bind(owner.public_key().to_bytes().as_slice()).bind(target.as_slice()).bind(parent.id) + .fetch_one(&pool).await.unwrap(); + let action: Uuid = sqlx::query_scalar("INSERT INTO relay_admin_actions (report_id, report_community_id, request_id, actor_pubkey, actor_role, action, state) VALUES ($1,$2,$3,$4,'operator','kick','succeeded') RETURNING id") + .bind(report).bind(community.as_uuid()).bind(Uuid::new_v4()) + .bind(owner.public_key().to_bytes().as_slice()).fetch_one(&pool).await.unwrap(); + state + .db + .deploy_kick_member( + community, + parent.id, + &target, + &owner.public_key().to_bytes(), + ) + .await + .unwrap(); + state.db.enqueue_admin_outbox(action, "system_message", serde_json::json!({ + "community_id":community.as_uuid(), "channel_id":parent.id, "target":hex::encode(target), + }), &action.to_string()).await.unwrap(); + let rows = state + .db + .claim_pending_admin_outbox_batch( + "sessions-test", + chrono::Utc::now() + chrono::Duration::seconds(60), + 10, + ) + .await + .unwrap(); + let row = rows.iter().find(|row| row.action_id == action).unwrap(); + crate::handlers::admin_outbox_worker::deliver_one(&state, row).await; + let delivered: String = sqlx::query_scalar("SELECT state FROM relay_admin_outbox WHERE id=$1") + .bind(row.id) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(delivered, "delivered"); + assert!(!state + .is_member_cached(community, child, &target) + .await + .unwrap()); + let notified: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM events WHERE community_id=$1 AND kind=$2 AND tags @> $3)", + ) + .bind(community.as_uuid()) + .bind(buzz_core::kind::KIND_MEMBER_REMOVED_NOTIFICATION as i32) + .bind(serde_json::json!([ + ["h", child.to_string()], + ["p", hex::encode(target)] + ])) + .fetch_one(&pool) + .await + .unwrap(); + assert!( + notified, + "child agents must receive the parent kick notification" + ); +} + +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn session_rollout_switch_gates_advertisement_and_signed_writes() { + for enabled in [false, true] { + let state = test_state(enabled).await; + let community = CommunityId::from_uuid(Uuid::new_v4()); + let host = format!("sessions-rollout-{}.test", community.as_uuid()); + let pool = sqlx::PgPool::connect(&crate::test_support::database_url()) + .await + .unwrap(); + sqlx::query("INSERT INTO communities(id,host) VALUES ($1,$2)") + .bind(community.as_uuid()) + .bind(&host) + .execute(&pool) + .await + .unwrap(); + let tenant = TenantContext::resolved(community, host.clone()); + let owner = Keys::generate(); + state + .db + .ensure_user(community, &owner.public_key().to_bytes()) + .await + .unwrap(); + let info = crate::nip11::nip11_document(&state, &host).await; + assert_eq!( + info.supported_extensions + .unwrap_or_default() + .iter() + .any(|extension| extension == "buzz-sessions-v1"), + enabled + ); + let id = Uuid::new_v4(); + let create = event( + &owner, + 9050, + id, + r#"{"action":"create","title":"Rollout"}"#, + vec![], + ); + let result = ingest_event(&state, &tenant, create, auth(&owner)).await; + if enabled { + assert!(result.unwrap().accepted); + } else { + assert!( + matches!(result, Err(crate::handlers::ingest::IngestError::Rejected(message)) if message.contains("sessions are not enabled")) + ); + } + assert_eq!( + state + .db + .session_info(community, id) + .await + .unwrap() + .is_some(), + enabled + ); + } +} diff --git a/crates/buzz-relay/src/handlers/side_effects.rs b/crates/buzz-relay/src/handlers/side_effects.rs index 7282c91342..a5ef9a5a86 100644 --- a/crates/buzz-relay/src/handlers/side_effects.rs +++ b/crates/buzz-relay/src/handlers/side_effects.rs @@ -37,7 +37,7 @@ pub fn is_side_effect_kind(kind: u32) -> bool { matches!(kind, 0 | 5 | 9000..=9022 | KIND_GIT_REPO_ANNOUNCEMENT | KIND_AGENT_PROFILE | 41001..=41003 | 40099) } -async fn evict_live_channel_subscriptions( +pub(crate) async fn evict_live_channel_subscriptions( tenant: &TenantContext, state: &Arc, channel_id: Uuid, @@ -64,7 +64,7 @@ async fn evict_live_channel_subscriptions( /// Failures are logged, not propagated: membership removal has already been /// committed, and the per-fire gate still denies a removed owner even if this /// disable write is lost. -async fn disable_departed_member_workflows( +pub(crate) async fn disable_departed_member_workflows( tenant: &TenantContext, state: &Arc, channel_id: Uuid, @@ -325,6 +325,25 @@ pub async fn validate_admin_event( let channel_id = extract_h_tag_channel(event).ok_or_else(|| anyhow::anyhow!("missing or invalid h tag"))?; + if let Some(session) = state + .db + .session_info(tenant.community(), channel_id) + .await? + { + if session.parent_id.is_some() && matches!(kind, 9000 | 9001 | 9021 | 9022) { + return Err(anyhow::anyhow!("manage members in the parent channel")); + } + if kind == 9002 + && event.tags.iter().any(|tag| { + let parts = tag.as_slice(); + parts.first().is_some_and(|part| part == "visibility") + && parts.get(1).is_none_or(|value| value != "private") + }) + { + return Err(anyhow::anyhow!("sessions must remain private")); + } + } + let actor_bytes = event.pubkey.to_bytes().to_vec(); // Reject mutations on archived channels — except kind:9002 with archived=false @@ -841,6 +860,45 @@ pub async fn emit_membership_notification( target_pubkey: &[u8], actor_pubkey: &[u8], notification_kind: u32, +) -> anyhow::Result<()> { + emit_one_membership_notification( + tenant, + state, + channel_id, + target_pubkey, + actor_pubkey, + notification_kind, + ) + .await?; + for child in state + .db + .child_sessions(tenant.community(), channel_id) + .await? + { + if notification_kind == KIND_MEMBER_REMOVED_NOTIFICATION { + evict_live_channel_subscriptions(tenant, state, child, target_pubkey).await; + disable_departed_member_workflows(tenant, state, child, target_pubkey).await; + } + emit_one_membership_notification( + tenant, + state, + child, + target_pubkey, + actor_pubkey, + notification_kind, + ) + .await?; + } + Ok(()) +} + +async fn emit_one_membership_notification( + tenant: &TenantContext, + state: &Arc, + channel_id: Uuid, + target_pubkey: &[u8], + actor_pubkey: &[u8], + notification_kind: u32, ) -> anyhow::Result<()> { let target_hex = hex::encode(target_pubkey); let actor_hex = hex::encode(actor_pubkey); @@ -1052,6 +1110,22 @@ pub async fn emit_group_discovery_events( tenant: &TenantContext, state: &Arc, channel_id: Uuid, +) -> anyhow::Result<()> { + emit_one_group_discovery_events(tenant, state, channel_id).await?; + for child in state + .db + .child_sessions(tenant.community(), channel_id) + .await? + { + emit_one_group_discovery_events(tenant, state, child).await?; + } + Ok(()) +} + +async fn emit_one_group_discovery_events( + tenant: &TenantContext, + state: &Arc, + channel_id: Uuid, ) -> anyhow::Result<()> { let channel = state .db @@ -1094,7 +1168,21 @@ pub async fn emit_group_discovery_events( // Buzz channels always require explicit membership tags.push(Tag::parse(["closed"])?); // Channel type tag so clients can distinguish stream/forum/dm without inference - tags.push(Tag::parse(["t", &channel.channel_type])?); + let session = state + .db + .session_info(tenant.community(), channel_id) + .await?; + tags.push(Tag::parse([ + "t", + if session.is_some() { + "session" + } else { + &channel.channel_type + }, + ])?); + if let Some(parent) = session.and_then(|session| session.parent_id) { + tags.push(Tag::parse(["parent", &parent.to_string()])?); + } // Optional topic / purpose for richer client UX if let Some(ref topic) = channel.topic { if !topic.is_empty() { diff --git a/crates/buzz-relay/src/nip11.rs b/crates/buzz-relay/src/nip11.rs index e6b18cdd0f..6354f45ced 100644 --- a/crates/buzz-relay/src/nip11.rs +++ b/crates/buzz-relay/src/nip11.rs @@ -293,6 +293,11 @@ pub(crate) async fn nip11_document(state: &crate::state::AppState, raw_host: &st admin_api.as_deref(), state.config.klipy.as_ref().map(|_| "klipy"), ); + if state.config.sessions_enabled { + info.supported_extensions + .get_or_insert_default() + .push("buzz-sessions-v1".to_string()); + } let tenant_host = if state.config.push_enabled { crate::tenant::bind_community(&state.db, raw_host) .await diff --git a/crates/buzz-relay/src/state.rs b/crates/buzz-relay/src/state.rs index 95372d5bc3..62bb444914 100644 --- a/crates/buzz-relay/src/state.rs +++ b/crates/buzz-relay/src/state.rs @@ -1038,11 +1038,19 @@ impl AppState { pub(crate) fn invalidate_membership_local( &self, community_id: CommunityId, - channel_id: Uuid, + _channel_id: Uuid, pubkey: &[u8], ) { - self.membership_cache - .invalidate(&(community_id, channel_id, pubkey.to_vec())); + let member = pubkey.to_vec(); + if self + .membership_cache + .invalidate_entries_if(move |(community, _, key), _| { + *community == community_id && *key == member + }) + .is_err() + { + self.membership_cache.invalidate_all(); + } self.accessible_channels_cache .invalidate(&(community_id, pubkey.to_vec())); } @@ -1623,6 +1631,36 @@ pub(crate) mod tests { } } + #[tokio::test] + async fn session_parent_invalidation_clears_warm_child_access() { + let state = test_state().await; + let community = CommunityId::from_uuid(Uuid::new_v4()); + let other = CommunityId::from_uuid(Uuid::new_v4()); + let parent = Uuid::new_v4(); + let child = Uuid::new_v4(); + let key = vec![1; 32]; + state + .membership_cache + .insert((community, parent, key.clone()), true); + state + .membership_cache + .insert((community, child, key.clone()), true); + state + .membership_cache + .insert((other, child, key.clone()), true); + state.invalidate_membership_local(community, parent, &key); + state.membership_cache.run_pending_tasks(); + assert!(state + .membership_cache + .get(&(community, parent, key.clone())) + .is_none()); + assert!(state + .membership_cache + .get(&(community, child, key.clone())) + .is_none()); + assert_eq!(state.membership_cache.get(&(other, child, key)), Some(true)); + } + #[test] fn send_to_resets_grace_counter_on_success() { let (mgr, id, _rx, _ctrl_rx, _cancel, bp) = setup_conn(16); diff --git a/docs/features/sessions.md b/docs/features/sessions.md new file mode 100644 index 0000000000..feff850c42 --- /dev/null +++ b/docs/features/sessions.md @@ -0,0 +1,111 @@ +# Channel-backed work sessions (initial protocol) + +This local implementation adds saved work conversations without changing ordinary +channel/message identity. Deployment requires migration `0045_sessions.sql` and +all serving relay pods upgraded before clients enable child sessions. +`BUZZ_ENABLE_SESSIONS` defaults to false and gates both command acceptance and +capability advertisement. Old pods cannot read inherited membership. Roll the +new image to the whole fleet with creation disabled, verify every pod, then +enable the switch in a second rollout. Updated pods with the switch off still +authorize and serve existing sessions. The ACP type-label change is compatible with existing private +channel routing. NIP-11 advertises `buzz-sessions-v1` only on an enabled new +relay; clients must gate creation on that extension. + +## Commands + +A signed kind **9050** event has exactly one `h` tag containing the session UUID. +An optional trailing `client-id` tag may contain one canonical UUID for outbox +retries; it grants no authority. +Content is a JSON object of at most 2048 UTF-8 bytes, with no unknown fields: + +- Create: `{"action":"create","title":"Work topic","parent_id":null}`. + The parent is optional; title must contain 1–120 characters after nonempty + validation. The client chooses a UUID before sending and retains the signed + event ID for retries. +- Move: `{"action":"move","parent_id":"","confirm_history":true}`. + Only a standalone owner can move. The destination must be an active stream or + forum in the same community, and the actor and all session participants must + already belong to it. Confirmation acknowledges full-history disclosure and + replacement of independent access. + +Normal signature, principal, ban/timeout, and ChannelsWrite checks apply. +Channel-restricted tokens are rejected for these initial commands, so a token +cannot share history beyond its allowed channels. State and signed receipt commit +atomically. Exact retries require current session access and repair discovery. + +## Access and discovery + +Storage remains a private stream with `is_session=true`; discovery emits +`["t","session"]` and, for a child, `["parent",""]`. No `hidden` tag is +used: existing ACP treats hidden private groups as DMs. + +Standalone membership uses normal private-channel invitations/roles. A child's +current membership and roles come entirely from its parent through +`effective_channel_members`. Former standalone membership does not grant access. +Child roster edits are rejected. Parent removals and deletion revoke child access; +cache invalidation and parent discovery/roster notifications propagate to children. +Sessions stay private, including through generic metadata edits. + +A `session_timeline:true` bridge filter with a single `#h` reads bounded keyset +history including replies. Existing aux, summaries, and signed bounds apply; +ordinary `top_level:true` channel reads keep their current behavior. Non-session +IDs are rejected for this extension. + +## Initial limits and validation + +Moving between parents or out of a parent is not implemented. People/agent +invitations use existing membership policy; detailed agent activity stays owner-only. +No shared runner or shared activity feed is introduced. + +The PostgreSQL test lane discovers `sessions::postgres_tests`. Both migration +and desired-state tests exercise create/retry, move, missing members, +unauthorized/cross-community attempts, reply paging, and revocation. They also +publish an inherited 39002 through the production replacement guard, reject an +empty physical roster, and prove the parent membership lock remains held until +publication. The desired-state path must use pgschema plus the repository's +post-apply reconciliation script. + +The relay integration test uses signed events through the HTTP router and +`ingest_event` with local Redis: parent invitation, child creation with an outbox identifier, rejected +unauthorized creation, accepted retry, prompt/reply, parent removal and denied +later sends. It also exercises the durable admin kick outbox against a warm child +access cache and verifies the child removal notification. Administrative kicks +directly against children are rejected; administrators must target the parent. + +A second relay state with session creation disabled reads the signed conversation +window through authenticated HTTP. Its warmed child-access cache receives a real +Redis membership invalidation after parent removal, and the subsequent HTTP read +is denied. A separate test checks that the rollout switch gates both signed +creation and NIP-11 advertisement. These tests pass in both migration and +pgschema desired-state modes. The two states share a test process; this does not +establish multi-pod WebSocket delivery or recovery from Redis failure. + +Local verification on 2026-09-15 (initial checks at `a9dd4d3bd`; subsequently +fast-forwarded over mobile-only changes to `5b9dbcb4c`): + +- Relay and ACP compilation passed. +- Migrated and pgschema-created database session tests passed. +- Signed relay integration with local PostgreSQL/Redis passed. +- Focused parser/cache tests and PostgreSQL discovery checks passed. + +These checks do not establish production readiness. Full repository validation, +WebSocket client end-to-end testing, multi-pod Redis invalidation/failure +recovery, and actual ACP agent execution remain before rollout. Keep child +creation gated in the production frontend until the shared backend is released. + +## Production rollout boundary + +The local frontend at port 1431 uses the production identity and relay, but does +not change the production relay binary. Enabling a frontend flag cannot add the +9050 command or inherited database access to that relay. + +Review and integrate this backend branch, then build an immutable relay image +using the repository release process and deploy it through the existing +production infrastructure workflow. Apply migration 0045 without rewriting any +previous migration. Keep `BUZZ_ENABLE_SESSIONS=false` until every serving pod supports the +extension, including any traffic-serving canary. Enable it in a separate +configuration rollout after verifying the image identities. +Verify NIP-11, signed creation, discovery, prompt/reply, and parent removal before +reopening child creation. Old binaries must not serve child sessions after any +have been created: they only understand physical memberships. A rollback after +creation requires a coordinated access-preserving plan, not an image-only swap. diff --git a/migrations/0045_sessions.sql b/migrations/0045_sessions.sql new file mode 100644 index 0000000000..a137365986 --- /dev/null +++ b/migrations/0045_sessions.sql @@ -0,0 +1,100 @@ +-- Sessions keep normal channel/message identity. Their optional parent is the +-- authority for membership, never a copied roster that can diverge. +ALTER TABLE channels ADD COLUMN is_session boolean NOT NULL DEFAULT false; +ALTER TABLE channels ADD COLUMN parent_channel_id uuid; +ALTER TABLE channels ADD CONSTRAINT session_parent_same_community + FOREIGN KEY (community_id, parent_channel_id) REFERENCES channels (community_id, id); +ALTER TABLE channels ADD CONSTRAINT session_parent_shape + CHECK (parent_channel_id IS NULL OR (is_session AND parent_channel_id <> id)); +CREATE INDEX channels_session_parent ON channels (community_id, parent_channel_id) + WHERE parent_channel_id IS NOT NULL; + +CREATE VIEW effective_channel_members AS + SELECT m.community_id, m.channel_id, m.pubkey, m.role, m.joined_at, + m.invited_by, m.removed_at, m.removed_by, m.hidden_at FROM channel_members m + JOIN channels c ON c.community_id = m.community_id AND c.id = m.channel_id + WHERE c.parent_channel_id IS NULL + UNION ALL + SELECT m.community_id, c.id AS channel_id, m.pubkey, m.role, + m.joined_at, m.invited_by, m.removed_at, m.removed_by, m.hidden_at + FROM channels c + JOIN channels p ON p.community_id = c.community_id AND p.id = c.parent_channel_id + JOIN channel_members m ON m.community_id = p.community_id AND m.channel_id = p.id + WHERE p.deleted_at IS NULL AND NOT p.is_session; + +ALTER TABLE channels ADD CONSTRAINT sessions_are_private CHECK (NOT is_session OR visibility = 'private'); + +-- Extend the existing freshness fence to inherited rosters. +CREATE OR REPLACE FUNCTION guard_channel_roster_snapshot() +RETURNS TRIGGER AS $$ +DECLARE + parent_id UUID; + canonical_members TEXT[]; + snapshot_members TEXT[]; +BEGIN + IF NEW.kind <> 39002 OR NEW.channel_id IS NULL THEN + RETURN NEW; + END IF; + + PERFORM pg_advisory_xact_lock(hashtextextended( + 'buzz_channel_membership:' || NEW.community_id::text || ':' || NEW.channel_id::text, + 0 + )); + + -- The child lock serializes moves; the parent lock serializes inherited + -- membership capture with additions/removals, including administrative kicks. + SELECT parent_channel_id INTO parent_id FROM channels + WHERE community_id = NEW.community_id AND id = NEW.channel_id; + IF parent_id IS NOT NULL THEN + PERFORM pg_advisory_xact_lock(hashtextextended( + 'buzz_channel_membership:' || NEW.community_id::text || ':' || parent_id::text, 0 + )); + END IF; + + SELECT COALESCE( + array_agg(encode(cm.pubkey, 'hex') || ':' || cm.role::text ORDER BY cm.pubkey), + ARRAY[]::TEXT[] + ) + INTO canonical_members + FROM effective_channel_members cm + WHERE cm.community_id = NEW.community_id + AND cm.channel_id = NEW.channel_id + AND cm.removed_at IS NULL; + + -- A roster is canonical only when every p tag uses the emitted four-field + -- shape, contains a 32-byte hex pubkey and valid authoritative role, has no + -- duplicate members, and exactly matches the active membership rows. + IF EXISTS ( + SELECT 1 + FROM jsonb_array_elements(NEW.tags) AS roster_tag(tag_json) + WHERE roster_tag.tag_json->>0 = 'p' + AND ( + jsonb_array_length(roster_tag.tag_json) <> 4 + OR COALESCE(roster_tag.tag_json->>1, '') !~ '^[0-9a-fA-F]{64}$' + OR roster_tag.tag_json->>2 <> '' + OR COALESCE(roster_tag.tag_json->>3, '') NOT IN ('owner', 'admin', 'bot', 'member', 'guest') + ) + ) THEN + RAISE EXCEPTION 'kind 39002 roster contains an invalid p tag' + USING ERRCODE = '23514'; + END IF; + + SELECT COALESCE( + array_agg( + lower((roster_tag.tag_json->>1)) || ':' || (roster_tag.tag_json->>3) + ORDER BY decode((roster_tag.tag_json->>1), 'hex') + ), + ARRAY[]::TEXT[] + ) + INTO snapshot_members + FROM jsonb_array_elements(NEW.tags) AS roster_tag(tag_json) + WHERE roster_tag.tag_json->>0 = 'p'; + + IF snapshot_members IS DISTINCT FROM canonical_members THEN + RAISE EXCEPTION 'kind 39002 roster does not match canonical channel membership' + USING ERRCODE = '23514'; + END IF; + + RETURN NEW; +END; +$$ LANGUAGE plpgsql; diff --git a/schema/schema.sql b/schema/schema.sql index 0950812562..e1c59f5c38 100644 --- a/schema/schema.sql +++ b/schema/schema.sql @@ -99,12 +99,21 @@ CREATE TABLE channels ( purpose_set_by BYTEA, purpose_set_at TIMESTAMPTZ, participant_hash BYTEA, + is_session BOOLEAN NOT NULL DEFAULT false, + parent_channel_id UUID, + CONSTRAINT session_parent_same_community FOREIGN KEY (community_id, parent_channel_id) + REFERENCES channels (community_id, id), + CONSTRAINT session_parent_shape CHECK (parent_channel_id IS NULL OR (is_session AND parent_channel_id <> id)), + CONSTRAINT sessions_are_private CHECK (NOT is_session OR visibility = 'private'), ttl_seconds INT, ttl_deadline TIMESTAMPTZ, PRIMARY KEY (community_id, id), CONSTRAINT chk_channels_id_not_nil CHECK (id <> '00000000-0000-0000-0000-000000000000'::uuid) ); +CREATE INDEX channels_session_parent ON channels (community_id, parent_channel_id) + WHERE parent_channel_id IS NOT NULL; + -- nip29 group id and DM participant hash are unique WITHIN a community, not globally. CREATE UNIQUE INDEX idx_channels_nip29_group ON channels (community_id, nip29_group_id) WHERE nip29_group_id IS NOT NULL; @@ -160,6 +169,19 @@ CREATE TABLE channel_members ( CREATE INDEX idx_channel_members_pubkey ON channel_members (community_id, pubkey) WHERE removed_at IS NULL; +CREATE VIEW effective_channel_members AS + SELECT m.community_id, m.channel_id, m.pubkey, m.role, m.joined_at, + m.invited_by, m.removed_at, m.removed_by, m.hidden_at FROM channel_members m + JOIN channels c ON c.community_id = m.community_id AND c.id = m.channel_id + WHERE c.parent_channel_id IS NULL + UNION ALL + SELECT m.community_id, c.id AS channel_id, m.pubkey, m.role, + m.joined_at, m.invited_by, m.removed_at, m.removed_by, m.hidden_at + FROM channels c + JOIN channels p ON p.community_id = c.community_id AND p.id = c.parent_channel_id + JOIN channel_members m ON m.community_id = p.community_id AND m.channel_id = p.id + WHERE p.deleted_at IS NULL AND NOT p.is_session; + -- ── Users ───────────────────────────────────────────────────────────────────── -- Conformance: "Users, profiles, NIP-05, and user search". One profile per -- (community, pubkey): the same key reposts kind:0 in each community it joins. @@ -1010,6 +1032,7 @@ FOR EACH ROW EXECUTE FUNCTION refresh_channel_ttl_after_event_insert(); CREATE OR REPLACE FUNCTION guard_channel_roster_snapshot() RETURNS TRIGGER AS $$ DECLARE + parent_id UUID; canonical_members TEXT[]; snapshot_members TEXT[]; BEGIN @@ -1022,12 +1045,22 @@ BEGIN 0 )); + -- The child lock serializes moves; the parent lock serializes inherited + -- membership capture with additions/removals, including administrative kicks. + SELECT parent_channel_id INTO parent_id FROM channels + WHERE community_id = NEW.community_id AND id = NEW.channel_id; + IF parent_id IS NOT NULL THEN + PERFORM pg_advisory_xact_lock(hashtextextended( + 'buzz_channel_membership:' || NEW.community_id::text || ':' || parent_id::text, 0 + )); + END IF; + SELECT COALESCE( array_agg(encode(cm.pubkey, 'hex') || ':' || cm.role::text ORDER BY cm.pubkey), ARRAY[]::TEXT[] ) INTO canonical_members - FROM channel_members cm + FROM effective_channel_members cm WHERE cm.community_id = NEW.community_id AND cm.channel_id = NEW.channel_id AND cm.removed_at IS NULL;