Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
130 changes: 111 additions & 19 deletions crates/buzz-db/src/store/channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ChannelRecord> {
if updates.is_empty() {
return Err(DbError::InvalidData(
Expand All @@ -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(
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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?;
Expand Down Expand Up @@ -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<ChannelRecord> {
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.
Expand Down Expand Up @@ -2645,6 +2650,7 @@ mod postgres_tests {
join_role: Some("guest".into()),
..Default::default()
},
&owner_pk,
)
.await
.expect("set join_role");
Expand All @@ -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<u8>, 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() {
Expand Down
11 changes: 10 additions & 1 deletion crates/buzz-db/src/store/channel_members.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2955,6 +2955,7 @@ mod postgres_tests {
join_role: join_role.map(str::to_string),
..Default::default()
},
&owner,
)
.await
.expect("flag channel");
Expand Down Expand Up @@ -4175,6 +4176,7 @@ mod postgres_tests {
join_role: Some("guest".into()),
..Default::default()
},
&owner,
)
.await
.expect("make announce channel");
Expand Down Expand Up @@ -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,
Expand All @@ -4335,6 +4338,7 @@ mod postgres_tests {
join_role: Some("member".into()),
..Default::default()
},
&owner,
)
.await
}
Expand Down Expand Up @@ -4615,14 +4619,18 @@ 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()),
..Default::default()
};
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), "")
Expand Down Expand Up @@ -5767,6 +5775,7 @@ mod postgres_tests {
visibility: Some("private".into()),
..Default::default()
},
&other_owner,
)
.await
.expect("make the channel private");
Expand Down
7 changes: 6 additions & 1 deletion crates/buzz-db/src/store/channel_name_postgres_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(|_| ())
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ impl Fixture {
unlisted: Some(unlisted),
..Default::default()
},
&self.owner.public_key().to_bytes(),
)
.await
.expect("set unlisted")
Expand Down Expand Up @@ -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");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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();
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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!(
Expand All @@ -35,6 +36,7 @@ async fn incremental_resets_for_first_artifact_during_channel_transition() {
visibility: Some("private".into()),
..Default::default()
},
&owner,
)
.await
.unwrap();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
2 changes: 2 additions & 0 deletions crates/buzz-relay/src/audio/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -11998,6 +11999,7 @@ mod tests {
join_role: Some("guest".into()),
..Default::default()
},
&sender,
)
.await
}
Expand Down
Loading
Loading