Skip to content

Commit af4730a

Browse files
matt2eclaude
andcommitted
fix(db): refuse new members of an archived channel under the channel row lock
An auto-join could add a new community member to a default channel after it was archived (jedwards27, second review on #8594). The auto-join lists the effective default channels and `join_channel_as_self` checks the archive state before the write, but `put_members` never read `archived_at`, and nothing ordered an archive against the membership write. An archive landing between the list and the insert still created the row and emitted the kind:40099, 39000/39002 and 44100. `put_members` and `put_members_with_event` now take the membership lock, the shared TTL lock and then the channel row `FOR NO KEY UPDATE`, the order a huddle join already uses, and refuse a target who is not an active member with `AccessDenied("channel is archived")` while `archived_at` is set. An auto-join that loses the race is logged and counted as a failed channel, with no row and no side effects. Active members keep their rows; only admission is refused. The review suggested treating archive and unarchive as admission changes so they take the membership lock. This fix locks the row instead, because the row is what every archive writes: `archive_channel`, a kind:9002 `archived` tag and the TTL reaper's single UPDATE, which takes no advisory lock at all and so would still race under the membership-lock version. It also leaves every archive writer unchanged. The refusal is not scoped to self-joins: the only production callers are kind:9000 (already refused on an archived channel at ingest), kind:9021 and the auto-join. No restore or import path re-adds members through `put_members`, and no test relies on adding to an archived channel. The cost is that a membership write now holds the channel row for its transaction. Writers of that row (settings writes, huddle joins, TTL refreshes, the reaper) wait for it, and reads do not. NOSTR.md "Default channels" now says a channel archived or made private while the join runs is one of the logged, unretried failures. Tests: - `put_member_waits_for_a_concurrent_archive` (buzz-db Postgres): an uncommitted reaper-style archive makes a join wait. Once the archive commits the join is refused with no row, and re-adding a removed member is refused too. In the other order, `archive_channel` waits for an admission that holds the locks, and the admitted member stays. - `auto_join_skips_a_default_channel_archived_while_it_joins` (buzz-relay Postgres): a flagged channel is archived in a held transaction. The auto-join lists it, passes the join body's check, then waits in `put_member`. After the archive commits there is no membership row, no kind:39002 entry, no kind:44100 and no `member_joined` notice. - Mutations: dropping the row lock from `lock_channel_for_member_put` fails both tests, and so does dropping the archived refusal from `put_members_on`. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Matt Toohey <[email protected]>
1 parent 749cf9f commit af4730a

5 files changed

Lines changed: 305 additions & 14 deletions

File tree

‎NOSTR.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,9 @@ admin flags. It does this once,
226226
at that moment, and never again on login or reconnect, so a later kind:9022
227227
leave stands. A channel that fails to join is logged and counted
228228
(`buzz_auto_join_failures_total`), not retried: the kind:39000 tag is the
229-
record a client reconciles against. `buzz-admin add-member` writes the
229+
record a client reconciles against. That includes a channel archived or made
230+
private while the join runs: the membership write decides both again under
231+
the channel's locks, so the member is not added and nothing is announced. `buzz-admin add-member` writes the
230232
roster row only and does not join default channels. Auto-join fires only at
231233
those roster-insert sites, so a community that does not require relay
232234
membership advertises the kind:39000 tag but auto-joins nobody; a client that

‎crates/buzz-db/src/store/channel.rs‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -988,9 +988,11 @@ impl ChannelSettingsWriter<'_> {
988988
/// 3. the channel row, `FOR NO KEY UPDATE`.
989989
///
990990
/// Roster publication holds the membership lock and then, at commit, takes
991-
/// the TTL lock and updates the row. A huddle join takes the membership
992-
/// lock, then the TTL lock, then the row. A writer that took these locks in
993-
/// any other order could wait for one of them while it waits for this one.
991+
/// the TTL lock and updates the row. A huddle join and a `put_members`
992+
/// membership write take the membership lock, then the TTL lock, then the
993+
/// row; the row lock is what orders them against an archive, which does not
994+
/// take the membership lock. A writer that took these locks in any other
995+
/// order could wait for one of them while it waits for this one.
994996
///
995997
/// Returns `ChannelNotFound` when the channel is missing or deleted.
996998
pub(crate) async fn lock_channel_for_settings_write<'tx>(

‎crates/buzz-db/src/store/channel_members.rs‎

Lines changed: 166 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -651,6 +651,11 @@ pub async fn add_member(
651651
/// neither a membership write nor a setting change can slip between the
652652
/// decision and the write.
653653
///
654+
/// An archived channel admits nobody new: a target who is not an active
655+
/// member is refused with `AccessDenied` while `archived_at` is set. The
656+
/// archive state is read under the channel row lock, which every archive
657+
/// write needs too (see [`lock_channel_for_member_put`]).
658+
///
654659
/// There is no creator exception: channel creation installs the creator as
655660
/// owner in the same transaction, so a creator without an active row was
656661
/// removed and is admitted like anyone else.
@@ -718,9 +723,10 @@ pub async fn put_members(
718723
)
719724
.await?;
720725

721-
// First statement: serialize the whole decision / owner-count / upsert
722-
// sequence against concurrent membership writes on this channel.
723-
acquire_channel_membership_lock(tx.conn(), community_id, channel_id).await?;
726+
// First statements: serialize the whole decision / owner-count / upsert
727+
// sequence against concurrent membership writes and archives of this
728+
// channel.
729+
lock_channel_for_member_put(&mut tx, channel_id).await?;
724730
let results = put_members_on(&mut tx, channel_id, targets, invited_by).await?;
725731
tx.commit().await?;
726732
Ok(results)
@@ -747,9 +753,8 @@ pub enum MemberPutEventWrite {
747753
/// transaction. If any write fails, nothing is stored, so the client can
748754
/// resend the same event and have it applied.
749755
///
750-
/// The membership lock comes first, as in [`put_members`] and the channel
751-
/// settings writers, so a second copy of the event waits for the first and
752-
/// then finds it stored.
756+
/// The locks of [`put_members`] come first, so a second copy of the event
757+
/// waits for the first and then finds it stored.
753758
pub(crate) async fn put_members_with_event(
754759
pool: &PgPool,
755760
push_enqueue: Option<crate::runtime::push_enqueue::PushEnqueue>,
@@ -767,7 +772,7 @@ pub(crate) async fn put_members_with_event(
767772
)
768773
.await?;
769774
tx.set_push_enqueue(push_enqueue);
770-
acquire_channel_membership_lock(tx.conn(), community_id, channel_id).await?;
775+
lock_channel_for_member_put(&mut tx, channel_id).await?;
771776

772777
// The same writes as `Db::insert_event_with_thread_metadata`.
773778
let (stored, inserted) = crate::event::insert_event_with_thread_metadata_tx(
@@ -795,6 +800,23 @@ pub(crate) async fn put_members_with_event(
795800
Ok(MemberPutEventWrite::Applied { stored, results })
796801
}
797802

803+
/// Take the locks of a [`put_members`] write on `tx`, in the channel lock
804+
/// order (see `channel::lock_channel_for_settings_write`): the membership
805+
/// lock, the shared TTL lock, then the channel row `FOR NO KEY UPDATE`.
806+
///
807+
/// The row lock is what orders the write against an archive. Every archive
808+
/// and unarchive updates that row (`archive_channel`, a kind:9002 `archived`
809+
/// tag, the TTL reaper's single UPDATE), and none of them takes the
810+
/// membership lock. So an archive either commits before [`put_members_on`]
811+
/// reads `archived_at`, or waits until this write commits.
812+
async fn lock_channel_for_member_put(tx: &mut AdmittedTx, channel_id: Uuid) -> Result<()> {
813+
let community_id = tx.community();
814+
acquire_channel_membership_lock(tx.conn(), community_id, channel_id).await?;
815+
lock_channel_ttl_shared_in_transaction(tx, channel_id).await?;
816+
lock_channel_archived_at_in_transaction(tx, channel_id).await?;
817+
Ok(())
818+
}
819+
798820
fn check_distinct_targets(targets: &[MemberPut<'_>]) -> Result<()> {
799821
let mut seen = std::collections::HashSet::with_capacity(targets.len());
800822
match targets.iter().find(|t| !seen.insert(t.pubkey)) {
@@ -807,7 +829,8 @@ fn check_distinct_targets(targets: &[MemberPut<'_>]) -> Result<()> {
807829
}
808830

809831
/// The decisions and upsert of [`put_members`], on a transaction that holds
810-
/// `channel_id`'s membership lock. The caller owns the commit.
832+
/// `channel_id`'s [`lock_channel_for_member_put`] locks. The caller owns the
833+
/// commit.
811834
async fn put_members_on(
812835
tx: &mut AdmittedTx,
813836
channel_id: Uuid,
@@ -816,6 +839,7 @@ async fn put_members_on(
816839
) -> Result<Vec<Result<PutMemberResult>>> {
817840
let community_id = tx.community();
818841
let channel = get_channel_tx(tx.conn(), community_id, channel_id).await?;
842+
let archived = channel.archived_at.is_some();
819843
let private = channel.visibility == "private";
820844
let join_role = buzz_core::channel::ChannelJoinRole::parse_fail_closed(&channel.join_role);
821845

@@ -853,6 +877,12 @@ async fn put_members_on(
853877
}
854878
let actor = invited_by.unwrap_or(target.pubkey);
855879
let current_role = roles.get(target.pubkey).cloned();
880+
if archived && current_role.is_none() {
881+
decided.push(Err(DbError::AccessDenied(
882+
"channel is archived".to_string(),
883+
)));
884+
continue;
885+
}
856886
let actor_role: Option<MemberRole> = roles
857887
.get(actor)
858888
.map(|r| {
@@ -3798,6 +3828,134 @@ mod postgres_tests {
37983828
.expect("join_role change");
37993829
}
38003830

3831+
/// An archive and an admission are ordered by the channel row lock, and an
3832+
/// archived channel admits nobody new. A join that waits on an uncommitted
3833+
/// archive is refused once it commits, with no row, and re-adding a
3834+
/// removed member is refused too. The other order: an archive waits for
3835+
/// an admission that holds the locks.
3836+
/// The archive here is the TTL reaper's single UPDATE, which takes no
3837+
/// advisory lock. Mutations: drop the row lock from
3838+
/// `lock_channel_for_member_put`, or the archived refusal from
3839+
/// `put_members_on` → RED.
3840+
#[tokio::test]
3841+
#[ignore = "requires Postgres"]
3842+
async fn put_member_waits_for_a_concurrent_archive() {
3843+
let pool = setup_pool().await;
3844+
let community_id = make_test_community(&pool).await;
3845+
let community = CommunityId::from_uuid(community_id);
3846+
let owner = random_pubkey();
3847+
let joiner = random_pubkey();
3848+
let removed = random_pubkey();
3849+
for pk in [&owner, &joiner, &removed] {
3850+
ensure_user(&pool, community, pk)
3851+
.await
3852+
.expect("ensure user");
3853+
}
3854+
let channel = create_test_channel(
3855+
&pool,
3856+
community_id,
3857+
"put-member-archive-race",
3858+
ChannelType::Stream,
3859+
ChannelVisibility::Open,
3860+
None,
3861+
&owner,
3862+
None,
3863+
)
3864+
.await
3865+
.expect("create channel");
3866+
put_member(&pool, community, channel.id, &removed, None, None)
3867+
.await
3868+
.expect("join before the archive");
3869+
remove_member(&pool, community, channel.id, &removed, &removed)
3870+
.await
3871+
.expect("leave before the archive");
3872+
3873+
let mut archive = pool.begin().await.expect("begin archive");
3874+
sqlx::query(
3875+
"UPDATE channels SET archived_at = NOW() \
3876+
WHERE community_id = $1 AND id = $2 AND archived_at IS NULL",
3877+
)
3878+
.bind(community_id)
3879+
.bind(channel.id)
3880+
.execute(&mut *archive)
3881+
.await
3882+
.expect("archive");
3883+
3884+
let join_pool = crate::test_support::named_pool("put-member-archive-race").await;
3885+
let join = tokio::spawn({
3886+
let channel_id = channel.id;
3887+
let joiner = joiner.clone();
3888+
async move { put_member(&join_pool, community, channel_id, &joiner, None, None).await }
3889+
});
3890+
crate::test_support::wait_for_lock_wait(&pool, "put-member-archive-race").await;
3891+
assert!(!join.is_finished(), "the join must wait for the archive");
3892+
archive.commit().await.expect("commit archive");
3893+
3894+
let err = join
3895+
.await
3896+
.expect("join task")
3897+
.expect_err("the join is decided on the archived channel");
3898+
assert!(
3899+
matches!(&err, DbError::AccessDenied(reason) if reason == "channel is archived"),
3900+
"{err:?}"
3901+
);
3902+
let readd = put_member(&pool, community, channel.id, &removed, None, Some(&owner))
3903+
.await
3904+
.expect_err("an archived channel does not reactivate a removed member");
3905+
assert!(matches!(readd, DbError::AccessDenied(_)), "{readd:?}");
3906+
let mut roles = Vec::new();
3907+
for pk in [&owner, &joiner, &removed] {
3908+
roles.push(
3909+
get_member_role(&pool, community, channel.id, pk)
3910+
.await
3911+
.expect("read role"),
3912+
);
3913+
}
3914+
assert_eq!(roles, [Some("owner".to_string()), None, None]);
3915+
3916+
// The other order: an archive waits for an admission that holds the
3917+
// locks, and the member it admitted stays a member.
3918+
crate::channel::unarchive_channel(&pool, community, channel.id)
3919+
.await
3920+
.expect("unarchive");
3921+
let mut admission = crate::begin_community_write_transaction(
3922+
&pool,
3923+
community,
3924+
crate::observability::WriterOperation::EventWrite,
3925+
)
3926+
.await
3927+
.expect("begin admission");
3928+
lock_channel_for_member_put(&mut admission, channel.id)
3929+
.await
3930+
.expect("lock for the admission");
3931+
let targets = [MemberPut {
3932+
pubkey: &joiner,
3933+
requested: None,
3934+
}];
3935+
let admitted = put_members_on(&mut admission, channel.id, &targets, None)
3936+
.await
3937+
.expect("admission");
3938+
assert!(admitted[0].is_ok(), "{admitted:?}");
3939+
let archive_pool = crate::test_support::named_pool("archive-vs-admission").await;
3940+
let archive = tokio::spawn({
3941+
let channel_id = channel.id;
3942+
async move { crate::channel::archive_channel(&archive_pool, community, channel_id).await }
3943+
});
3944+
crate::test_support::wait_for_lock_wait(&pool, "archive-vs-admission").await;
3945+
assert!(
3946+
!archive.is_finished(),
3947+
"an archive must wait for an admission in progress"
3948+
);
3949+
admission.commit().await.expect("commit admission");
3950+
archive.await.expect("archive task").expect("archive");
3951+
assert_eq!(
3952+
get_member_role(&pool, community, channel.id, &joiner)
3953+
.await
3954+
.expect("read role"),
3955+
Some("member".to_string())
3956+
);
3957+
}
3958+
38013959
/// A `join_role` change on an ephemeral channel and a roster publication
38023960
/// take the channel's locks in one order. The roster holds the membership
38033961
/// lock and refreshes the channel's TTL (TTL lock, then row) at commit. A

‎crates/buzz-relay/src/api/invites.rs‎

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1460,6 +1460,131 @@ mod postgres_tests {
14601460
);
14611461
}
14621462

1463+
/// A default channel archived after the auto-join listed it is skipped:
1464+
/// no membership row, no kind:39002 roster entry, no kind:44100 and no
1465+
/// `member_joined` notice. The test holds an uncommitted archive of the
1466+
/// listed channel, so the auto-join passes the list and the shared join
1467+
/// body's open/unarchived check on the committed state and then waits in
1468+
/// `put_member`; the archive commits and the join resumes on an archived
1469+
/// channel. Mutation: drop the channel row lock or the archived refusal
1470+
/// from `put_members` → RED.
1471+
#[tokio::test]
1472+
#[ignore = "requires Postgres"]
1473+
async fn auto_join_skips_a_default_channel_archived_while_it_joins() {
1474+
use crate::handlers::group_state_postgres_tests::{
1475+
create_channel, edit_channel, group_state_tags,
1476+
};
1477+
use crate::handlers::side_effects::auto_join_default_channels;
1478+
1479+
let host = format!(
1480+
"invites-auto-join-archive-{}.example",
1481+
Uuid::new_v4().simple()
1482+
);
1483+
let owner = Keys::generate();
1484+
let state = invite_test_state(&host)
1485+
.await
1486+
.expect("requires reachable Postgres and relay test state");
1487+
let community = state
1488+
.db
1489+
.lookup_community_by_host(&host)
1490+
.await
1491+
.expect("lookup")
1492+
.expect("community exists")
1493+
.id;
1494+
let tenant = buzz_core::TenantContext::resolved(community, &host);
1495+
let joiner = Keys::generate();
1496+
let joiner_hex = joiner.public_key().to_hex();
1497+
for (keys, role) in [(&owner, "owner"), (&joiner, "member")] {
1498+
state
1499+
.db
1500+
.add_relay_member(
1501+
community,
1502+
&keys.public_key().to_hex(),
1503+
role,
1504+
None,
1505+
&Keys::generate(),
1506+
)
1507+
.await
1508+
.map(|write| write.outcome)
1509+
.expect("seed relay member");
1510+
}
1511+
let starter = create_channel(&state, &tenant, &owner, &[]).await;
1512+
edit_channel(&state, &tenant, &owner, starter, &[&["auto_join", "true"]])
1513+
.await
1514+
.expect("relay owner flags channel");
1515+
1516+
let pool = state.db.pool().clone();
1517+
let mut archive = pool.begin().await.expect("begin archive");
1518+
let archive_pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()")
1519+
.fetch_one(&mut *archive)
1520+
.await
1521+
.expect("archive backend pid");
1522+
sqlx::query("UPDATE channels SET archived_at = NOW() WHERE community_id = $1 AND id = $2")
1523+
.bind(community.as_uuid())
1524+
.bind(starter)
1525+
.execute(&mut *archive)
1526+
.await
1527+
.expect("archive the default channel");
1528+
1529+
let auto_join = tokio::spawn({
1530+
let state = Arc::clone(&state);
1531+
let tenant = tenant.clone();
1532+
let joiner_hex = joiner_hex.clone();
1533+
async move { auto_join_default_channels(&tenant, &state, &joiner_hex).await }
1534+
});
1535+
// Wait until the join is blocked behind the archive, so it has
1536+
// already listed the channel and passed the join body's check.
1537+
let deadline = std::time::Instant::now() + Duration::from_secs(10);
1538+
loop {
1539+
let waiting: bool = sqlx::query_scalar(
1540+
"SELECT EXISTS (SELECT 1 FROM pg_stat_activity \
1541+
WHERE $1 = ANY(pg_blocking_pids(pid)))",
1542+
)
1543+
.bind(archive_pid)
1544+
.fetch_one(&pool)
1545+
.await
1546+
.expect("read lock waiters");
1547+
if waiting {
1548+
break;
1549+
}
1550+
assert!(
1551+
!auto_join.is_finished(),
1552+
"the auto-join finished without waiting for the archive"
1553+
);
1554+
assert!(
1555+
std::time::Instant::now() < deadline,
1556+
"the auto-join never waited for the archive"
1557+
);
1558+
tokio::time::sleep(Duration::from_millis(10)).await;
1559+
}
1560+
archive.commit().await.expect("commit archive");
1561+
tokio::time::timeout(Duration::from_secs(10), auto_join)
1562+
.await
1563+
.expect("the auto-join returns after the archive commits")
1564+
.expect("auto-join task must not panic");
1565+
1566+
assert_eq!(
1567+
channel_roles(&state, community, &[starter], &joiner).await,
1568+
[None],
1569+
"an archived default channel must not admit the new member"
1570+
);
1571+
assert!(
1572+
!group_state_tags(&state, &tenant, starter, 39002)
1573+
.await
1574+
.iter()
1575+
.any(|tag| tag[0] == "p" && tag[1] == joiner_hex),
1576+
"kind:39002 must not list the new member"
1577+
);
1578+
assert_eq!(
1579+
added_notification_count(&state, community, &joiner_hex).await,
1580+
0
1581+
);
1582+
assert_eq!(
1583+
member_joined_notice_count(&state, community, starter, &joiner_hex).await,
1584+
0
1585+
);
1586+
}
1587+
14631588
#[tokio::test]
14641589
#[ignore = "requires Postgres"]
14651590
async fn owner_mints_and_new_pubkey_claims() {

0 commit comments

Comments
 (0)