Skip to content

feat(relay): mint invites that never expire - #9690

Open
wpfleger96 wants to merge 6 commits into
mainfrom
duncan/invite-never-expires
Open

wpfleger96 wants to merge 6 commits into
mainfrom
duncan/invite-never-expires

Conversation

@wpfleger96

@wpfleger96 wpfleger96 commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

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=false and apply migrations separately, as docs/database.md describes. Never roll back below #9680 once a permanent link exists.

What it does

  • Never-expiring links: POST /api/invites and the operator mint accept "never_expires": true. The invite is stored with a NULL expires_at, and the mint response returns expires_at: null. It stays claimable until it's revoked or used up.
  • Validation: never_expires together with ttl_secs is a 400. An omitted ttl_secs still defaults to 72 hours, and finite links keep the 30-day cap.
  • Who can mint: unchanged, owner/admin only on both routes.
  • Migration 0106: ALTER TABLE relay_invites ALTER COLUMN expires_at DROP NOT NULL, under the same lock_timeout/statement_timeout as 0075. It only changes metadata and rewrites no rows. schema/tables/public/relay_invites.sql matches.
  • Revoking an unknown invite doesn't wait on claims: revoke checks that the invite exists in the community before taking the admission lock, so a revoke for an unknown id or code returns 404 without queueing behind claims. The check runs after the community write fence. On a miss, non-members are still refused (403) and restricted actors are still refused before the 404 is returned, so callers learn nothing new. On a hit, the locked path runs unchanged and re-reads the invite.
  • Rate limit: mint, list and revoke now go through the shared per-pubkey API limit (human_api_calls_per_min, 60-second window) before replay and membership, like the other signed HTTP APIs. An exhausted quota returns 429 rate-limited: quota exceeded; retry in Ns, and the limiter fails closed with a 503. Claim keeps its own limiter.
  • One locked role read: the SELECT role ... FOR SHARE read that mint and revoke share, and is_admin, now live in relay_members.rs. No behaviour change.

Tests

  • Unit: request validation for never_expires, alone and with ttl_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 with ttl_secs, and a member actor's refusal.
  • Schema: relay_invites joins the desired-state vs. migrations parity check. The invite catalog assertion now checks expires_at is nullable after both bootstrap paths.
  • Populated upgrade: finite, revoked and exhausted invites made before 0106 are unchanged by it and claim the same afterward. A permanent invite can then be minted and claimed.
  • Cleanup: the reap job never deletes a permanent invite, even with a cutoff 100 years out.
  • Revoke pre-check (Postgres): while the admission lock is held, revokes for an unknown id, an unknown code, and another community's invite all finish without waiting, while a known invite still waits. This test fails without the pre-check. Also covered: refusal order for non-members and restricted actors on an unknown invite, an invite deleted after the existence check returns not found, and the quiescing fence still wins for an unknown selector.
  • Rate limit (Postgres + Redis): mint, list and revoke each return 429 with an exhausted quota and 503 with no limiter, and each logs one denied line. Nothing is minted or revoked, and claim still succeeds under the exhausted quota. This test fails on the old replay-only path.
  • End-to-end: mint a permanent link, claim it, revoke it by code, and a new claim is refused.

TheSentinel454 added a commit that referenced this pull request Nov 19, 2026
## 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>
@wpfleger96
wpfleger96 marked this pull request as ready for review November 19, 2026 22:41
@wpfleger96
wpfleger96 requested a review from a team as a code owner November 19, 2026 22:41
joahg
joahg previously approved these changes Nov 20, 2026

@joahg joahg left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 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,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 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.

@TheSentinel454

Copy link
Copy Markdown
Contributor

🤖 Main now ends at relay migration 0104 (0098–0100 from #9710, 0101 from #9610, 0102–0104 from #9740). This PR still adds 0098, which main already has, so it needs to move to 0105.

  • Rename migrations/0098_relay_invites_optional_expiry.sql to 0105_relay_invites_optional_expiry.sql, and update the migration count test in crates/buzz-db/src/runtime/migration.rs to 105.

#9621 also needs a new number. Whichever of the two merges second takes 0106.

wpfleger96 added a commit that referenced this pull request Nov 20, 2026
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>
Base automatically changed from duncan/invite-list-revoke to main November 20, 2026 20:48
@wpfleger96
wpfleger96 dismissed joahg’s stale review November 20, 2026 20:48

The base branch was changed.

TheSentinel454 added a commit that referenced this pull request Nov 20, 2026
## 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>
wpfleger96 and others added 6 commits November 20, 2026 16:06
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>
@wpfleger96
wpfleger96 force-pushed the duncan/invite-never-expires branch from e2a7ac3 to be42b49 Compare November 20, 2026 21:22
@wpfleger96
wpfleger96 deployed to codex-review November 20, 2026 21:22 — with GitHub Actions Active
@github-actions github-actions Bot added the codex-security-review-current The posted Codex security review matches its recorded range. label Nov 20, 2026
@github-actions

Copy link
Copy Markdown

🔐 Codex Security Review

Note: This is an automated, security-focused review generated by Codex.
Use it as a supplement to human review; false positives are possible.

Scope

  • Exact PR diff: 2074adaa8542dd0094ba12c0b11b8a7402601cbc...be42b497160806424e3669162d36ba06b46bb75f
  • Model: gpt-6.1-sol

💡 Click "edited" above to see earlier reviews for this PR.


Review Summary

Overall Risk: NONE

No concrete security, correctness, or reliability findings were identified in the authorized PR range.

Findings

No concrete security, correctness, or reliability findings were identified.

Notes

  • Review was limited to read-only source and history inspection; builds and tests were not executed.

Generated by Codex Security Review |
Requested by: @wpfleger96 |
Workflow run

@wpfleger96

Copy link
Copy Markdown
Member Author

🤖 Addressed in be42b49. The migration is now 0106_relay_invites_optional_expiry.sql, since 0105 was taken on main by the push gateway migration, and the migration count test in crates/buzz-db/src/runtime/migration.rs matches.

This branch was successfully deployed

1 active deployment
codex-review — be42b497 Deployed Nov 20, 2026 by wpfleger96 via Run Codex Security Review #16984
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

codex-security-review-current The posted Codex security review matches its recorded range.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants