Repository navigation
feat(relay): mint invites that never expire - #9690
wpfleger96 wants to merge 6 commits into
Conversation
## Summary Retire the last foreign key in the push gateway schema: `push_gateway_delegations.installation_id → push_gateway_installations(id)`. This follows `docs/database.md` Rule 2 and the relay FK retirement work (#9399, #9404). - **Gateway migration 0008** drops the constraint. - **Relay migration 0101** drops the relay's legacy copy (Rule 4: gateway schema changes go in both). `schema/tables/public/push_gateway_delegations.sql` loses the inline `REFERENCES`. ## Required stop Every gateway and rollback target must run #9627 (`44cdd9fe`) or later before this merges and deploys. #9627 makes the reaper lock expired installations before it deletes their delegations. Without the FK, an older reaper can leave an orphaned delegation. This is step 2 of the Rule 5 retirement sequence; #9627 is step 1. ## Why the app already enforces the reference | Path | Check | |---|---| | `upsert_delegation` (only delegation insert) | Locks the installation `FOR UPDATE` in the same transaction; rejects a missing or revoked one. | | `create_installation` (replaces expired installations) | Locks the matching installations `FOR UPDATE`, deletes their delegations, then the installations. | | `reap_expired` | Locks expired installations `FOR UPDATE`, deletes their delegations, then the installations (#9627). | | `authorize_delivery` | Reads the installation through the delegation; a missing installation is `Rejected`. | | `revoke_delegation` | Updates the delegation only; an orphan has no effect. | | `revoke_installation`, `rotate_endpoint`, `advance_assertion_counter` | Update the installation; they never delete it. | The relay never reads or writes the `push_gateway_*` tables (the gateway requires its own database), so dropping the relay copy changes no relay behavior. ## Tests The gateway tests run against the migrated schema, which no longer has the FK, so they prove the app check. - `migrated_schema_has_no_foreign_keys` (new): the gateway schema has no foreign keys after migrations. It fails if gateway migration 0008 is removed. - `delegation_for_missing_installation_is_rejected` and `reaper_deletes_delegation_committed_while_it_waits` (from #9627) now run without the FK. - `reaper_retains_revocation_tombstones_until_authority_expiry`: its hand-built schema drops the FK too. - Relay: `push_gateway_delegations` joins the constraint parity check in `admin_schema_parity_between_desired_state_and_migrations`, and the migration count test covers 0101. ## Validation Blox at `33f7df90` (before the rename to 0101; CI covers the rebased head): - `cargo fmt --check`, clippy (`buzz-push-gateway`, `buzz-db`, all targets), gateway unit tests, `buzz-db` migration unit tests: pass. - `scripts/postgres-test-run.sh -p buzz-push-gateway --lib --tests`: 16/16 pass. - `buzz-db` Postgres tests for migrations, parity, push, floor retirement and retained guards: 56/56 pass, including `admin_schema_parity_between_desired_state_and_migrations`. - Must-fail check: with gateway migration 0008 removed, `migrated_schema_has_no_foreign_keys` fails (1 foreign key vs 0). ## Coordination - On main after #8696, #9398 and #9710 (relay 0095–0100). #9627 shipped this PR's reaper fix and tests separately, so this PR is the schema drop only. - Renumbered to relay 0101 after #9710 took 0098–0100 (rename only; file contents unchanged). #9690 and #9621 also add a relay 0098; whichever merges second renumbers. - #8328 adds the gateway's declarative schema with the inline FK. Whichever PR merges second removes it there. ## What got simpler One fewer database object. Every gateway reference check now lives in one place: the gateway's own transactions. buzz-review-completed 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
joahg
left a comment
There was a problem hiding this comment.
🤖 Checked the security-relevant paths: both mint routes stay owner/admin only (mint_relay_invite_as_admin, plus the restricted-issuer check), the claim path still enforces revocation, use limits and issuer restriction when expires_at is NULL, the list/status code and the retention reap (expires_at < cutoff) both handle NULL, and migration 0098 is a metadata-only DROP NOT NULL. Revocation comes from the base PR (#9680), so this must not merge or deploy ahead of it, as the description says. One non-blocking note on abuse surface inline. I read the code but did not run the Postgres-backed tests.
| "never_expires cannot be combined with ttl_secs", | ||
| )) | ||
| } | ||
| (true, None) => InviteExpiry::Never, |
There was a problem hiding this comment.
🤖 Non-blocking: nothing caps how many permanent links a community can hold, and never_expires with no max_uses is a link that anyone holding the code can use forever until an admin revokes it. Consider requiring max_uses for permanent links, or a per-community cap on active permanent invites, in a follow-up.
|
🤖 Main now ends at relay migration
#9621 also needs a new number. Whichever of the two merges second takes |
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>
## Summary Migrations up to `0104` dropped every trigger, function and foreign key. `docs/database.md` Rules 1 and 2 forbid adding them back, but nothing enforced that. This PR adds the guard. - **Migration lint.** `migrations_after_retirement_add_no_triggers_functions_or_foreign_keys` scans each migration numbered after `0104`. It fails on `CREATE [OR REPLACE] FUNCTION | PROCEDURE | TRIGGER | RULE`, `CREATE CONSTRAINT TRIGGER`, `CREATE EVENT TRIGGER`, `REFERENCES` and `FOREIGN KEY`, outside `--` comments. The error names the file and line, for example `migrations/0105_probe.sql:2: CREATE OR REPLACE FUNCTION`. Nested `/* */` comments are skipped. Quoted identifiers and string values are data, except a string passed to `EXECUTE` or `format(`. Each dollar-quoted body is scanned as SQL up to its closing delimiter, so DDL run through `EXECUTE` in a `DO` block is caught, and an apostrophe inside `$$...$$` cannot hide the rest of the file. It runs in the infra-free `buzz-db --lib` unit lane. - **Schema file check.** `desired_state_schema_layout_is_complete_and_schemabot_shaped` allows `schema/` files only under `tables/public/`, `types/`, `partitions/` and `seeds/`, and runs the same scan on every file. A `functions/` or `triggers/` file, or an inline `REFERENCES` in a table file, fails it. - **Catalog check.** `admin_schema_parity_between_desired_state_and_migrations` now asserts that both bootstrap paths (pgschema + reconcile, and all migrations) have zero non-internal triggers, event triggers, `public` functions and procedures, rules and foreign keys. Extension members (pgcrypto) are excluded. No allowlist is needed: main with all 104 migrations applied has none of these objects. Main now has `0105`, which passes the lint. Open PRs that add a migration only need to renumber to `0106` or later. The two open ones (#9621 and #9690) add no forbidden object. ### What got simpler - The parity test's per-table trigger comparisons (`events`, `event_mentions`, and the five tables `0096` unguarded) and its separate foreign-key check are replaced by one zero-object assertion. - The scoped-key lint no longer parses foreign keys. None may exist, so checking that they lead with `community_id` is dead logic. - `schema/schema.sql` drops its empty `-- functions` and `-- triggers` sections. Its header and `docs/database.md` stop describing `functions/` and `triggers/` directories that no longer exist, and the doc's "remaining triggers stay as a backstop" text now says they are gone. ### Checklist (`docs/database.md`) - [x] Phase: none. Test and docs change only. No migration and no runtime code. - [x] No trigger, function, procedure, rule or foreign key is added. - [x] No migration mutates rows. - [x] Rule 4 locations: no schema change. `schema/schema.sql` changes only comments. ### Related issue None found. ### Testing Run on a Linux workstation with PostgreSQL 17 at `b7254f90`, before the review fixes. CI passed with the first review fixes at `0fed6b1b`. `9749e618` adds dollar-quote, nested `EXECUTE $tag$` and `$1` cases to `schema_object_lint_reports_each_construct_with_its_line`, and CI checks it. - `cargo fmt --check` and `cargo clippy -p buzz-db --all-targets -D warnings`: pass. - `cargo test -p buzz-db --lib` and `cargo nextest run -p buzz-db --lib`: 223 passed. - `scripts/postgres-test-run.sh` for `admin_schema_parity_between_desired_state_and_migrations`, `migrated_catalog_retires_universal_fences_but_keeps_deletion_guards` and `pgschema_reapply_keeps_runtime_partitions`: 3 passed. - Proof the lint can fail: a temporary `migrations/0105_probe.sql` with a function and a `REFERENCES` column fails the lint with `migrations/0105_probe.sql:2: CREATE OR REPLACE FUNCTION` and `migrations/0105_probe.sql:3: REFERENCES`. - Proof the catalog check can fail: a temporary `0105` that creates `probe()` fails the parity test with `the migrations leave a trigger, function, rule or foreign key`, `left: ["function probe()"]`. - The catalog on main at `9c0bcd62`, with all 104 migrations applied through psql, has no triggers, functions, foreign keys, rules or event triggers. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
POST /api/invites and the operator mint accept never_expires: true, which stores a NULL expires_at. Combining it with ttl_secs is a 400; the 72-hour default and 30-day cap on finite links are unchanged, and minting stays owner/admin only. Migration 0098 drops NOT NULL on relay_invites.expires_at under bounded lock and statement timeouts. Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> Signed-off-by: Will Pfleger <wpfleger@block.xyz>
Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> Signed-off-by: Will Pfleger <wpfleger@block.xyz>
Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> Signed-off-by: Will Pfleger <wpfleger@block.xyz>
Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> Signed-off-by: Will Pfleger <wpfleger@block.xyz>
…imit Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> Signed-off-by: Will Pfleger <wpfleger@block.xyz>
Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> Signed-off-by: Will Pfleger <wpfleger@block.xyz>
e2a7ac3 to
be42b49
Compare
🔐 Codex Security Review
Review SummaryOverall Risk: NONE
FindingsNo concrete security, correctness, or reliability findings were identified. Notes
Generated by Codex Security Review | |
|
🤖 Addressed in be42b49. The migration is now |
Deploy order
Deploy only after #9680 is deployed everywhere. #9680 makes every reader of an invite's expiry accept a missing value. This PR adds the only writer of one, so every serving pod must already tolerate it.
Rollback floor is #9680. A #9680 pod that is already running keeps working after this migration. A #9680 pod started or restarted after migration 0106 has run fails startup with auto-migrate on, because it doesn't know migration 0106. Run such pods with
BUZZ_AUTO_MIGRATE=falseand apply migrations separately, asdocs/database.mddescribes. Never roll back below #9680 once a permanent link exists.What it does
POST /api/invitesand the operator mint accept"never_expires": true. The invite is stored with a NULLexpires_at, and the mint response returnsexpires_at: null. It stays claimable until it's revoked or used up.never_expirestogether withttl_secsis a 400. An omittedttl_secsstill defaults to 72 hours, and finite links keep the 30-day cap.ALTER TABLE relay_invites ALTER COLUMN expires_at DROP NOT NULL, under the samelock_timeout/statement_timeoutas 0075. It only changes metadata and rewrites no rows.schema/tables/public/relay_invites.sqlmatches.human_api_calls_per_min, 60-second window) before replay and membership, like the other signed HTTP APIs. An exhausted quota returns 429rate-limited: quota exceeded; retry in Ns, and the limiter fails closed with a 503. Claim keeps its own limiter.SELECT role ... FOR SHAREread that mint and revoke share, andis_admin, now live inrelay_members.rs. No behaviour change.Tests
never_expires, alone and withttl_secs. The HTTP mint test covers the 400 and the 200. The operator mint test covers a permanent mint (expires_at: null, then claimed), the 400 withttl_secs, and a member actor's refusal.relay_invitesjoins the desired-state vs. migrations parity check. The invite catalog assertion now checksexpires_atis nullable after both bootstrap paths.