Skip to content

Commit 40bc07a

Browse files
wpfleger96Duncan
andauthored
feat(relay): mint invites that never expire (#9690)
## Summary Community owners and admins can mint invite links that never expire. A mint request with `"never_expires": true` stores the invite with a NULL `expires_at`, and the response returns `expires_at: null`. The link stays claimable until it's revoked or used up. Requests without it still get the default finite expiry, finite links keep the 30-day cap, and `never_expires` together with `ttl_secs` is a 400. Migration 0112 drops `NOT NULL` from `relay_invites.expires_at`. It only changes metadata. On relays that require membership, both `POST /api/invites` and the operator route refuse a never-expiring link with a 403 unless the request also sends `"confirm_never_expires": true`. The operator route also returns the code `never_expires_not_allowed`. Sending `confirm_never_expires` without `never_expires` is a 400. The Buzz app (block/buzz-app#4120) matches the exact refusal text to offer its confirmation, so that text must stay stable. An invite now stops working once its creator is no longer an owner or admin, the same way a ban affects that person's invites. This applies to finite and never-expiring links alike. Demotion, removal and ownership transfer revoke the person's invites in the same transaction, under the invite admission lock, and getting the role back doesn't revive them. A claim also revokes an older invite whose creator has lost the role. Retention now deletes revoked invites once they're older than its cutoff, not only expired ones, so revoked never-expiring links don't pile up. Migration 0112 adds a partial index on `revoked_at` for this. Mint, list and revoke go through the shared per-pubkey API rate limit (`human_api_calls_per_min`, 60-second window) before the replay and membership checks. An exhausted quota returns 429 `rate-limited: quota exceeded; retry in Ns`. The limiter fails closed, so these routes return 503 while Redis is unavailable. Claim keeps its own limiter. Revoking an unknown invite returns 404 without waiting on the admission lock. There's no kill switch: a leaked never-expiring link has to be revoked on its own. ### Related issue Builds on #9680 (listing and revoking invites). Client: block/buzz-app#4120. ### Deploy order and rollback - Deploy only after #9680 is deployed to every serving relay. #9680 makes every reader of an invite's expiry accept a missing value, and this PR adds the only writer of one. - The rollback floor is #9680. Once a never-expiring link exists, never roll back below it: older relays can't decode a NULL `expires_at`, so claims of that link fail. - A #9680 relay that is already running keeps working after migration 0112. One that starts or restarts with auto-migrate on refuses the database, because it doesn't know 0112 (sqlx `VersionMissing`). Run it with `BUZZ_AUTO_MIGRATE=false` and apply migrations separately, as `docs/database.md` describes. - Self-hosted relay operators get this together with #9680 in one release, since no tagged relay release contains #9680 yet. For them, that release is the rollback floor. ### Schema change (`docs/database.md` checklist) - Phase: expand plus writer. #9680 shipped the readers that accept a NULL expiry. Migration 0112 relaxes the column and adds an index, and this PR adds the writers. - No trigger, function, procedure, rule or foreign key is added, and no migration rewrites rows. - Locks: 0112 starts with `SET LOCAL lock_timeout = '5s'` and `statement_timeout = '30s'`, like 0075. `DROP NOT NULL` changes only metadata. The partial index `relay_invites_revoked_at_idx` covers revoked rows only and is built inline in the same transaction, under those limits. There is no prebuild step. - Every schema location matches: `schema/tables/public/relay_invites.sql`, the desired-vs-migrated column and index parity test (which now covers `relay_invites`), and the embedded-migrator test, which checks both 0112 statements. `assert_admission_column` checks the nullable column after a pgschema reconcile. - The deployed relay against the new schema: `migration_schema_optional_expiry_keeps_populated_invites_and_admits_permanent_ones` migrates a populated database through 0112, checks that no row changes, and checks that existing finite, revoked and exhausted invites behave as before. #9680's `readers_accept_an_invite_without_expiry` covers its readers on a NULL expiry. ### Testing - CI run 46800668669 at 247b2b0 (merge 04b19be onto 86511a9): PostgreSQL Tests passed 1902/1902, including the new revocation, reap, confirmation and upgrade tests. Unit Tests, Rust Lint and Relay E2E are green. Relay E2E includes `test_never_expiring_invite_claims_then_revokes`, which runs on a relay that doesn't require membership. - An agent review at 927c87b also ran fmt, the buzz-db unit and `observability_source` tests and the PostgreSQL lane for every touched module locally, plus a test-merge onto main. The changes since then were checked by reading the code and by CI. - Still to do: an agent exercise against a local relay, then a human test (AGENTS.md, "Before opening a PR"). On a relay that requires membership: 1. `POST /api/invites` with `{"never_expires":true}` returns 403 with the refusal text. 2. Adding `"confirm_never_expires": true` returns 200 with `expires_at: null`. 3. `GET /api/invites` lists the link as active with no expiry. 4. A claim from a new key joins. 5. After the link's creator is demoted to member, the next claim gets 403, and promoting them back doesn't revive the link. 6. A fresh link revoked by its code returns 200, and a later claim gets 403. 7. In Buzz, choosing Never expires shows the confirmation, and Create permanent link mints the link. - The author adds `buzz-review-completed` once the human test is done. --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
1 parent 9043b51 commit 40bc07a

20 files changed

Lines changed: 1517 additions & 221 deletions

‎crates/buzz-db/src/runtime/migration.rs‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1200,7 +1200,16 @@ mod postgres_tests {
12001200
let mut migrations: Vec<_> = MIGRATOR.iter().collect();
12011201
migrations.sort_by_key(|migration| migration.version);
12021202

1203-
assert_eq!(migrations.len(), 111);
1203+
assert_eq!(migrations.len(), 112);
1204+
assert_eq!(migrations[111].version, 112);
1205+
assert!(migrations[111]
1206+
.sql
1207+
.as_str()
1208+
.contains("ALTER TABLE relay_invites ALTER COLUMN expires_at DROP NOT NULL"));
1209+
assert!(migrations[111]
1210+
.sql
1211+
.as_str()
1212+
.contains("IF to_regclass('public.relay_invites_revoked_at_idx') IS NULL THEN"));
12041213
assert_eq!(migrations[110].version, 111);
12051214
assert!(migrations[110]
12061215
.sql
@@ -3955,6 +3964,7 @@ mod postgres_tests {
39553964
"audit_log",
39563965
"media_publications",
39573966
"relay_members",
3967+
"relay_invites",
39583968
"relay_admin_actions",
39593969
"relay_admin_outbox",
39603970
"relay_operator_audit",
@@ -5071,6 +5081,38 @@ mod postgres_tests {
50715081
store.validate_serving_catalog().await.unwrap();
50725082
}
50735083

5084+
/// 0112 verifies a concurrently prebuilt revoked-invite index instead of
5085+
/// failing on it, and refuses one with the wrong definition.
5086+
#[tokio::test]
5087+
#[ignore = "requires Postgres"]
5088+
async fn migration_0112_verifies_a_prebuilt_revoked_invite_index() {
5089+
let pool = connect_test_pool().await;
5090+
reset_public_schema(&pool).await;
5091+
run_migrations_through(&pool, 111).await.unwrap();
5092+
sqlx::query("CREATE INDEX relay_invites_revoked_at_idx ON relay_invites (revoked_at)")
5093+
.execute(&pool)
5094+
.await
5095+
.unwrap();
5096+
let error = run_migrations_through(&pool, 112).await.unwrap_err();
5097+
assert!(
5098+
error.to_string().contains("invalid or wrong definition"),
5099+
"{error}"
5100+
);
5101+
sqlx::query("DROP INDEX relay_invites_revoked_at_idx")
5102+
.execute(&pool)
5103+
.await
5104+
.unwrap();
5105+
sqlx::query(
5106+
"CREATE INDEX CONCURRENTLY relay_invites_revoked_at_idx ON relay_invites (revoked_at) WHERE revoked_at IS NOT NULL",
5107+
)
5108+
.execute(&pool)
5109+
.await
5110+
.unwrap();
5111+
run_migrations_through(&pool, 112)
5112+
.await
5113+
.expect("0112 applies over a verified prebuild");
5114+
}
5115+
50745116
/// Verify migration 0044 applies cleanly against a DB that has rows in
50755117
/// the NIP-FI 0041+0042 tables. The immutability guards (no_delete,
50765118
/// no_truncate) are enforced via triggers; DROP TABLE bypasses them and

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

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,7 @@ async fn relay_invite_writers_require_application_admission() {
188188
&db.pool,
189189
*community,
190190
&"e".repeat(64),
191-
3600,
191+
super::relay_invite::InviteExpiry::After(3600),
192192
Some(1),
193193
)
194194
.await
@@ -208,11 +208,11 @@ async fn relay_invite_writers_require_application_admission() {
208208
.expect_err("invite claim must reject before row lock"),
209209
);
210210
}
211-
super::relay_invite::mint_relay_invite(
211+
crate::test_support::mint_issued_invite(
212212
&db.pool,
213213
communities[0],
214214
&"e".repeat(64),
215-
3600,
215+
super::relay_invite::InviteExpiry::After(3600),
216216
Some(1),
217217
)
218218
.await
@@ -859,11 +859,12 @@ async fn invite_sweep_admits_active_tenant_and_skips_quiescing_tenant() {
859859
.await
860860
.expect("seed invite");
861861
}
862-
assert_eq!(
862+
// Other tests' expired or revoked rows share the table, so count per tenant.
863+
assert!(
863864
super::relay_invite::reap_expired_relay_invites(&db.pool, cutoff)
864865
.await
865-
.unwrap(),
866-
1
866+
.unwrap()
867+
>= 1
867868
);
868869
for (community, expected) in [(communities[0], 0), (communities[1], 1)] {
869870
let count: i64 =

0 commit comments

Comments
 (0)