feat(relay): NIP-98 admin auth with Operator/Moderator roles and NIP-11 discovery - #3777
Open
wpfleger96 wants to merge 15 commits into
Open
feat(relay): NIP-98 admin auth with Operator/Moderator roles and NIP-11 discovery#3777wpfleger96 wants to merge 15 commits into
wpfleger96 wants to merge 15 commits into
Conversation
wpfleger96
force-pushed
the
wpfleger/admin-api-bearer-auth
branch
3 times, most recently
from
July 31, 2026 19:17
3fcbdc0 to
d014e40
Compare
kalvinnchau
previously approved these changes
Jul 31, 2026
kalvinnchau
left a comment
Contributor
There was a problem hiding this comment.
Re-reviewed at d014e40. The fail-closed config contract, constant-time bearer validation, host/origin ordering, insecure network-boundary mode, dashboard token lifecycle, authenticated attachment fetches, and CSP/static routing are coherent and covered. Deployment dependency is external: land bb-public#339 and wait for Argo rollout before deploying this relay image.
wpfleger96
force-pushed
the
wpfleger/admin-api-bearer-auth
branch
from
August 3, 2026 19:40
d014e40 to
e93d5be
Compare
wpfleger96
force-pushed
the
wpfleger/admin-api-bearer-auth
branch
2 times, most recently
from
August 3, 2026 20:22
9d54f68 to
1682a5e
Compare
wpfleger96
force-pushed
the
wpfleger/admin-api-bearer-auth
branch
from
August 11, 2026 00:19
5527704 to
1cdc816
Compare
wpfleger96
force-pushed
the
wpfleger/admin-api-bearer-auth
branch
2 times, most recently
from
August 12, 2026 18:24
6d893a5 to
02aba40
Compare
wpfleger96
added a commit
that referenced
this pull request
Aug 13, 2026
…y-scoped nav gate Close the desktop half of Thufir's #4768 pass-1 findings that need no relay change. The relay-contract consumption (canonical action DTO, real cancel route) waits on #3777. Processing report rows were disabled in the list, but the enforcement progress/retry/cancel UI lives only inside the detail view — so the row was locked exactly when an operator needs to inspect a pending or failed action. Keep processing rows navigable; the detail view already suppresses the resolve form for any non-open report. Feedback triage `status` was optional on the wire types and silently defaulted to "new" when absent, misreporting a reviewed/archived entry as new after reload. Make `status` required on both feedback DTOs and read it directly, and type PATCH's actual `{status}` echo instead of claiming a full summary record. The Moderation nav resolver keyed its 60s cache on pubkey alone, but NIP-11 discovery is relay-dependent — a workspace switch could serve the previous relay's verdict. Key the resolver on the connected relay origin (and gate its `enabled` on a resolved origin), and defer the `?section=moderation` invalid-section redirect while the resolver is unresolved so a direct link is not bounced before the probe can authorize. Co-authored-by: Will Pfleger <pfleger.will@gmail.com> Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
wpfleger96
force-pushed
the
wpfleger/admin-api-bearer-auth
branch
2 times, most recently
from
August 18, 2026 20:59
e7c9341 to
1e0b013
Compare
…IP-98 auth Gate the relay admin moderation API (/api/admin/v1) behind explicit authentication configuration selected by BUZZ_ADMIN_AUTH: token (default), disabled, or nip98. In nip98 mode every request carries a signed kind-27235 NIP-98 event; the authenticated pubkey resolves to an OPERATOR or MODERATOR principal from RELAY_OPERATOR_PUBKEYS, the RELAY_OWNER_PUBKEY fallback, or the relay_operators table. Replaces the BUZZ_ADMIN_INSECURE_NO_AUTH bypass with a role model that is revocable without rotating a shared secret and fails closed at every boundary. Co-authored-by: Will Pfleger <pfleger.will@gmail.com> Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
Desktop had no way to discover the admin API endpoint and forced users to type its URL by hand. Advertise the canonical admin origin (scheme://host[:port], no path) in the NIP-11 relay-information document under an optional admin_api field, present iff the admin surface is configured (config.admin.is_some()). Extract the loopback scheme rule into a shared scheme_for_host helper so the advertised origin and the NIP-98 u-tag the relay verifies can never use different schemes; a test enforces the invariant. The helper now parses IPv6 authorities (bracketed [::1]:3000 and bare ::1) correctly instead of letting a colon-split mangle them. Co-authored-by: Will Pfleger <pfleger.will@gmail.com> Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
RELAY_OPERATOR_PUBKEYS is the shared allowlist for both the NIP-98 admin console and the community-provisioning endpoints, but only provisioning needs RELAY_OPERATOR_API_ORIGIN. The boot hard-error forced admin-console operators to configure a provisioning surface they never use. Demote the boot error to a WARN naming the affected feature, and keep the provisioning endpoints fail-closed at request time: authorize_operator_request already rejects with a clean 500 when the origin is unset, before any replay or DB access. Document the decoupling and the NIP-11 admin_api advertisement in the env examples and the admin README. Co-authored-by: Will Pfleger <pfleger.will@gmail.com> Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
A bare IPv6 admin host (BUZZ_ADMIN_HOST=::1) passed authority validation but then interpolated unbracketed into the NIP-11 admin_api advertisement and the NIP-98 u-tag canonical URL, yielding http://::1 — which no URL parser accepts (an IPv6 authority must be bracketed per RFC 3986). Desktop discovery rejected it and no client could match the malformed signed URL. Reject the shape at config parse with an error naming the required bracketed form, matching the documented exact-authority contract. This makes the unbracketed multi-colon branch in scheme_for_host dead, so drop it. Replace the auth.rs assertions that pinned http://::1 as expected output with parseability tests; keep the advertised-vs-verified scheme-consistency invariant. Co-authored-by: Will Pfleger <pfleger.will@gmail.com> Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
…g parse
The bare-IPv6 bracket guard names the honest `::1` shape but skips
unclosed-bracket typos like `[::1` and `[::1:3000` — they start with
`[`, pass the guard, then interpolate into an unparseable
`http://[::1` NIP-11 advertisement and NIP-98 u-tag URL. Same defect
class as the bare-IPv6 case, just a typo shape.
Add a catch-all after the bracket guard: url::Url::parse("http://{host}")
must succeed, else reject with an error naming the host. This is a
validity gate only — the host is still stored verbatim, not normalized.
It kills every malformed authority in one guard, including shapes not
enumerated. url is already a buzz-relay dep.
Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
…parseable
The parse-only catch-all proved the whole `http://{host}` string is a
valid URL but not that {host} is exactly an authority. Query and fragment
delimiters are legal URL characters and were not in the forbidden set, so
`admin.example.com?x=1` and `[::1]#frag` passed startup: the suffix parsed
as query/fragment, then canonical_url appended the admin path after it
(`http://admin.example.com/?x=1/api/admin/v1/reports`), corrupting both the
NIP-11 advertisement and the NIP-98 u-tag URL — the same accepted-config/
unusable-URL class as the bare-IPv6 defect.
Validate the parsed sentinel structurally, mirroring parse_operator_api_origin:
host present, no credentials, path `/`, no query, no fragment. Any non-authority
character now lands in one of those and is rejected. Host still stored verbatim.
Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
…t DTO
The moderation console needs to reopen a terminally-resolved report, cancel a
failed enforcement action, and read the enforcement that ran against a target.
The prior surface exposed none of these: resolve returned an ad-hoc
`{status, actionId}`, report detail carried no action provenance, and feedback
from purged communities was silently dropped by an inner join.
- POST /reports/{id}/reopen returns a terminal report to `open` and records a
durable `reopen` audit row; idempotent on request_id, 409 if not terminal.
- POST /reports/{id}/cancel cancels a pre-mutation `failed` action (the only
recovery path — no composed client-side retry) and embeds the cancelled
action DTO as the last look at a record a later detail read serves as null.
- GET /reports/{id} and /resolve now carry `activeAction`, derived via a LEFT
JOIN LATERAL matching the report's active action or its succeeded enforcement
(`ORDER BY created_at DESC, id DESC`), so a dismissed-after-reopen report
still surfaces the enforcement that actually executed. reopen audit rows are
excluded (`action IN ('delete','kick','ban','timeout')`).
- Feedback list/detail switch to LEFT JOIN communities with nullable
communityId/communityHost so rows survive a tenant purge that severs
provenance (product_feedback.community_id SET NULL); the attachment path
fails closed to 404 on a severed row.
No migration added — activeAction is derived from existing indexes.
Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
… 409)
cancel_action fenced only on id+state='failed'+step_marker IS NULL, with
no report/community constraint, and discarded the report-reopen row count.
POST /reports/A/cancel {actionId:B} cancelled B's action, stranded B as
processing with a terminal action, and returned a fabricated {status:"open"}
for A.
Make cancellation one atomic, ownership-fenced transition mirroring
finalize_success: the action UPDATE now also fences report_id +
report_community_id, the report UPDATE now also fences status='processing',
and both updates must each affect exactly one row or the whole transaction
rolls back to false -> 409 with zero state change. This is what makes the
handler's hard-coded "status":"open" legitimate.
Adds an HTTP->DB regression: two processing reports sharing a community,
each with a distinct failed action; /reports/A/cancel {actionId:B} must 409
and leave both reports and both actions byte-for-byte unchanged.
Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
Person-directed enforcement (kick/ban/timeout) on an `event`-kind moderation report had no target user: the report row stores only the event id, and the reporter-supplied `p` tag is validation-shape only, never persisted. HTTP resolution and the crash-recovery worker each re-derive the target from the report + stored-event row, so both must agree on who enforcement acts against. Add `derive_enforcement_target` as the single source of truth: for `event` reports it overlays the stored event's author (server-owned truth from the events row) as the target pubkey, keeping the event id; pubkey/blob reports pass through unchanged. The HTTP driver and the recovery worker both call it, guaranteeing a stranded action re-derives against the same target it claimed. A pre-claim guard rejects kick/ban/ timeout with InvalidAction when the target pubkey is unresolvable (event purged or never accepted), leaving the report open and unclaimed rather than stranding it. Co-authored-by: Will Pfleger <pfleger.will@gmail.com> Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
The desired-state schema.sql had lagged the lease/claim-token migrations since they were authored: relay_admin_actions was missing action_lease_token/action_lease_expires_at and its lease index; relay_admin_outbox was missing attempt_count/retry_after/outbox_claim_token and still declared the pending index over the dropped lease_expires_at column. Bring desired state to the final 0035 shape and add a Postgres-backed parity test that bootstraps one probe DB from schema.sql, migrates another through 1-35, and asserts identical admin-table columns and index defs. Co-authored-by: Will Pfleger <pfleger.will@gmail.com> Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
The idx_relay_admin_outbox_pending index declared retry_after NULLS FIRST in both migration 0034 and schema.sql, but pgschema 1.7.4 (the real CI/test-relay bootstrap path) silently discards per-key NULLS FIRST when it re-emits the index, producing catalog indoption 0 0 while a fully-migrated database keeps 2 0. The desired-state bootstrap therefore diverged from the migration contract, and the prior parity regression missed it because it applied schema.sql via sqlx::raw_sql (which preserves NULLS FIRST) rather than through bin/pgschema. Drop NULLS FIRST from the index in both migration 0034 and schema.sql so both paths converge on plain-ascending (retry_after, created_at). The claim query's own ORDER BY retry_after NULLS FIRST, created_at ASC keeps the never-retried- first semantics; Postgres applies that ordering to the small pending candidate set regardless of the index's stored null ordering, and the partial predicate is what makes the index selective. Migrations 0032-0035 are branch-local and unshipped, so editing 0034 carries no checksum/brownfield risk. Rewrite the parity regression to bootstrap the desired state through the real bin/pgschema apply binary and assert per-key indoption (pg_index) alongside the rendered indexdef, so a construct pgschema cannot represent can no longer pass. Co-authored-by: Will Pfleger <pfleger.will@gmail.com> Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
…ute cancels Two defects from the kalvin-agent security review of the admin moderation API. Replay-before-authorization: authorize_nip98 claimed the deployment-scoped replay ID immediately after crypto verification, before resolve_admin_principal ran the roster check. Any validly-signing but unrostered key (every WARP-admitted laptop) could allocate replay slots at request rate. Split the NIP-98 path into verify-only (authorize_nip98, returns pubkey + event id) and a separate claim_nip98_replay called only after principal resolution succeeds, so an unrostered signer never consumes a slot. Fail-closed Redis behavior and the deployment-scoped key format are unchanged. Cancel actor trail: cancel_report discarded the resolved principal and cancel_action persisted nothing about who cancelled — the one mutation with no actor attribution while BUZZ_AUDIT_ENABLED=false. Add a cancelled_by column to relay_admin_actions (mirroring moderation_reports.resolved_by), stamped in the cancel UPDATE and surfaced through AdminActionDto.cancelledBy. Migration 0033 is branch-local and unshipped, so the column is added in place with matching schema.sql; the pgschema parity test round-trips it through bin/pgschema. Co-authored-by: Will Pfleger <pfleger.will@gmail.com> Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
Token-mode admin requests were read-only: mutations and staffing 403'd because a shared secret names no actor and every enforcement action must record a non-NULL actor pubkey. When the relay has a stable identity (configured BUZZ_RELAY_PRIVATE_KEY, or the deterministic dev key when BUZZ_REQUIRE_AUTH_TOKEN=false), the token arm now synthesizes an Operator principal attributed to the relay's own pubkey (AdminSource::RelayToken) — the same identity that signs moderation notices. A shared token means someone held the deployment secret, so the honest audit actor is the deployment identity, not a named person. Per-person attribution still requires nip98. Disabled mode stays read-only. Co-authored-by: Will Pfleger <pfleger.will@gmail.com> Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
wpfleger96
force-pushed
the
wpfleger/admin-api-bearer-auth
branch
from
August 19, 2026 17:55
1e0b013 to
0af7a91
Compare
The token-mode dismiss acceptance test queried moderation_actions.action = 'dismiss', but production writes 'dismiss_report' via enforcement_audit_action(), so it failed RowNotFound against real Postgres and never guarded the seam it named. Fix the query, fence by the seeded report's community + target instead of latest-row, and assert actor_authority = 'relay_operator' alongside actor_pubkey. Add a positive staffing acceptance test (PUT records the relay key as added_by, DELETE removes the row) so the full-Operator token privilege is pinned end-to-end, and select both ignored tests in the backend-integration Postgres CI lane — previously no api::admin ignored test ran in CI, so a regression dropping mutation attribution could ship green. Rename mounted_routes() to read_routes() to reflect that it only enumerates the GET surface. Co-authored-by: Will Pfleger <pfleger.will@gmail.com> Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
The dismiss acceptance test fenced its moderation_actions lookup on community + action + a fixed target [1u8;32] shared by every seed_admin_host_report() call. cleanup_admin_host_report deletes the report but not its audit row, so on a reused database a prior run's orphaned dismiss_report row could satisfy fetch_one() and the test would read the wrong actor — order/state dependent, not a real fence. Send a UUID-valued reason so the audit row carries a unique public_reason, fence the lookup on it, and delete that audit row after asserting. Both token-mode ignored tests now pass repeatedly against the same Postgres database with zero rows left behind. Co-authored-by: Will Pfleger <pfleger.will@gmail.com> Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Adds authenticated, role-based moderation to the relay admin API. On
mainthe admin API is read-only and gated only byHost/Originmatching; this branch adds an explicit authentication mode (BUZZ_ADMIN_AUTH), a two-tier Operator/Moderator principal model, mutation and staffing endpoints, and NIP-11 auto-discovery so clients never type the admin URL by hand.Authentication (
BUZZ_ADMIN_AUTH)BUZZ_ADMIN_AUTHacceptstoken(default),nip98, ordisabled. Configuration fails closed: any unrecognized value or conflicting combination (nip98+BUZZ_ADMIN_TOKEN,tokenmode without a valid 64-hexBUZZ_ADMIN_TOKEN, a malformedRELAY_OWNER_PUBKEYalongsidenip98) aborts startup.Host/Originmatching is retained in every mode as defense-in-depth.token— bearer auth with a deployment-wide shared secret. Read-write when the relay has a stable identity (a configuredBUZZ_RELAY_PRIVATE_KEY, or the deterministic dev key whenBUZZ_REQUIRE_AUTH_TOKEN=false): mutations and staffing are attributed to the relay's own pubkey as Operator — the same identity that signs moderation notices, the honest actor for a shared deployment secret. Without a stable identity it stays read-only (mutations403), preserving the never-NULL-actor invariant. Per-person attribution requiresnip98.nip98— per-request signed NIP-98 (kind 27235) events, resolved to an Operator or Moderator principal with per-person attribution and individual revocability.disabled— no credential; relies entirely on network-layer controls and logs aWARNon every boot. Read-only.Roles
Buzz has two independent authority axes after this change. Relay-level roles (new here) are deployment-global: they act across every community on the relay, through the admin API. Community-level roles (pre-existing, unchanged by this PR) are tenant-scoped: they act inside one community, through signed Nostr moderation commands.
Relay level (new)
delete/kick/ban/timeout) or decisions (dismiss/escalate); reopen and cancel; update feedback status; and manage the Operator/Moderator roster via the staffing endpoints.How a pubkey acquires a relay role (resolution order; config always outranks DB):
RELAY_OPERATOR_PUBKEYS→ Operator (sourceconfig)RELAY_OWNER_PUBKEYwhileRELAY_OPERATOR_PUBKEYSis empty → Operator (sourceowner_fallback, a break-glass grant for self-hosters that deactivates once any operator is configured)relay_operatorstable → Operator or Moderator (sourcedb, managed via the staffing endpoints)403In
tokenmode with a stable relay identity, the shared token synthesizes an Operator principal attributed to the relay's own pubkey (sourcerelay_token) — no roster lookup; the deployment identity is the actor.Community level (pre-existing, unchanged)
There is no community-level Moderator tier in v1; relay-level Moderator is the only role by that name.
Principal resolution and NIP-98 admission
resolve_admin_principal()returnsAdminPrincipal { pubkey, role, source }per the resolution order above;Nonenever falls through as a role. Admission is ordered so the replay guard is a privilege, not a public surface: signature/URL/method/payload-hash verification first, roster check second, and only then is the deployment-scoped replay id atomically consumed — a validly-signing but unrostered key never allocates a replay slot. Redis failure fails closed.Report resolution, recovery, and enforcement provenance
POST /reports/{id}/resolveis a crash-safe enforcement state machine: decision-only outcomes (dismiss/escalate) are a single CAS-plus-audit transaction; enforcement (delete/kick/ban/timeout) claims the report (open→processing), runs the durable mutation, then finalizes — a re-drive resumes at the step marker and converges to exactly-one enforcement, fenced by a lease and an outbox claim token.Person-directed enforcement on an
event-kind report derives its target from the stored event's author (server-owned truth, never the reporter'sptag) via a singlederive_enforcement_targetshared by the HTTP driver and the recovery worker. If the reported event was purged before its author could be read, person-directed actions are rejected pre-claim and the report staysopen;deleteneeds only the event id and is exempt.GET /reports/{id}and the resolve response carry anactiveActionfield surfacing the enforcement that actually executed — a report dismissed after a reopen still reports the ban that ran.POST /reports/{id}/reopenreturns a terminal report toopen(idempotent onrequestId).POST /reports/{id}/cancelis the sole recovery path for a pre-mutationfailedaction, attributed viarelay_admin_actions.cancelled_by.Feedback
GET /feedbackand/feedback/{id}survive a tenant purge: provenance columns are severed toNULLrather than cascade-deleted, and the attachment path fails closed to404on a severed row.PATCH /feedback/{id}updates lifecyclestatus(new/reviewed/archived).Staffing and probe
GET/PUT/DELETE /operators/{pubkey}are Operator-only; mutating a config-backed pubkey returns409 Conflict.GET /operatorsreturns the union of config and DB principals with per-entrysource.GET /probereports auth mode, role, source,canAct, andcanStafffor the desktop console.NIP-11 auto-discovery
The NIP-11 relay-information document gains an optional
admin_apifield carrying the canonical admin origin (scheme://host[:port], no path), present iffBUZZ_ADMIN_HOSTis set and omitted otherwise. The scheme follows the same loopback rule as NIP-98u-tag verification via a sharedscheme_for_hosthelper, so the advertised origin and the origin the relay verifies against can never diverge.Operator API origin decoupling
RELAY_OPERATOR_API_ORIGINis no longer required at boot whenRELAY_OPERATOR_PUBKEYSis set — it is used only by the community-provisioning endpoints, which fail closed at request time (with a boot-timeWARN) until it is set. The admin console needs no origin.Admin-web adaptation
The standalone
admin-webdashboard gains NIP-98 signing via a NIP-07 browser extension, auth-mode discovery, and a token prompt fortokenmode, with Playwright coverage of the auth and CSP paths.Migrations
0032_relay_operators.sql—relay_operatorsroster table (deployment-global),actor_authorityonmoderation_actions,processingstatus plusactive_action_idonmoderation_reports,statusonproduct_feedback.0033_relay_admin_actions.sql— enforcement-action table with arequest_ididempotency key, astep_markerfor crash recovery, and acancelled_byattribution column.0034_relay_admin_action_lease.sql— lease fencing for the action worker.0035_relay_admin_outbox_claim_token.sql— fenced claim token on the outbox worker.docs/admin/README.mddocuments the full principal model, NIP-98 event requirements, capabilities by role, the startup error matrix, and the discovery field.Production blast radius
A relay without
BUZZ_ADMIN_HOSTis completely unaffected — the admin surface stays disabled and bothBUZZ_ADMIN_AUTHandBUZZ_ADMIN_TOKENare ignored. Where it is set, this is a breaking change: the relay now requires an explicit authentication choice at boot (unsetBUZZ_ADMIN_AUTHdefaults totoken, which demands a validBUZZ_ADMIN_TOKEN;BUZZ_ADMIN_AUTH=disabledreproducesmain's priorHost/Origin-only gating), so the rollout config must land the env var alongside the image. Intokenmode, mutations are enabled and attributed to the relay identity when a stable relay key is present (production deployments already set one); without it, and indisabledmode, mutation routes return403. The four migrations add tables and columns without touching existing data.Related: block/buzz#4768 (desktop admin console consuming the
admin_apifield), squareup/bb-public#339 (Phase 4 rollout config)