Skip to content

Commit 989412f

Browse files
TheSentinel454Elrondclaude
committed
fix(invites): reject unknown claim codes before the admission lock
A v2 claim took the community-wide admission lock before looking up its token, so forged `v2.` codes from fresh keys could serialize a community's claims, bans and timeouts and hold shared writer-pool connections while queued. Check that the code exists with an indexed read first; the locked `FOR UPDATE` read stays authoritative. A restricted claimant presenting an unknown code now gets `invite_invalid`, which reveals nothing. Also from review: mint's owner-link 503 reuses `OWNER_LINK_ERROR` like the NIP-FI path; comments explain the admission wait behind membership snapshots, the defensive claim-owner revocation, and why issuer restrictions map to `invite_invalid`; TESTING.md notes that a rollback past 0074 needs `BUZZ_AUTO_MIGRATE` off (docs/database.md Rule 5). Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Luke Tornquist <[email protected]>
1 parent 12f462c commit 989412f

6 files changed

Lines changed: 48 additions & 3 deletions

File tree

‎TESTING.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,9 @@ keep it closed until it is active and repaired, then recheck zero before admitti
219219
traffic. After repair, timeouts/mutes only block temporarily; active bans still
220220
revoke permanently. A rollback to code that ignores `revoked_at` requires
221221
invitation admission paused, using the same traffic/writer controls if needed.
222+
It also requires `BUZZ_AUTO_MIGRATE` off: with auto-migration on (the Helm
223+
default), the old binary fails at startup with SQLx `VersionMissing(74)`. See
224+
[docs/database.md](docs/database.md) Rule 5.
222225
Legacy owner attribution uses the agent's currently recorded
223226
`agent_owner_pubkey`; deleting an owner user row out of band clears that link
224227
through its foreign key, so a later repair cannot recover the former

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

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,9 @@ pub async fn mint_relay_invite(
199199

200200
/// Lock invitation admission against community restriction and owner writes.
201201
/// Call before reading restrictions or locking an invite row, and hold to commit.
202+
/// A joined claim holds it through its NIP-43 membership snapshot, so mint, ban,
203+
/// timeout and first owner link wait for that snapshot, which grows with the
204+
/// member count. Claims reject unknown codes before taking it.
202205
pub(crate) async fn lock_admission(
203206
tx: &mut sqlx::PgConnection,
204207
community: CommunityId,
@@ -420,6 +423,21 @@ pub async fn claim_relay_invite_with_owner(
420423
verified_owner: Option<&str>,
421424
relay_keypair: &nostr::Keys,
422425
) -> Result<MembershipWrite<InviteClaimResult>> {
426+
// Unknown codes are free to forge, so reject them before taking the
427+
// community-wide admission lock; the locked read below stays authoritative.
428+
let known: bool = sqlx::query_scalar(
429+
"SELECT EXISTS (SELECT 1 FROM relay_invites \
430+
WHERE community_id = $1 AND token_hash = $2)",
431+
)
432+
.bind(community.as_uuid())
433+
.bind(token_hash)
434+
.fetch_one(pool)
435+
.await?;
436+
if !known {
437+
log_claim_outcome(community, None, "invalid", None, None);
438+
return Ok(MembershipWrite::unchanged(ClaimOutcome::Invalid.into()));
439+
}
440+
423441
let mut tx = crate::begin_community_write_transaction(
424442
pool,
425443
community,

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,9 @@ pub(super) async fn persist_claim_owner(
8282
}
8383
let link_created = sqlx::query("UPDATE users SET agent_owner_pubkey=$3 WHERE community_id=$1 AND pubkey=$2 AND agent_owner_pubkey IS NULL")
8484
.bind(community.as_uuid()).bind(&claimant_bytes).bind(&owner_bytes).execute(&mut *tx).await?.rows_affected() > 0;
85-
// Defensive parity with other owner writers; admission already rejects banned owners.
85+
// Defense in depth: `claimant_restricted` already refused a banned owner
86+
// under the same admission lock, so this finds nothing today. It keeps
87+
// parity with every other owner writer if that check ever moves.
8688
if link_created {
8789
super::revoke_restricted_agent_invites(tx, community, &claimant_bytes, &owner_bytes)
8890
.await?;

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

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -357,3 +357,22 @@ async fn linked_authorization_owner_and_missing_agent_do_not_wait_on_admission()
357357
));
358358
claim.rollback().await.unwrap();
359359
}
360+
361+
#[tokio::test]
362+
#[ignore = "requires Postgres"]
363+
async fn unknown_claim_code_is_rejected_without_waiting_on_admission() {
364+
let (pool, community, _, claimant) = fixture().await;
365+
let mut held = pool.begin().await.unwrap();
366+
lock_admission(&mut held, community).await.unwrap();
367+
// A forged code must not queue behind admission; if the claim takes the
368+
// lock before looking the code up, this bounded call cannot finish.
369+
let outcome = tokio::time::timeout(
370+
std::time::Duration::from_secs(5),
371+
claim_relay_invite_outcome(&pool, community, &[0xAB; 32], &claimant, None),
372+
)
373+
.await
374+
.expect("unknown code waited on the admission lock")
375+
.unwrap();
376+
assert_eq!(outcome, ClaimOutcome::Invalid);
377+
held.rollback().await.unwrap();
378+
}

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -330,7 +330,7 @@ async fn mint_invite_checked(
330330
super::relay_members::OwnerLink::Unavailable => {
331331
return api_error(
332332
StatusCode::SERVICE_UNAVAILABLE,
333-
"restriction lookup unavailable",
333+
crate::handlers::auth::OWNER_LINK_ERROR,
334334
)
335335
.into_response();
336336
}
@@ -517,6 +517,9 @@ pub async fn claim_invite(
517517
buzz_db::relay_invite::ClaimOutcome::Exhausted => {
518518
Err(api_error(StatusCode::FORBIDDEN, "invite_exhausted"))
519519
}
520+
// Deliberately indistinguishable, even for an issuer timeout whose
521+
// link works again later: a claim never reveals the issuer's
522+
// moderation state.
520523
buzz_db::relay_invite::ClaimOutcome::Revoked
521524
| buzz_db::relay_invite::ClaimOutcome::IssuerRestricted => {
522525
Err(api_error(StatusCode::FORBIDDEN, "invite_invalid"))

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -351,7 +351,7 @@ pub(super) mod postgres_tests {
351351
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
352352
assert_eq!(
353353
read_json(response).await["error"],
354-
"restriction lookup unavailable"
354+
crate::handlers::auth::OWNER_LINK_ERROR
355355
);
356356
let after: i64 = sqlx::query_scalar("SELECT count(*) FROM relay_invites")
357357
.fetch_one(state.db.pool())

0 commit comments

Comments
 (0)