Skip to content

Commit 792a9ce

Browse files
wpfleger96Duncan
andauthored
feat(relay): list and revoke invite links (#9680)
Stack: this PR → #9690 ## What this does Adds listing and revocation for v2 invite links, and makes every reader of an invite's expiry accept a missing value. - **`GET /api/invites?limit=&before=`** lists the community's v2 invites, newest first: id, creator, created/expiry/revoked times, uses and a computed `status` (`active`, `revoked`, `expired`, `exhausted`). Owner/admin only. The NIP-98 signature covers the full URL including the query. `limit` defaults to 50 (max 200). `next_before` is an opaque cursor holding the last row's `created_at` (microseconds) and id, so paging doesn't depend on that row still existing. - **`POST /api/invites/revoke`** takes exactly one of `{"id": "<uuid>"}` or `{"code": "v2...."}`. The code is hashed and looked up only inside the request's community. v1 and malformed codes get `400 invite_not_revocable`; an invite not in the community gets 404. Revoking twice returns the first `revoked_at`. Members who already joined stay. - **Authorization.** Mint, list and revoke share one HTTP admission helper (tenant bind → NIP-98 via NIP-FI → replay → membership/ban → NIP-OA owner link → role gate). Revoke's final decision is made in the write transaction, in the same order as mint: admission lock → actor's role row `FOR SHARE` → restriction check → invite row `FOR UPDATE`. Owners and admins can revoke any invite; any other member only one they created. A removed or restricted actor is refused. Mint now uses the same role-lock helper. - **Mint response** now includes `invite_id`. - **Nullable expiry readers.** Claim, list, the mint response and operator mint treat a missing `expires_at` as "never expires". The column is still `NOT NULL` here. - **Secrets.** No list/revoke response or access-log line contains a code or its hash; request errors are fixed strings that never echo input. Revoke logs only `invite_id`. A revoke the database refuses is logged as denied with its reason. ## Deploy order A follow-up PR adds links that never expire (`expires_at` nullable). **It depends on this PR being deployed everywhere first**, so every serving relay can read a missing expiry before one is written. ## Tests - DB (`relay_invite/manage_postgres_tests.rs`): revoke by code targets exactly one of two near-identical invites, idempotent revoke, community scoping, creator demoted to member can revoke theirs, a member who didn't create it is refused, a removed creator is refused, a restricted admin is refused, a demotion holding the role row or a restriction holding the admission lock makes revoke wait and then refuse with the row unchanged, a paused claim and a revoke serialize with the member kept, revoke is refused while the community is quiescing, paging survives deleting the cursor row, and a row with no expiry is listed, claimed, kept by the reaper and revocable (on a scratch database with `NOT NULL` dropped). - Relay (`invites/postgres_tests/manage_tests.rs`): list/revoke by id and code end to end, no code or hash in responses, member/non-member refusals, bad selectors, other-community lookups, query-string signature binding, malformed requests not echoing a code in responses or access logs, refused revokes logged as denied, and replayed list/revoke requests refused. --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
1 parent 81b4054 commit 792a9ce

9 files changed

Lines changed: 1582 additions & 113 deletions

File tree

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,10 @@ pub enum DbError {
5858
#[error("invitation issuer is not an owner or admin")]
5959
InviteIssuerNotAdmin,
6060

61+
/// The revoker is neither an owner or admin nor the invite's creator.
62+
#[error("invite revoker is not an owner, admin or the invite's creator")]
63+
InviteRevokeForbidden,
64+
6165
/// A verified invitation owner conflicts with the recorded owner.
6266
#[error("invitation owner does not match the recorded owner")]
6367
InviteOwnerMismatch,

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

Lines changed: 46 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ use crate::relay_members::{write_nip43_membership_snapshot, MembershipWrite};
3131
use crate::{CommunityId, Db};
3232

3333
mod claim_owner;
34+
mod manage;
3435
mod revocation;
3536

3637
/// Test-only pause point in the invite claim, keyed by community so
@@ -85,6 +86,11 @@ pub(crate) mod test_hook {
8586
}
8687
}
8788
pub use claim_owner::{claim_relay_membership_with_owner, MembershipClaimResult};
89+
use manage::lock_actor_role;
90+
pub use manage::{
91+
list_relay_invites, revoke_relay_invite, InviteSelector, InviteStatus, InviteSummary,
92+
RevokedInvite, MAX_INVITE_LIST_LIMIT,
93+
};
8894
pub(crate) use revocation::{revoke_banned_issuer_invites, revoke_restricted_agent_invites};
8995

9096
/// Outcome of a v2 invite claim. Expected invalid/expired/exhausted states are
@@ -147,8 +153,8 @@ pub struct MintedInvite {
147153
/// The full v2 code string (`v2.<base64url secret>`). Returned to the caller
148154
/// exactly once; the database stores only the SHA-256 hash.
149155
pub code: String,
150-
/// When the invite expires (UTC).
151-
pub expires_at: DateTime<Utc>,
156+
/// When the invite expires (UTC); `None` for an invite that never expires.
157+
pub expires_at: Option<DateTime<Utc>>,
152158
/// `None` means unlimited; `Some(n)` means at most `n` uses.
153159
pub max_uses: Option<i32>,
154160
/// Remaining uses at mint time (equals `max_uses` when bounded, `None`
@@ -247,18 +253,9 @@ async fn mint(
247253
)
248254
.await?;
249255
lock_admission(tx.conn(), community).await?;
250-
if require_admin {
251-
let role: Option<String> = sqlx::query_scalar(
252-
"SELECT role FROM relay_members \
253-
WHERE community_id = $1 AND pubkey = $2 FOR SHARE",
254-
)
255-
.bind(community.as_uuid())
256-
.bind(created_by)
257-
.fetch_optional(tx.conn())
258-
.await?;
259-
if !matches!(role.as_deref(), Some("owner" | "admin")) {
260-
return Err(crate::DbError::InviteIssuerNotAdmin);
261-
}
256+
if require_admin && !manage::is_admin(lock_actor_role(tx.conn(), community, created_by).await?)
257+
{
258+
return Err(crate::DbError::InviteIssuerNotAdmin);
262259
}
263260
if principal_restricted(tx.conn(), community, created_by).await? {
264261
return Err(crate::DbError::InviteRestricted);
@@ -282,7 +279,7 @@ async fn mint(
282279

283280
Ok(MintedInvite {
284281
code,
285-
expires_at,
282+
expires_at: Some(expires_at),
286283
max_uses,
287284
uses_remaining: max_uses,
288285
invite_id,
@@ -597,8 +594,9 @@ pub async fn claim_relay_invite_with_owner(
597594
let invite_id: uuid::Uuid = invite.try_get("id")?;
598595
let max_uses: Option<i32> = invite.try_get("max_uses")?;
599596
let use_count: i32 = invite.try_get("use_count")?;
600-
let expires_at: DateTime<Utc> = invite.try_get("expires_at")?;
601-
if expires_at <= Utc::now() {
597+
// `None` never expires; revocation and use limits still apply below.
598+
let expires_at: Option<DateTime<Utc>> = invite.try_get("expires_at")?;
599+
if expires_at.is_some_and(|at| at <= Utc::now()) {
602600
tx.rollback().await?;
603601
log_claim_outcome(
604602
community,
@@ -961,30 +959,12 @@ mod postgres_tests {
961959
}
962960
}
963961

964-
#[tokio::test]
965-
#[ignore = "requires Postgres"]
966-
async fn mint_after_quiescing_returns_typed_fence_without_persisting() {
967-
let scratch =
968-
ScratchDb::create(&crate::test_support::database_url(), "relay_invite_fence").await;
969-
let db = crate::Db::new(&crate::DbConfig {
970-
database_url: scratch.url().to_owned(),
971-
max_connections: 5,
972-
min_connections: 0,
973-
..crate::DbConfig::default()
974-
})
975-
.await
976-
.expect("connect invite deletion test DB");
977-
db.migrate().await.expect("migrate invite deletion test DB");
978-
let pool = db.pool.clone();
962+
/// Move `community` on `host` into deletion quiescing, where every
963+
/// community write is fenced.
964+
pub(super) async fn quiesce(db: &crate::Db, host: &str, community: CommunityId) {
979965
let store = db.deletion_store();
980-
let host = format!("relay-invite-fence-{}.example", Uuid::new_v4().simple());
981-
let community = db
982-
.ensure_configured_community(&host)
983-
.await
984-
.expect("create fenced invite community")
985-
.id;
986966
let request = store
987-
.submit(Some(&host), "owner", None, None)
967+
.submit(Some(host), "owner", None, None)
988968
.await
989969
.expect("submit deletion request");
990970
let empty_digest = hex::encode(sha2::Sha256::digest([]));
@@ -1031,6 +1011,30 @@ mod postgres_tests {
10311011
.begin_quiescing(&claim.lease)
10321012
.await
10331013
.expect("begin quiescing");
1014+
}
1015+
1016+
#[tokio::test]
1017+
#[ignore = "requires Postgres"]
1018+
async fn mint_after_quiescing_returns_typed_fence_without_persisting() {
1019+
let scratch =
1020+
ScratchDb::create(&crate::test_support::database_url(), "relay_invite_fence").await;
1021+
let db = crate::Db::new(&crate::DbConfig {
1022+
database_url: scratch.url().to_owned(),
1023+
max_connections: 5,
1024+
min_connections: 0,
1025+
..crate::DbConfig::default()
1026+
})
1027+
.await
1028+
.expect("connect invite deletion test DB");
1029+
db.migrate().await.expect("migrate invite deletion test DB");
1030+
let pool = db.pool.clone();
1031+
let host = format!("relay-invite-fence-{}.example", Uuid::new_v4().simple());
1032+
let community = db
1033+
.ensure_configured_community(&host)
1034+
.await
1035+
.expect("create fenced invite community")
1036+
.id;
1037+
quiesce(&db, &host, community).await;
10341038

10351039
let error = mint_relay_invite(&pool, community, &test_pubkey(), 3600, Some(1))
10361040
.await
@@ -1417,3 +1421,6 @@ mod owner_admission_postgres_tests;
14171421

14181422
#[cfg(test)]
14191423
mod writer_protocol_postgres_tests;
1424+
1425+
#[cfg(test)]
1426+
mod manage_postgres_tests;

0 commit comments

Comments
 (0)