diff --git a/crates/buzz-db/src/runtime/migration.rs b/crates/buzz-db/src/runtime/migration.rs index 560a1f031e2..b73c942a0a7 100644 --- a/crates/buzz-db/src/runtime/migration.rs +++ b/crates/buzz-db/src/runtime/migration.rs @@ -1036,7 +1036,12 @@ mod postgres_tests { let mut migrations: Vec<_> = MIGRATOR.iter().collect(); migrations.sort_by_key(|migration| migration.version); - assert_eq!(migrations.len(), 105); + assert_eq!(migrations.len(), 106); + assert_eq!(migrations[105].version, 106); + assert!(migrations[105] + .sql + .as_str() + .contains("ALTER TABLE relay_invites ALTER COLUMN expires_at DROP NOT NULL")); assert_eq!(migrations[104].version, 105); assert!(strip_sql_comments(migrations[104].sql.as_str()) .contains("ADD COLUMN finished BOOLEAN NOT NULL DEFAULT true;")); @@ -3487,6 +3492,7 @@ mod postgres_tests { "audit_log", "media_publications", "relay_members", + "relay_invites", "relay_admin_actions", "relay_admin_outbox", "relay_operator_audit", diff --git a/crates/buzz-db/src/store/admission_postgres_tests.rs b/crates/buzz-db/src/store/admission_postgres_tests.rs index f0ce61d78fb..63adc049546 100644 --- a/crates/buzz-db/src/store/admission_postgres_tests.rs +++ b/crates/buzz-db/src/store/admission_postgres_tests.rs @@ -188,7 +188,7 @@ async fn relay_invite_writers_require_application_admission() { &db.pool, *community, &"e".repeat(64), - 3600, + super::relay_invite::InviteExpiry::After(3600), Some(1), ) .await @@ -212,7 +212,7 @@ async fn relay_invite_writers_require_application_admission() { &db.pool, communities[0], &"e".repeat(64), - 3600, + super::relay_invite::InviteExpiry::After(3600), Some(1), ) .await diff --git a/crates/buzz-db/src/store/relay_invite.rs b/crates/buzz-db/src/store/relay_invite.rs index 7503a4158dd..e326482d4ba 100644 --- a/crates/buzz-db/src/store/relay_invite.rs +++ b/crates/buzz-db/src/store/relay_invite.rs @@ -85,8 +85,8 @@ pub(crate) mod test_hook { } } } +use crate::relay_members::{is_admin, lock_member_role}; pub use claim_owner::{claim_relay_membership_with_owner, MembershipClaimResult}; -use manage::lock_actor_role; pub use manage::{ list_relay_invites, revoke_relay_invite, InviteSelector, InviteStatus, InviteSummary, RevokedInvite, MAX_INVITE_LIST_LIMIT, @@ -164,11 +164,22 @@ pub struct MintedInvite { pub invite_id: uuid::Uuid, } -fn validate_mint_inputs(ttl_secs: u64, max_uses: Option) -> Result<()> { - if !(MIN_INVITE_TTL_SECS..=MAX_INVITE_TTL_SECS).contains(&ttl_secs) { - return Err(crate::error::DbError::InvalidData(format!( - "ttl_secs must be between {MIN_INVITE_TTL_SECS} and {MAX_INVITE_TTL_SECS}" - ))); +/// How long a minted invite stays claimable. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum InviteExpiry { + /// Expires this many seconds after minting, within the shared lifetime range. + After(u64), + /// Never expires; stored as a NULL `expires_at`. Revoke it to shut it off. + Never, +} + +fn validate_mint_inputs(expiry: InviteExpiry, max_uses: Option) -> Result<()> { + if let InviteExpiry::After(ttl_secs) = expiry { + if !(MIN_INVITE_TTL_SECS..=MAX_INVITE_TTL_SECS).contains(&ttl_secs) { + return Err(crate::error::DbError::InvalidData(format!( + "ttl_secs must be between {MIN_INVITE_TTL_SECS} and {MAX_INVITE_TTL_SECS}" + ))); + } } if let Some(max_uses) = max_uses { @@ -192,16 +203,16 @@ fn is_canonical_invite_pubkey(pubkey: &str) -> bool { /// Mint a v2 invite: generate a 32-byte random secret, hash it, persist the /// row, and return the plaintext code plus metadata. /// -/// `ttl_secs` must be in the shared invite lifetime range. +/// A finite `expiry` must be in the shared invite lifetime range. /// `max_uses` must be `None` (unlimited) or `Some(1..=10000)`. pub async fn mint_relay_invite( pool: &PgPool, community: CommunityId, created_by: &str, - ttl_secs: u64, + expiry: InviteExpiry, max_uses: Option, ) -> Result { - mint(pool, community, created_by, ttl_secs, max_uses, false).await + mint(pool, community, created_by, expiry, max_uses, false).await } /// Like [`mint_relay_invite`], but refuses with @@ -214,21 +225,21 @@ pub async fn mint_relay_invite_as_admin( pool: &PgPool, community: CommunityId, created_by: &str, - ttl_secs: u64, + expiry: InviteExpiry, max_uses: Option, ) -> Result { - mint(pool, community, created_by, ttl_secs, max_uses, true).await + mint(pool, community, created_by, expiry, max_uses, true).await } async fn mint( pool: &PgPool, community: CommunityId, created_by: &str, - ttl_secs: u64, + expiry: InviteExpiry, max_uses: Option, require_admin: bool, ) -> Result { - validate_mint_inputs(ttl_secs, max_uses)?; + validate_mint_inputs(expiry, max_uses)?; if !is_canonical_invite_pubkey(created_by) { return Err(crate::error::DbError::InvalidData( "invalid invitation issuer".into(), @@ -240,7 +251,10 @@ async fn mint( let code = encode_v2_code(&secret); let token_hash = hash_v2_code(&code); let now = Utc::now(); - let expires_at = now + chrono::Duration::seconds(ttl_secs as i64); + let expires_at = match expiry { + InviteExpiry::After(ttl_secs) => Some(now + chrono::Duration::seconds(ttl_secs as i64)), + InviteExpiry::Never => None, + }; // Mint a v2 opaque invite inside the same lifecycle gate as every other // community-scoped database write. The app-side guard is the community @@ -253,8 +267,7 @@ async fn mint( ) .await?; lock_admission(tx.conn(), community).await?; - if require_admin && !manage::is_admin(lock_actor_role(tx.conn(), community, created_by).await?) - { + if require_admin && !is_admin(lock_member_role(tx.conn(), community, created_by).await?) { return Err(crate::DbError::InviteIssuerNotAdmin); } if principal_restricted(tx.conn(), community, created_by).await? { @@ -279,7 +292,7 @@ async fn mint( Ok(MintedInvite { code, - expires_at: Some(expires_at), + expires_at, max_uses, uses_remaining: max_uses, invite_id, @@ -811,16 +824,16 @@ impl Db { /// once; only its SHA-256 hash is persisted. /// /// `max_uses` is `None` for unlimited or `Some(1..=10000)`. - /// `ttl_secs` must be in the shared invite lifetime range. + /// A finite `expiry` must be in the shared invite lifetime range. #[datastore_span(name = "mint_relay_invite", system = "postgresql")] pub async fn mint_relay_invite_as_admin( &self, community: CommunityId, created_by: &str, - ttl_secs: u64, + expiry: InviteExpiry, max_uses: Option, ) -> Result { - mint_relay_invite_as_admin(&self.pool, community, created_by, ttl_secs, max_uses).await + mint_relay_invite_as_admin(&self.pool, community, created_by, expiry, max_uses).await } /// Claim an invite and persist caller-verified ownership atomically. @@ -954,7 +967,8 @@ mod postgres_tests { (3600, Some(-1)), (3600, Some(MAX_INVITE_USES + 1)), ] { - let error = validate_mint_inputs(ttl, max_uses).expect_err("invalid mint contract"); + let error = validate_mint_inputs(InviteExpiry::After(ttl), max_uses) + .expect_err("invalid mint contract"); assert!(matches!(error, crate::DbError::InvalidData(_)), "{error:?}"); } } @@ -1036,9 +1050,15 @@ mod postgres_tests { .id; quiesce(&db, &host, community).await; - let error = mint_relay_invite(&pool, community, &test_pubkey(), 3600, Some(1)) - .await - .expect_err("quiescing must reject invite minting"); + let error = mint_relay_invite( + &pool, + community, + &test_pubkey(), + InviteExpiry::After(3600), + Some(1), + ) + .await + .expect_err("quiescing must reject invite minting"); assert!(matches!(error, crate::error::DbError::AccessDenied(_))); let invite_count: i64 = @@ -1057,9 +1077,15 @@ mod postgres_tests { let community = make_test_community(&pool).await; let first = test_pubkey(); let second = test_pubkey(); - let invite = mint_relay_invite(&pool, community, &test_pubkey(), 3600, Some(1)) - .await - .expect("mint bounded invite"); + let invite = mint_relay_invite( + &pool, + community, + &test_pubkey(), + InviteExpiry::After(3600), + Some(1), + ) + .await + .expect("mint bounded invite"); let hash = hash_v2_code(&invite.code); let keys = nostr::Keys::generate(); @@ -1128,9 +1154,15 @@ mod postgres_tests { let community = make_test_community(&pool).await; let first = test_pubkey(); let second = test_pubkey(); - let invite = mint_relay_invite(&pool, community, &test_pubkey(), 3600, Some(1)) - .await - .expect("mint bounded invite"); + let invite = mint_relay_invite( + &pool, + community, + &test_pubkey(), + InviteExpiry::After(3600), + Some(1), + ) + .await + .expect("mint bounded invite"); let hash = hash_v2_code(&invite.code); let keys = nostr::Keys::generate(); @@ -1177,9 +1209,15 @@ mod postgres_tests { let pool = setup_pool().await; let community_a = make_test_community(&pool).await; let community_b = make_test_community(&pool).await; - let invite = mint_relay_invite(&pool, community_a, &test_pubkey(), 3600, Some(2)) - .await - .expect("mint invite"); + let invite = mint_relay_invite( + &pool, + community_a, + &test_pubkey(), + InviteExpiry::After(3600), + Some(2), + ) + .await + .expect("mint invite"); let hash = hash_v2_code(&invite.code); assert_eq!( @@ -1230,12 +1268,24 @@ mod postgres_tests { async fn retention_sweep_deletes_only_invites_older_than_cutoff() { let pool = setup_pool().await; let community = make_test_community(&pool).await; - let old = mint_relay_invite(&pool, community, &test_pubkey(), 3600, Some(1)) - .await - .expect("mint old invite"); - let recent = mint_relay_invite(&pool, community, &test_pubkey(), 3600, Some(1)) - .await - .expect("mint recent invite"); + let old = mint_relay_invite( + &pool, + community, + &test_pubkey(), + InviteExpiry::After(3600), + Some(1), + ) + .await + .expect("mint old invite"); + let recent = mint_relay_invite( + &pool, + community, + &test_pubkey(), + InviteExpiry::After(3600), + Some(1), + ) + .await + .expect("mint recent invite"); let cutoff = Utc::now() - chrono::Duration::days(30); sqlx::query("UPDATE relay_invites SET expires_at = $1 WHERE community_id = $2 AND id = $3") @@ -1263,6 +1313,33 @@ mod postgres_tests { delete_test_community(&pool, community).await; } + #[tokio::test] + #[ignore = "requires Postgres"] + async fn retention_sweep_never_deletes_a_permanent_invite() { + let pool = setup_pool().await; + let community = make_test_community(&pool).await; + let permanent = + mint_relay_invite(&pool, community, &test_pubkey(), InviteExpiry::Never, None) + .await + .expect("mint permanent invite"); + assert_eq!(permanent.expires_at, None); + + for cutoff in [Utc::now(), Utc::now() + chrono::Duration::days(365 * 100)] { + reap_expired_relay_invites(&pool, cutoff) + .await + .expect("reap expired invites"); + } + let remaining: Vec = + sqlx::query_scalar("SELECT id FROM relay_invites WHERE community_id = $1") + .bind(community.as_uuid()) + .fetch_all(&pool) + .await + .expect("read remaining invites"); + assert_eq!(remaining, vec![permanent.invite_id]); + + delete_test_community(&pool, community).await; + } + #[tokio::test] #[ignore = "requires Postgres"] async fn retention_sweep_skips_quiescing_tenant_while_active_bystanders_progress() { @@ -1335,9 +1412,15 @@ mod postgres_tests { async fn unlimited_invites_count_each_new_member() { let pool = setup_pool().await; let community = make_test_community(&pool).await; - let invite = mint_relay_invite(&pool, community, &test_pubkey(), 3600, None) - .await - .expect("mint unlimited invite"); + let invite = mint_relay_invite( + &pool, + community, + &test_pubkey(), + InviteExpiry::After(3600), + None, + ) + .await + .expect("mint unlimited invite"); let hash = hash_v2_code(&invite.code); for (expected_count, pubkey) in [(1, test_pubkey()), (2, test_pubkey())] { @@ -1369,9 +1452,15 @@ mod postgres_tests { let pool = setup_pool().await; let community = make_test_community(&pool).await; let pubkey = test_pubkey(); - let invite = mint_relay_invite(&pool, community, &test_pubkey(), 3600, Some(1)) - .await - .expect("mint bounded invite"); + let invite = mint_relay_invite( + &pool, + community, + &test_pubkey(), + InviteExpiry::After(3600), + Some(1), + ) + .await + .expect("mint bounded invite"); let hash = hash_v2_code(&invite.code); let error = claim_relay_invite( diff --git a/crates/buzz-db/src/store/relay_invite/manage.rs b/crates/buzz-db/src/store/relay_invite/manage.rs index 8f081f3a7f9..7677a4a3133 100644 --- a/crates/buzz-db/src/store/relay_invite/manage.rs +++ b/crates/buzz-db/src/store/relay_invite/manage.rs @@ -3,8 +3,9 @@ //! Listing never returns a code or its hash. Revocation runs the same //! transaction gate as an owner/admin mint: the admission lock, then the //! actor's role row `FOR SHARE`, then the restriction check, all before the -//! invite row is locked. Owners and admins may revoke any invite; any other -//! member only one they created. +//! invite row is locked. An unknown invite is answered before the admission +//! lock, so it never queues behind claims. Owners and admins may revoke any +//! invite; any other member only one they created. use buzz_datastore_tracing::datastore_span; use chrono::{DateTime, Utc}; use sqlx::{PgPool, Row as _}; @@ -12,6 +13,7 @@ use uuid::Uuid; use super::{lock_admission, principal_restricted}; use crate::error::Result; +use crate::relay_members::{is_admin, lock_member_role}; use crate::{CommunityId, Db}; /// Largest page [`list_relay_invites`] returns. @@ -94,28 +96,6 @@ pub struct RevokedInvite { pub revoked_at: DateTime, } -/// The actor's role, read `FOR SHARE` so a concurrent demotion, removal or -/// ownership transfer waits for the caller's commit or lands first. Call -/// after [`lock_admission`]. -pub(super) async fn lock_actor_role( - conn: &mut sqlx::PgConnection, - community: CommunityId, - actor: &str, -) -> Result> { - Ok(sqlx::query_scalar( - "SELECT role FROM relay_members \ - WHERE community_id = $1 AND pubkey = $2 FOR SHARE", - ) - .bind(community.as_uuid()) - .bind(actor) - .fetch_optional(conn) - .await?) -} - -pub(super) fn is_admin(role: Option) -> bool { - matches!(role.as_deref(), Some("owner" | "admin")) -} - /// List `community`'s v2 invites, newest first. `before` is the /// `(created_at, id)` of the last invite on the previous page; it need not /// still exist. `limit` is clamped to `1..=MAX_INVITE_LIST_LIMIT`. @@ -154,6 +134,27 @@ pub async fn list_relay_invites( .collect() } +async fn invite_exists( + conn: &mut sqlx::PgConnection, + community: CommunityId, + selector: InviteSelector<'_>, +) -> Result { + let query = match selector { + InviteSelector::Id(id) => sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM relay_invites WHERE community_id = $1 AND id = $2)", + ) + .bind(community.as_uuid()) + .bind(id), + InviteSelector::TokenHash(hash) => sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM relay_invites \ + WHERE community_id = $1 AND token_hash = $2)", + ) + .bind(community.as_uuid()) + .bind(hash.as_slice()), + }; + Ok(query.fetch_one(conn).await?) +} + /// Revoke one invite in `community` on behalf of `actor`. /// /// `Ok(None)` when no invite in `community` matches. Revoking a revoked @@ -174,8 +175,21 @@ pub async fn revoke_relay_invite( crate::observability::WriterOperation::Authorization, ) .await?; + // An unknown selector is answered without queueing behind claims on the + // admission lock. These unlocked reads only refuse; the locked path + // below re-reads everything it authorizes a write on. + if !invite_exists(tx.conn(), community, selector).await? { + if !crate::relay_members::is_relay_member_on(tx.conn(), community, actor).await? { + return Err(crate::DbError::InviteRevokeForbidden); + } + if principal_restricted(tx.conn(), community, actor).await? { + return Err(crate::DbError::InviteRestricted); + } + tx.rollback().await?; + return Ok(None); + } lock_admission(tx.conn(), community).await?; - let role = lock_actor_role(tx.conn(), community, actor).await?; + let role = lock_member_role(tx.conn(), community, actor).await?; if role.is_none() { return Err(crate::DbError::InviteRevokeForbidden); } diff --git a/crates/buzz-db/src/store/relay_invite/manage_postgres_tests.rs b/crates/buzz-db/src/store/relay_invite/manage_postgres_tests.rs index bfb19942645..0cb2ef5de04 100644 --- a/crates/buzz-db/src/store/relay_invite/manage_postgres_tests.rs +++ b/crates/buzz-db/src/store/relay_invite/manage_postgres_tests.rs @@ -35,10 +35,10 @@ async fn revoke_by_code_targets_exactly_that_invite_and_is_idempotent() { let (pool, community, admin, claimant) = fixture().await; add_member(&pool, community, &admin, "admin").await; // Two invites that differ only in their secret. - let first = mint_relay_invite(&pool, community, &admin, 3600, Some(5)) + let first = mint_relay_invite(&pool, community, &admin, InviteExpiry::After(3600), Some(5)) .await .unwrap(); - let second = mint_relay_invite(&pool, community, &admin, 3600, Some(5)) + let second = mint_relay_invite(&pool, community, &admin, InviteExpiry::After(3600), Some(5)) .await .unwrap(); @@ -109,7 +109,7 @@ async fn revoke_is_scoped_to_the_community() { let (_, other, other_admin, _) = fixture().await; add_member(&pool, community, &admin, "admin").await; add_member(&pool, other, &other_admin, "admin").await; - let invite = mint_relay_invite(&pool, community, &admin, 3600, None) + let invite = mint_relay_invite(&pool, community, &admin, InviteExpiry::After(3600), None) .await .unwrap(); let hash = hash_v2_code(&invite.code); @@ -150,10 +150,10 @@ async fn creator_or_admin_may_revoke_and_other_members_may_not() { add_member(&pool, community, &creator, "admin").await; add_member(&pool, community, &other_member, "member").await; add_member(&pool, community, &admin, "admin").await; - let mine = mint_relay_invite(&pool, community, &creator, 3600, None) + let mine = mint_relay_invite(&pool, community, &creator, InviteExpiry::After(3600), None) .await .unwrap(); - let also_mine = mint_relay_invite(&pool, community, &creator, 3600, None) + let also_mine = mint_relay_invite(&pool, community, &creator, InviteExpiry::After(3600), None) .await .unwrap(); @@ -237,9 +237,15 @@ async fn restricted_admin_cannot_revoke() { // Another admin's invite, so only the actor's restriction can refuse. let other_admin = hex::encode([5; 32]); add_member(&pool, community, &other_admin, "admin").await; - let other = mint_relay_invite(&pool, community, &other_admin, 3600, None) - .await - .unwrap(); + let other = mint_relay_invite( + &pool, + community, + &other_admin, + InviteExpiry::After(3600), + None, + ) + .await + .unwrap(); assert!(matches!( revoke( &pool, @@ -285,9 +291,15 @@ async fn demotion_that_wins_the_role_row_refuses_the_revoke() { add_member(&pool, community, &admin, "admin").await; add_member(&pool, community, &other_admin, "admin").await; // Minted by someone else, so a demoted actor loses the right to revoke it. - let invite = mint_relay_invite(&pool, community, &other_admin, 3600, None) - .await - .unwrap(); + let invite = mint_relay_invite( + &pool, + community, + &other_admin, + InviteExpiry::After(3600), + None, + ) + .await + .unwrap(); let mut demotion = pool.begin().await.unwrap(); sqlx::query("UPDATE relay_members SET role = 'member' WHERE community_id = $1 AND pubkey = $2") @@ -313,9 +325,15 @@ async fn restriction_that_wins_admission_refuses_the_revoke() { let (pool, community, admin, other_admin) = fixture().await; add_member(&pool, community, &admin, "admin").await; add_member(&pool, community, &other_admin, "admin").await; - let invite = mint_relay_invite(&pool, community, &other_admin, 3600, None) - .await - .unwrap(); + let invite = mint_relay_invite( + &pool, + community, + &other_admin, + InviteExpiry::After(3600), + None, + ) + .await + .unwrap(); // A restriction writer holds the admission lock and bans the actor. let mut restriction = pool.begin().await.unwrap(); @@ -340,12 +358,97 @@ async fn restriction_that_wins_admission_refuses_the_revoke() { assert_eq!(revoked_at(&pool, community, invite.invite_id).await, None); } +#[tokio::test] +#[ignore = "requires Postgres"] +async fn unknown_invite_is_answered_without_waiting_for_admission() { + let (pool, community, admin, _) = fixture().await; + let (_, other, other_admin, _) = fixture().await; + add_member(&pool, community, &admin, "admin").await; + add_member(&pool, other, &other_admin, "admin").await; + let known = mint_relay_invite(&pool, community, &admin, InviteExpiry::After(3600), None) + .await + .unwrap(); + let foreign = mint_relay_invite(&pool, other, &other_admin, InviteExpiry::After(3600), None) + .await + .unwrap(); + let unknown_hash = [7u8; 32]; + let foreign_hash = hash_v2_code(&foreign.code); + + // A claim-like holder of the admission lock. + let mut holder = pool.begin().await.unwrap(); + lock_admission(&mut holder, community).await.unwrap(); + for selector in [ + InviteSelector::Id(Uuid::new_v4()), + InviteSelector::TokenHash(&unknown_hash), + InviteSelector::Id(foreign.invite_id), + InviteSelector::TokenHash(&foreign_hash), + ] { + let answer = tokio::time::timeout( + std::time::Duration::from_secs(5), + revoke(&pool, community, &admin, selector), + ) + .await + .expect("an unknown invite does not wait for admission"); + assert_eq!(answer.unwrap(), None); + } + + // A known invite still queues behind the holder. + let (revoking, name) = queued_revoke(community, &admin, known.invite_id).await; + wait_for_lock(&pool, &name, "advisory", &revoking).await; + holder.commit().await.unwrap(); + assert!(revoking.await.unwrap().unwrap().is_some()); + assert_eq!(revoked_at(&pool, other, foreign.invite_id).await, None); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn unknown_invite_keeps_the_refusals_for_nonmembers_and_restricted_actors() { + let (pool, community, admin, outsider) = fixture().await; + add_member(&pool, community, &admin, "admin").await; + let unknown = InviteSelector::Id(Uuid::new_v4()); + assert!(matches!( + revoke(&pool, community, &outsider, unknown).await, + Err(crate::DbError::InviteRevokeForbidden) + )); + ban_member(&pool, community, &[1; 32], &[3; 32], None, None) + .await + .unwrap(); + assert!(matches!( + revoke(&pool, community, &admin, unknown).await, + Err(crate::DbError::InviteRestricted) + )); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn invite_deleted_after_the_existence_check_is_not_found() { + let (pool, community, admin, _) = fixture().await; + add_member(&pool, community, &admin, "admin").await; + let invite = mint_relay_invite(&pool, community, &admin, InviteExpiry::After(3600), None) + .await + .unwrap(); + + // The revoke sees the invite, then waits for admission while it is deleted. + let mut holder = pool.begin().await.unwrap(); + lock_admission(&mut holder, community).await.unwrap(); + let (revoking, name) = queued_revoke(community, &admin, invite.invite_id).await; + wait_for_lock(&pool, &name, "advisory", &revoking).await; + sqlx::query("DELETE FROM relay_invites WHERE community_id = $1 AND id = $2") + .bind(community.as_uuid()) + .bind(invite.invite_id) + .execute(&mut *holder) + .await + .unwrap(); + holder.commit().await.unwrap(); + assert_eq!(revoking.await.unwrap().unwrap(), None); +} + #[tokio::test] #[ignore = "requires Postgres"] async fn claim_and_revoke_serialize_and_the_claim_keeps_its_member() { let (pool, community, admin, claimant) = fixture().await; add_member(&pool, community, &admin, "admin").await; - let invite = mint_relay_invite(&pool, community, &admin, 3600, Some(2)) + let invite = mint_relay_invite(&pool, community, &admin, InviteExpiry::After(3600), Some(2)) .await .unwrap(); let hash = hash_v2_code(&invite.code); @@ -402,7 +505,7 @@ async fn revoke_is_refused_while_the_community_is_quiescing() { let community = db.ensure_configured_community(&host).await.unwrap().id; let admin = hex::encode([6; 32]); add_member(&pool, community, &admin, "admin").await; - let invite = mint_relay_invite(&pool, community, &admin, 3600, None) + let invite = mint_relay_invite(&pool, community, &admin, InviteExpiry::After(3600), None) .await .unwrap(); super::postgres_tests::quiesce(&db, &host, community).await; @@ -417,6 +520,11 @@ async fn revoke_is_refused_while_the_community_is_quiescing() { .await, Err(crate::DbError::AccessDenied(_)) )); + // The lifecycle fence also wins over the unknown-invite answer. + assert!(matches!( + revoke(&pool, community, &admin, InviteSelector::Id(Uuid::new_v4())).await, + Err(crate::DbError::AccessDenied(_)) + )); assert_eq!(revoked_at(&pool, community, invite.invite_id).await, None); } @@ -427,7 +535,7 @@ async fn list_pages_newest_first_even_when_the_cursor_row_is_gone() { let mut minted = Vec::new(); for _ in 0..3 { minted.push( - mint_relay_invite(&pool, community, &admin, 3600, None) + mint_relay_invite(&pool, community, &admin, InviteExpiry::After(3600), None) .await .unwrap() .invite_id, @@ -472,7 +580,7 @@ async fn readers_accept_an_invite_without_expiry() { .execute(&pool) .await .unwrap(); - let invite = mint_relay_invite(&pool, community, &admin, 3600, None) + let invite = mint_relay_invite(&pool, community, &admin, InviteExpiry::After(3600), None) .await .unwrap(); sqlx::query("UPDATE relay_invites SET expires_at = NULL WHERE community_id = $1 AND id = $2") diff --git a/crates/buzz-db/src/store/relay_invite/owner_admission_postgres_tests.rs b/crates/buzz-db/src/store/relay_invite/owner_admission_postgres_tests.rs index ead36ec4b0a..1837e1fbdd3 100644 --- a/crates/buzz-db/src/store/relay_invite/owner_admission_postgres_tests.rs +++ b/crates/buzz-db/src/store/relay_invite/owner_admission_postgres_tests.rs @@ -12,7 +12,7 @@ async fn failed_policy_evidence_rolls_back_verified_owner_and_membership() { &pool, community, &postgres_tests::test_pubkey(), - 3600, + InviteExpiry::After(3600), Some(1), ) .await @@ -67,7 +67,7 @@ async fn successful_claim_reports_only_committed_user_creation() { &pool, community, &postgres_tests::test_pubkey(), - 3600, + InviteExpiry::After(3600), Some(1), ) .await @@ -140,9 +140,15 @@ async fn issuer_timeout_denies_temporarily_without_revoking_invite() { let community = postgres_tests::make_test_community(&pool).await; let issuer = postgres_tests::test_pubkey(); let claimant = postgres_tests::test_pubkey(); - let invite = mint_relay_invite(&pool, community, &issuer, 3600, Some(1)) - .await - .unwrap(); + let invite = mint_relay_invite( + &pool, + community, + &issuer, + InviteExpiry::After(3600), + Some(1), + ) + .await + .unwrap(); sqlx::query("INSERT INTO community_bans (community_id,pubkey,muted_until,actor_pubkey) VALUES ($1,$2,clock_timestamp()+interval '1 hour',$2)") .bind(community.as_uuid()).bind(hex::decode(&issuer).unwrap()).execute(&pool).await.unwrap(); assert_eq!( diff --git a/crates/buzz-db/src/store/relay_invite/revocation_postgres_tests.rs b/crates/buzz-db/src/store/relay_invite/revocation_postgres_tests.rs index 54da3cf1749..a8020e0978b 100644 --- a/crates/buzz-db/src/store/relay_invite/revocation_postgres_tests.rs +++ b/crates/buzz-db/src/store/relay_invite/revocation_postgres_tests.rs @@ -52,17 +52,17 @@ async fn ban_permanently_revokes_issued_invites_but_not_another_tenant() { .await .unwrap(); let other = CommunityId::from_uuid(other_id); - let invite = mint_relay_invite(&pool, community, &issuer, 3600, None) + let invite = mint_relay_invite(&pool, community, &issuer, InviteExpiry::After(3600), None) .await .unwrap(); - let unaffected = mint_relay_invite(&pool, other, &issuer, 3600, None) + let unaffected = mint_relay_invite(&pool, other, &issuer, InviteExpiry::After(3600), None) .await .unwrap(); ban_member(&pool, community, &[1; 32], &[3; 32], None, None) .await .unwrap(); assert!(matches!( - mint_relay_invite(&pool, community, &issuer, 3600, None).await, + mint_relay_invite(&pool, community, &issuer, InviteExpiry::After(3600), None).await, Err(crate::DbError::InviteRestricted) )); assert!(unban_member(&pool, community, &[1; 32], &[3; 32]) @@ -92,7 +92,7 @@ async fn ban_permanently_revokes_issued_invites_but_not_another_tenant() { .unwrap(), ClaimOutcome::Joined { .. } )); - let renewed = mint_relay_invite(&pool, community, &issuer, 3600, None) + let renewed = mint_relay_invite(&pool, community, &issuer, InviteExpiry::After(3600), None) .await .unwrap(); assert!(matches!( @@ -113,9 +113,15 @@ async fn ban_permanently_revokes_issued_invites_but_not_another_tenant() { #[ignore = "requires Postgres"] async fn nonmember_restrictions_cover_both_claim_formats_and_owner() { let (pool, community, issuer, claimant) = fixture().await; - let invite = mint_relay_invite(&pool, community, &issuer, 3600, Some(1)) - .await - .unwrap(); + let invite = mint_relay_invite( + &pool, + community, + &issuer, + InviteExpiry::After(3600), + Some(1), + ) + .await + .unwrap(); ban_member(&pool, community, &[2; 32], &[3; 32], None, None) .await .unwrap(); @@ -189,7 +195,7 @@ async fn issuer_agent_revocation_survives_owner_unban() { crate::user::set_agent_owner(&pool, community, &[1; 32], &[4; 32]) .await .unwrap(); - let invite = mint_relay_invite(&pool, community, &issuer, 3600, None) + let invite = mint_relay_invite(&pool, community, &issuer, InviteExpiry::After(3600), None) .await .unwrap(); ban_member(&pool, community, &[4; 32], &[3; 32], None, None) @@ -255,7 +261,14 @@ async fn stalled_production_mint_ignores_lifted_history_and_later_audit_touches( let (mint_pool, mint_name) = named_pool().await; let mint_issuer = issuer.clone(); let mint = tokio::spawn(async move { - mint_relay_invite(&mint_pool, community, &mint_issuer, 3600, None).await + mint_relay_invite( + &mint_pool, + community, + &mint_issuer, + InviteExpiry::After(3600), + None, + ) + .await }); wait_for_lock(&pool, &mint_name, "advisory", &mint).await; @@ -346,7 +359,7 @@ async fn stalled_production_mint_ignores_lifted_history_and_later_audit_touches( #[ignore = "requires Postgres"] async fn active_ban_lazily_revokes_new_protocol_rows() { let (pool, community, issuer, claimant) = fixture().await; - let invite = mint_relay_invite(&pool, community, &issuer, 3600, None) + let invite = mint_relay_invite(&pool, community, &issuer, InviteExpiry::After(3600), None) .await .unwrap(); let legacy_admission: bool = sqlx::query_scalar( @@ -510,9 +523,15 @@ async fn queued_claim( async fn claimant_ban_and_timeout_commit_before_queued_claim_without_consuming_a_use() { for timeout in [false, true] { let (pool, community, issuer, claimant) = fixture().await; - let invite = mint_relay_invite(&pool, community, &issuer, 3600, Some(1)) - .await - .unwrap(); + let invite = mint_relay_invite( + &pool, + community, + &issuer, + InviteExpiry::After(3600), + Some(1), + ) + .await + .unwrap(); // Hold the existing restriction row so the production writer stops only // after acquiring admission. The claim must queue behind that writer. ban_member(&pool, community, &[2; 32], &[3; 32], None, None) @@ -569,7 +588,7 @@ async fn claimant_ban_and_timeout_commit_before_queued_claim_without_consuming_a #[ignore = "requires Postgres"] async fn owner_materialization_commits_before_queued_agent_claim() { let (pool, community, issuer, agent) = fixture().await; - let invite = mint_relay_invite(&pool, community, &issuer, 3600, None) + let invite = mint_relay_invite(&pool, community, &issuer, InviteExpiry::After(3600), None) .await .unwrap(); sqlx::query("INSERT INTO users(community_id,pubkey) VALUES($1,$2),($1,$3)") @@ -604,9 +623,15 @@ async fn owner_materialization_commits_before_queued_agent_claim() { #[ignore = "requires Postgres"] async fn admission_first_then_ban_preserves_the_committed_use_and_denies_retries() { let (pool, community, issuer, claimant) = fixture().await; - let invite = mint_relay_invite(&pool, community, &issuer, 3600, Some(2)) - .await - .unwrap(); + let invite = mint_relay_invite( + &pool, + community, + &issuer, + InviteExpiry::After(3600), + Some(2), + ) + .await + .unwrap(); assert!(matches!( claim_relay_invite_outcome( &pool, diff --git a/crates/buzz-db/src/store/relay_invite/upgrade_postgres_tests.rs b/crates/buzz-db/src/store/relay_invite/upgrade_postgres_tests.rs index ae33ae0ab2d..4db98cefe95 100644 --- a/crates/buzz-db/src/store/relay_invite/upgrade_postgres_tests.rs +++ b/crates/buzz-db/src/store/relay_invite/upgrade_postgres_tests.rs @@ -415,6 +415,20 @@ async fn assert_admission_column(pool: &PgPool) { revoked, Some(("timestamp with time zone".into(), "YES".into(), None)) ); + let expires: Option<(String, String, Option)> = sqlx::query_as( + "SELECT data_type, is_nullable, column_default \ + FROM information_schema.columns \ + WHERE table_schema = 'public' AND table_name = 'relay_invites' \ + AND column_name = 'expires_at'", + ) + .fetch_optional(pool) + .await + .unwrap(); + assert_eq!( + expires, + Some(("timestamp with time zone".into(), "YES".into(), None)), + "a NULL expires_at is a never-expiring invite" + ); } async fn apply_pgschema_to_existing_database(pool: &PgPool) { @@ -686,3 +700,116 @@ async fn migration_schema_desired_pgschema_reconcile_matches_populated_upgrade() "pgschema preserves the legacy default for populated rows" ); } + +/// Version of `0106_relay_invites_optional_expiry.sql`. +const OPTIONAL_EXPIRY_MIGRATION: i64 = 106; + +async fn invite_rows( + pool: &PgPool, +) -> Vec<( + Uuid, + Option>, + Option>, + i32, + Option, +)> { + sqlx::query_as( + "SELECT id, expires_at, revoked_at, use_count, max_uses \ + FROM relay_invites ORDER BY id", + ) + .fetch_all(pool) + .await + .unwrap() +} + +async fn claim_outcome(pool: &PgPool, community: CommunityId, code: &str) -> ClaimOutcome { + claim_relay_invite( + pool, + community, + &hash_v2_code(code), + &hex::encode(rand::random::<[u8; 32]>()), + None, + &nostr::Keys::generate(), + ) + .await + .unwrap() + .outcome +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn migration_schema_optional_expiry_keeps_populated_invites_and_admits_permanent_ones() { + let (pool, _scratch) = crate::test_support::ScratchDb::migrated_through( + &crate::test_support::database_url(), + "invite_optional_expiry", + OPTIONAL_EXPIRY_MIGRATION - 1, + ) + .await; + let community = Uuid::new_v4(); + sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") + .bind(community) + .bind(format!("optional-expiry-{community}.example")) + .execute(&pool) + .await + .unwrap(); + let community = CommunityId::from_uuid(community); + let issuer = hex::encode([1u8; 32]); + let mint = |max_uses| { + mint_relay_invite( + &pool, + community, + &issuer, + InviteExpiry::After(3600), + max_uses, + ) + }; + let finite = mint(Some(5)).await.unwrap(); + let revoked = mint(None).await.unwrap(); + let exhausted = mint(Some(1)).await.unwrap(); + sqlx::query("UPDATE relay_invites SET revoked_at = now() WHERE id = $1") + .bind(revoked.invite_id) + .execute(&pool) + .await + .unwrap(); + assert!(matches!( + claim_outcome(&pool, community, &exhausted.code).await, + ClaimOutcome::Joined { .. } + )); + let before = invite_rows(&pool).await; + + crate::migration::run_migrations(&pool).await.unwrap(); + assert_admission_column(&pool).await; + assert_eq!( + invite_rows(&pool).await, + before, + "the migration rewrites no rows" + ); + + assert!(matches!( + claim_outcome(&pool, community, &finite.code).await, + ClaimOutcome::Joined { .. } + )); + assert_eq!( + claim_outcome(&pool, community, &revoked.code).await, + ClaimOutcome::Revoked + ); + assert_eq!( + claim_outcome(&pool, community, &exhausted.code).await, + ClaimOutcome::Exhausted + ); + + let permanent = mint_relay_invite(&pool, community, &issuer, InviteExpiry::Never, None) + .await + .unwrap(); + let stored: Option> = + sqlx::query_scalar("SELECT expires_at FROM relay_invites WHERE id = $1") + .bind(permanent.invite_id) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(stored, None); + assert!(matches!( + claim_outcome(&pool, community, &permanent.code).await, + ClaimOutcome::Joined { .. } + )); +} diff --git a/crates/buzz-db/src/store/relay_invite/writer_protocol_postgres_tests.rs b/crates/buzz-db/src/store/relay_invite/writer_protocol_postgres_tests.rs index 7157267ec92..bb64282ad42 100644 --- a/crates/buzz-db/src/store/relay_invite/writer_protocol_postgres_tests.rs +++ b/crates/buzz-db/src/store/relay_invite/writer_protocol_postgres_tests.rs @@ -105,9 +105,15 @@ async fn linking_banned_owner_revokes_agent_invites_but_timeout_does_not() { .await .unwrap(); } - let invite = mint_relay_invite(&pool, community, &issuer, 3600, Some(1)) - .await - .unwrap(); + let invite = mint_relay_invite( + &pool, + community, + &issuer, + InviteExpiry::After(3600), + Some(1), + ) + .await + .unwrap(); if banned { crate::moderation::ban_member(&pool, community, &[4; 32], &[3; 32], None, None) .await @@ -189,7 +195,7 @@ async fn linking_banned_owner_revokes_agent_invites_but_timeout_does_not() { async fn marker_writers_serialize_before_rows_and_commit_revocation_with_marker() { for timeout in [false, true] { let (pool, community, issuer, _) = fixture().await; - let invite = mint_relay_invite(&pool, community, &issuer, 3600, None) + let invite = mint_relay_invite(&pool, community, &issuer, InviteExpiry::After(3600), None) .await .unwrap(); for key in [[1; 32], [4; 32]] { @@ -200,9 +206,15 @@ async fn marker_writers_serialize_before_rows_and_commit_revocation_with_marker( crate::user::set_agent_owner(&pool, community, &[4; 32], &[1; 32]) .await .unwrap(); - let agent_invite = mint_relay_invite(&pool, community, &hex::encode([4; 32]), 3600, None) - .await - .unwrap(); + let agent_invite = mint_relay_invite( + &pool, + community, + &hex::encode([4; 32]), + InviteExpiry::After(3600), + None, + ) + .await + .unwrap(); if timeout { // A timeout must also repair revocation for an existing active ban, // rather than revoking invites for timeout-only principals. diff --git a/crates/buzz-db/src/store/relay_members.rs b/crates/buzz-db/src/store/relay_members.rs index 87f1be59a1b..99f1f52e91b 100644 --- a/crates/buzz-db/src/store/relay_members.rs +++ b/crates/buzz-db/src/store/relay_members.rs @@ -53,6 +53,30 @@ pub(crate) async fn is_relay_member_on( Ok(row.is_some()) } +/// `pubkey`'s role in `community`, read `FOR SHARE` on `conn` so a +/// concurrent demotion, removal or ownership transfer either lands first or +/// waits for the caller's commit. Callers take their community and admission +/// locks first; this takes no other lock. +pub(crate) async fn lock_member_role( + conn: &mut sqlx::PgConnection, + community: CommunityId, + pubkey: &str, +) -> Result> { + Ok(sqlx::query_scalar( + "SELECT role FROM relay_members \ + WHERE community_id = $1 AND pubkey = $2 FOR SHARE", + ) + .bind(community.as_uuid()) + .bind(pubkey) + .fetch_optional(conn) + .await?) +} + +/// Whether a role from [`lock_member_role`] is owner or admin. +pub(crate) fn is_admin(role: Option) -> bool { + matches!(role.as_deref(), Some("owner" | "admin")) +} + /// Returns `true` if any member of `community` holds the `admin` or `owner` /// role. Open relays don't *enforce* the roster, but startup /// (`bootstrap_owner`) and operator provisioning still populate it — this is @@ -3267,9 +3291,15 @@ mod postgres_tests { let _ = claim_relay_membership(&pool, community, &member, "member", Some(&first), &keys) .await .expect("add member"); - let invite = crate::relay_invite::mint_relay_invite(&pool, community, &owner, 3600, None) - .await - .expect("mint invite"); + let invite = crate::relay_invite::mint_relay_invite( + &pool, + community, + &owner, + crate::relay_invite::InviteExpiry::After(3600), + None, + ) + .await + .expect("mint invite"); let hash = buzz_core::invite::hash_v2_code(&invite.code); let mut removal = crate::begin_community_write_transaction( @@ -3338,9 +3368,15 @@ mod postgres_tests { let (community, owner) = owned_community(&pool).await; let member = test_pubkey(); let keys = nostr::Keys::generate(); - let invite = crate::relay_invite::mint_relay_invite(&pool, community, &owner, 3600, None) - .await - .expect("mint invite"); + let invite = crate::relay_invite::mint_relay_invite( + &pool, + community, + &owner, + crate::relay_invite::InviteExpiry::After(3600), + None, + ) + .await + .expect("mint invite"); let hash = buzz_core::invite::hash_v2_code(&invite.code); let uses = |pool: PgPool| async move { sqlx::query_scalar::<_, i32>( diff --git a/crates/buzz-relay/src/api/invites.rs b/crates/buzz-relay/src/api/invites.rs index 23f285a514b..cf3e9581798 100644 --- a/crates/buzz-relay/src/api/invites.rs +++ b/crates/buzz-relay/src/api/invites.rs @@ -41,6 +41,7 @@ use buzz_core::invite::{ use crate::invite_token; use crate::state::AppState; +use buzz_db::relay_invite::InviteExpiry; use super::{api_error, bridge, internal_error}; mod claim_auth; @@ -71,20 +72,35 @@ pub struct MintInviteRequest { /// must be an integer from 1 through [`MAX_INVITE_USES`]. #[serde(default)] pub max_uses: Option, + /// `true` mints an invite that never expires; it stays claimable until + /// revoked or exhausted. Cannot be combined with `ttl_secs`. + #[serde(default)] + pub never_expires: bool, } pub(crate) fn validate_mint_request( request: &MintInviteRequest, -) -> Result<(u64, Option), (StatusCode, Json)> { - let ttl = request.ttl_secs.unwrap_or(DEFAULT_INVITE_TTL_SECS); - if !(MIN_INVITE_TTL_SECS..=MAX_INVITE_TTL_SECS).contains(&ttl) { - return Err(api_error( - StatusCode::BAD_REQUEST, - &format!( - "ttl_secs must be between {} and {MAX_INVITE_TTL_SECS}", - MIN_INVITE_TTL_SECS - ), - )); +) -> Result<(InviteExpiry, Option), (StatusCode, Json)> { + let expiry = match (request.never_expires, request.ttl_secs) { + (true, Some(_)) => { + return Err(api_error( + StatusCode::BAD_REQUEST, + "never_expires cannot be combined with ttl_secs", + )) + } + (true, None) => InviteExpiry::Never, + (false, ttl) => InviteExpiry::After(ttl.unwrap_or(DEFAULT_INVITE_TTL_SECS)), + }; + if let InviteExpiry::After(ttl) = expiry { + if !(MIN_INVITE_TTL_SECS..=MAX_INVITE_TTL_SECS).contains(&ttl) { + return Err(api_error( + StatusCode::BAD_REQUEST, + &format!( + "ttl_secs must be between {} and {MAX_INVITE_TTL_SECS}", + MIN_INVITE_TTL_SECS + ), + )); + } } if let Some(max_uses) = request.max_uses { @@ -96,7 +112,7 @@ pub(crate) fn validate_mint_request( } } - Ok((ttl, request.max_uses)) + Ok((expiry, request.max_uses)) } /// Body for `POST /api/invites/claim`. @@ -308,8 +324,9 @@ pub(crate) enum InviteGate { } /// Admission shared by the invite-management routes, in order: tenant bind, -/// NIP-98 through NIP-FI admission for `method` and `path_and_query`, replay, -/// relay membership and ban, the NIP-OA owner link, then `gate`. +/// NIP-98 through NIP-FI admission for `method` and `path_and_query`, the +/// shared API rate limit, replay, relay membership and ban, the NIP-OA owner +/// link, then `gate`. Claim has its own limiter and does not come here. #[allow(clippy::result_large_err)] // Response is the natural error type for axum handlers pub(crate) async fn admit_invite_caller( state: &Arc, @@ -354,9 +371,10 @@ pub(crate) async fn admit_invite_caller( let mut caller = bridge::ProvenCaller::new(admission, slot, &tenant); let pubkey = caller.pubkey; - // Replay detection runs after NIP-98+assertion admission (both proofs verified). + // The shared per-pubkey API limit, then replay detection, after + // NIP-98+assertion admission (both proofs verified). caller - .replay(state, &tenant) + .rate_limit_and_replay(state, &tenant) .await .map_err(|e| e.into_response())?; @@ -432,12 +450,12 @@ async fn mint_invite_inner( })? }; - let (ttl, max_uses) = validate_mint_request(&request)?; + let (expiry, max_uses) = validate_mint_request(&request)?; // Mint a v2 opaque, database-backed invite. let invite = state .db - .mint_relay_invite_as_admin(tenant.community(), &sender_hex, ttl, max_uses) + .mint_relay_invite_as_admin(tenant.community(), &sender_hex, expiry, max_uses) .await .map_err(map_mint_error)?; @@ -901,6 +919,13 @@ mod postgres_tests { media_storage, ); state.nip98_replay = Arc::new(AlwaysFreshReplayGuard); + // Real Redis for the shared API rate limit, which fails closed. + let limiter = buzz_pubsub::redis_connection( + &std::env::var("REDIS_URL").unwrap_or("redis://127.0.0.1:6379".into()), + ) + .ok()?; + state.admission_rate_limiter = + Arc::new(buzz_pubsub::rate_limiter::RedisRateLimiter::new(limiter)); Some(Arc::new(state)) } @@ -985,26 +1010,41 @@ mod postgres_tests { #[test] fn mint_request_validation_enforces_bounds_without_a_database() { - use super::validate_mint_request; + use super::{validate_mint_request, InviteExpiry}; for (request, expected) in [ ( super::MintInviteRequest::default(), - (crate::invite_token::DEFAULT_INVITE_TTL_SECS, None), + ( + InviteExpiry::After(crate::invite_token::DEFAULT_INVITE_TTL_SECS), + None, + ), ), ( super::MintInviteRequest { ttl_secs: Some(MIN_INVITE_TTL_SECS), max_uses: Some(1), + ..Default::default() }, - (MIN_INVITE_TTL_SECS, Some(1)), + (InviteExpiry::After(MIN_INVITE_TTL_SECS), Some(1)), ), ( super::MintInviteRequest { ttl_secs: Some(MAX_INVITE_TTL_SECS), max_uses: Some(MAX_INVITE_USES), + ..Default::default() }, - (MAX_INVITE_TTL_SECS, Some(MAX_INVITE_USES)), + ( + InviteExpiry::After(MAX_INVITE_TTL_SECS), + Some(MAX_INVITE_USES), + ), + ), + ( + super::MintInviteRequest { + never_expires: true, + ..Default::default() + }, + (InviteExpiry::Never, None), ), ] { assert_eq!( @@ -1014,25 +1054,35 @@ mod postgres_tests { } for request in [ + super::MintInviteRequest { + ttl_secs: Some(3600), + max_uses: None, + never_expires: true, + }, super::MintInviteRequest { ttl_secs: None, max_uses: Some(0), + ..Default::default() }, super::MintInviteRequest { ttl_secs: None, max_uses: Some(-1), + ..Default::default() }, super::MintInviteRequest { ttl_secs: None, max_uses: Some(MAX_INVITE_USES + 1), + ..Default::default() }, super::MintInviteRequest { ttl_secs: Some(MIN_INVITE_TTL_SECS - 1), max_uses: None, + ..Default::default() }, super::MintInviteRequest { ttl_secs: Some(MAX_INVITE_TTL_SECS + 1), max_uses: None, + ..Default::default() }, ] { assert_eq!( @@ -1077,6 +1127,7 @@ mod postgres_tests { serde_json::json!({ "max_uses": MAX_INVITE_USES + 1 }), serde_json::json!({ "ttl_secs": MIN_INVITE_TTL_SECS - 1 }), serde_json::json!({ "ttl_secs": MAX_INVITE_TTL_SECS + 1 }), + serde_json::json!({ "never_expires": true, "ttl_secs": 3600 }), ] { let response = post_json( state.clone(), @@ -1096,6 +1147,7 @@ mod postgres_tests { serde_json::json!({ "max_uses": MAX_INVITE_USES }), serde_json::json!({ "ttl_secs": MIN_INVITE_TTL_SECS }), serde_json::json!({ "ttl_secs": MAX_INVITE_TTL_SECS }), + serde_json::json!({ "never_expires": true }), ] { let response = post_json( state.clone(), diff --git a/crates/buzz-relay/src/api/invites/postgres_tests/manage_tests.rs b/crates/buzz-relay/src/api/invites/postgres_tests/manage_tests.rs index cb81c950b2f..bae494e5d40 100644 --- a/crates/buzz-relay/src/api/invites/postgres_tests/manage_tests.rs +++ b/crates/buzz-relay/src/api/invites/postgres_tests/manage_tests.rs @@ -406,4 +406,98 @@ mod postgres_tests { } } } + + /// Mint, list and revoke share the per-pubkey API limit and fail closed + /// without it; claim keeps its own limiter. + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres and Redis"] + async fn mint_list_and_revoke_share_the_api_rate_limit() { + let (state, host, community, owner) = fixture().await; + let invite = mint(&state, &host, &owner).await; + let code = invite["code"].as_str().unwrap().to_owned(); + let revoke_body = serde_json::json!({ "id": invite["invite_id"] }).to_string(); + + let mut quota = (*state).clone(); + let mut auth_config = quota.config.auth.clone(); + auth_config.rate_limits.human_api_calls_per_min = 0; + quota.auth = Arc::new(buzz_auth::AuthService::new(auth_config)); + let quota = Arc::new(quota); + let mut unavailable = (*state).clone(); + let dead = buzz_pubsub::redis_connection("redis://127.0.0.1:1").unwrap(); + unavailable.admission_rate_limiter = + Arc::new(buzz_pubsub::rate_limiter::RedisRateLimiter::new(dead)); + let unavailable = Arc::new(unavailable); + + for (state, status, reason) in [ + ("a, StatusCode::TOO_MANY_REQUESTS, "quota_exceeded"), + ( + &unavailable, + StatusCode::SERVICE_UNAVAILABLE, + "admission_unavailable", + ), + ] { + for route in ["mint", "list", "revoke"] { + let (_guard, out) = crate::access::tests::capture_scoped(); + let response = match route { + "mint" => { + post_json(state.clone(), &host, "/api/invites", &owner, "{}".into()).await + } + "list" => { + get_signed(state.clone(), &host, "/api/invites", "/api/invites", &owner) + .await + } + _ => { + post_json( + state.clone(), + &host, + "/api/invites/revoke", + &owner, + revoke_body.clone(), + ) + .await + } + }; + assert_eq!(response.status(), status, "{route}"); + let error = read_json(response).await["error"] + .as_str() + .unwrap() + .to_owned(); + if status == StatusCode::TOO_MANY_REQUESTS { + let secs = error + .strip_prefix("rate-limited: quota exceeded; retry in ") + .and_then(|rest| rest.strip_suffix('s')) + .unwrap_or_else(|| panic!("{route}: {error}")); + assert!(secs.parse::().is_ok(), "{route}: {error}"); + } else { + assert_eq!(error, "rate-limited: shared admission unavailable"); + } + let lines = out.lines(); + assert_eq!(lines.len(), 1, "{route}: {lines:?}"); + assert_eq!(lines[0]["outcome"], "denied", "{route}"); + assert_eq!(lines[0]["reason"], reason, "{route}"); + } + } + + // Nothing was minted or revoked, and claim is not on the shared limit. + let listed = state + .db + .list_relay_invites(community, 50, None) + .await + .unwrap(); + assert_eq!(listed.len(), 1); + assert_eq!(listed[0].revoked_at, None); + let claim = post_json( + quota.clone(), + &host, + "/api/invites/claim", + &Keys::generate(), + serde_json::json!({ "code": code }).to_string(), + ) + .await; + assert_eq!( + claim.status(), + StatusCode::OK, + "claim keeps its own limiter" + ); + } } diff --git a/crates/buzz-relay/src/api/operator/invites.rs b/crates/buzz-relay/src/api/operator/invites.rs index 70f862bacf3..1aea8e341da 100644 --- a/crates/buzz-relay/src/api/operator/invites.rs +++ b/crates/buzz-relay/src/api/operator/invites.rs @@ -31,6 +31,8 @@ struct Request { ttl_secs: Option, #[serde(default)] max_uses: Option, + #[serde(default)] + never_expires: bool, } /// Mint an invite as the operator-attested `actor_pubkey`, who must be an @@ -64,9 +66,10 @@ pub async fn mint_community_invite( "invalid actor_pubkey: expected 64-char hex pubkey", ) })?; - let (ttl, max_uses) = validate_mint_request(&MintInviteRequest { + let (expiry, max_uses) = validate_mint_request(&MintInviteRequest { ttl_secs: request.ttl_secs, max_uses: request.max_uses, + never_expires: request.never_expires, }) .map_err(|error| with_code(error, "invalid_request"))?; let community = CommunityId::from_uuid(request.community_id); @@ -96,7 +99,7 @@ pub async fn mint_community_invite( // invite minted while an archive lands cannot be claimed while archived. let invite = state .db - .mint_relay_invite_as_admin(community, &actor, ttl, max_uses) + .mint_relay_invite_as_admin(community, &actor, expiry, max_uses) .await .map_err(|error| match error { buzz_db::DbError::InviteIssuerNotAdmin => { diff --git a/crates/buzz-relay/src/api/operator/postgres_tests/creation_policy_postgres_tests.rs b/crates/buzz-relay/src/api/operator/postgres_tests/creation_policy_postgres_tests.rs index 9753a9655ef..58840335a91 100644 --- a/crates/buzz-relay/src/api/operator/postgres_tests/creation_policy_postgres_tests.rs +++ b/crates/buzz-relay/src/api/operator/postgres_tests/creation_policy_postgres_tests.rs @@ -146,7 +146,12 @@ mod postgres_tests { // never enroll the caller into the extra (host is authoritative). let invite = state .db - .mint_relay_invite_as_admin(extra_id, &owner.public_key().to_hex(), 3600, Some(1)) + .mint_relay_invite_as_admin( + extra_id, + &owner.public_key().to_hex(), + buzz_db::relay_invite::InviteExpiry::After(3600), + Some(1), + ) .await .expect("invite fixture"); let joiner = Keys::generate(); diff --git a/crates/buzz-relay/src/api/operator/postgres_tests/invite_postgres_tests.rs b/crates/buzz-relay/src/api/operator/postgres_tests/invite_postgres_tests.rs index 3984255d5a7..4a6a1cfdcfe 100644 --- a/crates/buzz-relay/src/api/operator/postgres_tests/invite_postgres_tests.rs +++ b/crates/buzz-relay/src/api/operator/postgres_tests/invite_postgres_tests.rs @@ -132,6 +132,22 @@ mod postgres_tests { assert_eq!(json["max_uses"], 5); assert_eq!(json["uses_remaining"], 5); + // A permanent link has no expiry and still claims. + let response = mint( + &state, + &operator, + request(&owner, serde_json::json!({ "never_expires": true })), + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + let json = read_json(response).await; + assert_eq!(json.get("expires_at"), Some(&Value::Null), "{json}"); + let code = json["code"].as_str().expect("code").to_owned(); + assert_eq!( + claim(&state, &host, &Keys::generate(), &code).await, + StatusCode::OK + ); + // A restricted admin keeps the role but can no longer mint. state .db @@ -155,10 +171,14 @@ mod postgres_tests { ); // The relay's roster decides authority, whatever the operator asserts. - for actor in [&member, &outsider] { + for (actor, limits) in [ + (&member, serde_json::json!({})), + (&member, serde_json::json!({ "never_expires": true })), + (&outsider, serde_json::json!({})), + ] { assert_eq!( error( - mint(&state, &operator, request(actor, serde_json::json!({}))).await, + mint(&state, &operator, request(actor, limits)).await, StatusCode::FORBIDDEN, "not_owner" ) @@ -172,6 +192,10 @@ mod postgres_tests { serde_json::json!({ "ttl_secs": 30 * 24 * 60 * 60 + 1 }), "ttl_secs must be between", ), + ( + serde_json::json!({ "never_expires": true, "ttl_secs": 3600 }), + "never_expires cannot be combined with ttl_secs", + ), ( serde_json::json!({ "max_uses": 0 }), "max_uses must be between", diff --git a/crates/buzz-test-client/tests/e2e_relay.rs b/crates/buzz-test-client/tests/e2e_relay.rs index e854102f06a..2671c311d4b 100644 --- a/crates/buzz-test-client/tests/e2e_relay.rs +++ b/crates/buzz-test-client/tests/e2e_relay.rs @@ -323,6 +323,39 @@ async fn test_invite_mint_and_claim_admits_new_pubkey() { ); } +/// A never-expiring link mints with a null expiry, admits a joiner, and stops +/// admitting once revoked by its code. +#[tokio::test] +#[ignore] +async fn test_never_expiring_invite_claims_then_revokes() { + let owner = test_owner_keys(); + seed_relay_owner(&owner).await; + + let mint_response = invite_post(&owner, "/api/invites", r#"{"never_expires":true}"#).await; + assert_eq!(mint_response.status(), reqwest::StatusCode::OK); + let mint_json: serde_json::Value = mint_response.json().await.expect("mint JSON"); + assert_eq!(mint_json.get("expires_at"), Some(&serde_json::Value::Null)); + let code = mint_json + .get("code") + .and_then(serde_json::Value::as_str) + .expect("mint response includes code"); + let claim_body = serde_json::json!({ "code": code }).to_string(); + + let claim_response = invite_post(&Keys::generate(), "/api/invites/claim", &claim_body).await; + assert_eq!(claim_response.status(), reqwest::StatusCode::OK); + let claim_json: serde_json::Value = claim_response.json().await.expect("claim JSON"); + assert_eq!( + claim_json.get("status").and_then(serde_json::Value::as_str), + Some("joined") + ); + + let revoke_response = invite_post(&owner, "/api/invites/revoke", &claim_body).await; + assert_eq!(revoke_response.status(), reqwest::StatusCode::OK); + + let refused = invite_post(&Keys::generate(), "/api/invites/claim", &claim_body).await; + assert_eq!(refused.status(), reqwest::StatusCode::FORBIDDEN); +} + /// Claiming an invite joins the new member to the community's default /// channels: the relay owner flags one, the claim puts the claimer on its /// kind:39002 roster and stores one relay-signed kind:44100 for them, and a diff --git a/migrations/0106_relay_invites_optional_expiry.sql b/migrations/0106_relay_invites_optional_expiry.sql new file mode 100644 index 00000000000..74d1320bf36 --- /dev/null +++ b/migrations/0106_relay_invites_optional_expiry.sql @@ -0,0 +1,6 @@ +SET LOCAL lock_timeout = '5s'; +SET LOCAL statement_timeout = '30s'; + +-- A NULL expires_at is an invite that never expires. Readers tolerate NULL +-- since the previous release; deploy it everywhere before this migration. +ALTER TABLE relay_invites ALTER COLUMN expires_at DROP NOT NULL; diff --git a/schema/tables/public/relay_invites.sql b/schema/tables/public/relay_invites.sql index 5a7f2c19527..06fb6f8dc74 100644 --- a/schema/tables/public/relay_invites.sql +++ b/schema/tables/public/relay_invites.sql @@ -2,6 +2,7 @@ -- Conformance: durable invite records for atomic redemption, community-scoped. -- Stores only SHA-256(code) as 32-byte BYTEA; never the reusable bearer code. -- PK and UNIQUE both lead with community_id. max_uses NULL = unlimited. +-- expires_at NULL = never expires. CREATE TABLE relay_invites ( community_id UUID NOT NULL, @@ -10,7 +11,7 @@ CREATE TABLE relay_invites ( role TEXT NOT NULL DEFAULT 'member' CHECK (role = 'member'), max_uses INTEGER CHECK (max_uses BETWEEN 1 AND 10000), use_count INTEGER NOT NULL DEFAULT 0 CHECK (use_count >= 0), - expires_at TIMESTAMPTZ NOT NULL, + expires_at TIMESTAMPTZ, revoked_at TIMESTAMPTZ, legacy_admission BOOLEAN NOT NULL DEFAULT true, created_by TEXT NOT NULL,