Skip to content

Commit 5eed095

Browse files
ngoodger-blockBuildyclaude
committed
fix(relay): recheck auto_join authority at commit under the membership list lock
kind:9002 auto_join authority was decided from a roster read before the write, so an admin demoted in between could still set a default channel. The write now decides it again as its last step before commit, reading the actor's community role and grants under the kind:13534 membership list lock that every roster change holds while it commits. The list lock comes last, after the channel TTL and row locks and any communities update, as it does for every roster writer. Locking the actor's roster row inside the channel write instead deadlocked an owner's auto_join + unlisted edit (channel row, owner row, then community row) against an ownership transfer (community row, owner rows, then the list); the new test reproduces that interleaving. Co-authored-by: Buildy <9c2fd8f72fad905d31cdf563c3920011399bd334523d6b3c84c0dc124bcfb380@sprout-oss.stage.blox.sqprod.co> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Nikolaj Goodger <ngoodger@squareup.com>
1 parent 7726d47 commit 5eed095

4 files changed

Lines changed: 293 additions & 46 deletions

File tree

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

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1737,6 +1737,11 @@ pub struct ChannelMetadataEdit {
17371737
/// Set when the actor is the channel's owner or admin. An operator rename
17381738
/// without it applies only to a listed channel.
17391739
pub channel_authority: bool,
1740+
/// The relay's pubkey, set for a user-signed edit: settings that take
1741+
/// community authority, such as `auto_join`, are then decided again at
1742+
/// commit from the actor's role and grants, read under this relay's
1743+
/// membership-list lock.
1744+
pub community_authority_relay: Option<nostr::PublicKey>,
17401745
}
17411746

17421747
/// The result of [`Db::apply_channel_metadata_event`].
@@ -1867,7 +1872,9 @@ pub(crate) async fn apply_channel_metadata_event(
18671872
archived,
18681873
operator_rename: _,
18691874
channel_authority: _,
1875+
community_authority_relay,
18701876
} = edit;
1877+
let needs_steward = columns.auto_join.is_some();
18711878
let actor = event.pubkey.to_bytes();
18721879
if !columns.is_empty() {
18731880
update_channel_on(&mut locked, columns, &actor).await?;
@@ -1890,6 +1897,24 @@ pub(crate) async fn apply_channel_metadata_event(
18901897
crate::insert_mentions_in_transaction(locked.tx(), message, Some(channel_id)).await?;
18911898
}
18921899
}
1900+
// Decided last, after the channel TTL and row locks and any `communities`
1901+
// update above: the membership-list lock is the final lock every roster
1902+
// writer takes (a grant change locks roster rows, then the list; an
1903+
// ownership transfer the community row, then owner rows, then the list),
1904+
// so taking it here, last, cannot close a cycle with any of them.
1905+
if let Some(relay) = community_authority_relay.filter(|_| needs_steward) {
1906+
let authority = crate::relay_members::community_authority_at_commit(
1907+
locked.tx(),
1908+
relay.as_bytes(),
1909+
event.pubkey.as_bytes(),
1910+
)
1911+
.await?;
1912+
if !authority.is_steward() {
1913+
return Err(DbError::AccessDenied(
1914+
"actor not authorized: community authority changed".to_string(),
1915+
));
1916+
}
1917+
}
18931918
tx.commit().await?;
18941919
Ok(ChannelMetadataWrite {
18951920
stored,

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

Lines changed: 53 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -452,6 +452,58 @@ pub async fn update_relay_member_role(
452452
commit_membership_write(tx, updated, updated, relay_keypair).await
453453
}
454454

455+
/// The advisory lock key of `community`'s kind:13534 membership list, which
456+
/// `relay_pubkey` signs. Every roster change holds it while it commits.
457+
pub fn membership_list_lock_key(community: CommunityId, relay_pubkey: &[u8]) -> i64 {
458+
replaceable::event_replacement_lock_key(
459+
community,
460+
buzz_core::kind::KIND_NIP43_MEMBERSHIP_LIST as i32,
461+
relay_pubkey,
462+
None,
463+
)
464+
}
465+
466+
async fn lock_membership_list(tx: &mut crate::AdmittedTx, relay_pubkey: &[u8]) -> Result<()> {
467+
let key = membership_list_lock_key(tx.community(), relay_pubkey);
468+
observability::observe_event_lock(
469+
observability::LockType::Membership,
470+
buzz_core::kind::KIND_NIP43_MEMBERSHIP_LIST as i32,
471+
sqlx::query("SELECT pg_advisory_xact_lock($1)")
472+
.bind(key)
473+
.execute(tx.conn()),
474+
)
475+
.await?;
476+
Ok(())
477+
}
478+
479+
/// `actor`'s community role and grants, read on `tx` under the membership
480+
/// list lock: a grant change, demotion or removal either commits first and is
481+
/// seen here, or waits until `tx` commits. Like every roster writer's, the
482+
/// list lock must be the last lock `tx` takes, so call this after the
483+
/// transaction's other writes.
484+
pub(crate) async fn community_authority_at_commit(
485+
tx: &mut crate::AdmittedTx,
486+
relay_pubkey: &[u8],
487+
actor: &[u8],
488+
) -> Result<buzz_core::community::CommunityAuthority> {
489+
lock_membership_list(tx, relay_pubkey).await?;
490+
let row = sqlx::query(
491+
"SELECT role, grants FROM relay_members WHERE community_id = $1 AND pubkey = $2",
492+
)
493+
.bind(tx.community().as_uuid())
494+
.bind(hex::encode(actor))
495+
.fetch_optional(tx.conn())
496+
.await?;
497+
Ok(match row {
498+
Some(row) => {
499+
let role: String = row.try_get("role")?;
500+
let grants: Vec<String> = row.try_get("grants")?;
501+
buzz_core::community::CommunityAuthority::new(Some(&role), &grants)
502+
}
503+
None => buzz_core::community::CommunityAuthority::default(),
504+
})
505+
}
506+
455507
/// The outcome of [`set_relay_member_grant`].
456508
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
457509
pub enum GrantResult {
@@ -1198,20 +1250,7 @@ pub(crate) async fn write_nip43_membership_snapshot(
11981250
let community_id = tx.community();
11991251
let kind_i32 = buzz_core::kind::KIND_NIP43_MEMBERSHIP_LIST as i32;
12001252
let pubkey_bytes = relay_keypair.public_key().to_bytes();
1201-
let lock_key = replaceable::event_replacement_lock_key(
1202-
community_id,
1203-
kind_i32,
1204-
pubkey_bytes.as_slice(),
1205-
None,
1206-
);
1207-
observability::observe_event_lock(
1208-
observability::LockType::Membership,
1209-
kind_i32,
1210-
sqlx::query("SELECT pg_advisory_xact_lock($1)")
1211-
.bind(lock_key)
1212-
.execute(tx.conn()),
1213-
)
1214-
.await?;
1253+
lock_membership_list(tx, pubkey_bytes.as_slice()).await?;
12151254

12161255
let rows = sqlx::query(
12171256
"SELECT pubkey, role, grants FROM relay_members \

‎crates/buzz-relay/src/handlers/community_grants_postgres_tests.rs‎

Lines changed: 166 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,17 @@
1-
//! Postgres-backed tests for community grants (kind:9034).
1+
//! Postgres-backed tests for community grants (kind:9034) and the community
2+
//! authority the relay decides again at commit: `community_authority_at_commit`
3+
//! reads the actor's role and grants with a plain read under the
4+
//! membership-list lock, immediately before commit.
25
36
use std::sync::Arc;
47

58
use buzz_core::TenantContext;
69
use buzz_db::event::EventQuery;
710
use nostr::{Event, EventBuilder, Keys, Kind, Tag};
11+
use uuid::Uuid;
812

9-
use crate::handlers::group_state_postgres_tests::{community, state};
13+
use crate::handlers::group_state_postgres_tests::{community, edit_channel, http_auth, state};
14+
use crate::handlers::ingest::ingest_event;
1015
use crate::handlers::relay_admin::handle_relay_admin_event;
1116
use crate::state::AppState;
1217

@@ -73,6 +78,36 @@ pub(crate) async fn grants(state: &AppState, tenant: &TenantContext, keys: &Keys
7378
.unwrap_or_default()
7479
}
7580

81+
/// Ingests a kind:9007 for a new channel with `extra` tags. Returns the
82+
/// channel id, or the relay's refusal.
83+
pub(crate) async fn try_create(
84+
state: &Arc<AppState>,
85+
tenant: &TenantContext,
86+
keys: &Keys,
87+
channel_id: Uuid,
88+
extra: &[&[&str]],
89+
) -> Result<Uuid, String> {
90+
let mut tags = vec![
91+
strs(&["h", &channel_id.to_string()]),
92+
strs(&["name", &format!("c-{}", channel_id.simple())]),
93+
];
94+
tags.extend(extra.iter().map(|t| strs(t)));
95+
match ingest_event(state, tenant, sign(keys, 9007, tags), http_auth(keys)).await {
96+
Ok(result) if result.accepted => Ok(channel_id),
97+
Ok(result) => Err(result.message),
98+
Err(error) => Err(format!("{error:?}")),
99+
}
100+
}
101+
102+
pub(crate) async fn create(
103+
state: &Arc<AppState>,
104+
tenant: &TenantContext,
105+
keys: &Keys,
106+
extra: &[&[&str]],
107+
) -> Result<Uuid, String> {
108+
try_create(state, tenant, keys, Uuid::new_v4(), extra).await
109+
}
110+
76111
/// Owners and admins appoint maintainers; an admin cannot touch another
77112
/// admin's grants; the target must be a member of the same community; and the
78113
/// relay-signed roster lists the grant. A grant in one community gives
@@ -206,3 +241,132 @@ async fn a_demoted_admin_cannot_change_grants() {
206241
assert!(revoke.await.expect("revoke task").is_err());
207242
assert_eq!(grants(&state, &tenant, &member).await, vec!["maintainer"]);
208243
}
244+
245+
/// Holds the community's membership-list lock on `tx`, as every roster
246+
/// writer does while it commits.
247+
pub(crate) async fn lock_membership_list(
248+
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
249+
state: &AppState,
250+
tenant: &TenantContext,
251+
) {
252+
sqlx::query("SELECT pg_advisory_xact_lock($1)")
253+
.bind(buzz_db::relay_members::membership_list_lock_key(
254+
tenant.community(),
255+
state.relay_keypair.public_key().as_bytes(),
256+
))
257+
.execute(&mut **tx)
258+
.await
259+
.expect("membership-list lock");
260+
}
261+
262+
/// `auto_join` authority is decided again at commit: an admin's edit racing
263+
/// their demotion waits for it and is then refused.
264+
/// Mutation: drop the authority recheck from `apply_channel_metadata_event`
265+
/// → the edit commits after the demotion → RED.
266+
#[tokio::test]
267+
#[ignore = "requires Postgres"]
268+
async fn an_auto_join_edit_racing_a_demotion_is_refused() {
269+
let state = state().await;
270+
let tenant = community(&state, "auto-join-demote").await;
271+
let (owner, admin) = (Keys::generate(), Keys::generate());
272+
seed(&state, &tenant, &owner, "owner").await;
273+
seed(&state, &tenant, &admin, "admin").await;
274+
let channel_id = create(&state, &tenant, &owner, &[]).await.expect("open");
275+
276+
let pool = sqlx::PgPool::connect(&crate::test_support::database_url())
277+
.await
278+
.expect("pool");
279+
let mut demote = pool.begin().await.expect("begin");
280+
sqlx::query("UPDATE relay_members SET role = 'member' WHERE community_id = $1 AND pubkey = $2")
281+
.bind(tenant.community().as_uuid())
282+
.bind(admin.public_key().to_hex())
283+
.execute(&mut *demote)
284+
.await
285+
.expect("demote");
286+
lock_membership_list(&mut demote, &state, &tenant).await;
287+
288+
let edit = tokio::spawn({
289+
let (state, tenant, admin) = (state.clone(), tenant.clone(), admin.clone());
290+
async move {
291+
edit_channel(
292+
&state,
293+
&tenant,
294+
&admin,
295+
channel_id,
296+
&[&["auto_join", "true"]],
297+
)
298+
.await
299+
}
300+
});
301+
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
302+
assert!(!edit.is_finished(), "the edit waits for the demotion");
303+
demote.commit().await.expect("commit");
304+
assert!(edit.await.expect("edit task").is_err());
305+
assert!(
306+
!state
307+
.db
308+
.get_channel_for_event_write(tenant.community(), channel_id)
309+
.await
310+
.expect("channel")
311+
.auto_join
312+
);
313+
}
314+
315+
/// The recheck takes the membership-list lock last, as roster writers do, so
316+
/// an owner's `auto_join` and `unlisted` edit (which also touches the
317+
/// community row) and a writer holding the community row, then the owner
318+
/// rows, then the list lock both complete.
319+
/// Mutation: take the authority recheck before the channel writes, with the
320+
/// owner's roster row locked → deadlock → RED.
321+
#[tokio::test]
322+
#[ignore = "requires Postgres"]
323+
async fn an_auto_join_edit_and_an_ownership_change_do_not_deadlock() {
324+
let state = state().await;
325+
let tenant = community(&state, "auto-join-owner-lock").await;
326+
let owner = Keys::generate();
327+
seed(&state, &tenant, &owner, "owner").await;
328+
let channel_id = create(&state, &tenant, &owner, &[]).await.expect("open");
329+
330+
let pool = sqlx::PgPool::connect(&crate::test_support::database_url())
331+
.await
332+
.expect("pool");
333+
let mut transfer = pool.begin().await.expect("begin");
334+
sqlx::query("SELECT 1 FROM communities WHERE id = $1 FOR NO KEY UPDATE")
335+
.bind(tenant.community().as_uuid())
336+
.execute(&mut *transfer)
337+
.await
338+
.expect("lock community");
339+
340+
let edit = tokio::spawn({
341+
let (state, tenant, owner) = (state.clone(), tenant.clone(), owner.clone());
342+
async move {
343+
edit_channel(
344+
&state,
345+
&tenant,
346+
&owner,
347+
channel_id,
348+
&[&["auto_join", "true"], &["unlisted", "true"]],
349+
)
350+
.await
351+
}
352+
});
353+
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
354+
sqlx::query(
355+
"SELECT 1 FROM relay_members WHERE community_id = $1 AND role = 'owner' FOR UPDATE",
356+
)
357+
.bind(tenant.community().as_uuid())
358+
.execute(&mut *transfer)
359+
.await
360+
.expect("lock owners");
361+
lock_membership_list(&mut transfer, &state, &tenant).await;
362+
transfer.commit().await.expect("commit");
363+
edit.await.expect("edit task").expect("edit");
364+
assert!(
365+
state
366+
.db
367+
.get_channel_for_event_write(tenant.community(), channel_id)
368+
.await
369+
.expect("channel")
370+
.auto_join
371+
);
372+
}

0 commit comments

Comments
 (0)