Files
buzz/crates/buzz-relay/src/router.rs
Will Pfleger 86b9142a09 refactor(relay): NIP-98 admin auth with Operator/Moderator roles and NIP-11 discovery (#3777)
Adds authenticated, role-based moderation to the relay admin API. On
`main` the admin API is read-only and gated only by `Host`/`Origin`
matching; this branch adds NIP-98 authentication, 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_AUTH` accepts `nip98` or `disabled`. Leaving it unset
defaults to `nip98` (fail-secure). Configuration fails closed: any other
value aborts startup, while a lingering `BUZZ_ADMIN_TOKEN` is ignored
with a startup warning — token (bearer) authentication is not supported.
`Host`/`Origin` matching is retained in every mode as defense-in-depth.

- **`nip98`** (default) — per-request signed NIP-98 (kind 27235) events,
resolved to an Operator or Moderator principal with per-person
attribution and individual revocability. Read-write per resolved
principal.
- **`disabled`** — no credential; relies entirely on network-layer
controls (reverse proxy, VPN, firewall) and logs a `WARN` on every boot.
Always read-only: `authorize()` resolves no principal, so mutation and
staffing routes always `403`.

## 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)

| Role | Description |
|---|---|
| **Operator** | Full control of the deployment's moderation surface:
read all reports, feedback, and attachments across every community;
resolve reports with enforcement (`delete`/`kick`/`ban`/`timeout`) or
decisions (`dismiss`/`escalate`); reopen and cancel; update feedback
status; and manage the Operator/Moderator roster via the staffing
endpoints. |
| **Moderator** | Day-to-day triage: everything an Operator can do
except staffing — cannot view or change the roster. |

How a pubkey acquires a relay role (resolution order; config always
outranks DB):

1. Listed in `RELAY_OPERATOR_PUBKEYS` → **Operator** (source `config`)
2. Equals `RELAY_OWNER_PUBKEY` while `RELAY_OPERATOR_PUBKEYS` is empty →
**Operator** (source `owner_fallback`, a break-glass grant for
self-hosters that deactivates once any operator is configured)
3. Row in the `relay_operators` table → **Operator** or **Moderator**
(source `db`, managed via the staffing endpoints)
4. No match → `403`

### Community level (pre-existing, unchanged)

| Role | Description |
|---|---|
| **Owner** (community) | Full authority within their community: every
moderation action (delete, kick, ban/unban, timeout/untimeout, resolve
reports, view queue) plus member, role, and invite management. No guard
rails. |
| **Admin** (community) | Same community-wide moderation capabilities as
owner, except an admin cannot ban or time out the owner or a fellow
admin — only the owner may action an admin. Manages members and invites;
only the owner grants the admin role. |
| **Member** (community) | Standard participant; no moderation
capability. |
| **Owner / Admin** (channel) | Channel-local authority only: delete
messages and kick users within their own channel. |
| **Member / Guest / Bot** (channel) | No moderation authority. |

There is no community-level Moderator tier in v1; relay-level Moderator
is the only role by that name.

## Escalation scoping

The operator report queue is an escalation backstop, not the community's
day-to-day triage surface (per `VISION_MODERATION`, the severe class is
the platform's to review rather than the community's). Two rules enforce
that:

- **Escalated-by-default listing.** `GET /reports` with no `status`
parameter returns only `escalated` reports. An explicit
`status=<open|resolved|dismissed|escalated>` filter is always honored as
given, and full visibility across every status stays available for
platform-safety and legal review via `scope=all` (which lists reports
regardless of status). `scope` accepts only `all` and is ignored when an
explicit `status` is present.
- **Auto-escalated `illegal` reports.** Member reports whose category is
`illegal` are ingested with `status=escalated` rather than `open`, so
the severe class reaches the operator backstop without waiting for a
community admin to forward it. Every other category still lands `open`.
Auto-escalation only sets the queue status — it records no moderator
decision and stamps no resolver, so an auto-escalated report is
indistinguishable downstream from an admin-escalated one: the reopen
route returns it to `open` on the same terms, keyed only on status,
never on how the report became escalated.

## Principal resolution and NIP-98 admission

`resolve_admin_principal()` returns `AdminPrincipal { pubkey, role,
source }` per the resolution order above; `None` never 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}/resolve` is 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's
`p` tag) via a single `derive_enforcement_target` shared 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 stays `open`; `delete` needs only the event id and is
exempt.

`GET /reports/{id}` and the resolve response carry an `activeAction`
field surfacing the enforcement that actually executed — a report
dismissed after a reopen still reports the ban that ran. `POST
/reports/{id}/reopen` returns a terminal report to `open` (idempotent on
`requestId`). `POST /reports/{id}/cancel` is the sole recovery path for
a pre-mutation `failed` action, attributed via
`relay_admin_actions.cancelled_by`.

## Feedback

`GET /feedback` and `/feedback/{id}` survive a tenant purge: provenance
columns are severed to `NULL` rather than cascade-deleted, and the
attachment path fails closed to `404` on a severed row. `PATCH
/feedback/{id}` updates lifecycle `status`
(`new`/`reviewed`/`archived`).

## Staffing and probe

`GET/PUT/DELETE /operators/{pubkey}` are Operator-only; mutating a
config-backed pubkey returns `409 Conflict`. `GET /operators` returns
the union of config and DB principals with per-entry `source`. `GET
/probe` reports auth mode, role, source, `canAct`, and `canStaff` for
the desktop console.

## NIP-11 auto-discovery

The NIP-11 relay-information document gains an optional `admin_api`
field carrying the canonical admin origin (`scheme://host[:port]`, no
path), present iff `BUZZ_ADMIN_HOST` is set and omitted otherwise. The
scheme follows the same loopback rule as NIP-98 `u`-tag verification via
a shared `scheme_for_host` helper, so the advertised origin and the
origin the relay verifies against can never diverge.

## Operator API origin decoupling

`RELAY_OPERATOR_API_ORIGIN` is no longer required at boot when
`RELAY_OPERATOR_PUBKEYS` is set — it is used only by the
community-provisioning endpoints, which fail closed at request time
(with a boot-time `WARN`) until it is set. The admin console needs no
origin.

## Admin-web adaptation

The standalone `admin-web` dashboard signs each request as a NIP-98
event via a NIP-07 browser extension, discovers the auth mode with a
single unauthenticated probe (`200` → `disabled`, anything else →
`nip98`, fail-secure), and carries no token entry surface. Playwright
coverage exercises the NIP-98 and CSP paths.

## Security hardening

Three findings from security review are folded in:

- **Append-only roster audit.** `PUT`/`DELETE /operators/{pubkey}`
mutate the deployment-wide root of trust, but the upsert overwrites
`role`/`added_by` in place and the delete removes the only row — so a
grant→revoke sequence left no trace of who was ever granted or by whom.
Each mutation now writes an `relay_operator_audit` row (actor, target,
`grant`/`revoke`, pre-image `prev_role`, `new_role`, timestamp) inside
the same transaction as the mutation. A per-target transaction-scoped
advisory lock serializes concurrent mutations of the same pubkey before
the pre-image read, so the recorded `prev_role` is always the true
predecessor even under a concurrent-grant race. Chronology is keyed on a
`BIGINT GENERATED ALWAYS AS IDENTITY` `seq` column, not the wall clock:
the serializing lock guarantees insertion order and `seq` captures it,
so ordered reads (`ORDER BY seq`) follow the true privilege chain even
across a backward NTP step that a `clock_timestamp()` ordering would
invert. `created_at` (`clock_timestamp()`) is retained as informational
occurrence time only. Append-only by construction — no `UPDATE`/`DELETE`
path and no API surface. A no-op delete writes nothing.
- **`expirationSecs` overflow.** The timeout path built `Utc::now() +
Duration::seconds(secs as i64)` from an attacker-controlled `u64`:
`i64::MAX` panicked the handler, and a wrapped-negative magnitude minted
a *past* expiry that still passed validation. `compute_timeout_until`
now rejects zero, rejects magnitudes above a documented
`MAX_TIMEOUT_SECS` (365 days), and uses checked
`try_seconds`/`checked_add_signed` so no input can panic or produce a
past expiry — over-cap, zero, `i64::MAX`, and wrapping-negative inputs
all return a clean `4xx`.
- **Uppercase-hex config-backed bypass.** Config pubkeys are lowercased
at parse, but the `409` immutability check raw-string-compared the path
param while `decode_hex_pubkey` accepted uppercase — so `PUT
/operators/{UPPERCASE}` skipped the guard and wrote a shadow row for the
same 32 bytes. The validated param is now canonicalized (lowercased)
before the `409` check, DB write, `DELETE`, and response body.

## Migrations

- `0035_relay_operators.sql` — `relay_operators` roster table
(deployment-global), `actor_authority` on `moderation_actions`,
`processing` status plus `active_action_id` on `moderation_reports`,
`status` on `product_feedback`.
- `0036_relay_admin_actions.sql` — enforcement-action table with a
`request_id` idempotency key, a `step_marker` for crash recovery, and a
`cancelled_by` attribution column.
- `0037_relay_admin_action_lease.sql` — lease fencing for the action
worker.
- `0038_relay_admin_outbox_claim_token.sql` — fenced claim token on the
outbox worker.
- `0039_relay_operator_audit.sql` — append-only `relay_operator_audit`
trail for roster mutations (see Security hardening).

`docs/admin/README.md` documents 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_HOST` is completely unaffected — the admin
surface stays disabled and `BUZZ_ADMIN_AUTH` is ignored; a lingering
`BUZZ_ADMIN_TOKEN` logs a startup warning and must be removed. Where
`BUZZ_ADMIN_HOST` **is** set, unset `BUZZ_ADMIN_AUTH` defaults to
`nip98` (per-person signed auth); `BUZZ_ADMIN_AUTH=disabled` reproduces
`main`'s prior `Host`/`Origin`-only gating but is read-only (mutation
routes `403`). The five migrations add tables and columns without
touching existing data.

---

Related: [block/buzz#4768](https://github.com/block/buzz/pull/4768)
(desktop admin console consuming the `admin_api` field),
[squareup/bb-public#339](https://github.com/squareup/bb-public/pull/339)
(Phase 4 rollout config)

---------

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>
2026-08-28 11:43:05 -04:00

826 lines
32 KiB
Rust

//! axum routers — app (WebSocket + REST), health (K8s probes), metrics (Prometheus).
use std::sync::atomic::Ordering;
use std::sync::Arc;
use axum::{
body::Body,
extract::{ConnectInfo, FromRequest, State, WebSocketUpgrade},
http::{header, HeaderMap, HeaderValue, Request, StatusCode},
middleware,
response::{IntoResponse, Json},
routing::{get, post, put},
Router,
};
use serde_json::json;
use tower::ServiceExt;
use tower_http::cors::{AllowOrigin, CorsLayer};
use tower_http::limit::RequestBodyLimitLayer;
use tower_http::services::ServeDir;
use tower_http::trace::{HttpMakeClassifier, TraceLayer};
use crate::api;
use crate::audio;
use crate::connection::handle_connection;
use crate::metrics::track_metrics;
use crate::nip11::{nip11_document, relay_info_handler};
use crate::state::AppState;
/// Build the axum [`Router`] with all relay routes, middleware, and CORS configuration.
///
/// Pure Nostr protocol: WebSocket (NIP-01), HTTP bridge (NIP-98), media (Blossom),
/// git (smart HTTP), NIP-05, and health probes.
pub fn build_router(state: Arc<AppState>) -> Router {
let media_body_limit = state
.config
.media
.max_image_bytes
.max(state.config.media.max_video_bytes) as usize;
let media_router = Router::new()
.route("/upload", put(api::media::upload_blob))
.route("/media/upload", put(api::media::upload_blob))
.route(
"/media/{sha256_ext}",
get(api::media::get_blob).head(api::media::head_blob),
)
.layer(RequestBodyLimitLayer::new(media_body_limit))
.with_state(state.clone());
let git_router = api::git::git_router(state.clone());
let git_policy_router = api::git::git_policy_router(state.clone());
let admin_enabled = state.config.admin.is_some();
let admin_web_dir = state
.config
.admin
.as_ref()
.and_then(|config| config.web_dir.clone());
let admin_router = admin_enabled
.then(|| Router::new().nest("/api/admin/v1", api::admin::router(state.clone())));
let api_router = Router::new()
// WebSocket + NIP-11
.route("/", get(nip11_or_ws_handler))
.route("/info", get(relay_info_handler))
.route("/.well-known/nostr.json", get(api::nip05::nostr_nip05))
// Health endpoints
.route("/health", get(health_handler))
.route("/_liveness", get(liveness_handler))
.route("/_readiness", get(readiness_handler))
// Nostr HTTP bridge (NIP-98 auth)
.route("/events", post(api::bridge::submit_event))
.route("/query", post(api::bridge::query_events))
.route("/count", post(api::bridge::count_events))
// Relay-owned third-party GIF metadata proxy (NIP-98 auth).
.route(api::gifs::SEARCH_PATH, post(api::gifs::search))
.route(api::gifs::SHARE_PATH, post(api::gifs::share))
.route(
"/workflows/{workflow_id}/runs",
get(api::workflows::workflow_runs),
)
.route(
"/workflows/{workflow_id}/runs/{run_id}/approvals",
get(api::workflows::run_approvals),
)
.route(
"/operator/communities",
get(api::operator::list_owned_communities).post(api::operator::provision_community),
)
.route(
"/operator/communities/archive",
post(api::operator::archive_community),
)
.route(
"/operator/communities/unarchive",
post(api::operator::unarchive_community),
)
.route(
"/operator/communities/availability",
get(api::operator::community_availability),
)
.route(
"/operator/communities/transfer",
post(api::operator::transfer_community),
)
// Relay invites: mint (owner/admin) + claim (membership-gate exempt)
.route("/api/invites", post(api::invites::mint_invite))
.route("/api/join-policy", get(api::invites::join_policy))
// Policy documents as standalone pages — desktop opens these in the
// system browser instead of rendering the Markdown in-app.
.route(
"/api/join-policy/terms",
get(api::invites::join_policy_terms),
)
.route(
"/api/join-policy/privacy",
get(api::invites::join_policy_privacy),
)
.route(
"/api/invites/accept-policy",
post(api::invites::accept_policy),
)
.route("/api/invites/claim", post(api::invites::claim_invite))
// Moderation queue reads (NIP-98 auth + mod-authz gate, L6)
.route("/moderation/reports", get(api::bridge::moderation_reports))
.route("/moderation/audit", get(api::bridge::moderation_audit))
.route(
"/moderation/restricted",
get(api::bridge::moderation_restricted),
)
// Webhook trigger (secret-authenticated, no NIP-98)
.route("/hooks/{id}", post(api::bridge::workflow_webhook))
// Mesh demo echo probe — testbed-only; 404 unless BUZZ_MESH=on and
// BUZZ_MESH_DEMO_ECHO=on (see api::mesh_demo).
.route("/_mesh/demo/echo", post(api::mesh_demo::demo_echo))
// Huddle audio WebSocket route
.route(
"/huddle/{channel_id}/audio",
get(audio::handler::ws_audio_handler),
)
// Reject request bodies larger than 1 MB to prevent resource exhaustion.
.layer(RequestBodyLimitLayer::new(1024 * 1024))
.with_state(state.clone());
// Merge — each sub-router carries its own body limit.
// Metrics → Trace → CORS applied once over the combined router.
let mut merged = api_router
.merge(media_router)
.merge(git_router)
.merge(git_policy_router);
if let Some(admin_router) = admin_router {
merged = merged.merge(admin_router);
}
// Serve both bundles from one fallback. The admin host is checked first so
// it can never fall through to the public web bundle.
let web_dir = state.config.web_dir.clone();
if admin_web_dir.is_some() || web_dir.is_some() {
let admin_index = admin_web_dir.as_ref().map(|dir| dir.join("index.html"));
let admin_files = admin_web_dir.map(ServeDir::new);
let web_index = web_dir.as_ref().map(|dir| dir.join("index.html"));
let web_files = web_dir.map(ServeDir::new);
let serve_git_web_gui = state.config.serve_git_web_gui;
let fallback_state = state.clone();
let spa_fallback = tower::service_fn(move |req: axum::extract::Request| {
let admin_index = admin_index.clone();
let admin_files = admin_files.clone();
let web_index = web_index.clone();
let web_files = web_files.clone();
let state = fallback_state.clone();
async move {
let path = req.uri().path();
let admin_host = api::admin::is_admin_host(&state, req.headers());
if admin_host {
if let (Some(index), Some(files)) = (admin_index, admin_files) {
if is_admin_static_path(path) {
return files
.oneshot(req)
.await
.map(|response| with_admin_csp(response.into_response()));
}
if is_admin_spa_path(path) {
return Ok(with_admin_csp(read_spa_index(&index).await));
}
}
return Ok(with_admin_csp(StatusCode::NOT_FOUND.into_response()));
}
if let (Some(index), Some(files)) = (web_index, web_files) {
if path.starts_with("/assets/") {
return files.oneshot(req).await.map(IntoResponse::into_response);
}
if should_serve_spa(path, serve_git_web_gui) {
return Ok(read_spa_index(&index).await);
}
}
Ok(StatusCode::NOT_FOUND.into_response())
}
});
merged = merged.fallback_service(spa_fallback);
}
merged
.layer(middleware::from_fn(track_metrics))
.layer(http_trace_layer())
.layer(build_cors_layer(&state.config.cors_origins))
}
fn http_trace_layer() -> TraceLayer<HttpMakeClassifier, fn(&Request<Body>) -> tracing::Span> {
TraceLayer::new_for_http().make_span_with(make_http_span as fn(&Request<Body>) -> tracing::Span)
}
fn make_http_span(request: &Request<Body>) -> tracing::Span {
tracing::info_span!(
target: "buzz_relay",
"http.request",
otel.kind = "server",
http.request.method = %request.method(),
)
}
fn is_admin_spa_path(path: &str) -> bool {
path == "/"
|| path == "/reports"
|| path.starts_with("/reports/")
|| path == "/feedback"
|| path.starts_with("/feedback/")
}
/// Files served from the admin bundle directory verbatim. `/assets/*` is the
/// hashed Vite output; `/favicon.svg` is the one root-level file the bundle
/// emits and the document links. Everything else on the admin host is a 404 —
/// the directory is not browsable.
fn is_admin_static_path(path: &str) -> bool {
path.starts_with("/assets/") || path == "/favicon.svg"
}
fn is_invite_landing_path(path: &str) -> bool {
path.strip_prefix("/invite/")
.is_some_and(|code| !code.is_empty() && !code.contains('/'))
}
fn should_serve_spa(path: &str, serve_git_web_gui: bool) -> bool {
is_invite_landing_path(path) || (serve_git_web_gui && is_git_web_gui_path(path))
}
fn is_git_web_gui_path(path: &str) -> bool {
path == "/" || path == "/repos" || path.starts_with("/repos/")
}
async fn read_spa_index(index: &std::path::Path) -> axum::response::Response {
match tokio::fs::read(index).await {
Ok(body) => axum::response::Html(body).into_response(),
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
}
}
/// The admin dashboard holds the operator token in `sessionStorage`, so its
/// documents and assets are locked to same-origin code with no framing. `blob:`
/// images are required: attachments are fetched with the token and rendered
/// from object URLs. Applied only to the admin host — the public bundle keeps
/// its own headers.
#[rustfmt::skip]
const ADMIN_CSP: &str = "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'";
fn with_admin_csp(mut response: axum::response::Response) -> axum::response::Response {
response.headers_mut().insert(
header::CONTENT_SECURITY_POLICY,
HeaderValue::from_static(ADMIN_CSP),
);
response
}
/// Serve the admin bundle's `index.html` for a browser request to `/`. Any
/// non-HTML request to the admin authority is a 404: the relay protocol is not
/// exposed there.
async fn admin_spa_document(state: &AppState, accept: &str) -> axum::response::Response {
let index = state
.config
.admin
.as_ref()
.and_then(|config| config.web_dir.as_ref())
.filter(|_| accept.contains("text/html"))
.map(|dir| dir.join("index.html"));
match index {
Some(index) => read_spa_index(&index).await,
None => StatusCode::NOT_FOUND.into_response(),
}
}
/// Build the health-only router for K8s probes (port 8080 in CAKE).
///
/// No metrics middleware, no auth, no CORS, no body limit.
pub fn build_health_router(state: Arc<AppState>) -> Router {
Router::new()
.route("/_liveness", get(liveness_handler))
.route("/_readiness", get(readiness_handler))
.route("/_status", get(status_handler))
.route("/_mesh", get(mesh_status_handler))
.with_state(state)
}
/// Content-negotiated: NIP-11 JSON for plain HTTP, WebSocket upgrade otherwise.
async fn nip11_or_ws_handler(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
req: axum::extract::Request,
) -> impl IntoResponse {
let addr = req
.extensions()
.get::<ConnectInfo<std::net::SocketAddr>>()
.map(|ci| ci.0)
.unwrap_or_else(|| std::net::SocketAddr::from(([0, 0, 0, 0], 0)));
let accept = headers
.get("accept")
.and_then(|v| v.to_str().ok())
.unwrap_or("");
let raw_host = headers
.get(axum::http::header::HOST)
.and_then(|v| v.to_str().ok())
.unwrap_or("");
// `/` is an explicit relay route, so it never reaches the SPA fallback.
// Short-circuit the exact admin authority here and never let it serve the
// public web bundle, NIP-11 document, or WebSocket endpoint.
if api::admin::is_admin_host(&state, &headers) {
return with_admin_csp(admin_spa_document(&state, accept).await);
}
if accept.contains("application/nostr+json") {
return Json(nip11_document(&state, raw_host).await).into_response();
}
// Row zero: bind the connection to its community from the request host
// BEFORE the WebSocket upgrade, so no frame is ever read on an unbound
// connection. The host is the authoritative selector; an unmapped host or a
// lookup failure fails closed with a generic rejection — never a default
// tenant. NIP-11 above is served before binding and stays fail-open: an
// unmapped host still gets the document (with host-scoped fields like
// `icon` simply absent), so the doc cannot leak which hosts are mapped.
let tenant = match crate::tenant::bind_community(&state.db, raw_host).await {
Ok(ctx) => ctx,
Err(_) => {
// Generic rejection: do not distinguish "unmapped" from "lookup
// error", and never echo the host, so an unauthenticated caller
// cannot probe which communities exist on this deployment.
return (
StatusCode::NOT_FOUND,
"relay: no community is configured for this host",
)
.into_response();
}
};
let max_frame_bytes = state.config.max_frame_bytes;
match WebSocketUpgrade::from_request(req, &state).await {
Ok(ws) => {
// Shutting down: refuse new sockets instead of accepting a
// connection onto a dying pod. Readiness already returns 503, but
// that only stops K8s routing — direct and in-flight upgrades
// still reach here during the pre-drain grace window. Clients
// treat the refusal as a normal dial failure and retry, landing
// on a healthy pod.
if state.shutting_down.load(Ordering::Relaxed) {
return (StatusCode::SERVICE_UNAVAILABLE, "relay restarting").into_response();
}
limit_relay_websocket(ws, max_frame_bytes)
.on_upgrade(move |socket| handle_connection(socket, state, addr, tenant))
.into_response()
}
Err(_) => {
// Browser requesting HTML and Git web GUI is enabled → serve SPA.
if state.config.serve_git_web_gui {
if let Some(ref dir) = state.config.web_dir {
if accept.contains("text/html") {
let index = dir.join("index.html");
if let Ok(body) = tokio::fs::read(&index).await {
return axum::response::Html(body).into_response();
}
}
}
}
// Not a WS request and not asking for nostr+json — serve NIP-11 as fallback.
Json(nip11_document(&state, raw_host).await).into_response()
}
}
}
fn limit_relay_websocket<F>(
ws: WebSocketUpgrade<F>,
max_frame_bytes: usize,
) -> WebSocketUpgrade<F> {
// recv_loop keeps the application-level check as defense in depth, but
// parser limits must be set before tungstenite assembles the message.
ws.max_message_size(max_frame_bytes)
.max_frame_size(max_frame_bytes)
}
async fn health_handler() -> impl IntoResponse {
(StatusCode::OK, "ok")
}
async fn liveness_handler() -> impl IntoResponse {
(StatusCode::OK, "ok")
}
/// Readiness probe — checks shutdown flag, Postgres, and Redis connectivity.
async fn readiness_handler(State(state): State<Arc<AppState>>) -> impl IntoResponse {
use std::time::Duration;
if state.shutting_down.load(Ordering::Relaxed) {
return (
StatusCode::SERVICE_UNAVAILABLE,
Json(json!({"status": "shutting_down"})),
)
.into_response();
}
let check = async {
let (pg_ok, redis_ok, deletion_catalog_ok) = tokio::join!(
state.db.ping(),
async { state.redis_pool.get().await.is_ok() },
async { state.db.validate_deletion_serving_catalog().await.is_ok() },
);
(pg_ok, redis_ok, deletion_catalog_ok)
};
let (pg_ok, redis_ok, deletion_catalog_ok) =
tokio::time::timeout(Duration::from_secs(2), check)
.await
.unwrap_or((false, false, false));
if pg_ok && redis_ok && deletion_catalog_ok {
(StatusCode::OK, Json(json!({"status": "ready"}))).into_response()
} else {
(
StatusCode::SERVICE_UNAVAILABLE,
Json(json!({
"status": "not_ready",
"postgres": pg_ok,
"redis": redis_ok,
"deletion_catalog": deletion_catalog_ok
})),
)
.into_response()
}
}
fn status_payload(uptime_secs: u64) -> serde_json::Value {
json!({
"service": "buzz-relay",
"version": env!("CARGO_PKG_VERSION"),
"uptime_seconds": uptime_secs,
"build": {
"source_sha": crate::build_info::source_sha(),
"id": crate::build_info::build_id(),
"url": crate::build_info::build_url(),
},
})
}
/// Status endpoint — service name, version, uptime, and intrinsic build identity.
async fn status_handler(State(state): State<Arc<AppState>>) -> impl IntoResponse {
Json(status_payload(state.started_at.elapsed().as_secs()))
}
/// `/_mesh` — live mesh status: peer table, connection/phi state, per-peer
/// counters, fence-rejection totals. Mesh-off reports `{"enabled": false}` so
/// operators can distinguish "off" from "on with zero peers".
async fn mesh_status_handler(State(state): State<Arc<AppState>>) -> impl IntoResponse {
match state.mesh() {
Some(handle) => Json(serde_json::to_value(handle.status()).unwrap_or_else(
|e| json!({"enabled": true, "error": format!("status serialize: {e}")}),
)),
None => Json(json!({"enabled": false})),
}
}
/// Build a CORS layer from the configured origins list.
fn build_cors_layer(cors_origins: &[String]) -> CorsLayer {
if cors_origins.is_empty() {
return CorsLayer::permissive();
}
let origins: Vec<axum::http::HeaderValue> = cors_origins
.iter()
.filter_map(|o| o.parse::<axum::http::HeaderValue>().ok())
.collect();
if origins.is_empty() {
tracing::error!(
"BUZZ_CORS_ORIGINS set but no valid origins could be parsed — \
refusing to fall back to permissive CORS. Fix the origins or unset \
the variable for development mode."
);
return CorsLayer::new();
}
CorsLayer::new()
.allow_origin(AllowOrigin::list(origins))
.allow_methods(tower_http::cors::Any)
.allow_headers(tower_http::cors::Any)
}
#[cfg(test)]
mod tests {
use axum::{routing::get, Router};
use futures_util::SinkExt;
use opentelemetry::trace::TracerProvider as _;
use opentelemetry_sdk::trace::{InMemorySpanExporter, SdkTracerProvider};
use tokio::net::TcpListener;
use tokio::sync::mpsc;
use tokio_tungstenite::{connect_async, tungstenite::Message};
use tower::ServiceBuilder;
use tracing::Instrument as _;
use tracing_subscriber::prelude::*;
use super::*;
#[test]
fn invite_landing_path_requires_exactly_one_nonempty_code_segment() {
assert!(is_invite_landing_path("/invite/payload.mac"));
assert!(!is_invite_landing_path("/invite/"));
assert!(!is_invite_landing_path("/invite/code/extra"));
assert!(!is_invite_landing_path("/repos"));
assert!(!is_invite_landing_path("/"));
}
#[test]
fn git_web_gui_paths_are_explicit() {
assert!(is_git_web_gui_path("/"));
assert!(is_git_web_gui_path("/repos"));
assert!(is_git_web_gui_path("/repos/example"));
assert!(!is_git_web_gui_path("/repository"));
assert!(!is_git_web_gui_path("/arbitrary"));
assert!(!is_git_web_gui_path("/api/invites"));
}
#[test]
fn invite_is_always_served_but_git_gui_requires_opt_in() {
assert!(should_serve_spa("/invite/payload.mac", false));
assert!(should_serve_spa("/invite/payload.mac", true));
assert!(!should_serve_spa("/", false));
assert!(!should_serve_spa("/repos/example", false));
assert!(should_serve_spa("/", true));
assert!(should_serve_spa("/repos/example", true));
assert!(!should_serve_spa("/arbitrary", true));
}
/// Relay state serving both bundles: the admin SPA on `admin.example` and
/// the public SPA on any other host.
async fn spa_state(admin_dir: &std::path::Path, web_dir: &std::path::Path) -> Arc<AppState> {
let mut config = crate::config::Config::from_env().expect("default config loads");
config.require_relay_membership = false;
config.redis_url = "redis://127.0.0.1:1".to_string();
config.web_dir = Some(web_dir.to_path_buf());
config.admin = Some(crate::config::AdminConfig {
host: "admin.example".to_string(),
auth: crate::config::AdminAuth::Disabled,
web_dir: Some(admin_dir.to_path_buf()),
});
let pool = sqlx::PgPool::connect_lazy(&config.database_url).expect("lazy pg pool");
let db = buzz_db::Db::from_pool(pool.clone());
let redis_pool = deadpool_redis::Config::from_url(&config.redis_url)
.create_pool(Some(deadpool_redis::Runtime::Tokio1))
.expect("redis pool");
let pubsub = Arc::new(
buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone())
.await
.expect("pubsub manager"),
);
let audit = buzz_audit::AuditService::new(pool.clone());
let auth = buzz_auth::AuthService::new(config.auth.clone());
let search = buzz_search::SearchService::new(pool.clone());
let workflow_engine = Arc::new(buzz_workflow::WorkflowEngine::new(
db.clone(),
buzz_workflow::WorkflowConfig::default(),
));
let media_storage = buzz_media::MediaStorage::new(&config.media).expect("media storage");
let (state, _audit_shutdown) = AppState::new(
config,
db,
redis_pool,
audit,
pubsub,
auth,
search,
workflow_engine,
nostr::Keys::generate(),
media_storage,
);
Arc::new(state)
}
/// A minimal built SPA: an index document, one hashed asset, and the
/// root-level favicon Vite copies out of `public/`.
fn write_bundle(dir: &std::path::Path) {
std::fs::create_dir_all(dir.join("assets")).expect("assets dir");
std::fs::write(dir.join("index.html"), "<!doctype html>").expect("index.html");
std::fs::write(dir.join("assets/app.js"), "export {};").expect("bundle asset");
std::fs::write(dir.join("favicon.svg"), "<svg/>").expect("favicon");
}
async fn spa_response(
state: Arc<AppState>,
host: &str,
path: &str,
) -> axum::response::Response {
build_router(state)
.oneshot(
Request::get(path)
.header(axum::http::header::HOST, host)
.header(axum::http::header::ACCEPT, "text/html")
.body(Body::empty())
.expect("request"),
)
.await
.expect("response")
}
#[tokio::test]
async fn admin_spa_documents_and_assets_carry_the_admin_csp() {
let admin_dir = tempfile::tempdir().expect("admin bundle dir");
let web_dir = tempfile::tempdir().expect("public bundle dir");
write_bundle(admin_dir.path());
write_bundle(web_dir.path());
let state = spa_state(admin_dir.path(), web_dir.path()).await;
for path in [
"/",
"/reports",
"/feedback/abc",
"/assets/app.js",
"/favicon.svg",
] {
let response = spa_response(state.clone(), "admin.example", path).await;
assert_eq!(
response
.headers()
.get(header::CONTENT_SECURITY_POLICY)
.and_then(|value| value.to_str().ok()),
Some(ADMIN_CSP),
"{path} must carry the admin CSP"
);
}
}
#[tokio::test]
async fn the_admin_host_serves_the_favicon_the_document_links() {
let admin_dir = tempfile::tempdir().expect("admin bundle dir");
let web_dir = tempfile::tempdir().expect("public bundle dir");
write_bundle(admin_dir.path());
write_bundle(web_dir.path());
let state = spa_state(admin_dir.path(), web_dir.path()).await;
let response = spa_response(state.clone(), "admin.example", "/favicon.svg").await;
assert_eq!(response.status(), StatusCode::OK);
// The bundle directory is not browsable: only the assets Vite emits at
// the root are reachable, never arbitrary files beside them.
for path in ["/index.html", "/nope.svg"] {
let response = spa_response(state.clone(), "admin.example", path).await;
assert_eq!(response.status(), StatusCode::NOT_FOUND, "{path}");
}
}
#[test]
fn the_admin_csp_never_allows_inline_or_eval() {
assert!(
!ADMIN_CSP.contains("unsafe-inline") && !ADMIN_CSP.contains("unsafe-eval"),
"the dashboard performs signed admin requests — inline script or style must stay blocked"
);
}
#[tokio::test]
async fn the_public_spa_is_untouched_by_the_admin_csp() {
let admin_dir = tempfile::tempdir().expect("admin bundle dir");
let web_dir = tempfile::tempdir().expect("public bundle dir");
write_bundle(admin_dir.path());
write_bundle(web_dir.path());
let state = spa_state(admin_dir.path(), web_dir.path()).await;
for path in ["/invite/payload.mac", "/assets/app.js"] {
let response = spa_response(state.clone(), "public.example", path).await;
assert_eq!(response.status(), StatusCode::OK, "{path}");
assert!(
response
.headers()
.get(header::CONTENT_SECURITY_POLICY)
.is_none(),
"{path} on the public host must keep its own headers"
);
}
}
#[test]
fn status_payload_exposes_source_and_build_identity() {
let payload = status_payload(42);
assert_eq!(payload["service"], "buzz-relay");
assert_eq!(payload["version"], env!("CARGO_PKG_VERSION"));
assert_eq!(payload["uptime_seconds"], 42);
for field in ["source_sha", "id", "url"] {
assert!(
payload["build"][field]
.as_str()
.is_some_and(|value| !value.is_empty()),
"build.{field} must be a non-empty string"
);
}
}
#[tokio::test(flavor = "current_thread")]
async fn http_and_datastore_spans_are_exported_in_the_same_trace() {
let exporter = InMemorySpanExporter::default();
let provider = SdkTracerProvider::builder()
.with_simple_exporter(exporter.clone())
.build();
let subscriber = tracing_subscriber::registry().with(
tracing_opentelemetry::layer()
.with_tracer(provider.tracer("test"))
.with_filter(crate::telemetry::otel_env_filter(None)),
);
let _subscriber_guard = tracing::subscriber::set_default(subscriber);
let service = ServiceBuilder::new()
.layer(http_trace_layer())
.service(tower::service_fn(
|_: axum::http::Request<axum::body::Body>| async {
async {}
.instrument(tracing::info_span!(
target: "buzz_datastore",
"SELECT",
otel.kind = "client",
db.system.name = "postgresql",
))
.await;
Ok::<_, std::convert::Infallible>(axum::response::Response::new(
axum::body::Body::empty(),
))
},
));
service
.oneshot(
axum::http::Request::get("/")
.body(axum::body::Body::empty())
.unwrap(),
)
.await
.unwrap();
provider.force_flush().unwrap();
let spans = exporter.get_finished_spans().unwrap();
let http = spans
.iter()
.find(|span| span.name == "http.request")
.unwrap();
let datastore = spans.iter().find(|span| span.name == "SELECT").unwrap();
assert_eq!(
datastore.span_context.trace_id(),
http.span_context.trace_id()
);
assert_eq!(datastore.parent_span_id, http.span_context.span_id());
}
async fn handler_receives_message_with_limit(limit: usize, size: usize) -> bool {
let (received_tx, mut received_rx) = mpsc::unbounded_channel();
let app = Router::new().route(
"/",
get(move |ws: WebSocketUpgrade| {
let received_tx = received_tx.clone();
async move {
limit_relay_websocket(ws, limit).on_upgrade(move |mut socket| async move {
let _ = received_tx.send(matches!(socket.recv().await, Some(Ok(_))));
})
}
}),
);
let listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("bind test WebSocket listener");
let addr = listener.local_addr().expect("test listener address");
let server = tokio::spawn(async move {
axum::serve(listener, app)
.await
.expect("test WebSocket server");
});
let (mut client, _) = connect_async(format!("ws://{addr}/"))
.await
.expect("connect test WebSocket client");
client
.send(Message::Text("x".repeat(size).into()))
.await
.expect("send test WebSocket message");
let received = tokio::time::timeout(std::time::Duration::from_secs(2), received_rx.recv())
.await
.expect("server should process the test message")
.expect("server should report whether it received the message");
server.abort();
let _ = server.await;
received
}
#[tokio::test]
async fn relay_websocket_parser_rejects_oversized_messages_before_handler_reads_them() {
let limit = 64;
assert!(
handler_receives_message_with_limit(limit, limit).await,
"messages at the relay limit should still reach the handler"
);
assert!(
!handler_receives_message_with_limit(limit, limit + 1).await,
"oversized messages must be rejected by the WebSocket parser before the handler sees them"
);
}
}