mirror of
https://github.com/block/buzz.git
synced 2026-11-28 04:01:45 +00:00
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>
This commit is contained in:
@@ -110,7 +110,8 @@ policy operation. This removal does not erase receipts or rewrite schema.
|
||||
|
||||
## Request enforcement and discovery
|
||||
|
||||
`off` ignores stored requirements; `shadow` enforces stored true; `enforce` is a
|
||||
`off` ignores stored requirements; `shadow` enforces stored true and communities inside the
|
||||
`BUZZ_NIP_FI_ENFORCE_PERCENT` cohort; `enforce` is a
|
||||
global requirement floor; `deny_protected` denies protected traffic. Report
|
||||
`effective_required` alongside stored state so disable under enforce and enable
|
||||
under off cannot be mistaken for effective changes. Evaluating policy lookups
|
||||
@@ -125,9 +126,12 @@ lease after disable. It cannot renew that stale lease. `/info` advertises effect
|
||||
### Existing connections
|
||||
|
||||
The periodic revalidator reads stored policy without row-locking transactions.
|
||||
After disable it stops requesting required-policy closes; a concurrent sweep may
|
||||
request one last non-FI close from its earlier snapshot. That client reconnects
|
||||
under optional policy. FI-admitted sockets retain their finite lifetime and then
|
||||
When disable makes the effective policy optional, it stops requesting
|
||||
required-policy closes; a concurrent sweep may request one last non-FI close from
|
||||
its earlier snapshot. That client reconnects under optional policy. A community
|
||||
inside the `BUZZ_NIP_FI_ENFORCE_PERCENT` cohort, or any community under global
|
||||
`enforce`, stays required: its non-FI sockets keep closing on revalidation, and
|
||||
reconnects still need FI. FI-admitted sockets retain their finite lifetime and then
|
||||
reconnect under current policy. Disable does not reopen or force-logout sessions.
|
||||
Re-enable repeats the optional-lease drain; non-FI root/audio sockets close through
|
||||
existing revalidation. Valid FI-admitted sockets retain existing rules.
|
||||
|
||||
@@ -40,7 +40,7 @@ Conformance obligations:
|
||||
| Surface | Today's observable behavior | Tenant source | Community-global vs operator-global | Required DB/index/RLS scope | Auth/fan-out/search effects | Single-community compatibility check | Open decision/test |
|
||||
|---|---|---|---|---|---|---|---|
|
||||
| Row zero: host binding | A user connects to one relay URL and all state they can observe belongs to that relay. | `resolve_host(connection.host)` before handler entry. | Community-global selector; operator only manages the host map. | `communities(host, id, signing_key, …)`; every scoped table references immutable `community_id`. | All auth, event, REST, media, git, search, pub/sub, and workflow paths consume `TenantContext`; host/token mismatch rejects generically. | One host maps to the default community; no client-visible protocol field changes. | Add model/prose gate that `ctx.community` is derived from host, not supplied by the client. |
|
||||
| NIP-11 relay info and relay `self` | `GET /`/`/info` returns one relay info document; `RelayInfo::build` advertises static NIPs, a stable relay signing pubkey when configured, the community's workspace icon (NIP-WP), host-specific `requires_nip_fi` and compatible FI capability fields, and the config-derived `buzz-gif` descriptor when GIF search is configured. | Host-derived community for community-specific facts; host policy is read from the primary by normalized Host (unknown/non-serving host → generic 404, unavailable policy → 503); optional workspace `icon` is pre-fetched as a scalar via `bind_community`; GIF provider availability is passed as a credential-free config scalar; no other DB lookup from unauthenticated global state unless explicitly through `TenantContext`. | NIP-11 is community-global. Operator-global software/version and GIF provider configuration may be shared; relay `self` for group/system/audit signing is per-community; `icon` is per-community intentionally-public presentation. | `communities.signing_key` or equivalent per-community signing material; no platform-global `self` for tenant-observable system events. | Unauthenticated reads must not become enumeration oracles for other communities: host-specific fields reveal only the requesting host's public icon, requirement and capabilities, never a neighboring community's facts. Discovery is no-store. The GIF descriptor reveals provider availability but never its credential; NIP-43 advertisement reflects membership enforcement for that community only. | One community retains existing capability/descriptor semantics; the additive requirement boolean reflects stored policy OR global enforce. | Signature/static-input lint remains: `RelayInfo::build` must not grow unscoped DB/search/audit inputs — host-scoped or config-derived scalars (like `icon`, pairing URL, and GIF provider) are passed in pre-derived. |
|
||||
| NIP-11 relay info and relay `self` | `GET /`/`/info` returns one relay info document; `RelayInfo::build` advertises static NIPs, a stable relay signing pubkey when configured, the community's workspace icon (NIP-WP), host-specific `requires_nip_fi` and compatible FI capability fields, and the config-derived `buzz-gif` descriptor when GIF search is configured. | Host-derived community for community-specific facts; host policy is read from the primary by normalized Host (unknown/non-serving host → generic 404, unavailable policy → 503); optional workspace `icon` is pre-fetched as a scalar via `bind_community`; GIF provider availability is passed as a credential-free config scalar; no other DB lookup from unauthenticated global state unless explicitly through `TenantContext`. | NIP-11 is community-global. Operator-global software/version and GIF provider configuration may be shared; relay `self` for group/system/audit signing is per-community; `icon` is per-community intentionally-public presentation. | `communities.signing_key` or equivalent per-community signing material; no platform-global `self` for tenant-observable system events. | Unauthenticated reads must not become enumeration oracles for other communities: host-specific fields reveal only the requesting host's public icon, requirement and capabilities, never a neighboring community's facts. Discovery is no-store. The GIF descriptor reveals provider availability but never its credential; NIP-43 advertisement reflects membership enforcement for that community only. | One community retains existing capability/descriptor semantics; the additive requirement boolean reflects stored policy OR global enforce OR, in `shadow`, membership in the `BUZZ_NIP_FI_ENFORCE_PERCENT` cohort. | Signature/static-input lint remains: `RelayInfo::build` must not grow unscoped DB/search/audit inputs — host-scoped or config-derived scalars (like `icon`, pairing URL, and GIF provider) are passed in pre-derived. |
|
||||
| API tokens and NIP-98 replay | API/NIP-98 clients authenticate REST/media/git; API tokens may carry scopes and channel IDs; NIP-98 replay uses an in-process seen-set today. | Host-derived community plus token's stamped community; stamps must agree. | Community-global token namespace; operator-global only for deployment health/secrets. | `api_tokens` gains `community_id`; token hash uniqueness and lookup are `(community_id, token_hash)` or the token cryptographically embeds community and lookup verifies both. Channel claims must reference channels in the same community. | Replay seen-set key is `(community_id, event_id)` in shared HA storage or equivalent sticky routing; NIP-98 `u` URL host must match `req.community`. | Existing single-community tokens continue to authorize the same scopes/channels after backfill to default community. | HA gate: Redis/shared seen-set with atomic insert-if-absent and TTL ≥ replay window, or documented single-replica/sticky alternative. |
|
||||
| Relay membership, pubkey allowlist, archived identities | `relay_members`, `pubkey_allowlist`, and `archived_identities` are relay-global gates over pubkeys. | Host-derived community for tenant access; operator context only for platform administration. | Community-global membership/allowlist/archive by default. Operator-global only for explicit platform ops tables that are never tenant-observable. | Add `community_id` to these tables; primary/unique keys become `(community_id, pubkey)` and indexes include `community_id`. | Membership errors remain generic. NIP-OA owner checks test owner membership in the same community. Identity archive requests cannot hide/archive a key in another community. | One default community preserves today's closed/open relay behavior and admin CLI semantics after commands target the default community. | Decide any future operator-global super-admin surface separately; do not reuse tenant membership tables for it. |
|
||||
| Users, profiles, NIP-05, and user search | Kind:0 updates sync a `users` row; NIP-05 handles are unique; `/api/users/search` searches display name/NIP-05/pubkey. | Channel-less events use `req.community`; NIP-05 domain is the connected community host. | Community-global. Same pubkey can have one profile per community; users repost kind:0 in each community they join. | `users` gains `community_id`; keys/uniques are `(community_id, pubkey)`, `(community_id, lower(nip05_handle))`, and `(community_id, okta_user_id)` where applicable. Profile event replacement is scoped by `(community_id, pubkey)`. | Search and batch profile reads include `community_id`; NIP-05 lookup only resolves handles for the requested host/community. No cross-community profile inheritance. | Existing users backfill into the default community; profile APIs and CLI output stay unchanged. | Add tests for same pubkey with different profile/NIP-05 in two communities and for NIP-05 same local part on two hosts. |
|
||||
|
||||
@@ -983,10 +983,10 @@ A relay SHOULD advertise core support in NIP-11 as:
|
||||
|
||||
A multi-community relay MAY additionally publish a host-specific top-level
|
||||
`requires_nip_fi` boolean. This expresses mandatory admission evidence, separately
|
||||
from support for the protocol. In Buzz it is the stored community requirement OR
|
||||
global enforce; capability is advertised when global mode evaluates OR that
|
||||
requirement is true. Required hosts therefore retain both existing capability
|
||||
fields and the descriptor above. Optional shadow hosts still advertise capability.
|
||||
from support for the protocol. Capability is advertised when the relay evaluates
|
||||
NIP-FI evidence for that host or the host requires it. Required hosts therefore
|
||||
retain both existing capability fields and the descriptor above; hosts that
|
||||
evaluate evidence without requiring it still advertise capability.
|
||||
Root NIP-11 and `/info` MUST agree and use `Cache-Control: no-store`. An unknown or
|
||||
non-serving Host returns generic 404; unavailable host policy returns 503.
|
||||
|
||||
|
||||
@@ -178,8 +178,9 @@ snapshot loads in `off`, but every `BUZZ_NIP_FI_RESOLVER_*` and
|
||||
|
||||
Set `BUZZ_NIP_FI_MODE=shadow`. Each pod now loads the snapshot before any
|
||||
listener binds, refreshes it every 30 s, and records what enforce would decide
|
||||
without refusing anything. Shadow labels database-source records
|
||||
`community="bound"` or `"unmapped"`, never a host.
|
||||
without refusing anything in communities whose effective policy is optional;
|
||||
stored-Required and cohort communities still enforce. Shadow labels
|
||||
database-source records `community="bound"` or `"unmapped"`, never a host.
|
||||
|
||||
- Go, held for at least a day of normal traffic:
|
||||
- `time() - buzz_nip_fi_binding_snapshot_loaded_timestamp_seconds` stays
|
||||
@@ -194,13 +195,71 @@ without refusing anything. Shadow labels database-source records
|
||||
for its token owner.
|
||||
- No-go: any of these fails. Return to `off` and investigate.
|
||||
|
||||
### Staged enforce
|
||||
|
||||
To enforce for a growing share of communities before switching the whole relay,
|
||||
keep `BUZZ_NIP_FI_MODE=shadow` and set `BUZZ_NIP_FI_ENFORCE_PERCENT`, an integer
|
||||
from 0 to 100 (default 0). It is read once at startup, so each change is a
|
||||
rollout; a malformed or out-of-range value refuses startup.
|
||||
|
||||
- It acts only in `shadow`. In `off` it has no effect, and `enforce` ignores it
|
||||
because every community already enforces.
|
||||
- A community stored as Optional enforces when its bucket is below the
|
||||
percentage. The bucket is the SHA-256 digest of the community UUID's 16
|
||||
RFC 4122 bytes, with the digest's first 8 bytes read as a big-endian `u64`,
|
||||
mod 100. The bucket never changes for a community, so raising the
|
||||
percentage only adds communities, and lowering it removes the most recently
|
||||
added ones.
|
||||
- A community stored as Required enforces at any percentage.
|
||||
- An enforcing community gets the same treatment as a stored-Required one:
|
||||
logins without valid evidence are refused, its NIP-11 document reports
|
||||
`requires_nip_fi: true`, and open sockets without valid evidence are closed.
|
||||
Its stored flag does not change.
|
||||
- A required admission, stored Required or inside the cohort, is refused when
|
||||
the receiving pod holds an active deny for the key. A revocation closes open
|
||||
connections only in `enforce`; in `shadow` an open connection stays until its
|
||||
deadline. Stored-Required communities already behave this way.
|
||||
- Denies are stored in Redis and restored on restart, but a healthy pod
|
||||
learns of new ones through best-effort pub/sub and can miss one. See
|
||||
[Revocation during a deploy](#revocation-during-a-deploy).
|
||||
|
||||
Raise the percentage in steps, holding each one for normal traffic.
|
||||
|
||||
- Go: the shadow signals keep holding, the `nip-fi enforce deny` lines on log
|
||||
target `buzz_relay::nip_fi_enforce` are only what you expect to deny, and
|
||||
login 503s stay at their shadow baseline.
|
||||
- No-go: set `BUZZ_NIP_FI_ENFORCE_PERCENT=0` and investigate.
|
||||
|
||||
A rollback is a full rollout too: pods run mixed percentages until it
|
||||
finishes. There is no per-community exemption, so removing one community
|
||||
means lowering the percentage to its bucket or below, which also drops every
|
||||
community in a higher bucket.
|
||||
|
||||
### Enforce
|
||||
|
||||
Set `BUZZ_NIP_FI_MODE=enforce`. Watch the same signals, plus the rate of 503
|
||||
responses on login.
|
||||
Set `BUZZ_NIP_FI_MODE=enforce` and leave `BUZZ_NIP_FI_ENFORCE_PERCENT` at 100.
|
||||
It has no effect in `enforce`. Follow
|
||||
[Switching shadow → enforce](#switching-shadow--enforce) so shadow-accepted
|
||||
disconnects carry over.
|
||||
Watch the same signals, plus the rate of 503 responses on login.
|
||||
|
||||
- Go: the shadow signals keep holding, and 503s stay at their shadow baseline.
|
||||
- No-go: logins return 503 or are refused unexpectedly. Set `mode=off` (below).
|
||||
- No-go: logins return 503 or are refused unexpectedly. Set `mode=shadow` and
|
||||
lower `BUZZ_NIP_FI_ENFORCE_PERCENT` to the last known-good value. A mode-only
|
||||
rollback at 100 still requires every community: it restores only the staged
|
||||
revocation behavior, not optional admission. Stored-Required communities stay
|
||||
required either way. Never roll back with `mode=off`: `off` also turns off
|
||||
stored-Required enforcement. In the same rollout, unset
|
||||
`BUZZ_NIP_FI_ACCEPT_SHADOW_DISCONNECTS` or set it to `false`: `true` is
|
||||
invalid in `shadow` and the pods refuse to start.
|
||||
|
||||
Shadow pods restore active denies from both stores. Those denies still
|
||||
reject admission for stored-Required and remaining cohort communities;
|
||||
optional communities only record the would-deny verdict. Shadow does not
|
||||
close existing sessions. When returning to `enforce`, set
|
||||
`BUZZ_NIP_FI_ACCEPT_SHADOW_DISCONNECTS=true` and follow
|
||||
[Switching shadow → enforce](#switching-shadow--enforce) again, measuring the
|
||||
bridge-retention interval from the latest shadow pods.
|
||||
|
||||
### Alerts
|
||||
|
||||
|
||||
@@ -67,12 +67,18 @@ read its status or retry that exact file. A committed replay never reapplies pol
|
||||
|
||||
Inspect `mode` and `effective_required` separately from the stored flag.
|
||||
`enforce` keeps FI required after disable; `off` suspends FI after enable.
|
||||
`shadow` follows the stored flag. An enable receipt remains pending even after
|
||||
local sweeps, since it cannot certify fleet-wide connection closure. Required
|
||||
host caches can over-restrict for their remaining one-second lease after disable.
|
||||
A racing sweep may close one last non-FI socket; it can reconnect under optional
|
||||
policy. FI-admitted sockets retain their finite deadline. Re-enable repeats the
|
||||
optional-lease drain and existing periodic revalidation.
|
||||
`shadow` follows the stored flag, and also requires FI for communities inside
|
||||
the `BUZZ_NIP_FI_ENFORCE_PERCENT` cohort; a stored disable does not take a
|
||||
community out of the cohort, only lowering the percentage does. An enable
|
||||
receipt remains pending even after local sweeps, since it cannot certify
|
||||
fleet-wide connection closure. Required host caches can over-restrict for their
|
||||
remaining one-second lease after disable. When the effective policy becomes
|
||||
optional, a racing sweep may close one last non-FI socket; it can reconnect
|
||||
under optional policy. A community inside the cohort, or any community under
|
||||
global `enforce`, stays required: its non-FI sockets keep closing on
|
||||
revalidation, and reconnects still need FI. FI-admitted sockets retain their
|
||||
finite deadline. Re-enable repeats the optional-lease drain and existing
|
||||
periodic revalidation.
|
||||
|
||||
The old `nip-fi-upgrade` command and endpoint are removed. Requests to that
|
||||
route now return 404. Recover historical receipts with `nip-fi-policy status
|
||||
|
||||
Reference in New Issue
Block a user