Skip to content

Commit 8e3140d

Browse files
kalvinnchaupeonclaude
committed
fix(relay): check invite issuer role inside the mint transaction
read the issuer's owner/admin role for share inside the mint transaction, after the admission lock, so a concurrent demotion, removal or ownership transfer either lands first and refuses the mint or waits for it. both /api/invites and the operator route mint through db::mint_relay_invite_as_admin. the operator route drops its separate role read, records the target community and the not_relay_admin or restricted refusal on its access line, uses coded_api_error for its own errors, and narrows the lifecycle comment to what the transaction rechecks. postgres tests cover a demotion and a deletion fence landing mid-mint. Co-authored-by: peon <9ac6794b000690b7e814eb1805ad32405d0bec7d52838de3a86cf967565dacc0@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Kalvin Chau <[email protected]>
1 parent 0e560c3 commit 8e3140d

5 files changed

Lines changed: 226 additions & 41 deletions

File tree

‎crates/buzz-db/src/error.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,10 @@ pub enum DbError {
5454
#[error("invitation principal is restricted")]
5555
InviteRestricted,
5656

57+
/// The invitation issuer is not an owner or admin at mint time.
58+
#[error("invitation issuer is not an owner or admin")]
59+
InviteIssuerNotAdmin,
60+
5761
/// A verified invitation owner conflicts with the recorded owner.
5862
#[error("invitation owner does not match the recorded owner")]
5963
InviteOwnerMismatch,

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

Lines changed: 45 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,33 @@ pub async fn mint_relay_invite(
142142
created_by: &str,
143143
ttl_secs: u64,
144144
max_uses: Option<i32>,
145+
) -> Result<MintedInvite> {
146+
mint(pool, community, created_by, ttl_secs, max_uses, false).await
147+
}
148+
149+
/// Like [`mint_relay_invite`], but refuses with
150+
/// [`DbError::InviteIssuerNotAdmin`](crate::DbError::InviteIssuerNotAdmin)
151+
/// unless `created_by` is an owner or admin inside the mint transaction. The
152+
/// role row is held `FOR SHARE` through commit, so a concurrent demotion,
153+
/// removal or ownership transfer either lands first and refuses this mint or
154+
/// waits for it.
155+
pub async fn mint_relay_invite_as_admin(
156+
pool: &PgPool,
157+
community: CommunityId,
158+
created_by: &str,
159+
ttl_secs: u64,
160+
max_uses: Option<i32>,
161+
) -> Result<MintedInvite> {
162+
mint(pool, community, created_by, ttl_secs, max_uses, true).await
163+
}
164+
165+
async fn mint(
166+
pool: &PgPool,
167+
community: CommunityId,
168+
created_by: &str,
169+
ttl_secs: u64,
170+
max_uses: Option<i32>,
171+
require_admin: bool,
145172
) -> Result<MintedInvite> {
146173
validate_mint_inputs(ttl_secs, max_uses)?;
147174
if !is_canonical_invite_pubkey(created_by) {
@@ -168,6 +195,19 @@ pub async fn mint_relay_invite(
168195
)
169196
.await?;
170197
lock_admission(tx.conn(), community).await?;
198+
if require_admin {
199+
let role: Option<String> = sqlx::query_scalar(
200+
"SELECT role FROM relay_members \
201+
WHERE community_id = $1 AND pubkey = $2 FOR SHARE",
202+
)
203+
.bind(community.as_uuid())
204+
.bind(created_by)
205+
.fetch_optional(tx.conn())
206+
.await?;
207+
if !matches!(role.as_deref(), Some("owner" | "admin")) {
208+
return Err(crate::DbError::InviteIssuerNotAdmin);
209+
}
210+
}
171211
if principal_restricted(tx.conn(), community, created_by).await? {
172212
return Err(crate::DbError::InviteRestricted);
173213
}
@@ -693,20 +733,21 @@ pub async fn claim_relay_invite_with_owner(
693733
}
694734

695735
impl Db {
696-
/// Mints a v2 use-limited relay invite. The plaintext code is returned
697-
/// exactly once; only its SHA-256 hash is persisted.
736+
/// Mints a v2 use-limited relay invite for an owner or admin; see
737+
/// [`mint_relay_invite_as_admin`]. The plaintext code is returned exactly
738+
/// once; only its SHA-256 hash is persisted.
698739
///
699740
/// `max_uses` is `None` for unlimited or `Some(1..=10000)`.
700741
/// `ttl_secs` must be in the shared invite lifetime range.
701742
#[datastore_span(name = "mint_relay_invite", system = "postgresql")]
702-
pub async fn mint_relay_invite(
743+
pub async fn mint_relay_invite_as_admin(
703744
&self,
704745
community: CommunityId,
705746
created_by: &str,
706747
ttl_secs: u64,
707748
max_uses: Option<i32>,
708749
) -> Result<MintedInvite> {
709-
mint_relay_invite(&self.pool, community, created_by, ttl_secs, max_uses).await
750+
mint_relay_invite_as_admin(&self.pool, community, created_by, ttl_secs, max_uses).await
710751
}
711752

712753
/// Claim an invite and persist caller-verified ownership atomically.

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,10 @@ pub async fn accept_policy(
234234
pub(crate) fn map_mint_error(error: buzz_db::DbError) -> (StatusCode, Json<Value>) {
235235
match error {
236236
buzz_db::DbError::InviteRestricted => api_error(StatusCode::FORBIDDEN, "invite_restricted"),
237+
buzz_db::DbError::InviteIssuerNotAdmin => api_error(
238+
StatusCode::FORBIDDEN,
239+
"only relay owners and admins can create invites",
240+
),
237241
buzz_db::DbError::InvalidData(message) | buzz_db::DbError::DeletionSafety(message) => {
238242
api_error(StatusCode::BAD_REQUEST, &message)
239243
}
@@ -410,7 +414,7 @@ async fn mint_invite_inner(
410414
// Mint a v2 opaque, database-backed invite.
411415
let invite = state
412416
.db
413-
.mint_relay_invite(tenant.community(), &sender_hex, ttl, max_uses)
417+
.mint_relay_invite_as_admin(tenant.community(), &sender_hex, ttl, max_uses)
414418
.await
415419
.map_err(map_mint_error)?;
416420

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

Lines changed: 35 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
//! membership data at mint time, exactly as `POST /api/invites` does.
66
77
use super::*;
8+
use crate::access::AuthReason;
89
use crate::api::invites::{
910
map_mint_error, minted_invite_json, validate_mint_request, MintInviteRequest,
1011
};
@@ -50,21 +51,17 @@ pub async fn mint_community_invite(
5051
_ => error,
5152
})?;
5253
let request: Request = serde_json::from_slice(&body).map_err(|e| {
53-
with_code(
54-
api_error(
55-
StatusCode::BAD_REQUEST,
56-
&format!("invalid community-invite JSON: {e}"),
57-
),
54+
coded_api_error(
55+
StatusCode::BAD_REQUEST,
5856
"invalid_request",
57+
&format!("invalid community-invite JSON: {e}"),
5958
)
6059
})?;
6160
let actor = validate_pubkey_hex(&request.actor_pubkey).ok_or_else(|| {
62-
with_code(
63-
api_error(
64-
StatusCode::BAD_REQUEST,
65-
"invalid actor_pubkey: expected 64-char hex pubkey",
66-
),
61+
coded_api_error(
62+
StatusCode::BAD_REQUEST,
6763
"invalid_request",
64+
"invalid actor_pubkey: expected 64-char hex pubkey",
6865
)
6966
})?;
7067
let (ttl, max_uses) = validate_mint_request(&MintInviteRequest {
@@ -80,38 +77,40 @@ pub async fn mint_community_invite(
8077
.await
8178
.map_err(|e| internal_error(&format!("community invite host lookup: {e}")))?
8279
.ok_or_else(|| {
83-
with_code(
84-
api_error(StatusCode::NOT_FOUND, "community not found"),
80+
coded_api_error(
81+
StatusCode::NOT_FOUND,
8582
"community_not_found",
83+
"community not found",
8684
)
8785
})?;
88-
let role = state
89-
.db
90-
.get_relay_member(community, &actor)
91-
.await
92-
.map_err(|e| internal_error(&format!("community invite role lookup: {e}")))?
93-
.map(|member| member.role);
94-
if !matches!(role.as_deref(), Some("owner" | "admin")) {
95-
return Err(with_code(
96-
api_error(
97-
StatusCode::FORBIDDEN,
98-
"only relay owners and admins can create invites",
99-
),
100-
"not_owner",
101-
));
102-
}
103-
// The mint re-checks lifecycle and the actor's restriction atomically.
86+
slot.in_community(community);
87+
// The mint checks the actor's role and restriction, and the community's
88+
// deletion state, in one transaction. It does not re-check archiving: an
89+
// invite minted while an archive lands cannot be claimed while archived.
10490
let invite = state
10591
.db
106-
.mint_relay_invite(community, &actor, ttl, max_uses)
92+
.mint_relay_invite_as_admin(community, &actor, ttl, max_uses)
10793
.await
108-
.map_err(|error| {
109-
let error = map_mint_error(error);
110-
match error.0 {
111-
StatusCode::FORBIDDEN => with_code(error, "restricted"),
112-
StatusCode::SERVICE_UNAVAILABLE => with_code(error, "unavailable"),
113-
StatusCode::BAD_REQUEST => with_code(error, "invalid_request"),
114-
_ => error,
94+
.map_err(|error| match error {
95+
buzz_db::DbError::InviteIssuerNotAdmin => {
96+
slot.finish(AuthResult::Denied(AuthReason::NotRelayAdmin));
97+
coded_api_error(
98+
StatusCode::FORBIDDEN,
99+
"not_owner",
100+
"only relay owners and admins can create invites",
101+
)
102+
}
103+
buzz_db::DbError::InviteRestricted => {
104+
slot.finish(AuthResult::Denied(AuthReason::Restricted));
105+
with_code(map_mint_error(error), "restricted")
106+
}
107+
error => {
108+
let error = map_mint_error(error);
109+
match error.0 {
110+
StatusCode::SERVICE_UNAVAILABLE => with_code(error, "unavailable"),
111+
StatusCode::BAD_REQUEST => with_code(error, "invalid_request"),
112+
_ => error,
113+
}
115114
}
116115
})?;
117116
slot.detail(crate::access::Detail {

‎crates/buzz-relay/src/api/operator/postgres_tests/invite_postgres_tests.rs‎

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,4 +241,141 @@ mod postgres_tests {
241241
"community not found"
242242
);
243243
}
244+
245+
/// Mint on a task while `holder` keeps an uncommitted change, wait until
246+
/// the mint is blocked on it, then commit it and return the mint response.
247+
async fn mint_across_commit(
248+
state: &Arc<AppState>,
249+
operator: &Keys,
250+
body: Value,
251+
mut holder: sqlx::Transaction<'static, sqlx::Postgres>,
252+
) -> axum::response::Response {
253+
let holder_pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()")
254+
.fetch_one(&mut *holder)
255+
.await
256+
.expect("holder pid");
257+
let task = tokio::spawn({
258+
let (state, operator) = (state.clone(), operator.clone());
259+
async move { mint(&state, &operator, body).await }
260+
});
261+
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
262+
loop {
263+
let blocked: bool = sqlx::query_scalar(
264+
"SELECT EXISTS (SELECT 1 FROM pg_stat_activity \
265+
WHERE $1 = ANY(pg_blocking_pids(pid)))",
266+
)
267+
.bind(holder_pid)
268+
.fetch_one(state.db.pool())
269+
.await
270+
.expect("read lock waiters");
271+
if blocked {
272+
break;
273+
}
274+
assert!(!task.is_finished(), "the mint finished without waiting");
275+
assert!(
276+
std::time::Instant::now() < deadline,
277+
"the mint never waited for the uncommitted change"
278+
);
279+
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
280+
}
281+
holder.commit().await.expect("commit holder");
282+
task.await.expect("mint task")
283+
}
284+
285+
#[tokio::test]
286+
#[ignore = "requires Postgres"]
287+
async fn operator_mint_rechecks_role_and_lifecycle_inside_the_mint() {
288+
let operator = Keys::generate();
289+
let Some(state) = operator_test_state(std::slice::from_ref(&operator)).await else {
290+
return;
291+
};
292+
let [owner, admin] = std::array::from_fn(|_| Keys::generate());
293+
let host = format!("community-{}.example", Uuid::new_v4().simple());
294+
assert_eq!(
295+
provision_community(state.clone(), &operator, &host, &owner)
296+
.await
297+
.status(),
298+
StatusCode::OK
299+
);
300+
let community = state
301+
.db
302+
.lookup_community_by_host(&host)
303+
.await
304+
.expect("lookup community")
305+
.expect("community exists")
306+
.id;
307+
let admin_hex = admin.public_key().to_hex();
308+
state
309+
.db
310+
.add_relay_member(community, &admin_hex, "admin", None, &state.relay_keypair)
311+
.await
312+
.map(|write| write.outcome)
313+
.expect("seed admin");
314+
let request = |actor: &Keys| {
315+
serde_json::json!({
316+
"community_id": community.to_string(),
317+
"actor_pubkey": actor.public_key().to_hex(),
318+
})
319+
};
320+
let invites = || async {
321+
sqlx::query_scalar::<_, i64>(
322+
"SELECT count(*) FROM relay_invites WHERE community_id = $1",
323+
)
324+
.bind(community.as_uuid())
325+
.fetch_one(state.db.pool())
326+
.await
327+
.expect("count invites")
328+
};
329+
330+
// A demotion that lands while the mint is in flight refuses it.
331+
let mut holder = state.db.pool().begin().await.expect("begin demotion");
332+
sqlx::query(
333+
"UPDATE relay_members SET role = 'member' WHERE community_id = $1 AND pubkey = $2",
334+
)
335+
.bind(community.as_uuid())
336+
.bind(&admin_hex)
337+
.execute(&mut *holder)
338+
.await
339+
.expect("demote admin");
340+
error(
341+
mint_across_commit(&state, &operator, request(&admin), holder).await,
342+
StatusCode::FORBIDDEN,
343+
"not_owner",
344+
)
345+
.await;
346+
assert_eq!(invites().await, 0, "a refused mint must not persist");
347+
348+
// A deletion fence that lands after the host lookup refuses it too.
349+
let mut holder = state.db.pool().begin().await.expect("begin fence");
350+
sqlx::query("SELECT pg_advisory_xact_lock(community_deletion_lock_key($1))")
351+
.bind(community.as_uuid())
352+
.execute(&mut *holder)
353+
.await
354+
.expect("take deletion lock");
355+
// Fence as the deletion executor does, so the tombstone guard admits it.
356+
sqlx::query(
357+
"SELECT set_config('buzz.deletion_executor_community', $1::text, true), \
358+
set_config('buzz.deletion_fence_generation', (deletion_fence_generation + 1)::text, true) \
359+
FROM communities WHERE id = $1",
360+
)
361+
.bind(community.as_uuid())
362+
.execute(&mut *holder)
363+
.await
364+
.expect("act as deletion executor");
365+
sqlx::query(
366+
"UPDATE communities SET deletion_state = 'quiescing', \
367+
deletion_fence_generation = deletion_fence_generation + 1 WHERE id = $1",
368+
)
369+
.bind(community.as_uuid())
370+
.execute(&mut *holder)
371+
.await
372+
.expect("fence community");
373+
error(
374+
mint_across_commit(&state, &operator, request(&owner), holder).await,
375+
StatusCode::SERVICE_UNAVAILABLE,
376+
"unavailable",
377+
)
378+
.await;
379+
assert_eq!(invites().await, 0, "a fenced mint must not persist");
380+
}
244381
}

0 commit comments

Comments
 (0)