mirror of
https://github.com/block/buzz.git
synced 2026-12-01 13:42:45 +00:00
feat(relay): add NIP-FI shadow mode for HTTP, WebSocket and admin (#8034)
Stack: this PR → #8062 🤖 Follows #8028 (merged). Adds `BUZZ_NIP_FI_MODE=shadow`. The relay loads and validates the full enforce configuration (issuers, communities, lifetimes, command issuers), evaluates NIP-FI evidence wherever enforce would decide, and records what enforce would have done, while every request, upgrade and session behaves exactly as in `off`. The one approved exception is admin disconnect: shadow verifies the command and returns `200`, where Off has no verifier and returns `503`. It lets an operator measure the would-deny rate, including Hosts missing from `BUZZ_NIP_FI_COMMUNITIES`, before switching to `enforce`. - **Mode predicates.** `NipFiMode` gains `is_off`, `restricts`, `evaluates`, `enforces`, `denies_unconditionally` and `observes_only`, built on two exhaustive `match` bases (`restricts`, `evaluates`); `is_off` is a `matches!` and the rest derive from the bases, so a new mode cannot silently fall into one side. Every call site uses them, including the Git membership-lookup failure from #8005, which uses `restricts()` so shadow keeps Off's body. A test scans each crate's `src/` and fails on any `NipFiMode::<variant>` in production code outside the predicate definitions and the env parser, which catches `==`, `matches!` on any number of lines, `if let` and or-patterns. - **Startup.** Shadow goes through enforce's path, so every enforce startup refusal applies, including the required connection lifetime. Missing-setting errors name the configured mode through one formatter (`mode_requires`); the enforce text is byte-identical. Shadow builds the assertion verifier and claims command replays under its own Redis prefix, both through the production `AppState::new`. - **HTTP and Blossom.** `admit_nip_fi_http` keeps Off's result in shadow and additionally replays enforce in enforce's order: first the router guard's steps (community, then assertion), then the handler's steps (NIP-98, pairing, deny set) on the same NIP-98 proof, through `evaluate_enforce_steps`, which enforce shares. A Host mapped in config but missing from the communities table, with a valid assertion, records an admit, because enforce's guard passes and its 404 is not a NIP-FI denial. A dev-mode `X-Pubkey` identity is marked unsigned and is never an enforce proof, so shadow records it as a `nip98` would-deny. On bridge and Blossom routes, the strict proof check (payload tag, Blossom `Strict`) runs as a separate pure check that consumes no replay entry and records on its own series, so it never counts as an admission verdict. Shadow records exactly one verdict for every identity, community or credential refusal enforce would make, with Off's status, body and challenge unchanged: bridge, workflows, Blossom, Git transport and settings, GIF search and share, and invite minting record the `community` would-deny when the Host is unmapped. Git's missing or malformed credentials still reject before any database work, and shadow records the enforce verdict for that failed proof. The router guard stays transparent in shadow. - **WebSocket, root and audio.** The upgrade check evaluates the attached assertion once. An upgrade enforce would refuse records that would-deny; otherwise the assertion goes into a shadow-only session object and the upgrade returns as in Off. The assertion never reaches the connection, the identity registries, the admission gate, terminal frames or cancellation. Each session records at most one admission verdict. **Pairing** is recorded on both ingresses right after a valid NIP-42 proof, before ordinary relay policy, where enforce pairs: a key mismatch or claimless assertion is a `pairing` denial. **The deny-set check** runs where enforce runs it, after registration: a hit is a `deny_set` denial, and a clean read keeps the session pending and registered. **The admit** is recorded only when the connection is actually admitted: on root at the AUTH commit, after ordinary policy; on audio when the participant join transaction commits, after relay membership, channel membership, the final ban and membership decision, mesh routing and the join's own checks, and before publication. A NIP-42 failure, which comes before pairing, and any refusal between pairing and the admit (ordinary policy, mesh, or a join refusal inside the join transaction) retires the observer when the refusal is decided, before any refusal frame, rollback or cleanup is awaited, so it leaves no record even if the deadline passes during that cleanup. A record-only deadline task, armed at upgrade with enforce's `compute_session_deadline`, records `expired` when enforce would have closed an admitted session. If the deadline passes while the session is still pending, that is its single admission verdict, a denial with `stage=deadline`, and a later AUTH records nothing. A deny for the key (admin or cross-pod) records `revoked` on an admitted session; if it arrives after the deny-set check but before the admit, including a deny refused for capacity, the session keeps a pending-revocation mark and records the admit followed by exactly one `revoked` end, matching enforce's phase-independent close, and the deadline cannot take that end. The phase, the mark and retirement change together under one session lock. Each session records at most one end. The session holds the socket's cancellation token for recording only: once the socket is cancelled, no transition records anything, even while connection references remain (a cancel fence; the token never feeds a close action). Upgrade would-denies carry the ingress route, `ws` or `audio`. - **Admin disconnect.** Shadow verifies the command and records the deny entry, so later admissions record would-denies, but closes no session; the response stays `{"disconnected": true}`. Shadow publishes cross-pod on its own channel, `buzz:nip-fi:shadow-disconnect`, which only shadow pods subscribe to, so no enforce pod (including older builds that know only `buzz:nip-fi:disconnect`) acts on a shadow command. Shadow pods also keep listening on `buzz:nip-fi:disconnect`, so their deny record includes enforce's real disconnects. Shadow claims command replays under `buzz:nip-fi:shadow-command:{hash}`: replays are still rejected within shadow, and a shadow accept never uses up the enforce claim. Enforce and Off keep the same channel, keys and close behavior. - **NIP-11.** Shadow serves the same document as enforce, including `limitation.federated_identity`, because clients only attach evidence to a relay that advertises it. ## Recording | Series | Labels | One increment per | |---|---|---| | `buzz_nip_fi_shadow_total` | `route` (`http`, `ws`, `audio`), `stage`, `outcome`, `community` | decision enforce would make: an HTTP admission, a refused upgrade, a session's NIP-FI AUTH decision, or its deadline passing before AUTH (`stage=deadline`) | | `buzz_nip_fi_shadow_strict_proof_total` | `route` (`bridge`, `blossom`), `outcome` (`pass`, `rejected`), `community` | strict NIP-98 side check | | `buzz_nip_fi_shadow_session_end_total` | `route` (`ws`, `audio`), `reason` (`expired`, `revoked`), `community` | admitted session enforce would have ended (admitted sessions only) | | `buzz_nip_fi_shadow_disconnect_total` | `route` (`admin`, `cross_pod`), `outcome` | disconnect-path event, in place of the real disconnect, lag, capacity and poison counters | `community` is the configured canonical URI or `unmapped`, never the raw `Host`; an unmapped or empty Host records `stage=community, outcome=unavailable`. A shadow pod never moves an enforce disconnect or failure counter. Strict-proof rates use their own `pass + rejected` total, and session-end rates divide by the `admit` count for the same route. There is no per-verdict `info` log; a would-deny writes a `debug` line with no token, claim or issuer. The pre-existing enforce `debug` line for the proven NIP-98 key is shared and also fires in shadow. Admin commands rejected for a bad header, body or proof, a replay, or a dependency error record no shadow verdict; only capacity rejection is counted. ## Not observed - Handler-side path-validation exits: an invalid Git owner or repo name on default-branch, a media path that is not a valid hash, and a Git pack URL with a query string record nothing from the handler. The router guard still records what enforce would refuse at the guard (for example a missing assertion), because enforce refuses those requests before it validates the path. - A refusal that is not a NIP-FI decision, such as a tenant-binding 404 behind a passing guard, or an ordinary WebSocket refusal after pairing (a ban, membership or join refusal before admission). ## Follow-ups - A bounded `route` label per HTTP surface (bridge, Blossom, Git, …) on `buzz_nip_fi_shadow_total`; today every HTTP verdict carries `route=http`. - One shared helper for the ten copied `observe_unbound` recording hooks, stacked on this PR. The shadow recorder and session suites and the root pairing witness run in `just test-unit` and the `scripts/run-tests.sh` fallback; the `AppState::new` shadow witness, which exercises the command verifier against real Redis, runs in the `external_infra_redis` lane. NIP-FI env tests recover a poisoned env lock so one panic cannot cascade. --------- Signed-off-by: Will Pfleger <pfleger.will@gmail.com> Signed-off-by: Will Pfleger <wpfleger@block.xyz> Signed-off-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> Signed-off-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz>
This commit is contained in:
@@ -42,6 +42,10 @@ pub fn conn_control_channel(ctx: &TenantContext) -> String {
|
||||
/// connected to at that moment is irrelevant.
|
||||
pub const NIP_FI_DISCONNECT_CHANNEL: &str = "buzz:nip-fi:disconnect";
|
||||
|
||||
/// Channel for disconnects accepted in shadow mode. Only shadow pods
|
||||
/// subscribe, so a shadow command never reaches an enforce pod.
|
||||
pub const NIP_FI_SHADOW_DISCONNECT_CHANNEL: &str = "buzz:nip-fi:shadow-disconnect";
|
||||
|
||||
/// A NIP-FI admin-disconnect command broadcast cross-pod after the local deny
|
||||
/// entry is inserted. Every pod merges this entry into its own deny map and
|
||||
/// closes any matching sessions (same `max(until)` rule as the local path).
|
||||
@@ -217,17 +221,18 @@ async fn connect_and_subscribe(
|
||||
|
||||
// ── NIP-FI disconnect subscriber ──────────────────────────────────────────────
|
||||
|
||||
/// Subscribes to [`NIP_FI_DISCONNECT_CHANNEL`] and forwards commands to the
|
||||
/// Subscribes to `channels` and forwards commands to the
|
||||
/// broadcast. Mirrors [`run_conn_control_subscriber`]: reconnect loop with
|
||||
/// exponential backoff. Never returns.
|
||||
pub async fn run_nip_fi_disconnect_subscriber(
|
||||
redis_url: String,
|
||||
broadcast_tx: broadcast::Sender<NipFiDisconnect>,
|
||||
channels: &'static [&'static str],
|
||||
) {
|
||||
let mut backoff_secs = BACKOFF_INITIAL_SECS;
|
||||
|
||||
loop {
|
||||
match connect_and_subscribe_nip_fi(&redis_url, &broadcast_tx).await {
|
||||
match connect_and_subscribe_nip_fi(&redis_url, &broadcast_tx, channels).await {
|
||||
Ok(()) => {
|
||||
backoff_secs = BACKOFF_INITIAL_SECS;
|
||||
tracing::warn!(
|
||||
@@ -249,15 +254,14 @@ pub async fn run_nip_fi_disconnect_subscriber(
|
||||
async fn connect_and_subscribe_nip_fi(
|
||||
redis_url: &str,
|
||||
broadcast_tx: &broadcast::Sender<NipFiDisconnect>,
|
||||
channels: &[&str],
|
||||
) -> Result<(), redis::RedisError> {
|
||||
let client = redis::Client::open(redis_url)?;
|
||||
let mut conn = client.get_async_pubsub().await?;
|
||||
|
||||
conn.subscribe(NIP_FI_DISCONNECT_CHANNEL).await?;
|
||||
conn.subscribe(channels).await?;
|
||||
|
||||
tracing::info!(
|
||||
"Redis NIP-FI disconnect subscriber connected — listening on {NIP_FI_DISCONNECT_CHANNEL}"
|
||||
);
|
||||
tracing::info!("Redis NIP-FI disconnect subscriber connected — listening on {channels:?}");
|
||||
|
||||
let mut stream = conn.on_message();
|
||||
while let Some(msg) = stream.next().await {
|
||||
|
||||
@@ -190,12 +190,17 @@ impl PubSubManager {
|
||||
/// Starts the NIP-FI disconnect subscriber loop with automatic
|
||||
/// reconnection. Runs forever — spawn this in a background task.
|
||||
///
|
||||
/// Every pod subscribes to this global channel; on receipt it merges the
|
||||
/// deny entry and closes matching local sessions.
|
||||
pub async fn run_nip_fi_disconnect_subscriber(self: Arc<Self>) {
|
||||
/// Subscribes to `channels`: every NIP-FI pod hears the enforce channel,
|
||||
/// and a shadow pod also hears its own. On receipt the pod merges the
|
||||
/// deny entry; an enforce pod closes matching local sessions.
|
||||
pub async fn run_nip_fi_disconnect_subscriber(
|
||||
self: Arc<Self>,
|
||||
channels: &'static [&'static str],
|
||||
) {
|
||||
conn_control::run_nip_fi_disconnect_subscriber(
|
||||
self.redis_url.clone(),
|
||||
self.nip_fi_disconnect_tx.clone(),
|
||||
channels,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
@@ -329,20 +334,21 @@ impl PubSubManager {
|
||||
Ok(subscriber_count)
|
||||
}
|
||||
|
||||
/// Publish a NIP-FI disconnect command to all pods on the global channel.
|
||||
/// Publish a NIP-FI disconnect command to all pods listening on `channel`.
|
||||
///
|
||||
/// Called after the local deny entry is inserted. Remote pods receive this
|
||||
/// and apply the same `max(until)` merge + all-community session close.
|
||||
/// Fire-and-forget: the HTTP response does not wait on delivery.
|
||||
pub async fn publish_nip_fi_disconnect(
|
||||
&self,
|
||||
channel: &str,
|
||||
command: &NipFiDisconnect,
|
||||
) -> Result<i64, PubSubError> {
|
||||
use crate::conn_control::{encode_nip_fi_disconnect, NIP_FI_DISCONNECT_CHANNEL};
|
||||
use crate::conn_control::encode_nip_fi_disconnect;
|
||||
let mut conn = self.pool.get().await?;
|
||||
let payload = encode_nip_fi_disconnect(command)?;
|
||||
let subscriber_count: i64 = redis::cmd("PUBLISH")
|
||||
.arg(NIP_FI_DISCONNECT_CHANNEL)
|
||||
.arg(channel)
|
||||
.arg(&payload)
|
||||
.query_async(&mut conn)
|
||||
.await?;
|
||||
|
||||
@@ -3,9 +3,11 @@
|
||||
//! Implements [`CommandReplayGuard`] from `buzz-auth` with the same
|
||||
//! `SET NX EX` shape and TTL clamp as [`crate::RedisNip98ReplayGuard`].
|
||||
|
||||
use buzz_auth::nip_fi::{
|
||||
namespaced_command_replay_key, COMMAND_REPLAY_PREFIX, SHADOW_COMMAND_REPLAY_PREFIX,
|
||||
};
|
||||
use buzz_auth::{
|
||||
command_replay_key, error::AuthError, CommandReplayGuard, DEFAULT_REPLAY_TTL_SECS,
|
||||
MAX_REPLAY_TTL_SECS,
|
||||
error::AuthError, CommandReplayGuard, DEFAULT_REPLAY_TTL_SECS, MAX_REPLAY_TTL_SECS,
|
||||
};
|
||||
|
||||
/// Redis-backed NIP-FI command replay seen-set.
|
||||
@@ -14,12 +16,25 @@ use buzz_auth::{
|
||||
/// is a first claim and `nil` is a replay.
|
||||
pub struct RedisCommandReplayGuard {
|
||||
pool: deadpool_redis::Pool,
|
||||
prefix: &'static str,
|
||||
}
|
||||
|
||||
impl RedisCommandReplayGuard {
|
||||
/// Create a new replay guard backed by the given Redis connection pool.
|
||||
pub fn new(pool: deadpool_redis::Pool) -> Self {
|
||||
Self { pool }
|
||||
Self {
|
||||
pool,
|
||||
prefix: COMMAND_REPLAY_PREFIX,
|
||||
}
|
||||
}
|
||||
|
||||
/// A guard for shadow pods: claims live under
|
||||
/// `buzz:nip-fi:shadow-command:{hash}`, disjoint from enforce claims.
|
||||
pub fn shadow(pool: deadpool_redis::Pool) -> Self {
|
||||
Self {
|
||||
pool,
|
||||
prefix: SHADOW_COMMAND_REPLAY_PREFIX,
|
||||
}
|
||||
}
|
||||
|
||||
async fn conn(&self) -> Result<deadpool_redis::Connection, AuthError> {
|
||||
@@ -42,7 +57,7 @@ impl CommandReplayGuard for RedisCommandReplayGuard {
|
||||
let ttl = ttl_secs.clamp(DEFAULT_REPLAY_TTL_SECS, MAX_REPLAY_TTL_SECS);
|
||||
let mut conn = self.conn().await?;
|
||||
let result: Option<String> = redis::cmd("SET")
|
||||
.arg(command_replay_key(issuer, jti))
|
||||
.arg(namespaced_command_replay_key(self.prefix, issuer, jti))
|
||||
.arg("1")
|
||||
.arg("NX")
|
||||
.arg("EX")
|
||||
|
||||
Reference in New Issue
Block a user