mirror of
https://github.com/block/buzz.git
synced 2026-11-28 20:22:39 +00:00
6b0dfc1957fb6cb87d40b5c3bd6570aa7e8a896e
9 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
cb4a83a406 |
feat(relay): add percentage-based NIP-FI enforcement rollout in shadow mode (#9758)
Adds `BUZZ_NIP_FI_ENFORCE_PERCENT`, a permanent operator setting for moving a relay from `shadow` to `enforce` in stages. While the relay runs in `shadow`, it enforces NIP-FI for a stable, growing share of communities (integer 0-100, default 0, read at startup). Operators raise it in steps, watch denials, then switch to `BUZZ_NIP_FI_MODE=enforce`, where the setting has no effect. Unset, behaviour is unchanged. - **Cohort:** a community is in when `rollout_bucket(id) < percent`. The bucket is SHA-256 over the UUID's 16 RFC 4122 big-endian bytes, first 8 bytes as a big-endian `u64`, mod 100. Cohorts are nested as the percentage rises and stable across renames. Golden vectors freeze the hash. - **One helper:** `NipFiRelayConfig::policy_required(id, stored)` returns `stored || in_rollout`, and only shadow mode widens it; `NipFiRelayConfig::effective_mode(id, stored)` applies it to the relay mode. They feed every field of the three `Policy` constructions (`resolve`, `bind_for_upgrade`, and live-socket revalidation), so a rollout community gets the same admission, upgrade, NIP-11 `requires_nip_fi`, binding check, `configured_mode` and deny-map guard as a stored-Required one. `Policy::stored_required` is renamed `policy_required` to match. - **Stored policy stays raw:** the host cache, `CommunityAuthPolicy`, stored-policy writes, the upgrade drain and the CAS/receipt fields don't change. Operator `effective_required` reports the derived requirement through `effective_mode`. - **Validation:** a malformed or out-of-range value refuses startup in every mode. Outside shadow the setting has no effect. - **Precedence:** a community stored Required always enforces, at any percentage, so lowering the percentage never stops it. A community stored Optional that falls inside the cohort can't opt out: a stored disable succeeds but enforcement stays on, and the only way to drop it is to lower the percentage to its bucket or below, which also drops every community in a higher bucket. - **Logging:** the `nip-fi enforce deny` and `nip-fi enforce session end` lines move to target `buzz_relay::nip_fi_enforce`, so a log filter can keep real denials while suppressing shadow would-deny volume. Startup logs one `NIP-FI config loaded` info line (target `buzz_relay`) with `mode` and `enforce_percent`, so pods running different percentages during a rollout show up in log search. - **Docs:** `docs/operator-nip-fi-bindings.md` gains a "Staged enforce" runbook step between Shadow and Enforce, with go/no-go signals, rollback (lower the percentage) and its cost: each change is a full rollout, and there is no per-community exemption. A required admission is refused when the receiving pod holds an active deny for the key; revocation closes open connections only in `enforce`, as for stored-Required communities today. Denies live only in each pod's memory and spread asynchronously, so a restarted pod, or an `enforce` pod during the switch from `shadow`, can miss one; the key can then sign in until its outstanding assertions expire (the issuer's `maximum_assertion_age_seconds` plus `skew_seconds`, if the issuer stops issuing), and finishing a rollout does not restore missed denies. The runbook describes recovery, not continuity: re-push freshly signed disconnect commands once the new pods are serving (resent old commands can fail replay and command-age checks), or wait out the bound counted from when the issuer stopped issuing. A revoked key can still be admitted before recovery, and in `shadow` a later re-push does not close a connection opened in that window. The Enforce step leaves the percentage at 100, where it has no effect. Its rollback for admission failures sets `shadow` and lowers the percentage to the last known-good value; a mode-only rollback at 100 still requires every community. Never roll back with `off`, which also turns off stored-Required enforcement. A stored disable makes reconnects optional only when the effective policy becomes optional. The upgrade runbook, community auth doc, `ARCHITECTURE.md` and the multi-tenant conformance table say cohort communities are required in `shadow` too. The NIP-FI spec drops its Buzz implementation note and describes capability advertisement in generic terms; its normative `MAY` is unchanged. --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> |
||
|
|
e8a8e4cb6a |
feat(nip-fi): scope disconnects to tokens issued through revoke_through, stored durably (#9917)
## Summary Builds on #9860 (merged as `c0932db19c`). A NIP-FI disconnect command can now carry `revoke_through` (C), an integral NumericDate. With C, the relay refuses and closes only assertions whose verified signed `iat` is at or before C, until `until`. Tokens issued after C are admitted straight away. Without C, the deny covers the whole key, as before. - **Spec:** `docs/nips/NIP-FI.md` adds the `revoke_through` claim and a Deny scope section (admission, close scope, merging, records, the issuer's duty) with a behavioral oracle. The existing deny, command-algorithm, oracle and security text now carry scope. The deny set's storage text is #9860's (shared storage, restored before admission); this PR adds no wire claim or storage schema to the spec. - **Parsing:** a `revoke_through` that is `null`, nonnumeric, fractional or unrepresentable is rejected as `evidence_rejected` before any state changes. - **Verified `iat`:** `VerifiedAssertion::issued_at()` comes from the time-checked `iat`, not from profile evidence. `NipFiSession` records it at registration. - **One predicate:** `DenyScope::covers` compares the full verified instant (fractional `iat` included) against C. It decides admission (WebSocket and HTTP, with asserted key and owner checked separately) and every close scan (root and audio registries, the command route, cross-pod delivery, shadow accounting). - **Merge:** `DenyEntry::merge` takes the later `until`. Whole-key beats a cutoff, two cutoffs merge to the larger C, and expired entries contribute nothing. Activity is read from a clock sampled inside the issuer shard lock, so an entry that expires while a merge waits contributes nothing. A past-`until` command still does its scoped close without changing an active entry. The close scope widens to any stronger active entry, and a poisoned shard closes the whole key. - **Bus:** `NipFiDisconnect.revoke_through` is optional. A message without it means whole-key. - **Durable cutoff (Redis):** the cutoff lives in its own per-issuer hash, `<deny prefix>-revoke-through:<sha256(iss)>`, field `pubkey_hex`, value C. The exact-`until` hash keeps only `secs:nanos`. One accept script merges `until` and scope by the same rule as `DenyEntry::merge` and gives all three keys one expiry. It judges whether the command and the stored entry are still active by Redis `TIME` as it runs, not by the authentication clock. Before any write it checks the target's stored cutoff by restore's rule: a disconnect over an unreadable one returns `unreadable`, `try_claim` fails (`503`), the claim stays unused and nothing is recorded. Restore judges expiry when it merges. Restore reads both hashes in one script and joins them before merging, looking deny keys up in a set (linear at capacity), so a missing cutoff field is a whole-key deny. A cutoff that isn't an integer, or names no deny, is `reason="unreadable"`. As in #9860, one bad record does not hide the others: restore still applies every readable deny (a deny under a malformed cutoff as the whole key; an orphan cutoff adds nothing) and then fails, so admission stays closed. `LoadDenies` and `LoadDeniesError::Unreadable { readable }` now carry `DenyEntry`, and a restore counts a same-`until` scope widening as changed, so it closes the sessions it newly covers. - **Runbook:** `docs/operator-nip-fi-bindings.md` names the cutoff hash and how to clear a bad cutoff. It warns that deleting an orphaned cutoff leaves no deny at all, and that a disconnect over a bad stored cutoff fails until it is cleared. ## Deploy and rollback Deploy this to every relay pod before any issuer sends `revoke_through`. Until then, a pod still on the old build ignores the claim and blocks the whole key, so the agent stays locked out until its old token expires. Rolling a relay back to #9860 is safe. That build reads only the exact-`until` hash, which this PR writes in the same format, so it restores every cutoff as a whole-key deny and never fails its restore on this data. It ignores `revoke_through` in commands and bus messages, and every accept it makes clears the target's stored cutoff, so its whole-key revokes are never narrowed by a cutoff this build stored. All of this only over-blocks: agents wait for their old tokens to expire instead of getting back in at once. ## Testing Behavior tests cover old and fresh tokens at admission and in close scans, redelivery leaving fresh root and audio sessions open, cross-pod delivery, an owner whole-key deny blocking a fresh agent token, same-deadline scope changes in both orders, an expired whole-key entry followed by a cutoff, past-`until` commands, invalid `revoke_through` values, legacy bus messages, fractional `iat` at C and C + 0.5 through real verification, replay-claim waits that cross an entry's expiry, and root/audio handler straddle cases where the signed `iat` differs from registration time. Each of these was checked to fail when the code it guards is broken: - the route's published bus message keeps the cutoff on another pod (fails if `nip_fi_disconnect_message` drops `revoke_through`); - a cutoff command over an active whole-key entry closes a fresh session (fails if the route skips close-scope widening); - a poisoned shard's close scope is whole-key; - shadow `would_close` ends only sessions issued at or before C; - a cutoff in Redis restores as a cutoff (fails if the accept script stops writing the cutoff hash), and #9860's reader, taken from its final head `02627cce`, decodes the same record as a whole-key deny; - #9860's writer, copied verbatim from `02627cce`, writing over a stored cutoff with an equal or shorter `until`, then a fresh restore by this build, gives a whole-key deny; - a full revoke that expires between authentication and its Redis write neither widens a cutoff nor, once stored and expired, overrides one (fails with the authentication clock); - a whole key that is live when restore reads and expired when it merges gives way to the stored cutoff (the load is gated, not slept; fails if restore merges at the pre-read time); - the Redis merge matches `DenyEntry::merge` for whole-over-cutoff, cutoff-over-whole, two cutoffs under a shorter or longer `until`, and an expired whole key (fails if a whole-key write stops clearing the cutoff); - pruning clears an expired entry's cutoff, from a fixture seeded already expired in one atomic step; - a same-`until` scope widening is `Merged`, not `Unchanged` (fails if the change test compares `until` only); - a cutoff that isn't an integer, is out of range or has no deny fails the restore as `unreadable`; - a malformed cutoff leaves its deny restorable as the whole key, an orphan cutoff adds nothing, and a good cutoff still scopes its key, while the load still fails as `unreadable`; - a disconnect over a complete active deny whose stored cutoff is fractional or out of range fails with the claim unused and the index (with scores), exact and cutoff hashes unchanged (fails with the accept script's check removed); the script's bounds are pinned to chrono's range. - through the real Redis load and restore, a readable deny next to a bad record keeps its cutoff: a session issued at C is closed, one issued after C stays open, and admission stays fenced (fails if the partial payload drops scope). --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> |
||
|
|
c0932db19c |
fix(relay): persist NIP-FI revocations across restarts and bridge shadow to enforce (#9860)
## Summary Stack: this PR → #9917 NIP-FI revocations (deny entries from `POST /api/nip-fi/disconnect`) now survive relay restarts and lost pub/sub subscriptions, and an enforce relay can optionally carry over revocations accepted during the `shadow` period. ## Changes - **Durable deny store (Redis).** Per mode and issuer hash, a sorted set (score = `until` in ms, rounded up) plus a hash holding the exact signed `until`, merged by maximum. One Lua script runs all checks before any write: replay → expiry/capacity → write. Outcomes: claimed, replay (403), full (503, nothing written). Every write and prune also clears the target's field in the issuer's revoke-through cutoff hash, so a full revoke is never narrowed by a cutoff a newer relay version stored. A Redis error is an unknown outcome (503); the issuer sends a fresh command. - **Shared capacity.** `deny_set_capacity` is enforced in Redis, across pods. - **Fail-closed restore.** A pod starts closed to protected admission, refusing as authorization unavailable (HTTP 503 and the matching Nostr denial on root and audio AUTH; `shadow` records it as unavailable). Active deny entries still refuse with 403. Each key's verdict (allowed, denied, unavailable) comes from one read of the deny map, so a restore that starts mid-check is never reported as a revocation. A single consumer task restores by generation: wait for a confirmed subscription, load the stores, apply buffered messages, then reopen. A reconnect, a lag, or a received deny that does not fit the local capacity starts a new generation, so admission reopens only once the active union fits. A restore merges every stored entry first, then closes sessions only for targets it added or extended (also when it fails part-way; a capacity miss or a store error for one issuer or source doesn't end the pass, so every reachable target is still merged or closed and the first failure keeps admission closed), so restoring after a Redis blip doesn't walk every connection once per entry. While a restore keeps failing, the consumer still applies disconnects that arrive, so revoked sessions close while admission stays closed; the retry runs on a fixed one-second deadline that traffic can't push back. A stored deny record that doesn't parse fails the restore rather than being skipped; the issuer's other records are still applied and their sessions closed. Restore failures are counted in `buzz_nip_fi_deny_restore_failures_total{reason}`; a stored record that doesn't decode is counted as `reason="unreadable"`, apart from `store` (Redis unavailable). - **Bridge setting.** `BUZZ_NIP_FI_ACCEPT_SHADOW_DISCONNECTS` (default false, enforce only) makes an enforce pod also subscribe to the shadow channel and restore the shadow store. - **NIP-FI spec.** Restart behaviour now allows shared storage that is restored before protected connections or HTTP requests are admitted. Disconnects document the unknown-outcome reply: when a relay can't tell whether its shared-storage write applied, it returns `503` `authorization unavailable` and closes no sessions, and the caller retries with a freshly signed command (new `jti`). Added to the step 7 pseudocode, the disconnect response table and the `authorization_unavailable` rejection row. - **Runbook.** New "Revocation during a deploy" section in `docs/operator-nip-fi-bindings.md`: coverage (restarts, not lost Redis data), non-evicting Redis, disconnect responses, capacity, boot behaviour when Redis is unreachable, recovering from an unreadable deny record (`HDEL`), and the shadow → enforce rollout steps. ## Tests - Restart restores denies from the shared store; unavailable store keeps admission closed; consumer reopens only for a live, restored subscription. - Store error returns 503 and the command retries; lost reply returns 503 and needs a fresh command. - Capacity enforced across pods; over-capacity restore stays closed; a capacity miss during the restore handoff or after a successful restore keeps or closes admission. - A restoring deny map refuses as unavailable (503 / bare close), not revoked, at each admission point: WebSocket upgrade, protected HTTP, root AUTH and audio, and when the restore starts during the check. - Restore closes only added or extended targets, still closes them when it fails part-way (a capacity miss, a failing source before a healthy one, and the first-visited issuer failing before a healthy one, and an unreadable record reported as `unreadable`, not `store`), and live delivery of an unchanged entry still closes sessions. A broadcast lag after a restore restores again. During repeated restore failures, delivered disconnects still close their sessions, admission stays closed, and steady traffic doesn't delay the next attempt (run on a paused Tokio clock). - The buzz-pubsub deny-store key and rounding unit tests now run in `just test-unit` and `run-tests.sh`. - Subscribe channels and restore sources follow mode and bridge; config rejects the bridge outside enforce. - Redis-backed (ignored, run in CI's NIP-FI Redis step; each case uses its own store namespace): script checks before writing and keeps exact `until`; expired entries free their slot and a shorter command never lowers a score (`ZADD GT`); bridge restores shadow-period denies on enforce pods; a record with an unreadable key or `until` fails the load while every readable active record after it still loads, and expired entries are still filtered; restore applies a good record past a bad one for the same issuer, closing its sessions and leaving others open, fails as `unreadable` with admission unavailable, and reopens on retry once the record is removed (fixture hashes expire after 60s); an accept with an equal or shorter `until`, and a prune, clear the target's stored cutoff. --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> Co-authored-by: wpfleger <wpfleger@users.noreply.github.com> |
||
|
|
2cd40badb8 |
Manage community NIP-FI policy with enable, disable and status (#9176)
## Summary Operators can enable, disable and inspect a community's stored NIP-FI requirement through signed POST/GET `/operator/communities/nip-fi-policy` and `buzz-admin nip-fi-policy`. This replaces the old enable-only endpoint and drops the `nip-fi-upgrade` command added earlier in this PR, along with obsolete compatibility code. Each saved intent binds its desired state and observed generation/state. Every accepted new intent advances the generation, including same-state changes. Committed retries recover history without reapplying policy; stale requests are refused. Current status exposes one pair of reusable `expected_*` preconditions. Historical receipts remain readable after policy changes or target deletion, including old rows with null preconditions. Their UUIDs cannot be reused for new requests. Migration 0085 stays additive; main’s default-channel recovery migration retains version 0084. It preserves old receipt rows and INSERT compatibility. Operator instructions cover use, recovery and client migration: [usage guide]( |
||
|
|
446e9e0762 |
Allow operators to set initial NIP-FI policy on create (#9211)
Trusted operators can choose `initial_requires_nip_fi` on create-only community provisioning. True commits required policy (generation 1), validated issuer bindings and the owner with the new community in one transaction. Omitted, null or false preserves optional creation; a non-null field in legacy ensure mode returns coded 400. Missing effective bindings refuses required insertion without leaving a row. The response reports policy read from the stored row. Same-owner create-only replay now accurately reports `existed` instead of `created`; it stays successful and read-only, including after policy disable or issuer-config changes. Different-owner conflict, legacy ensure, bootstrap and the operator authorization gate retain their behavior. This adds no schema changes or server-wide default flag. Upgrade the whole serving relay fleet before callers request true. An old writer may ignore the field and insert an optional row: response checks detect it but cannot undo it, and later lookup remains read-only. Turn caller targeting off before relay rollback. Mode off stores policy but bypasses enforcement, independently of the upgrade gate. ### Related issue Replaces closed #9172. The separate lifecycle API remains in #9176. ### Validation Draft head: `bf16a1e0aba102c3be86f9621bd53d2cae98661c`. Independent source review covers this head. Formatting, diff sanity, Clippy, build, all 14 signed HTTP scenarios and full local `just ci` pass at this head. GitHub reports 59 successful and 38 skipped checks, with none pending or failing in the collected snapshot. At parent `b9d9423a6058387f42c310f5a7e4dbe0c8d8b40f`, all 1,978 package tests and 1,346 PostgreSQL tests passed (PostgreSQL concurrency 2). Four deliberate mutations were detected and restored. Clippy then found seven needless borrows in the new HTTP test; this head removes those borrows only. Earlier validation passed 1,344/1,346 PostgreSQL tests at concurrency 8; the replay assertion was corrected and the timeout disappeared at concurrency 2. Failed-run evidence is retained. At this head, the first mandatory push-hook attempt failed all nine boot-lifecycle tests on child startup deadlines. A subsequent serial run passed all nine (seven PostgreSQL-only cases skipped), with unchanged deadlines and source. The first diagnostic was interrupted during compilation without a result; all evidence is retained. A normal-hook retry was stopped when the author explicitly authorized one push with `--no-verify` for this exact commit. That exception skips local pre-push hooks for publication only; failed hooks and remaining validation still gate readiness. Explicit human runtime confirmation remains a separate acceptance step; agents have not attested it. Generated with Codex Validation update at the same draft head: Clippy, build and all 14 signed HTTP workflow scenarios passed, including atomic required creation, stored-policy replay after disable without a current binding, and refusal without leaving a row. The first live harness run stopped after 12 checks because its SQL helper fetched rows after an UPDATE without RETURNING; that harness query was corrected and the complete workflow passed. Relay source stayed unchanged. The full local `just ci` run failed in `mobile-check`: Dart formatting reported 266 changes among 1,068 files, with unresolved `flutter_lints` configuration warnings. The format check used `--output=none`; the worktree remains clean. Repository validation is therefore not green. That failure is retained as historical evidence; see the successful setup-corrected rerun below. Explicit human runtime confirmation remains separate. Final local validation: after `just mobile-install`, `mobile-check` passed without formatting edits, and full `just ci` completed successfully at `bf16a1e0aba102c3be86f9621bd53d2cae98661c`. Tracked files remained clean after installation and after the complete run. This confirms the earlier mobile formatting failure resulted from missing worktree dependencies. All failed runs remain preserved. GitHub's current ready-for-review state is preserved; no agent added `buzz-review-completed` or attested human runtime acceptance. --------- Signed-off-by: Brad Seiler <seiler@squareup.com> Co-authored-by: Honor <e0bf479eeebe47dde1e35705212a4df70616a7bc834d907ddfb18cf0405f8b1b@buzz.block.builderlab.xyz> Co-authored-by: Honor <e0bf479eeebe47dde1e35705212a4df70616a7bc834d907ddfb18cf0405f8b1b@seiler-test.communities.public.builderlabstaging.xyz> |
||
|
|
a1f79e3aba |
feat(relay): persist NIP-FI upgrades (BUZZ-510) (#8985)
## Summary Record that a community requires NIP-FI and provide an idempotent operator API to enable it and recover the original receipt. Acceptance checks the current owner, host, lifecycle and existing issuer trust in one transaction. It never creates trust. Receipts survive community deletion so an operation UUID cannot be reused. New acceptances default to disabled through `BUZZ_NIP_FI_UPGRADES_ENABLED`. Disabled calls return HTTP 503 `upgrades_disabled`; identical retries and authenticated readback still recover existing receipts. Policy is permanent: stopping new calls or rolling back code does not clear it. Last-issuer removal is refused for required communities, and bulk backfill leaves missing bindings for explicit operator repair. Apply additive migration 0082 before code. Existing communities remain optional. This layer records acceptance and reports only `pending` or `unavailable`; deploy and verify [per-request enforcement](https://github.com/block/buzz/pull/8988) and [session activation](https://github.com/block/buzz/pull/8991) before enabling acceptance. The global enforce floor remains. See [the operator contract](https://github.com/block/buzz/blob/seiler/BUZZ-510/relay-auth-upgrade/docs/community-auth-upgrades.md) for signing, recovery and containment. ### Related issue [BUZZ-510](https://linear.app/squareup/issue/BUZZ-510/relay-persist-community-nip-fi-requirements-and-expose-idempotent). Base of native stack `8989`; retains trunk's enforcement telemetry from [#8974](https://github.com/block/buzz/pull/8974). Includes a separate commit that repairs an observer timing flake in a desktop test required by the repository gate. ### Testing Controlled local regressions detect the old disabled error code and removal of the last issuer with `allow_last=true`; intended source is restored. Full PostgreSQL validation and the updated live relay/admin exercise remain pending. Human acceptance remains open. No deployment or production activation. Generated with Codex --------- Signed-off-by: Brad Seiler <seiler@squareup.com> Co-authored-by: Honor <e0bf479eeebe47dde1e35705212a4df70616a7bc834d907ddfb18cf0405f8b1b@seiler-test.communities.public.builderlabstaging.xyz> |
||
|
|
369ffa0380 |
feat(relay): verify NIP-FI agent tokens and admit agents through owners (#8401)
The relay side of NIP-FI agent tokens. An agent token has its own type, `nip-fi-agent+jwt`, and carries its human owner's pubkey in `nostr_owner_pubkey`. This PR verifies that claim, makes denying or disconnecting the owner cut off every agent that owner authorized, and makes the verified owner decide community admission. A relay without agent support refuses the unknown type, so nothing needs to advertise or configure agent support. The `NIP-FI.md` text for the agent type is included. Builds on #8372 and #8377 (both merged). ### Owner claim and owner deny - **Token type binds the owner claim (`buzz-auth`).** A `DedicatedNipFi` issuer policy accepts `nip-fi+jwt` (human) and `nip-fi-agent+jwt` (agent); `AccessTokenAtJwt` policies stay `at+jwt`-only with their `client_id` and subject rules unchanged, and unknown types are refused. An agent token must carry a lowercase-hex `nostr_owner_pubkey` distinct from its `nostr_pubkey`; a human or `at+jwt` token carrying the claim with any value, including null, is `evidence_rejected`. The verified owner is exposed as `VerifiedAssertion::owner()`. - **No agent switch.** There is no relay setting, NIP-11 field or operator binding field for agent support. - **Session owner.** Each connection records its NIP-FI issuer and the agent's owner (`NipFiSession`) on the root WebSocket manager and the audio registry. `disconnect_nip_fi(iss, target)` closes a connection when either its own key or its recorded owner equals the target. - **Owner deny check.** `nip_fi_core::assertion_denied` checks the deny set for both `(iss, k)` and `(iss, owner)`, and every existing deny check uses it: WebSocket before upgrade and after registration, HTTP, audio, and the shadow observer, so shadow and enforce make the same decisions. The shadow disconnect observer matches a session's key or owner under its issuer with the same rule, so an owner's disconnect records a would-close for its agents. ### Shadow owner check In shadow mode, WebSocket AUTH, audio join and HTTP admission record a `Stage::Owner` verdict when an admitted agent token's owner is banned (`owner/denied`), conflicts with the agent's stored owner (`owner/denied`), or cannot be checked because a read failed (`owner/unavailable`). These are reads only; shadow admission is unchanged. Shadow applies the same stored-owner rule as enforce but never writes the link, so it can't predict a later owner-link write failure, or which of two racing first links wins. ### Admission through the verified owner - **Owner bans, unconditionally.** `community_ban_outcome` takes the token owner and checks its ban in place of a NIP-OA owner. That applies whether the agent is a member itself, the relay is open, or the agent is admitted through its owner. - **Owner-derived membership.** In `api::relay_members::check_membership`, an agent that is a member itself is still admitted first. Otherwise, when a verified assertion names an owner, the owner's membership decides (`MembershipDecision::ViaOwner`), and no NIP-OA is needed on the connection. The issuer has already passed this community's NIP-FI binding check at that point. When a token owner is present it is the only owner considered. - **Stored-owner consistency.** `link_agent_owner` replaces the boolean `materialize_nip_oa_owner` result with `OwnerLink::{Linked, Conflict, Unavailable}`. An unset stored owner is recorded, so relay bans and roster removal of the owner reach the agent through `revoke_live_access`. Shadow and enforce judge the stored owner through one read, `stored_owner_link`, and `link_agent_owner` writes (atomically, first write wins) only when that read finds no owner; a failed read fails closed. If the stored owner differs from the token owner, the request is refused with `authorization denied` on HTTP, WS and audio. A NIP-OA owner conflict keeps its existing link-error refusal. - **One decision on every surface.** Root WS AUTH, audio registration and every NIP-98 HTTP route (bridge, `buzz/v1`, git transport and settings, invites, media, workflows, moderation reads) pass `NipFiAdmission::token_owner()` / `VerifiedAssertion::owner()` into the same ban, membership and owner-link steps. The final socket check rereads bans and writer-side membership; it doesn't reread the owner link, which is written once from NULL. HTTP membership still goes through the bounded replica read. With a verified agent token, every HTTP admission refusal, including the fresh ban rereads in `buzz/v1` and Git settings, is NIP-FI's fixed `authorization_denied` (or `authorization_unavailable` when a dependency fails), and audio checks bans before writing the owner link. `enforce_relay_membership` now takes the `TenantContext`, because it writes the owner link. - **Publishing.** A ban caught while publishing over `POST /events` after the shared membership check is also an admission refusal. Ingest reports it as a typed `IngestError::Ban` (banned, or ban lookup unavailable) at the write gate, the HTTP typing indicator's cached gate, and the moderation and relay-admin command rereads. `IngestError::Ban` carries the legacy error. The bridge turns it into the fixed `authorization denied` / `authorization unavailable` only when the request carries a verified agent token. WebSocket and token-less HTTP responses are byte-for-byte unchanged, and timeouts, scopes, permissions and every other ingest error keep their existing responses. ### Rollout - **Deploy the relay before kgoose.** An older relay refuses `nip-fi-agent+jwt`, so agents are locked out until both are deployed. Humans are unaffected. - **There is no agent-only switch.** Setting NIP-FI to shadow or off turns it off for humans too. - **Rollback is safe for owner links.** Stored owner links survive a rollback, and the older code still honors them. - **Shadow signals:** in `buzz_nip_fi_shadow_total`, `stage="owner"` means an owner would-deny (`owner/denied`) or an owner read that was unavailable (`owner/unavailable`), not a success. A clean agent admission shows as `stage="admit", outcome="admit"`. - **The relay checks that the owner is a member, not which issuer the owner logged in through.** In a community that trusts several issuers, any trusted issuer can name any member as owner. That matches the spec: the issuer is trusted to vouch for the owner, and kgoose requires the owner's attestation. Agent tokens are only issued to relays whose NIP-FI binding trusts the issuer, and NIP-FI itself is off unless configured. No deployed config or secrets change. --------- Signed-off-by: Will Pfleger <pfleger.will@gmail.com> Signed-off-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> |
||
|
|
5b433d9292 |
feat(relay): resolve NIP-FI issuer bindings from the database (#8377)
Stack: #8372 (merged) → this PR → #8399 → #8401 Makes relay login checks read the per-community NIP-FI issuer bindings that #8372 stores. Without this, the relay can't keep up with bb-public, where new communities are created at every signup and a static `BUZZ_NIP_FI_COMMUNITIES` list won't do. **Source switch.** `BUZZ_NIP_FI_COMMUNITY_SOURCE=database` resolves each community's trusted issuers from `community_nip_fi_issuers`, filtered by the issuer registry, instead of the static list. Each community gets its own policy ID: the base ID no longer hashes every community audience, and the final ID hashes the base plus this community's audience, so policy IDs change once (see `docs/operator-nip-fi-bindings.md`). `Config::from_env` refuses to start, in every mode, on an unknown source, on `database` together with `BUZZ_NIP_FI_COMMUNITIES`, and on `database` without `BUZZ_NIP_FI_PROVISION_BINDING`. `BUZZ_NIP_FI_RESOLVER_*` and `BUZZ_NIP_FI_SNAPSHOT_*` are validated in every mode, so a bad value fails the deploy that sets it. In `off` mode no resolver is built and no snapshot is loaded. **Resolver (`nip_fi_resolver.rs`).** - **Snapshot:** each pod loads every binding into memory, capped at `BUZZ_NIP_FI_SNAPSHOT_MAX_ROWS` (going over is a failed load). It refreshes every 30 s, start to start, with jitter that only shortens the delay and backoff after failures. Each attempt is limited by `BUZZ_NIP_FI_SNAPSHOT_REFRESH_TIMEOUT_MS`, which must be shorter than the interval. A refresh whose deadline passes before it publishes publishes nothing. The old snapshot is dropped off the runtime. - **Freshness:** a host in a snapshot loaded under two minutes ago is answered from memory. Any other host, and every host once the snapshot is stale, goes to a live lookup. Every answer carries a deadline two minutes after the read behind it started, and WS, HTTP and audio recheck it just before admitting. - **Live lookups:** bounded and single-flight. In-flight lookups are capped by `BUZZ_NIP_FI_RESOLVER_MAX_INFLIGHT` (default 8, clamped below the database pool size), and the pending hosts and their waiters have fixed caps. Positive answers are used for that admission only. A "not found" is cached for 5 s, up to `BUZZ_NIP_FI_RESOLVER_NEGATIVE_CACHE_MAX` hosts, and only when no snapshot was published and no binding was created while it ran. A lookup that panics still leaves the pending map. - **Removal:** a removed binding stops admitting new connections within 30 s plus the refresh timeout (40 s by default) while refreshes succeed, and within two minutes of the last good load while they fail. Open WebSocket sessions are not rechecked when a binding is removed; they end at their own session deadline. **Shadow mode** resolves through the same path as enforce, including the database lookup and the freshness rules. It keeps the resolved binding's deadline and checks it at the same point as enforce; a binding that goes stale during the tenant lookup is recorded as `stage=deadline, outcome=unavailable`, without changing the legacy response or closing the socket. With `source=database` its `community` metric label is only `bound` or `unmapped`; with `source=env` it keeps the existing per-community audience label, so current shadow dashboards are unchanged. Each request resolves its Host once: the router guard's resolution, failures included, is reused by shadow recording and admission. **Provisioning.** Both operator provisioning paths drop this pod's cached "not found" for the new host after a commit that bound issuers, so the creator's first login looks it up. **Startup and readiness.** With `source=database` and a mode other than `off`, the first snapshot loads before any listener binds, under its own startup phase `nip_fi_snapshot_load`. A failed load exits non-zero, so a pod is never ready without a snapshot. **Operational consequence:** boot already fails when the database is unreachable; what is new is that a snapshot over `BUZZ_NIP_FI_SNAPSHOT_MAX_ROWS` or a load past its timeout also crash-loops new pods. After two minutes the old pods' snapshots go stale and most logins fall through to the 8-slot live lookup, which sheds the rest with 503. The way out is raising the cap or timeout, or `mode=off`. **Metrics.** `buzz_nip_fi_binding_snapshot_*` covers loads, failures, rows and freshness. `buzz_nip_fi_binding_snapshot_loaded_timestamp_seconds` is written on every refresh attempt, so alert on `time() - x > 120` together with `absent(x)`. `buzz_nip_fi_binding_snapshot_rows` against `buzz_nip_fi_binding_snapshot_max_rows` gives the headroom to the row cap. `buzz_nip_fi_resolver_*` covers live lookups and the negative cache. The env vars and alerts are documented in `.env.example`, the chart README and `docs/operator-nip-fi-bindings.md`, which also has the staged off → shadow → enforce rollout for `source=database` with go/no-go signals at each step, and the over-cap and load-timeout failure modes with their ways out. **Regression coverage.** Router-level tests run the database resolver through the real `build_router` for root WS, audio and protected HTTP, in enforce and shadow mode. Over PostgreSQL and Redis, two pods using the env community source (two exact bindings) replay assertions retained from before a disconnect through a real root NIP-42 session, the audio deny-set check and signed NIP-98 requests: they are denied on both pods, and a root session upgraded before the disconnect is refused by the post-registration deny-set check. Postgres tests in `buzz-db` check that archived and quiescing communities, and issuers missing from the registry, never reach the snapshot or the live lookup. Process-level `boot_lifecycle` tests spawn the real relay with `source=database`: an over-cap or timed-out startup load exits non-zero with no health listener bound, and a loadable snapshot lets readiness turn ready. --------- Signed-off-by: Will Pfleger <pfleger.will@gmail.com> Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> |
||
|
|
6286a54321 |
feat(relay): store per-community NIP-FI issuer bindings (#8372)
Stack: this PR → #8377 → #8399 → #8401 bb-public creates communities all the time, so a hand-edited `BUZZ_NIP_FI_COMMUNITIES` map can't list them. This PR stores an explicit NIP-FI issuer allowlist for each community in the database and writes it when the community is created. Login checks don't read the table yet; that comes in #8377 together with the database-backed resolver. Operator steps are in [`docs/operator-nip-fi-bindings.md`](docs/operator-nip-fi-bindings.md). **Storage.** Migration `0066_community_nip_fi_issuers` adds `community_nip_fi_issuers (community_id, issuer, created_at)`, with primary key `(community_id, issuer)` and the community write fence attached. The assertion audience is `https://<communities.host>`, so the table has no `aud` column. Zero rows means no binding. The table is included in whole-community deletion and purge. **One bindable rule.** `BUZZ_NIP_FI_PROVISION_BINDING` (`{"host_suffix": ..., "authorized_issuers": [...]}`) is parsed in `buzz-auth` with `BUZZ_NIP_FI_ISSUERS`, whatever `BUZZ_NIP_FI_MODE` is set to, and both the relay and `buzz-admin` use the same parser. Each authorized issuer must be a configured issuer (1 to 2048 bytes), and the suffix must not cover any host declared in `BUZZ_NIP_FI_COMMUNITIES`; an unreadable declaration refuses startup even in mode `off`. `ProvisionBindingPolicy::is_bindable(host)` is true for a host exactly one label under the suffix that is not reserved. It decides creation-time binding, explicit `bind`, and what the lookup route reports. **Binding on creation.** Rows are written in the same transaction as the community insert on all three creation paths (`POST /operator/communities` `create_only`, its legacy convergence branch, and startup bootstrap), and only when the call actually created the community, so existing rows are never rewritten. **Reserved host.** A host whose `https://<host>` equals a configured `command_audiences` value never holds a binding. Operator provisioning of it is rejected with a 400 and the `reserved_host` error code, bootstrap creates it unbound, and the availability route reports it unavailable with an error code. `main.rs` calls `verify_reserved_hosts_unbound` at startup; if a reserved host has rows the relay refuses to start and names the fix (`buzz-admin nip-fi unbind --host <h> --issuer <i>`, or revert the command audience). A database failure during that check is a separate `Check` error. **Operator commands.** - `buzz-admin nip-fi backfill` pages unbound communities by host (1000 per page) and binds each page with one `INSERT ... SELECT` limited to active communities. It skips communities being deleted, always prints `{rows_bound, unbound, unbound_hosts, truncated}`, and exits non-zero while any bindable community is still unbound. Archived communities are bound on purpose. Both bind paths take the shared deletion lock and then lock the community row (`FOR NO KEY UPDATE`, in id order for a batch), the same order deletion uses, and the backfill insert also requires the community to still have no binding, so an operator `bind` that lands after the backfill listed a community wins and the default issuer is not added beside it. - `buzz-admin nip-fi bind --host --issuer` refuses a reserved host, a host outside the suffix, or an unconfigured issuer. - `buzz-admin nip-fi unbind --host --issuer` refuses to remove a community's last issuer (archive or delete the community instead), with one exception: when a valid provisioning policy shows that backfill can't bind the host (it's reserved, or outside the suffix), the last issuer can be removed. That is the reserved-host recovery path in the runbook. A missing or malformed policy doesn't block `unbind`; it just means the exception never applies. **Lookup route.** `GET /operator/communities/nip-fi-binding?host=` (NIP-98, `RELAY_OPERATOR_PUBKEYS`) reads the database and returns `{host, active, issuers[]}`. `host` is the stored host. It returns 404 for an unknown host, 200 with `active:false` for an archived or quiescing community, and `issuers:[]` when no provisioning policy is set. It lists only issuers that are configured and on a bindable host. kgoose depends on this contract; it is also documented in the runbook. **NIP-FA.** The `relay_url` bullet now also says: "An adapter MAY obtain its exact relay list from a configured, authenticated source; it MUST still compare `relay_url` exactly." **Deployment dependency.** The kgoose config side is already handled by [cash-server#137671](https://github.com/squareup/cash-server/pull/137671). In public-community mode it requires the command audience not to be a community audience. --------- Signed-off-by: Will Pfleger <pfleger.will@gmail.com> Signed-off-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> |