diff --git a/crates/buzz-db/src/store/channel.rs b/crates/buzz-db/src/store/channel.rs index a775de71646..1085efc8571 100644 --- a/crates/buzz-db/src/store/channel.rs +++ b/crates/buzz-db/src/store/channel.rs @@ -1103,13 +1103,14 @@ impl ChannelUpdate { /// At least one field must be provided; returns `InvalidData` otherwise. /// Returns the updated `ChannelRecord` on success. /// -/// It has no sender, so it does not apply the private-to-open rule that -/// kind:9002 enforces (`apply_channel_metadata_event`); user edits go there. +/// `sender` must be the authenticated pubkey making the change. It decides +/// the private-to-open rule, as for kind:9002 (see [`update_channel_on`]). pub async fn update_channel( pool: &PgPool, community_id: CommunityId, channel_id: Uuid, updates: ChannelUpdate, + sender: &[u8], ) -> Result { if updates.is_empty() { return Err(DbError::InvalidData( @@ -1124,7 +1125,7 @@ pub async fn update_channel( ) .await?; let mut locked = lock_channel_for_settings_write(&mut tx, channel_id, &updates).await?; - update_channel_on(&mut locked, updates).await?; + update_channel_on(&mut locked, updates, sender).await?; tx.commit().await?; get_channel_with_operation( @@ -1304,11 +1305,25 @@ async fn lock_channel_row( /// Writes the set fields of `updates` to the locked channel row on `tx`. /// The caller owns the commit. +/// +/// Opening a private channel publishes its existing history to new readers. +/// So a private channel may be opened only when it has never held anyone but +/// `sender` and `sender`'s own agents (NIP-OA), for example a Solo chat; +/// removed members count, because their posts stay. A visibility change +/// holds the membership lock (`lock_channel_for_settings_write`), so the +/// member set read here stays the same until commit. async fn update_channel_on( w: &mut ChannelSettingsWriter<'_>, mut updates: ChannelUpdate, + sender: &[u8], ) -> Result<()> { w.check_covers(&updates)?; + if updates.visibility.as_deref() == Some(ChannelVisibility::Open.as_str()) + && w.previous_visibility() == ChannelVisibility::Private.as_str() + && has_member_besides_sender_and_agents(w, sender).await? + { + return Err(DbError::AccessDenied(PRIVATE_TO_OPEN_REFUSAL.to_string())); + } let channel_id = w.channel_id; let tx = &mut *w.tx; let community_id = tx.community(); @@ -1724,18 +1739,6 @@ pub(crate) async fn apply_channel_metadata_event( return Err(DbError::AccessDenied("channel is not archived".to_string())); } } - // Opening a private channel changes the admission rules under everyone - // who joined it, so only a channel that holds nobody but the sender and - // the sender's own agents (NIP-OA) may be opened, for example a Solo - // chat. A visibility change holds the membership lock - // (`lock_channel_for_settings_write`), so the member set read here stays - // the same until commit. - if edit.columns.visibility.as_deref() == Some(ChannelVisibility::Open.as_str()) - && locked.previous_visibility() == ChannelVisibility::Private.as_str() - && has_member_besides_sender_and_agents(&mut locked, &event.pubkey.to_bytes()).await? - { - return Err(DbError::AccessDenied(PRIVATE_TO_OPEN_REFUSAL.to_string())); - } // `auto_join` only makes sense where a kind:9021 self-join would work: // an open, unarchived channel. Decide it here, under the row lock and // after the archive decision, on the state this event leaves behind, so @@ -1771,7 +1774,7 @@ pub(crate) async fn apply_channel_metadata_event( } = edit; let actor = event.pubkey.to_bytes(); if !columns.is_empty() { - update_channel_on(&mut locked, columns).await?; + update_channel_on(&mut locked, columns, &actor).await?; } if let Some(topic) = topic { set_topic_on(&mut locked, &topic, &actor).await?; @@ -2210,16 +2213,18 @@ impl Db { .await } - /// Updates a channel's name and/or description. It does not apply the - /// private-to-open rule; user edits go through kind:9002. + /// Applies every field set in `updates`, visibility included. `sender` + /// must be the authenticated pubkey making the change; it decides the + /// private-to-open rule. #[datastore_span(name = "update_channel", system = "postgresql")] pub async fn update_channel( &self, community_id: CommunityId, channel_id: Uuid, updates: ChannelUpdate, + sender: &[u8], ) -> Result { - update_channel(&self.pool, community_id, channel_id, updates).await + update_channel(&self.pool, community_id, channel_id, updates, sender).await } /// Sets the topic for a channel. @@ -2645,6 +2650,7 @@ mod postgres_tests { join_role: Some("guest".into()), ..Default::default() }, + &owner_pk, ) .await .expect("set join_role"); @@ -2666,11 +2672,97 @@ mod postgres_tests { join_role: Some("admin".into()), ..Default::default() }, + &owner_pk, ) .await .is_err()); } + /// `update_channel` applies the kind:9002 private-to-open rule to its + /// `sender`: opening fails while anyone else is, or was, a member, and the + /// channel stays private. A channel holding only the sender opens. + /// + /// Mutation: drop the check from `update_channel_on` → the shared + /// channel opens (RED). + #[tokio::test] + #[ignore = "requires Postgres"] + async fn update_channel_refuses_opening_a_private_channel_with_other_members() { + let pool = setup_pool().await; + let community_id = make_test_community(&pool).await; + let community = CommunityId::from_uuid(community_id); + let (owner, other) = (random_pubkey(), random_pubkey()); + let open = || ChannelUpdate { + visibility: Some("open".into()), + ..Default::default() + }; + let add = |channel: Uuid, pubkey: Vec, removed: bool| { + let pool = pool.clone(); + async move { + sqlx::query( + "INSERT INTO channel_members (community_id, channel_id, pubkey, removed_at) \ + VALUES ($1, $2, $3, CASE WHEN $4 THEN now() END)", + ) + .bind(community_id) + .bind(channel) + .bind(pubkey) + .bind(removed) + .execute(&pool) + .await + .expect("insert member"); + } + }; + + for removed in [false, true] { + let shared = create_test_channel( + &pool, + community_id, + "shared", + ChannelType::Stream, + ChannelVisibility::Private, + None, + &owner, + None, + ) + .await + .expect("create shared channel"); + add(shared.id, other.clone(), removed).await; + for sender in [&owner, &other] { + let err = update_channel(&pool, community, shared.id, open(), sender) + .await + .expect_err("opening a shared private channel must fail"); + assert!( + matches!(&err, DbError::AccessDenied(m) if m == PRIVATE_TO_OPEN_REFUSAL), + "removed={removed}: {err:?}" + ); + } + assert_eq!( + get_channel(&pool, community, shared.id) + .await + .expect("reload shared") + .visibility, + "private", + "removed={removed}" + ); + } + + let solo = create_test_channel( + &pool, + community_id, + "solo", + ChannelType::Stream, + ChannelVisibility::Private, + None, + &owner, + None, + ) + .await + .expect("create solo channel"); + let opened = update_channel(&pool, community, solo.id, open(), &owner) + .await + .expect("the only member may open the channel"); + assert_eq!(opened.visibility, "open"); + } + #[tokio::test] #[ignore = "requires Postgres"] async fn test_unarchive_expired_ephemeral_channel_renews_ttl_deadline() { diff --git a/crates/buzz-db/src/store/channel_members.rs b/crates/buzz-db/src/store/channel_members.rs index 0d0286c7841..98488c5bbb9 100644 --- a/crates/buzz-db/src/store/channel_members.rs +++ b/crates/buzz-db/src/store/channel_members.rs @@ -2955,6 +2955,7 @@ mod postgres_tests { join_role: join_role.map(str::to_string), ..Default::default() }, + &owner, ) .await .expect("flag channel"); @@ -4175,6 +4176,7 @@ mod postgres_tests { join_role: Some("guest".into()), ..Default::default() }, + &owner, ) .await .expect("make announce channel"); @@ -4326,6 +4328,7 @@ mod postgres_tests { let update = tokio::spawn({ let pool = pool.clone(); let channel_id = channel.id; + let owner = owner.clone(); async move { crate::channel::update_channel( &pool, @@ -4335,6 +4338,7 @@ mod postgres_tests { join_role: Some("member".into()), ..Default::default() }, + &owner, ) .await } @@ -4615,6 +4619,7 @@ mod postgres_tests { let update = tokio::spawn({ let pool = pool.clone(); let channel_id = channel.id; + let owner = owner.clone(); async move { let updates = crate::channel::ChannelUpdate { join_role: Some("guest".into()), @@ -4622,7 +4627,10 @@ mod postgres_tests { }; match writer { SettingsWriter::UpdateChannel => { - crate::channel::update_channel(&pool, community, channel_id, updates).await + crate::channel::update_channel( + &pool, community, channel_id, updates, &owner, + ) + .await } SettingsWriter::Kind9002 => { let edit_event = nostr::EventBuilder::new(nostr::Kind::Custom(9002), "") @@ -5767,6 +5775,7 @@ mod postgres_tests { visibility: Some("private".into()), ..Default::default() }, + &other_owner, ) .await .expect("make the channel private"); diff --git a/crates/buzz-db/src/store/channel_name_postgres_tests.rs b/crates/buzz-db/src/store/channel_name_postgres_tests.rs index bc387dc2a3c..1d64183d3d6 100644 --- a/crates/buzz-db/src/store/channel_name_postgres_tests.rs +++ b/crates/buzz-db/src/store/channel_name_postgres_tests.rs @@ -75,7 +75,12 @@ impl Fixture { async fn update(&self, channel: Uuid, update: ChannelUpdate) -> crate::error::Result<()> { self.db - .update_channel(self.community, channel, update) + .update_channel( + self.community, + channel, + update, + &self.owner.public_key().to_bytes(), + ) .await .map(|_| ()) } diff --git a/crates/buzz-db/src/store/unlisted_channels_postgres_tests.rs b/crates/buzz-db/src/store/unlisted_channels_postgres_tests.rs index a47647ce3b0..dbba7b7bd8f 100644 --- a/crates/buzz-db/src/store/unlisted_channels_postgres_tests.rs +++ b/crates/buzz-db/src/store/unlisted_channels_postgres_tests.rs @@ -79,6 +79,7 @@ impl Fixture { unlisted: Some(unlisted), ..Default::default() }, + &self.owner.public_key().to_bytes(), ) .await .expect("set unlisted") @@ -311,6 +312,7 @@ async fn unlisted_private_channel_stays_private_and_opens_unlisted() { visibility: Some("open".into()), ..Default::default() }, + &f.owner.public_key().to_bytes(), ) .await .expect("open the channel"); diff --git a/crates/buzz-relay/src/api/artifact_postgres_tests/sync_access_postgres_tests.rs b/crates/buzz-relay/src/api/artifact_postgres_tests/sync_access_postgres_tests.rs index 89f08e9338d..8486b43c92b 100644 --- a/crates/buzz-relay/src/api/artifact_postgres_tests/sync_access_postgres_tests.rs +++ b/crates/buzz-relay/src/api/artifact_postgres_tests/sync_access_postgres_tests.rs @@ -142,6 +142,7 @@ async fn sync_ignores_unchanged_visibility_and_resets_on_ttl_changes() { name: Some("renamed".into()), ..Default::default() }, + &f.owner.public_key().to_bytes(), ) .await .unwrap(); @@ -155,6 +156,7 @@ async fn sync_ignores_unchanged_visibility_and_resets_on_ttl_changes() { ttl_seconds: Some(Some(3600)), ..Default::default() }, + &f.owner.public_key().to_bytes(), ) .await .unwrap(); @@ -342,6 +344,7 @@ async fn incremental_resets_when_a_move_source_loses_access() { visibility: Some("private".into()), ..Default::default() }, + &f.owner.public_key().to_bytes(), ) .await .unwrap(); @@ -393,6 +396,7 @@ async fn sync_policy_update_can_pass_a_channel_key_share() { visibility: Some("private".into()), ..Default::default() }, + &f.owner.public_key().to_bytes(), ), ) .await @@ -473,6 +477,7 @@ async fn incremental_unlisted_channels_require_membership_or_named_scope() { unlisted: Some(true), ..Default::default() }, + &f.owner.public_key().to_bytes(), ) .await .unwrap(); @@ -523,6 +528,7 @@ async fn incremental_unlisted_channels_require_membership_or_named_scope() { unlisted: Some(false), ..Default::default() }, + &f.owner.public_key().to_bytes(), ) .await .unwrap(); diff --git a/crates/buzz-relay/src/api/artifact_postgres_tests/sync_cursor_postgres_tests.rs b/crates/buzz-relay/src/api/artifact_postgres_tests/sync_cursor_postgres_tests.rs index eab9488eb2a..97cb4fe264b 100644 --- a/crates/buzz-relay/src/api/artifact_postgres_tests/sync_cursor_postgres_tests.rs +++ b/crates/buzz-relay/src/api/artifact_postgres_tests/sync_cursor_postgres_tests.rs @@ -114,6 +114,7 @@ async fn sync_channel_scope_limits_candidates_and_keeps_source_removals() { visibility: Some("private".into()), ..Default::default() }, + &f.owner.public_key().to_bytes(), ) .await .unwrap(); diff --git a/crates/buzz-relay/src/api/artifact_postgres_tests/sync_policy_postgres_tests.rs b/crates/buzz-relay/src/api/artifact_postgres_tests/sync_policy_postgres_tests.rs index c3cc3d9f1d4..d5af5714491 100644 --- a/crates/buzz-relay/src/api/artifact_postgres_tests/sync_policy_postgres_tests.rs +++ b/crates/buzz-relay/src/api/artifact_postgres_tests/sync_policy_postgres_tests.rs @@ -19,6 +19,7 @@ async fn incremental_resets_for_first_artifact_during_channel_transition() { let pool = f.pool.clone(); let community = f.community; let home = f.home; + let owner = f.owner.public_key().to_bytes(); let transition = tokio::spawn(async move { if delete_channel { assert!( @@ -35,6 +36,7 @@ async fn incremental_resets_for_first_artifact_during_channel_transition() { visibility: Some("private".into()), ..Default::default() }, + &owner, ) .await .unwrap(); diff --git a/crates/buzz-relay/src/api/artifact_postgres_tests/sync_postgres_tests.rs b/crates/buzz-relay/src/api/artifact_postgres_tests/sync_postgres_tests.rs index db76a358c54..4255f721513 100644 --- a/crates/buzz-relay/src/api/artifact_postgres_tests/sync_postgres_tests.rs +++ b/crates/buzz-relay/src/api/artifact_postgres_tests/sync_postgres_tests.rs @@ -269,6 +269,7 @@ async fn sync_policy_changes_reset_without_hidden_channel_ids() { visibility: Some("private".into()), ..Default::default() }, + &f.owner.public_key().to_bytes(), ) .await .unwrap(); diff --git a/crates/buzz-relay/src/audio/handler.rs b/crates/buzz-relay/src/audio/handler.rs index 4c0dd354e92..b5ee227bf52 100644 --- a/crates/buzz-relay/src/audio/handler.rs +++ b/crates/buzz-relay/src/audio/handler.rs @@ -11989,6 +11989,7 @@ mod tests { }); let update = tokio::spawn({ let pool = pool.clone(); + let sender = member_key.public_key().to_bytes(); async move { buzz_db::channel::update_channel( &pool, @@ -11998,6 +11999,7 @@ mod tests { join_role: Some("guest".into()), ..Default::default() }, + &sender, ) .await } diff --git a/crates/buzz-relay/src/handlers/auth.rs b/crates/buzz-relay/src/handlers/auth.rs index ecbc7d9e0d0..d4c2c9c3205 100644 --- a/crates/buzz-relay/src/handlers/auth.rs +++ b/crates/buzz-relay/src/handlers/auth.rs @@ -3005,6 +3005,7 @@ mod tests { auto_join: Some(true), ..Default::default() }, + &owner.public_key().to_bytes(), ) .await .expect("flag channel"); diff --git a/docs/operator-user-deletion-executor.md b/docs/operator-user-deletion-executor.md index 592ec378c42..59364e514c2 100644 --- a/docs/operator-user-deletion-executor.md +++ b/docs/operator-user-deletion-executor.md @@ -122,6 +122,13 @@ error, not an implicit skip. The inventory's version selects the currently supported rules; future versions must retain the rules needed by active requests. No full execution plan is created upfront. +If the real `purge_db` keeps any of the user's messages in a channel, it must +also keep the user's `channel_members` row for that channel, marked removed. The +relay refuses to open a private channel that has or had a member other than the +sender and the sender's own agents (kind:9002 in `NOSTR.md`), and it finds former +members only through these rows. Without the row, the channel could be opened and +its history, those messages included, made public. + `previous_stage_id` is bookkeeping for uninterrupted execution. It must belong to this request. After restart pass `None`; the database current row is the source of truth. An old non-current stage is never transitioned twice.