diff --git a/Cargo.lock b/Cargo.lock index 418d921e88..cf294d2878 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1383,10 +1383,12 @@ dependencies = [ "buzz-core", "chrono", "futures-util", + "hex", "nostr 0.44.7", "redis", "serde", "serde_json", + "sha2 0.11.0", "thiserror 2.0.18", "tokio", "tracing", diff --git a/Justfile b/Justfile index e5e441bd8d..6c535703d9 100644 --- a/Justfile +++ b/Justfile @@ -408,9 +408,10 @@ test-unit: cargo nextest run -p buzz-audit --lib # Cross-pod disconnect payload tests (NIP-FI and community archive # fence), the shared Redis connection's timeout bounds (loopback - # fake peers), and the full-queue retain (no Redis dialed); all - # infra-free. Keep the Cargo fallback in step. - cargo nextest run -p buzz-pubsub --lib -E 'test(/^conn_control::tests::/) + test(/^connection::tests::/) + test(=tests::queue_full_retain_does_not_wait_and_schedules_reconciliation)' + # fake peers), the full-queue retain (no Redis dialed), and the NIP-FI + # deny-store key and rounding tests; all infra-free. Keep the Cargo + # fallback in step. + cargo nextest run -p buzz-pubsub --lib -E 'test(/^conn_control::tests::/) + test(/^connection::tests::/) + test(=tests::queue_full_retain_does_not_wait_and_schedules_reconciliation) + test(/^nip_fi_command_replay::tests::/)' # buzz-auth NIP-FI verifier doctests. The sealed-authority # `compile_fail` doctests prove the default-feature public API alone # cannot forge the issuer→JWKS authority; nextest does not run diff --git a/crates/buzz-auth/src/lib.rs b/crates/buzz-auth/src/lib.rs index 5aa677d817..626c0e2f85 100644 --- a/crates/buzz-auth/src/lib.rs +++ b/crates/buzz-auth/src/lib.rs @@ -76,17 +76,17 @@ pub use scope::{parse_scopes, Scope}; pub use nip_fi::{ command_replay_key, validate_nip_fi_config, AssertionKeySet, AssertionPolicyId, BindRefusal, - CanonicalCapabilities, ClientSubjectPosture, CommandError, CommandIssuerPolicy, - CommandPolicyError, CommandReplayGuard, CommandResult, CommandVerifier, CommunityBinding, - CommunityBindingError, ConfidentialAssertion, CrossPodMergeResult, DenialClass, DenySetFull, - FederatedAssertionVerifier, FederatedIdentity, FederatedIdentityDiscovery, FreshnessClass, - HttpJwksFetcher, IssuerCapacity, IssuerJwksConfig, IssuerKeySource, IssuerPolicy, - IssuerPolicyError, IssuerRegistry, JwksFetchError, JwksFetcher, JwksSourceContract, - NipFiDenyMap, NipFiMode, NipFiStartupError, ProductionJwksSource, ProvisionBindingError, - ProvisionBindingPolicy, RevalidationDependencies, SubjectClass, SubjectClassContract, - TokenClass, TransportContractId, VerifiedAssertion, VerifierError, VerifyAssertion, - CLIENT_ATTACHED_HEADER, COMMAND_JWT_TYP, MAX_COMMAND_AGE_SECONDS, NOSTR_OWNER_PUBKEY_CLAIM, - NOSTR_PUBKEY_CLAIM, OAUTH_CLIENT_ID_CLAIM, + CanonicalCapabilities, ClaimOutcome, ClientSubjectPosture, CommandClaim, CommandError, + CommandIssuerPolicy, CommandPolicyError, CommandReplayGuard, CommandResult, CommandVerifier, + CommunityBinding, CommunityBindingError, ConfidentialAssertion, CrossPodMergeResult, + DenialClass, DenySetFull, DenyStatus, FederatedAssertionVerifier, FederatedIdentity, + FederatedIdentityDiscovery, FreshnessClass, HttpJwksFetcher, IssuerCapacity, IssuerJwksConfig, + IssuerKeySource, IssuerPolicy, IssuerPolicyError, IssuerRegistry, JwksFetchError, JwksFetcher, + JwksSourceContract, LoadDenies, LoadDeniesError, NipFiDenyMap, NipFiMode, NipFiStartupError, + ProductionJwksSource, ProvisionBindingError, ProvisionBindingPolicy, RevalidationDependencies, + SubjectClass, SubjectClassContract, TokenClass, TransportContractId, VerifiedAssertion, + VerifierError, VerifyAssertion, CLIENT_ATTACHED_HEADER, COMMAND_JWT_TYP, + MAX_COMMAND_AGE_SECONDS, NOSTR_OWNER_PUBKEY_CLAIM, NOSTR_PUBKEY_CLAIM, OAUTH_CLIENT_ID_CLAIM, }; #[cfg(any(test, feature = "test-utils"))] diff --git a/crates/buzz-auth/src/nip_fi/command.rs b/crates/buzz-auth/src/nip_fi/command.rs index 4b5da49d48..0b16df0d6e 100644 --- a/crates/buzz-auth/src/nip_fi/command.rs +++ b/crates/buzz-auth/src/nip_fi/command.rs @@ -15,18 +15,19 @@ //! claim ([`super::command_replay`]), then commit the slot (both-or-neither). //! 7. Return [`CommandResult`]. //! -//! Fail-closed: any failure inserts no deny entry, closes no session and -//! publishes nothing. A failure after step 6's shared claim may leave that -//! claim in place until its TTL (a guard error whose `SET` reply was lost, or a -//! process stopped between claim and commit); that is fail closed, since a -//! retry is then denied. +//! Fail-closed: a rejected command inserts no deny entry, closes no session +//! and publishes nothing. A guard error is an unknown outcome: the shared +//! claim and durable deny may already be written (a lost reply), so a retry +//! of the same command may be refused as a replay and the issuer sends a +//! fresh command. A process stopped between claim and local commit leaves +//! the durable deny for the next restore. use chrono::{DateTime, Utc}; use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; use nostr::PublicKey; use serde_json::{Map, Value}; -use super::command_replay::CommandReplayGuard; +use super::command_replay::{ClaimOutcome, CommandClaim, CommandReplayGuard}; use super::config::{ IssuerPolicy, IssuerRegistry, MAX_JTI_BYTES, MAX_SUBJECT_BYTES, MAX_TOKEN_BYTES, }; @@ -262,17 +263,19 @@ impl CommandVerifier { /// * `body_pubkey` — the `pubkey` field parsed from the JSON body. /// * `replay` — the shared command replay guard. /// - /// Order: authenticate, reserve a local slot, claim `(iss, jti)` in the - /// shared guard, then commit the slot. A full deny set fails before the - /// shared claim, so `DenySetFull` never consumes the command and it can be - /// retried. A replayed or failed claim, or a cancelled future, drops the - /// local slot; the commit after a successful claim cannot fail. + /// Order: authenticate, reserve a local slot, then in one shared step + /// check replay and the issuer's shared capacity and, only if both pass, + /// claim `(iss, jti)` and record the deny entry durably; then commit the + /// slot. A full deny set (local or shared) writes nothing, so + /// `DenySetFull` never consumes the command and it can be retried. A + /// replayed or failed claim, or a cancelled future, drops the local slot; + /// the commit after a successful claim cannot fail. /// - /// A claim can still remain without a local deny entry when Redis applied - /// it but its reply was lost (`AuthorizationUnavailable`), or when the - /// process stops between claim and commit. That inserts no deny entry, - /// closes no session and publishes nothing; it fails closed, since a retry - /// is denied until the claim's TTL. + /// When the shared step applied but its reply was lost + /// (`AuthorizationUnavailable`), or the process stops between claim and + /// commit, the claim and the durable deny entry remain without a local + /// one. The entry reaches pods at their next restore; a retry of the + /// same command is a replay, so the issuer sends a fresh command. pub async fn verify( &self, token: &str, @@ -286,16 +289,19 @@ impl CommandVerifier { let reservation = self.reserve(&cmd, now)?; // Cover the command's remaining validity plus this pod's skew, so a // pod whose clock trails still sees the claim; the guard floors this. - match replay - .try_claim( - &cmd.issuer, - &cmd.jti, - claim_ttl_secs(cmd.effective_expiry, now, cmd.skew_seconds), - ) - .await - { - Ok(true) => {} - Ok(false) => return Err(CommandError::AuthorizationDenied), + let claim = CommandClaim { + issuer: &cmd.issuer, + jti: &cmd.jti, + ttl_secs: claim_ttl_secs(cmd.effective_expiry, now, cmd.skew_seconds), + target: &cmd.target_pubkey, + until: cmd.until, + capacity: cmd.capacity, + now, + }; + match replay.try_claim(claim).await { + Ok(ClaimOutcome::Claimed) => {} + Ok(ClaimOutcome::Replay) => return Err(CommandError::AuthorizationDenied), + Ok(ClaimOutcome::Full) => return Err(CommandError::DenySetFull), Err(_) => return Err(CommandError::AuthorizationUnavailable), } Ok(Self::commit(&cmd, reservation)) @@ -479,6 +485,7 @@ impl CommandVerifier { effective_expiry: exp.min(iat_plus_cmd_age), until, skew_seconds: base_policy.skew_seconds(), + capacity: cmd_policy.deny_set_capacity(), }) } @@ -517,6 +524,7 @@ struct AuthenticatedCommand { effective_expiry: DateTime, until: DateTime, skew_seconds: u64, + capacity: usize, } // ── Internal helpers ────────────────────────────────────────────────────────── @@ -1372,6 +1380,7 @@ mod tests { enum Claim { Accept, Replay, + Full, Fail, Hang, } @@ -1398,12 +1407,12 @@ mod tests { impl CommandReplayGuard for ScriptedGuard { fn try_claim<'a>( &'a self, - _issuer: &'a str, - _jti: &'a str, - _ttl_secs: u64, + _claim: CommandClaim<'a>, ) -> std::pin::Pin< Box< - dyn std::future::Future> + Send + 'a, + dyn std::future::Future> + + Send + + 'a, >, > { self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); @@ -1412,13 +1421,22 @@ mod tests { // Yield once so concurrent verifies interleave at the claim. tokio::task::yield_now().await; match claim { - Claim::Accept => Ok(true), - Claim::Replay => Ok(false), + Claim::Accept => Ok(ClaimOutcome::Claimed), + Claim::Replay => Ok(ClaimOutcome::Replay), + Claim::Full => Ok(ClaimOutcome::Full), Claim::Fail => Err(crate::error::AuthError::Internal("simulated".into())), Claim::Hang => std::future::pending().await, } }) } + + fn load_denies<'a>( + &'a self, + _issuer: &'a str, + _now: DateTime, + ) -> crate::nip_fi::LoadDenies<'a> { + Box::pin(async { Ok(Vec::new()) }) + } } /// A verifier whose issuer shard holds exactly one deny entry. @@ -1494,6 +1512,7 @@ mod tests { let cv = one_slot_verifier(); for (claim, expected) in [ (Claim::Replay, CommandError::AuthorizationDenied), + (Claim::Full, CommandError::DenySetFull), (Claim::Fail, CommandError::AuthorizationUnavailable), ] { let target = target_key(); diff --git a/crates/buzz-auth/src/nip_fi/command_replay.rs b/crates/buzz-auth/src/nip_fi/command_replay.rs index b1d7e5b0c7..a73db2cbf5 100644 --- a/crates/buzz-auth/src/nip_fi/command_replay.rs +++ b/crates/buzz-auth/src/nip_fi/command_replay.rs @@ -8,33 +8,94 @@ //! The claim is taken after the command is fully authenticated (so a forgery //! cannot burn a legitimate `jti`) and after this pod has reserved its local //! deny-entry slot (so a `503 deny set full` never consumes the command). +//! +//! The same atomic step also records the deny entry durably, so a restarted +//! pod can restore it (see [`CommandReplayGuard::load_denies`]). Every check +//! (replay, shared capacity) runs before any write: a `Replay` or `Full` +//! outcome leaves the store unchanged. use std::{future::Future, pin::Pin}; +use chrono::{DateTime, Utc}; +use nostr::PublicKey; + use sha2::{Digest, Sha256}; use crate::error::AuthError; -/// Shared seen-set for NIP-FI command `(iss, jti)` pairs. +/// One authenticated command, as presented to the shared store. +#[derive(Debug, Clone, Copy)] +pub struct CommandClaim<'a> { + /// Exact `iss` of the command. + pub issuer: &'a str, + /// The command's `jti`. + pub jti: &'a str, + /// Claim TTL; implementations clamp it as the NIP-98 guard does. + pub ttl_secs: u64, + /// The signed target key. + pub target: &'a PublicKey, + /// The signed `until`, exact. + pub until: DateTime, + /// This issuer's `deny_set_capacity`, enforced across every pod. + pub capacity: usize, + /// Verifier clock: entries with `until <= now` are expired. + pub now: DateTime, +} + +/// Outcome of [`CommandReplayGuard::try_claim`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ClaimOutcome { + /// The claim is new; the deny entry (if `until > now`) is recorded. + Claimed, + /// `(iss, jti)` was already claimed. Nothing was written. + Replay, + /// The issuer's shared deny set is full. Nothing was written, so the + /// same command may be retried. + Full, +} + +/// Shared seen-set and durable deny store for NIP-FI commands. /// -/// The production implementation lives in `buzz-pubsub` (Redis `SET NX EX`). +/// The production implementation lives in `buzz-pubsub` (one Redis script). /// An in-memory implementation is provided behind /// `cfg(any(test, feature = "test-utils"))`. pub trait CommandReplayGuard: Send + Sync { - /// Atomically claim `(issuer, jti)`. + /// Atomically check replay and shared capacity, then claim `(iss, jti)` + /// and record the deny entry. /// - /// Returns `Ok(true)` when newly claimed (proceed) and `Ok(false)` when - /// already claimed (the caller MUST reject the command as replay). On - /// `Err` callers MUST fail closed. Implementations MUST use an atomic - /// set-if-absent and clamp `ttl_secs` to - /// [`crate::DEFAULT_REPLAY_TTL_SECS`]..=[`crate::MAX_REPLAY_TTL_SECS`], - /// as the NIP-98 guard does. + /// On `Err` the outcome is unknown (the write may have applied and only + /// its reply been lost); callers MUST fail closed. fn try_claim<'a>( &'a self, - issuer: &'a str, - jti: &'a str, - ttl_secs: u64, - ) -> Pin> + Send + 'a>>; + claim: CommandClaim<'a>, + ) -> Pin> + Send + 'a>>; + + /// Every recorded deny entry for `issuer` with `until > now`, at its exact + /// signed `until`. + fn load_denies<'a>(&'a self, issuer: &'a str, now: DateTime) -> LoadDenies<'a>; +} + +/// The future [`CommandReplayGuard::load_denies`] returns. +pub type LoadDenies<'a> = Pin< + Box)>, LoadDeniesError>> + Send + 'a>, +>; + +/// Why [`CommandReplayGuard::load_denies`] failed. +#[derive(Debug, thiserror::Error)] +pub enum LoadDeniesError { + /// The store could not be read. + #[error(transparent)] + Store(#[from] AuthError), + /// A stored deny record could not be decoded. `readable` holds every + /// active record that did decode, so the caller can still apply them; + /// the load is still a failure. + #[error("unreadable deny record: {record}")] + Unreadable { + /// The first record that could not be decoded. + record: String, + /// The active records that decoded. + readable: Vec<(PublicKey, DateTime)>, + }, } /// Redis key for a command replay claim: @@ -67,22 +128,62 @@ pub fn namespaced_command_replay_key(prefix: &str, issuer: &str, jti: &str) -> S format!("{prefix}:{}", hex::encode(hasher.finalize())) } -/// Process-local seen-set for tests. Instances shared via `Arc` model pods +/// Process-local store for tests. Instances shared via `Arc` model pods /// sharing one Redis. #[cfg(any(test, feature = "test-utils"))] #[derive(Default)] -pub struct InMemoryCommandReplayGuard(std::sync::Mutex>); +pub struct InMemoryCommandReplayGuard(std::sync::Mutex); + +#[cfg(any(test, feature = "test-utils"))] +#[derive(Default)] +struct InMemoryStore { + claims: std::collections::HashSet, + denies: std::collections::HashMap>>, +} #[cfg(any(test, feature = "test-utils"))] impl CommandReplayGuard for InMemoryCommandReplayGuard { fn try_claim<'a>( &'a self, - issuer: &'a str, - jti: &'a str, - _ttl_secs: u64, - ) -> Pin> + Send + 'a>> { - let key = command_replay_key(issuer, jti); - Box::pin(async move { Ok(self.0.lock().expect("replay set").insert(key)) }) + claim: CommandClaim<'a>, + ) -> Pin> + Send + 'a>> { + let key = command_replay_key(claim.issuer, claim.jti); + let mut store = self.0.lock().expect("replay store"); + let outcome = if store.claims.contains(&key) { + ClaimOutcome::Replay + } else { + let active = claim.until > claim.now; + let denies = store.denies.entry(claim.issuer.to_owned()).or_default(); + denies.retain(|_, until| *until > claim.now); + if active && !denies.contains_key(claim.target) && denies.len() >= claim.capacity { + ClaimOutcome::Full + } else { + if active { + let until = denies.entry(*claim.target).or_insert(claim.until); + *until = (*until).max(claim.until); + } + store.claims.insert(key); + ClaimOutcome::Claimed + } + }; + Box::pin(async move { Ok(outcome) }) + } + + fn load_denies<'a>(&'a self, issuer: &'a str, now: DateTime) -> LoadDenies<'a> { + let denies = self + .0 + .lock() + .expect("replay store") + .denies + .get(issuer) + .map(|d| { + d.iter() + .filter(|(_, u)| **u > now) + .map(|(k, u)| (*k, *u)) + .collect() + }) + .unwrap_or_default(); + Box::pin(async move { Ok(denies) }) } } diff --git a/crates/buzz-auth/src/nip_fi/deny_map.rs b/crates/buzz-auth/src/nip_fi/deny_map.rs index 047786083d..aa27169edf 100644 --- a/crates/buzz-auth/src/nip_fi/deny_map.rs +++ b/crates/buzz-auth/src/nip_fi/deny_map.rs @@ -1,8 +1,14 @@ //! In-memory NIP-FI deny set. //! -//! Holds `(iss, pubkey) → until` entries. No persistence — a relay restart -//! forgets active entries (Option B, as decided). The issuer re-push path is -//! documented as the mitigation but is not implemented here. +//! Holds `(iss, pubkey) → until` entries. The map itself is RAM; the relay +//! restores it from the shared store ([`super::CommandReplayGuard`]) at +//! startup and after every lost subscription. While a restore is pending, +//! [`NipFiDenyMap::is_denied`] fails closed for every key. +//! +//! * **Restore fence**: [`NipFiDenyMap::begin_restore`] opens a new generation +//! and closes admission; [`NipFiDenyMap::finish_restore`] reopens it only +//! for the generation that is still current, so a restore overtaken by a +//! newer one can never reopen admission. //! //! ## Invariants //! @@ -39,6 +45,7 @@ use chrono::{DateTime, Utc}; use dashmap::DashMap; use nostr::PublicKey; use std::collections::{HashMap, HashSet}; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; // ── Error type ──────────────────────────────────────────────────────────────── @@ -223,7 +230,7 @@ impl IssuerShard { pubkey_hex: &str, until: DateTime, now: DateTime, - ) -> Result<(), CapacityExceeded> { + ) -> Result { // Overwriting an existing (active or expired) entry never grows the // map, and a pending key already holds the slot this entry fills. if !self.entries.contains_key(pubkey_hex) @@ -233,12 +240,14 @@ impl IssuerShard { return Err(CapacityExceeded); } - let effective_until = match self.entries.get(pubkey_hex) { - Some(&existing) => existing.max(until), - None => until, - }; - self.entries.insert(pubkey_hex.to_owned(), effective_until); - Ok(()) + // Changed when the entry is new or `until` extends it. + match self.entries.get(pubkey_hex) { + Some(&existing) if existing >= until => Ok(false), + _ => { + self.entries.insert(pubkey_hex.to_owned(), until); + Ok(true) + } + } } } @@ -301,11 +310,26 @@ pub(crate) enum ReserveError { CapacityExceeded, } +/// The deny-set verdict for one key, from [`NipFiDenyMap::deny_status`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DenyStatus { + /// No active entry: admit. + Allowed, + /// An active entry (or a poisoned shard): refuse as revoked. + Denied, + /// A restore is pending, so the deny set is unknown: refuse as + /// authorization unavailable. + Unavailable, +} + /// Outcome of a cross-pod deny merge. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum CrossPodMergeResult { - /// Entry was inserted or updated (max-merge applied). + /// Entry was inserted or its `until` extended. Merged, + /// An entry with an equal or later `until` was already held; the map is + /// unchanged. + Unchanged, /// Issuer is not locally configured; message rejected. UnknownIssuer, /// Per-issuer capacity ceiling reached; the missed entry was not recorded. @@ -332,6 +356,9 @@ pub struct NipFiDenyMap { shards: Arc>>, /// Default per-issuer capacity, used when no issuer-specific override exists. default_capacity: usize, + /// Current restore generation and the latest generation restored. + /// Admission is open only while they are equal. + restore: Arc<(AtomicU64, AtomicU64)>, } /// A per-issuer capacity override supplied at construction time. @@ -359,9 +386,37 @@ impl NipFiDenyMap { Self { shards: Arc::new(shards), default_capacity, + restore: Arc::default(), } } + /// Open a new restore generation and close admission until + /// [`Self::finish_restore`] is called with it. + pub fn begin_restore(&self) -> u64 { + self.restore.0.fetch_add(1, Ordering::SeqCst) + 1 + } + + /// Reopen admission if `generation` is still the current one. + pub fn finish_restore(&self, generation: u64) -> bool { + let current = self.restore.0.load(Ordering::SeqCst); + if current != generation { + return false; + } + self.restore.1.fetch_max(generation, Ordering::SeqCst); + // A newer generation may have begun meanwhile; it compares unequal. + true + } + + /// True once the current restore generation has completed. + pub fn is_restored(&self) -> bool { + self.restore.1.load(Ordering::SeqCst) == self.restore.0.load(Ordering::SeqCst) + } + + /// The issuers this map holds shards for (every configured issuer). + pub fn issuers(&self) -> Vec { + self.shards.iter().map(|s| s.key().clone()).collect() + } + /// Returns `true` when `(iss, pubkey)` has an active deny entry at `now`. /// /// Used by S4 (WS admission step 6) and S5 (HTTP admission step 5). @@ -369,14 +424,32 @@ impl NipFiDenyMap { /// /// Fails **closed**: a poisoned shard lock returns `true` (deny) so that a /// damaged shard cannot silently admit a denied pubkey. + /// + /// Also fails closed (returns `true` for every key) while a restore is + /// pending. pub fn is_denied(&self, issuer: &str, pubkey: &PublicKey, now: DateTime) -> bool { - let pubkey_hex = pubkey.to_hex(); - match self.shards.get(issuer) { + self.deny_status(issuer, pubkey, now) != DenyStatus::Allowed + } + + /// The deny-set verdict for `(iss, pubkey)` at `now`, read once: + /// [`DenyStatus::Unavailable`] while a restore is pending, else + /// [`DenyStatus::Denied`] for an active entry or a poisoned shard (fail + /// closed), else [`DenyStatus::Allowed`]. [FI-TRACE-DENY-SET] + pub fn deny_status(&self, issuer: &str, pubkey: &PublicKey, now: DateTime) -> DenyStatus { + if !self.is_restored() { + return DenyStatus::Unavailable; + } + let denied = match self.shards.get(issuer) { Some(shard) => shard .lock() - .map(|guard| guard.is_denied(&pubkey_hex, now)) + .map(|guard| guard.is_denied(&pubkey.to_hex(), now)) .unwrap_or(true), // poisoned shard → fail closed (deny) None => false, + }; + if denied { + DenyStatus::Denied + } else { + DenyStatus::Allowed } } @@ -464,7 +537,8 @@ impl NipFiDenyMap { CrossPodMergeResult::ShardPoisoned } Ok(mut guard) => match guard.merge_entry(&pubkey_hex, until, now) { - Ok(()) => CrossPodMergeResult::Merged, + Ok(true) => CrossPodMergeResult::Merged, + Ok(false) => CrossPodMergeResult::Unchanged, Err(CapacityExceeded) => { // Cannot record the deny entry — return the outcome so // the caller can close the delivered target's sessions @@ -514,6 +588,34 @@ mod tests { NipFiDenyMap::new(100, vec![]) } + #[test] + fn pending_restore_denies_every_key_until_its_generation_finishes() { + let m = map(); + let key = Keys::generate().public_key(); + assert!(!m.is_denied("iss", &key, Utc::now()), "a new map is open"); + + let first = m.begin_restore(); + assert!( + m.is_denied("iss", &key, Utc::now()), + "closed while restoring" + ); + assert_eq!( + m.deny_status("iss", &key, Utc::now()), + DenyStatus::Unavailable, + "closed as unavailable, not revoked" + ); + // A reconnect opens a newer generation before the first finishes. + let second = m.begin_restore(); + assert!(!m.finish_restore(first), "a stale restore must not reopen"); + assert!(m.is_denied("iss", &key, Utc::now())); + assert!(m.finish_restore(second)); + assert!(!m.is_denied("iss", &key, Utc::now())); + // Clones share the fence. + let clone = m.clone(); + m.begin_restore(); + assert!(clone.is_denied("iss", &key, Utc::now())); + } + fn iss() -> &'static str { "https://issuer.example.com" } @@ -886,7 +988,7 @@ mod tests { // Second merge: shorter — must not shorten. assert_eq!( m.merge_cross_pod_deny(iss(), &k, shorter, now), - CrossPodMergeResult::Merged + CrossPodMergeResult::Unchanged ); // At 400s: still denied (longer wins). assert!( @@ -916,7 +1018,7 @@ mod tests { ); assert_eq!( m.merge_cross_pod_deny(iss(), &k, until, now), - CrossPodMergeResult::Merged + CrossPodMergeResult::Unchanged ); // Still denied at 200s (no spurious second-insert count growth). assert!( diff --git a/crates/buzz-auth/src/nip_fi/mod.rs b/crates/buzz-auth/src/nip_fi/mod.rs index f558028b4e..3c73c44185 100644 --- a/crates/buzz-auth/src/nip_fi/mod.rs +++ b/crates/buzz-auth/src/nip_fi/mod.rs @@ -33,7 +33,8 @@ pub use command::{ #[cfg(any(test, feature = "test-utils"))] pub use command_replay::InMemoryCommandReplayGuard; pub use command_replay::{ - command_replay_key, namespaced_command_replay_key, CommandReplayGuard, COMMAND_REPLAY_PREFIX, + command_replay_key, namespaced_command_replay_key, ClaimOutcome, CommandClaim, + CommandReplayGuard, LoadDenies, LoadDeniesError, COMMAND_REPLAY_PREFIX, SHADOW_COMMAND_REPLAY_PREFIX, }; pub use community::{CommunityBinding, CommunityBindingError}; @@ -43,7 +44,7 @@ pub use config::{ NOSTR_OWNER_PUBKEY_CLAIM, NOSTR_PUBKEY_CLAIM, OAUTH_CLIENT_ID_CLAIM, }; pub use denial::DenialClass; -pub use deny_map::{CrossPodMergeResult, DenySetFull, IssuerCapacity, NipFiDenyMap}; +pub use deny_map::{CrossPodMergeResult, DenySetFull, DenyStatus, IssuerCapacity, NipFiDenyMap}; pub use discovery::{ AssertionFreshnessDiscovery, FederatedIdentityDiscovery, FreshnessClassDiscovery, }; diff --git a/crates/buzz-pubsub/Cargo.toml b/crates/buzz-pubsub/Cargo.toml index 0d859b5e8d..77331ab4be 100644 --- a/crates/buzz-pubsub/Cargo.toml +++ b/crates/buzz-pubsub/Cargo.toml @@ -21,6 +21,8 @@ thiserror = { workspace = true } nostr = { workspace = true } futures-util = { workspace = true } arc-swap = { workspace = true } +sha2 = { workspace = true } +hex = { workspace = true } [dev-dependencies] -tokio = { workspace = true } +tokio = { workspace = true, features = ["test-util"] } diff --git a/crates/buzz-pubsub/src/conn_control.rs b/crates/buzz-pubsub/src/conn_control.rs index e610e18259..e850d81a54 100644 --- a/crates/buzz-pubsub/src/conn_control.rs +++ b/crates/buzz-pubsub/src/conn_control.rs @@ -18,7 +18,9 @@ use buzz_core::{CommunityId, TenantContext}; use chrono::{DateTime, Utc}; use futures_util::StreamExt; use serde::{Deserialize, Serialize}; +use std::sync::{Arc, Mutex}; use tokio::sync::broadcast; +use tokio::time::{Duration, Instant}; use uuid::Uuid; use crate::topic::BUZZ_PREFIX; @@ -68,6 +70,25 @@ pub struct NipFiDisconnect { pub until_unix_nanos: u32, } +/// State of this pod's NIP-FI disconnect subscription. Every confirmed +/// subscribe and every loss increments `epoch`; `live` tells which it was. +/// A consumer that restores state on each live epoch misses no message +/// published after Redis confirmed the subscription. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct NipFiSubscription { + /// Increments on every change. + pub epoch: u64, + /// Redis has confirmed the subscription and it has not ended since. + pub live: bool, +} + +fn set_subscription(tx: &tokio::sync::watch::Sender, live: bool) { + tx.send_modify(|s| { + s.epoch += 1; + s.live = live; + }); +} + /// Encode a [`NipFiDisconnect`] message to a JSON string for publication on /// the Redis pub/sub channel. /// @@ -233,45 +254,96 @@ async fn connect_and_subscribe( // ── NIP-FI disconnect subscriber ────────────────────────────────────────────── +/// First NIP-FI reconnect delay. Admission is closed while the subscription +/// is down, so this subscriber retries much sooner than the shared backoff. +const NIP_FI_BACKOFF_INITIAL: Duration = Duration::from_millis(250); +/// NIP-FI reconnect delay cap. +const NIP_FI_BACKOFF_MAX: Duration = Duration::from_secs(4); +/// A confirmed subscription that lasted this long counts as healthy: its end +/// reconnects at once and resets the backoff. A shorter one is a failure, +/// so confirm-then-drop cycles keep backing off instead of spinning. +const NIP_FI_HEALTHY_LIVE: Duration = Duration::from_secs(1); + /// Subscribes to `channels` and forwards commands to the -/// broadcast. Mirrors [`run_conn_control_subscriber`]: reconnect loop with -/// exponential backoff. Never returns. +/// broadcast, reporting each confirmed subscription and loss on +/// `subscription`. Reconnects with a short capped backoff (see +/// [`NIP_FI_BACKOFF_MAX`]). Never returns. pub async fn run_nip_fi_disconnect_subscriber( redis_url: String, broadcast_tx: broadcast::Sender, + subscription: tokio::sync::watch::Sender, channels: &'static [&'static str], ) { - let mut backoff_secs = BACKOFF_INITIAL_SECS; + nip_fi_retry_loop(subscription, |confirmed| { + connect_and_subscribe_nip_fi(redis_url.clone(), broadcast_tx.clone(), confirmed, channels) + }) + .await +} +/// Reports a confirmed NIP-FI subscription: records when Redis confirmed it +/// and publishes the live epoch. +struct NipFiConfirm { + at: Arc>>, + subscription: Arc>, +} + +impl NipFiConfirm { + fn confirmed(&self) { + *self.at.lock().unwrap_or_else(|e| e.into_inner()) = Some(Instant::now()); + set_subscription(&self.subscription, true); + } +} + +/// The NIP-FI reconnect loop. `attempt` runs one connection; it calls +/// [`NipFiConfirm::confirmed`] once Redis has confirmed the subscription, +/// then returns when the subscription ends. +async fn nip_fi_retry_loop( + subscription: tokio::sync::watch::Sender, + mut attempt: F, +) -> ! +where + F: FnMut(NipFiConfirm) -> Fut, + Fut: std::future::Future>, +{ + let subscription = Arc::new(subscription); + let mut backoff = NIP_FI_BACKOFF_INITIAL; loop { - match connect_and_subscribe_nip_fi(&redis_url, &broadcast_tx, channels).await { - Ok(()) => { - backoff_secs = BACKOFF_INITIAL_SECS; - tracing::warn!( - "Redis NIP-FI disconnect stream ended (clean disconnect) — reconnecting in {backoff_secs}s" - ); - } - Err(e) => { - tracing::error!( - "Redis NIP-FI disconnect error: {e} — reconnecting in {backoff_secs}s" - ); - } + let at = Arc::new(Mutex::new(None)); + let result = attempt(NipFiConfirm { + at: Arc::clone(&at), + subscription: Arc::clone(&subscription), + }) + .await; + set_subscription(&subscription, false); + match &result { + Ok(()) => tracing::warn!("Redis NIP-FI disconnect stream ended (clean disconnect)"), + Err(e) => tracing::error!("Redis NIP-FI disconnect error: {e}"), } - tokio::time::sleep(tokio::time::Duration::from_secs(backoff_secs)).await; - backoff_secs = (backoff_secs * 2).min(BACKOFF_MAX_SECS); + let confirmed_at = *at.lock().unwrap_or_else(|e| e.into_inner()); + if confirmed_at.is_some_and(|at| at.elapsed() >= NIP_FI_HEALTHY_LIVE) { + backoff = NIP_FI_BACKOFF_INITIAL; + tracing::info!("Redis NIP-FI disconnect subscriber reconnecting now"); + continue; + } + tracing::info!("Redis NIP-FI disconnect subscriber reconnecting in {backoff:?}"); + tokio::time::sleep(backoff).await; + backoff = (backoff * 2).min(NIP_FI_BACKOFF_MAX); } } async fn connect_and_subscribe_nip_fi( - redis_url: &str, - broadcast_tx: &broadcast::Sender, + redis_url: String, + broadcast_tx: broadcast::Sender, + confirm: NipFiConfirm, channels: &[&str], ) -> Result<(), redis::RedisError> { let client = redis::Client::open(redis_url)?; let mut conn = client.get_async_pubsub().await?; + // Returns once Redis has confirmed the subscription. conn.subscribe(channels).await?; + confirm.confirmed(); tracing::info!("Redis NIP-FI disconnect subscriber connected — listening on {channels:?}"); @@ -305,6 +377,106 @@ async fn connect_and_subscribe_nip_fi( mod tests { use super::*; + /// One scripted NIP-FI connection attempt: `None` fails before Redis + /// confirms; `Some(d)` confirms, stays live for `d`, then drops. + async fn run_script(script: Vec>) -> (Vec, Vec) { + let (tx, mut rx) = tokio::sync::watch::channel(NipFiSubscription::default()); + let starts = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let origin = Instant::now(); + let steps = std::sync::Arc::new(std::sync::Mutex::new(std::collections::VecDeque::from( + script, + ))); + let recorded = std::sync::Arc::clone(&starts); + let task = tokio::spawn(async move { + nip_fi_retry_loop(tx, |confirm| { + recorded.lock().unwrap().push(origin.elapsed()); + let step = steps.lock().unwrap().pop_front(); + async move { + match step { + None => std::future::pending().await, + Some(None) => { + Err(redis::RedisError::from(std::io::Error::other("refused"))) + } + Some(Some(live)) => { + confirm.confirmed(); + tokio::time::sleep(live).await; + Err(redis::RedisError::from(std::io::Error::other("dropped"))) + } + } + } + }) + .await + }); + let mut states = Vec::new(); + while let Ok(Ok(())) = tokio::time::timeout(Duration::from_secs(60), rx.changed()).await { + states.push(*rx.borrow_and_update()); + } + task.abort(); + let starts = starts.lock().unwrap().clone(); + (starts, states) + } + + fn gaps(starts: &[Duration]) -> Vec { + starts.windows(2).map(|w| w[1] - w[0]).collect() + } + + const MS: fn(u64) -> Duration = Duration::from_millis; + + #[tokio::test(start_paused = true)] + async fn nip_fi_failed_connects_back_off_to_a_four_second_cap() { + let (starts, states) = run_script(vec![None; 7]).await; + assert_eq!( + gaps(&starts), + [250, 500, 1000, 2000, 4000, 4000, 4000].map(MS), + ); + assert!( + states.iter().all(|s| !s.live), + "never confirmed: {states:?}" + ); + } + + #[tokio::test(start_paused = true)] + async fn nip_fi_healthy_subscription_end_reconnects_at_once_and_resets() { + // Climb the backoff, then a healthy 5 s subscription, then failures. + let (starts, states) = run_script(vec![ + None, + None, + None, + Some(Duration::from_secs(5)), + None, + None, + ]) + .await; + assert_eq!( + gaps(&starts), + [250, 500, 1000, 5000, 250, 500].map(MS), + "healthy end retries immediately, then the backoff restarts at 250 ms" + ); + // One live epoch, then its loss; every attempt bumps the epoch + // (6 losses + 1 confirmation), and the watch ends not live. + let live: Vec<_> = states.iter().filter(|s| s.live).collect(); + assert_eq!(live.len(), 1); + let last = states.last().expect("states"); + assert_eq!((last.epoch, last.live), (7, false)); + } + + #[tokio::test(start_paused = true)] + async fn nip_fi_confirm_then_drop_keeps_backing_off() { + let flap = Some(MS(100)); + let (starts, states) = run_script(vec![flap; 7]).await; + // Each gap is 100 ms live plus the backoff step: no reset, no spin. + assert_eq!( + gaps(&starts), + [350, 600, 1100, 2100, 4100, 4100, 4100].map(MS), + ); + // Every flap reports confirmation then loss, in order. + assert_eq!(states.len(), 14); + for (i, s) in states.iter().enumerate() { + assert_eq!(s.epoch, i as u64 + 1); + assert_eq!(s.live, i % 2 == 0); + } + } + fn ctx(id: u128, host: &str) -> TenantContext { TenantContext::resolved(CommunityId::from_uuid(Uuid::from_u128(id)), host) } diff --git a/crates/buzz-pubsub/src/lib.rs b/crates/buzz-pubsub/src/lib.rs index e7f85d5380..988d8d7efb 100644 --- a/crates/buzz-pubsub/src/lib.rs +++ b/crates/buzz-pubsub/src/lib.rs @@ -61,9 +61,9 @@ use tokio::sync::{broadcast, mpsc, oneshot, watch, Mutex, Notify}; use crate::cache_invalidation::{ cache_invalidation_channel, CacheInvalidation, ScopedCacheInvalidation, }; -pub use crate::conn_control::NipFiDisconnect; use crate::conn_control::{conn_control_channel, ConnControl, ScopedConnControl}; pub use crate::conn_control::{decode_nip_fi_disconnect, encode_nip_fi_disconnect}; +pub use crate::conn_control::{NipFiDisconnect, NipFiSubscription}; pub use crate::topic::{channel_key, global_key, EventTopic, EventTopicKey}; /// A Nostr event received on a scoped Redis event topic, broadcast to local subscribers. @@ -140,6 +140,7 @@ pub struct PubSubManager { cache_invalidation_tx: broadcast::Sender, conn_control_tx: broadcast::Sender, nip_fi_disconnect_tx: broadcast::Sender, + nip_fi_subscription: watch::Sender, link: watch::Sender, } @@ -172,6 +173,7 @@ impl PubSubManager { cache_invalidation_tx, conn_control_tx, nip_fi_disconnect_tx, + nip_fi_subscription: watch::Sender::new(NipFiSubscription::default()), link: watch::Sender::new(LinkState::default()), }) } @@ -230,6 +232,7 @@ impl PubSubManager { conn_control::run_nip_fi_disconnect_subscriber( self.redis_url.clone(), self.nip_fi_disconnect_tx.clone(), + self.nip_fi_subscription.clone(), channels, ) .await; @@ -363,6 +366,12 @@ impl PubSubManager { self.nip_fi_disconnect_tx.subscribe() } + /// Watch the NIP-FI disconnect subscription: every confirmed subscribe + /// and every loss bumps its epoch. + pub fn watch_nip_fi_subscription(&self) -> watch::Receiver { + self.nip_fi_subscription.subscribe() + } + /// Publish a cache-key drop to all pods. Fire-and-forget at the call site: /// the local cache is already dropped synchronously; this carries the same /// drop cross-pod. A dropped publish is backstopped by the REQ denial-path diff --git a/crates/buzz-pubsub/src/nip_fi_command_replay.rs b/crates/buzz-pubsub/src/nip_fi_command_replay.rs index 47b3c0369d..a798da9e66 100644 --- a/crates/buzz-pubsub/src/nip_fi_command_replay.rs +++ b/crates/buzz-pubsub/src/nip_fi_command_replay.rs @@ -1,73 +1,261 @@ -//! Redis-backed NIP-FI command replay seen-set. +//! Redis-backed NIP-FI command replay seen-set and durable deny store. //! -//! Implements [`CommandReplayGuard`] from `buzz-auth` with the same -//! `SET NX EX` shape and TTL clamp as [`crate::RedisNip98ReplayGuard`]. +//! Implements [`CommandReplayGuard`] from `buzz-auth`. One Lua script checks +//! replay and the issuer's shared capacity, and only when both pass sets the +//! claim (`SET … EX`, same TTL clamp as [`crate::RedisNip98ReplayGuard`]) and +//! records the deny entry. Per issuer, entries live in three keys that expire +//! with their latest entry: +//! +//! * `{deny}:{sha256(iss)}` — sorted set, member `pubkey_hex`, score `until` +//! in ms rounded **up**: the index for expiry and capacity. An entry is +//! removed only once its score is below `now`, so never early. +//! * `{deny}-until:{sha256(iss)}` — hash, field `pubkey_hex`, value the exact +//! signed `until` as `secs:nanos`, merged by maximum. +//! * `{deny}-revoke-through:{sha256(iss)}` — hash, field `pubkey_hex`: never +//! written here; every accept clears its target's field so a full revoke +//! is never narrowed by a cutoff another relay version stored. +//! +//! Only the issuer's hash is stored; readers map it back through configured +//! issuers. use buzz_auth::nip_fi::{ namespaced_command_replay_key, COMMAND_REPLAY_PREFIX, SHADOW_COMMAND_REPLAY_PREFIX, }; use buzz_auth::{ - error::AuthError, CommandReplayGuard, DEFAULT_REPLAY_TTL_SECS, MAX_REPLAY_TTL_SECS, + error::AuthError, ClaimOutcome, CommandClaim, CommandReplayGuard, LoadDeniesError, + DEFAULT_REPLAY_TTL_SECS, MAX_REPLAY_TTL_SECS, }; +use chrono::{DateTime, Utc}; +use nostr::PublicKey; +use sha2::{Digest, Sha256}; +use std::{future::Future, pin::Pin}; -/// Redis-backed NIP-FI command replay seen-set. -/// -/// `try_claim` issues `SET buzz:nip-fi:command:{hash} 1 NX EX `; `OK` -/// is a first claim and `nil` is a replay. +/// Deny-store key prefix for enforce-mode accepts. +pub const DENY_STORE_PREFIX: &str = "buzz:nip-fi:deny"; + +/// Deny-store key prefix for shadow-mode accepts, disjoint from enforce. +pub const SHADOW_DENY_STORE_PREFIX: &str = "buzz:nip-fi:shadow-deny"; + +/// KEYS: claim, index, exact, cutoff. ARGV: ttl, pubkey_hex, score_ms, secs, nanos, +/// capacity, now_ms, active (0/1). +const ACCEPT_SCRIPT: &str = r" +if redis.call('EXISTS', KEYS[1]) == 1 then return 'replay' end +local active = ARGV[8] == '1' +if active then + local expired = redis.call('ZRANGEBYSCORE', KEYS[2], '-inf', '(' .. ARGV[7]) + for _, member in ipairs(expired) do + redis.call('HDEL', KEYS[3], member) + redis.call('HDEL', KEYS[4], member) + end + redis.call('ZREMRANGEBYSCORE', KEYS[2], '-inf', '(' .. ARGV[7]) + if not redis.call('ZSCORE', KEYS[2], ARGV[2]) + and redis.call('ZCARD', KEYS[2]) >= tonumber(ARGV[6]) then + return 'full' + end +end +redis.call('SET', KEYS[1], '1', 'EX', ARGV[1]) +if active then + redis.call('ZADD', KEYS[2], 'GT', ARGV[3], ARGV[2]) + local cur = redis.call('HGET', KEYS[3], ARGV[2]) + local keep = false + if cur then + local s, n = string.match(cur, '^(%-?%d+):(%d+)$') + s, n = tonumber(s), tonumber(n) + local ns, nn = tonumber(ARGV[4]), tonumber(ARGV[5]) + keep = s > ns or (s == ns and n >= nn) + end + if not keep then redis.call('HSET', KEYS[3], ARGV[2], ARGV[4] .. ':' .. ARGV[5]) end + redis.call('HDEL', KEYS[4], ARGV[2]) + local top = redis.call('ZRANGE', KEYS[2], -1, -1, 'WITHSCORES') + redis.call('PEXPIREAT', KEYS[2], top[2]) + redis.call('PEXPIREAT', KEYS[3], top[2]) + redis.call('PEXPIREAT', KEYS[4], top[2]) +end +return 'claimed' +"; + +/// Redis-backed NIP-FI command replay seen-set and deny store. pub struct RedisCommandReplayGuard { pool: crate::RedisConnection, - prefix: &'static str, + prefix: std::borrow::Cow<'static, str>, + deny_prefix: std::borrow::Cow<'static, str>, } impl RedisCommandReplayGuard { - /// Create a new replay guard backed by the shared Redis connection. + /// Enforce-mode claims and deny records. pub fn new(pool: crate::RedisConnection) -> Self { Self { pool, - prefix: COMMAND_REPLAY_PREFIX, + prefix: COMMAND_REPLAY_PREFIX.into(), + deny_prefix: DENY_STORE_PREFIX.into(), } } - /// A guard for shadow pods: claims live under - /// `buzz:nip-fi:shadow-command:{hash}`, disjoint from enforce claims. + /// Shadow-mode claims and deny records, disjoint from enforce. pub fn shadow(pool: crate::RedisConnection) -> Self { Self { pool, - prefix: SHADOW_COMMAND_REPLAY_PREFIX, + prefix: SHADOW_COMMAND_REPLAY_PREFIX.into(), + deny_prefix: SHADOW_DENY_STORE_PREFIX.into(), } } + + /// Claims and deny records under `namespace`, disjoint from both modes. + /// For tests that must not share capacity with other cases on one Redis. + #[doc(hidden)] + pub fn namespaced(pool: crate::RedisConnection, namespace: &str) -> Self { + Self { + pool, + prefix: format!("{namespace}:command").into(), + deny_prefix: format!("{namespace}:deny").into(), + } + } +} + +/// Index (sorted set) and exact-`until` (hash) keys for `issuer` under `prefix`. +pub fn deny_store_keys(prefix: &str, issuer: &str) -> (String, String) { + let hash = hex::encode(Sha256::digest(issuer.as_bytes())); + (format!("{prefix}:{hash}"), format!("{prefix}-until:{hash}")) +} + +/// Per-target revoke-through cutoff hash for `issuer` under `prefix`. +pub fn revoke_through_key(prefix: &str, issuer: &str) -> String { + let hash = hex::encode(Sha256::digest(issuer.as_bytes())); + format!("{prefix}-revoke-through:{hash}") +} + +/// `until` in whole ms, rounded up. +fn ceil_ms(t: DateTime) -> i64 { + let ms = t.timestamp_millis(); + if t.timestamp_subsec_nanos().is_multiple_of(1_000_000) { + ms + } else { + ms + 1 + } +} + +fn internal(e: impl std::fmt::Display) -> AuthError { + tracing::warn!(error = %e, "nip-fi command store: redis failed"); + AuthError::Internal(format!("nip-fi command store: {e}")) } impl CommandReplayGuard for RedisCommandReplayGuard { fn try_claim<'a>( &'a self, - issuer: &'a str, - jti: &'a str, - ttl_secs: u64, - ) -> std::pin::Pin> + Send + 'a>> - { + claim: CommandClaim<'a>, + ) -> Pin> + Send + 'a>> { Box::pin(async move { - let ttl = ttl_secs.clamp(DEFAULT_REPLAY_TTL_SECS, MAX_REPLAY_TTL_SECS); + let ttl = claim + .ttl_secs + .clamp(DEFAULT_REPLAY_TTL_SECS, MAX_REPLAY_TTL_SECS); + let (index, exact) = deny_store_keys(&self.deny_prefix, claim.issuer); let mut conn = self.pool.clone(); - let result: Option = redis::cmd("SET") - .arg(namespaced_command_replay_key(self.prefix, issuer, jti)) - .arg("1") - .arg("NX") - .arg("EX") + let reply: String = redis::Script::new(ACCEPT_SCRIPT) + .key(namespaced_command_replay_key( + &self.prefix, + claim.issuer, + claim.jti, + )) + .key(index) + .key(exact) + .key(revoke_through_key(&self.deny_prefix, claim.issuer)) .arg(ttl) + .arg(claim.target.to_hex()) + .arg(ceil_ms(claim.until)) + .arg(claim.until.timestamp()) + .arg(claim.until.timestamp_subsec_nanos()) + .arg(claim.capacity) + .arg(claim.now.timestamp_millis()) + .arg(u8::from(claim.until > claim.now)) + .invoke_async(&mut conn) + .await + .map_err(internal)?; + match reply.as_str() { + "claimed" => Ok(ClaimOutcome::Claimed), + "replay" => Ok(ClaimOutcome::Replay), + "full" => Ok(ClaimOutcome::Full), + other => Err(internal(format!("unexpected reply: {other}"))), + } + }) + } + + fn load_denies<'a>(&'a self, issuer: &'a str, now: DateTime) -> buzz_auth::LoadDenies<'a> { + Box::pin(async move { + let (_, exact) = deny_store_keys(&self.deny_prefix, issuer); + let mut conn = self.pool.clone(); + let entries: Vec<(Vec, Vec)> = redis::cmd("HGETALL") + .arg(exact) .query_async(&mut conn) .await - .map_err(|e| { - tracing::warn!(error = %e, "nip-fi command replay: redis SET NX EX failed"); - AuthError::Internal(format!("Redis SET NX EX: {e}")) - })?; - match result.as_deref() { - Some("OK") => Ok(true), - None => Ok(false), - Some(other) => Err(AuthError::Internal(format!( - "unexpected SET NX EX reply: {other}" - ))), + .map_err(internal)?; + // An unreadable record fails the load: skipping it would reopen + // admission without that revocation. Every other record is + // still decoded, so the caller can apply them meanwhile. + let mut denies = Vec::with_capacity(entries.len()); + let mut bad = None; + for (key, until) in entries { + match decode(key, until) { + Ok((key, until)) if until > now => denies.push((key, until)), + Ok(_) => {} + Err(record) => { + tracing::warn!(record, "nip-fi command store: unreadable deny record"); + bad.get_or_insert(record); + } + } + } + match bad { + None => Ok(denies), + Some(record) => Err(LoadDeniesError::Unreadable { + record, + readable: denies, + }), } }) } } + +fn parse_until(value: &str) -> Option> { + let (secs, nanos) = value.split_once(':')?; + DateTime::from_timestamp(secs.parse().ok()?, nanos.parse().ok()?) +} + +/// One `HGETALL` field and value as a deny, or the record that won't decode. +fn decode(key: Vec, until: Vec) -> Result<(PublicKey, DateTime), String> { + let (Ok(key), Ok(until)) = (String::from_utf8(key), String::from_utf8(until)) else { + return Err("deny record that is not UTF-8".into()); + }; + let key = PublicKey::from_hex(&key).map_err(|_| format!("deny key {key}"))?; + let until = parse_until(&until).ok_or_else(|| format!("deny until {until} for {key}"))?; + Ok((key, until)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ceil_ms_never_rounds_down() { + let t = DateTime::from_timestamp(10, 1).unwrap(); + assert_eq!(ceil_ms(t), 10_001); + let t = DateTime::from_timestamp(10, 2_000_000).unwrap(); + assert_eq!(ceil_ms(t), 10_002); + } + + #[test] + fn keys_hold_only_the_issuer_hash() { + let (index, exact) = deny_store_keys(DENY_STORE_PREFIX, "https://issuer.example"); + assert!(!index.contains("issuer.example")); + assert!(exact.starts_with("buzz:nip-fi:deny-until:")); + assert_ne!( + deny_store_keys(SHADOW_DENY_STORE_PREFIX, "i").0, + deny_store_keys(DENY_STORE_PREFIX, "i").0 + ); + } + + #[test] + fn exact_until_round_trips() { + let t = DateTime::from_timestamp(1_795_000_000, 123_456_789).unwrap(); + let s = format!("{}:{}", t.timestamp(), t.timestamp_subsec_nanos()); + assert_eq!(parse_until(&s), Some(t)); + } +} diff --git a/crates/buzz-relay/src/api/nip_fi.rs b/crates/buzz-relay/src/api/nip_fi.rs index fadcdbdbac..0bb32604ef 100644 --- a/crates/buzz-relay/src/api/nip_fi.rs +++ b/crates/buzz-relay/src/api/nip_fi.rs @@ -245,16 +245,251 @@ pub fn disconnect_publish_channel(mode: NipFiMode) -> &'static str { } /// Channels this pod receives disconnects on. Shadow also hears enforce's -/// real disconnects so its deny record matches. -pub fn disconnect_subscribe_channels(mode: NipFiMode) -> &'static [&'static str] { +/// real disconnects so its deny record matches. An enforce pod hears shadow +/// disconnects only with `accept_shadow` (`BUZZ_NIP_FI_ACCEPT_SHADOW_DISCONNECTS`), +/// for the deploy that switches shadow → enforce. +pub fn disconnect_subscribe_channels( + mode: NipFiMode, + accept_shadow: bool, +) -> &'static [&'static str] { use buzz_pubsub::conn_control::{NIP_FI_DISCONNECT_CHANNEL, NIP_FI_SHADOW_DISCONNECT_CHANNEL}; - if mode.observes_only() { + if mode.observes_only() || accept_shadow { &[NIP_FI_DISCONNECT_CHANNEL, NIP_FI_SHADOW_DISCONNECT_CHANNEL] } else { &[NIP_FI_DISCONNECT_CHANNEL] } } +/// Stores this pod restores its deny map from, matching +/// [`disconnect_subscribe_channels`]: always the enforce store, plus the +/// shadow store on a shadow pod or with `accept_shadow`. +pub fn restore_sources( + pool: buzz_pubsub::RedisConnection, + mode: NipFiMode, + accept_shadow: bool, +) -> Vec> { + let mut sources: Vec> = vec![Arc::new( + buzz_pubsub::RedisCommandReplayGuard::new(pool.clone()), + )]; + if mode.observes_only() || accept_shadow { + sources.push(Arc::new(buzz_pubsub::RedisCommandReplayGuard::shadow(pool))); + } + sources +} + +/// Load every stored deny entry from `sources` into this pod's map. `Ok` +/// only when every entry was recorded; a store error or a capacity miss is +/// `Err`, and the caller keeps admission closed. +/// +/// Entries are merged first; sessions are closed afterwards, only for targets +/// the merge added or extended, on every exit, so a retry that finds an entry +/// unchanged never hides a close. A capacity or poison miss gets the same +/// failsafe close as live delivery. A failure does not end the pass: every +/// remaining entry, issuer and source is still merged or closed, and the +/// first failure is returned. +pub async fn restore_nip_fi_denies( + state: &crate::state::AppState, + sources: &[Arc], +) -> Result<(), &'static str> { + let Some(deny_map) = state.nip_fi_deny_map.as_deref() else { + return Ok(()); + }; + let mut changed = Vec::new(); + let result = merge_stored_denies(state, deny_map, sources, &mut changed).await; + for message in &changed { + close_nip_fi_sessions(state, message, "restored"); + } + result +} + +async fn merge_stored_denies( + state: &crate::state::AppState, + deny_map: &buzz_auth::NipFiDenyMap, + sources: &[Arc], + changed: &mut Vec, +) -> Result<(), &'static str> { + use buzz_auth::CrossPodMergeResult; + // Keep going past a failure so every reachable target is closed in this + // pass; the first failure still fails the restore. + let mut result = Ok(()); + for source in sources { + for issuer in deny_map.issuers() { + let now = chrono::Utc::now(); + let entries = match source.load_denies(&issuer, now).await { + Ok(entries) => entries, + Err(buzz_auth::LoadDeniesError::Store(_)) => { + result = result.and(Err("store")); + continue; + } + // Apply the records that decoded; the restore still fails. + Err(buzz_auth::LoadDeniesError::Unreadable { readable, .. }) => { + result = result.and(Err("unreadable")); + readable + } + }; + for (key, until) in entries { + let message = buzz_pubsub::NipFiDisconnect { + issuer: issuer.clone(), + pubkey_bytes: key.to_bytes().to_vec(), + until_unix: until.timestamp(), + until_unix_nanos: until.timestamp_subsec_nanos(), + }; + match merge_nip_fi_disconnect(state, &message, now) { + NipFiDisconnectApplyResult::Applied(CrossPodMergeResult::Merged) => { + changed.push(message) + } + NipFiDisconnectApplyResult::Applied(CrossPodMergeResult::Unchanged) => {} + NipFiDisconnectApplyResult::Applied(merge) => { + close_after_merge(state, &message, merge); + result = result.and(Err("capacity")); + } + NipFiDisconnectApplyResult::Disabled | NipFiDisconnectApplyResult::Rejected => { + // Unreachable with consistent config; close defensively. + close_nip_fi_sessions(state, &message, "rejected"); + result = result.and(Err("capacity")); + } + } + } + } + } + result +} + +/// The single owner of this pod's deny map restoration and cross-pod +/// consumer. +/// +/// Admission (every `is_denied`) stays closed until a restore completes for +/// the current generation. Each loss of the Redis subscription, and each +/// broadcast lag, opens a new generation and restores again, so a restore +/// overtaken by a newer subscription can never reopen admission. Order per +/// generation: subscription confirmed → load stores → apply messages that +/// arrived meanwhile → reopen. Never returns while the broadcast is open. +pub async fn run_nip_fi_disconnect_consumer( + state: Arc, + mut rx: tokio::sync::broadcast::Receiver, + mut subscription: tokio::sync::watch::Receiver, + sources: Vec>, +) { + use tokio::sync::broadcast::error::{RecvError, TryRecvError}; + let mode = state.config.nip_fi.mode; + let Some(deny_map) = state.nip_fi_deny_map.clone() else { + return; + }; + let retry = std::time::Duration::from_secs(1); + 'generation: loop { + let generation = deny_map.begin_restore(); + // Wait for a confirmed subscription. + let epoch = loop { + let current = *subscription.borrow_and_update(); + if current.live { + break current.epoch; + } + if subscription.changed().await.is_err() { + return; + } + }; + // Restore; retry while the subscription stays the same. + while let Err(reason) = restore_nip_fi_denies(&state, &sources).await { + metrics::counter!("buzz_nip_fi_deny_restore_failures_total", "reason" => reason) + .increment(1); + tracing::warn!( + reason, + "nip-fi: deny restore failed; admission stays closed" + ); + // Keep closing revoked sessions while admission stays closed. + // The deadline is fixed, so traffic cannot postpone the retry. + let wait = tokio::time::sleep(retry); + tokio::pin!(wait); + loop { + tokio::select! { + () = &mut wait => break, + msg = rx.recv() => match msg { + Ok(msg) => { + if !retained(apply_nip_fi_disconnect(&state, &msg, chrono::Utc::now())) { + continue 'generation; + } + } + Err(RecvError::Lagged(n)) => { + count_disconnect_event(mode, "buzz_nip_fi_disconnect_lag_total", "cross_pod", "lag", n); + continue 'generation; + } + Err(RecvError::Closed) => return, + }, + } + } + if subscription.borrow().epoch != epoch { + continue 'generation; + } + } + // Apply what arrived during the restore. + loop { + match rx.try_recv() { + Ok(msg) => { + if !retained(apply_nip_fi_disconnect(&state, &msg, chrono::Utc::now())) { + continue 'generation; + } + } + Err(TryRecvError::Empty) => break, + Err(TryRecvError::Lagged(n)) => { + count_disconnect_event( + mode, + "buzz_nip_fi_disconnect_lag_total", + "cross_pod", + "lag", + n, + ); + continue 'generation; + } + Err(TryRecvError::Closed) => return, + } + } + if subscription.borrow().epoch != epoch || !deny_map.finish_restore(generation) { + continue; + } + loop { + tokio::select! { + msg = rx.recv() => match msg { + Ok(msg) => { + if !retained(apply_nip_fi_disconnect(&state, &msg, chrono::Utc::now())) { + tracing::warn!("NIP-FI deny not retained; closing admission and restoring"); + continue 'generation; + } + } + Err(RecvError::Lagged(n)) => { + count_disconnect_event(mode, "buzz_nip_fi_disconnect_lag_total", "cross_pod", "lag", n); + tracing::warn!("NIP-FI disconnect consumer lagged by {n} messages; restoring"); + continue 'generation; + } + Err(RecvError::Closed) => { + tracing::error!("NIP-FI disconnect broadcast channel closed"); + return; + } + }, + changed = subscription.changed() => { + if changed.is_err() { + return; + } + continue 'generation; + } + } + } + } +} + +/// Whether a consumed disconnect left the deny map complete. A capacity miss +/// or poisoned shard did not record the deny, so admission must close and the +/// consumer restore until the active union fits. A rejected message (unknown +/// issuer, bad key) carries no deny this pod could hold. +fn retained(result: NipFiDisconnectApplyResult) -> bool { + !matches!( + result, + NipFiDisconnectApplyResult::Applied( + buzz_auth::CrossPodMergeResult::CapacityExceeded + | buzz_auth::CrossPodMergeResult::ShardPoisoned + ) + ) +} + /// Count a disconnect-path event on its `real` counter, or in shadow on /// `buzz_nip_fi_shadow_disconnect_total{route, outcome}` instead, so a /// shadow pod never moves an enforce disconnect metric. @@ -334,6 +569,19 @@ pub fn apply_nip_fi_disconnect( state: &crate::state::AppState, message: &buzz_pubsub::NipFiDisconnect, now: chrono::DateTime, +) -> NipFiDisconnectApplyResult { + let result = merge_nip_fi_disconnect(state, message, now); + if let NipFiDisconnectApplyResult::Applied(merge) = result { + close_after_merge(state, message, merge); + } + result +} + +/// Validate, clamp and merge one disconnect into the deny map; closes nothing. +fn merge_nip_fi_disconnect( + state: &crate::state::AppState, + message: &buzz_pubsub::NipFiDisconnect, + now: chrono::DateTime, ) -> NipFiDisconnectApplyResult { let deny_map = match state.nip_fi_deny_map.as_deref() { Some(m) => m, @@ -389,27 +637,44 @@ pub fn apply_nip_fi_disconnect( until = until.min(ceiling); } - // Merge the deny entry. + NipFiDisconnectApplyResult::Applied(deny_map.merge_cross_pod_deny( + &message.issuer, + &pubkey, + until, + now, + )) +} + +/// Close (or, in shadow, record would-close for) every session of the +/// message's target. +fn close_nip_fi_sessions( + state: &crate::state::AppState, + message: &buzz_pubsub::NipFiDisconnect, + reason: &str, +) { + if state.config.nip_fi.mode.observes_only() { + let sessions = &state.nip_fi_shadow_sessions; + return sessions.would_close(&message.issuer, &message.pubkey_bytes); + } + let closed = state + .conn_manager + .disconnect_nip_fi(&message.issuer, &message.pubkey_bytes) + + state + .community_connections + .disconnect_nip_fi(&message.issuer, &message.pubkey_bytes); + if closed > 0 { + tracing::debug!(closed, reason = reason, "nip-fi cross-pod: closed sessions"); + } +} + +/// Close the target's sessions for every merge outcome except +/// `UnknownIssuer`, and log/metric the failsafe outcomes. +fn close_after_merge( + state: &crate::state::AppState, + message: &buzz_pubsub::NipFiDisconnect, + merge_result: buzz_auth::CrossPodMergeResult, +) { use buzz_auth::CrossPodMergeResult; - let merge_result = deny_map.merge_cross_pod_deny(&message.issuer, &pubkey, until, now); - - // Close sessions for all merge outcomes except UnknownIssuer, never in shadow. - let close_sessions = |reason: &str| { - if state.config.nip_fi.mode.observes_only() { - let sessions = &state.nip_fi_shadow_sessions; - return sessions.would_close(&message.issuer, &message.pubkey_bytes); - } - let closed = state - .conn_manager - .disconnect_nip_fi(&message.issuer, &message.pubkey_bytes) - + state - .community_connections - .disconnect_nip_fi(&message.issuer, &message.pubkey_bytes); - if closed > 0 { - tracing::debug!(closed, reason = reason, "nip-fi cross-pod: closed sessions"); - } - }; - let mode = state.config.nip_fi.mode; // What a capacity or poison failsafe does to targeted sessions here. let action = if mode.observes_only() { @@ -417,9 +682,9 @@ pub fn apply_nip_fi_disconnect( } else { "targeted sessions closed" }; - match &merge_result { - CrossPodMergeResult::Merged => { - close_sessions("merged"); + match merge_result { + CrossPodMergeResult::Merged | CrossPodMergeResult::Unchanged => { + close_nip_fi_sessions(state, message, "merged"); } CrossPodMergeResult::UnknownIssuer => { tracing::warn!("nip-fi cross-pod: merge returned UnknownIssuer — rejected"); @@ -429,7 +694,7 @@ pub fn apply_nip_fi_disconnect( action, "nip-fi cross-pod: deny set full for issuer — no map entry (capacity miss; issuer re-push is the recovery path)" ); - close_sessions("capacity-exceeded"); + close_nip_fi_sessions(state, message, "capacity-exceeded"); let real = "buzz_nip_fi_cross_pod_capacity_exceeded_total"; count_disconnect_event(mode, real, "cross_pod", "capacity", 1); } @@ -438,13 +703,11 @@ pub fn apply_nip_fi_disconnect( action, "nip-fi cross-pod: issuer shard is poisoned (fail-closed)" ); - close_sessions("poisoned shard failsafe"); + close_nip_fi_sessions(state, message, "poisoned shard failsafe"); let real = "buzz_nip_fi_cross_pod_shard_poison_total"; count_disconnect_event(mode, real, "cross_pod", "poison", 1); } } - - NipFiDisconnectApplyResult::Applied(merge_result) } /// Build the NIP-FI command components from the issuer policies and key source. @@ -1928,6 +2191,7 @@ mod route_integration_tests { )]; config.nip_fi = NipFiRelayConfig { profile_policies: Vec::new(), + accept_shadow_disconnects: false, source: Default::default(), mode: NipFiMode::Enforce, registry: registry.clone(), @@ -3437,15 +3701,26 @@ mod route_integration_tests { impl buzz_auth::CommandReplayGuard for CountingReplayGuard { fn try_claim<'a>( &'a self, - issuer: &'a str, - jti: &'a str, - ttl_secs: u64, + claim: buzz_auth::CommandClaim<'a>, ) -> std::pin::Pin< - Box> + Send + 'a>, + Box< + dyn std::future::Future< + Output = Result, + > + Send + + 'a, + >, > { self.claims .fetch_add(1, std::sync::atomic::Ordering::SeqCst); - self.inner.try_claim(issuer, jti, ttl_secs) + self.inner.try_claim(claim) + } + + fn load_denies<'a>( + &'a self, + issuer: &'a str, + now: chrono::DateTime, + ) -> buzz_auth::LoadDenies<'a> { + self.inner.load_denies(issuer, now) } } @@ -3514,27 +3789,854 @@ mod route_integration_tests { forged_command_leaves_shared_claim_unconsumed(guard.clone(), Some(&guard), false).await; } - struct FailingReplayGuard; + // ── Durable deny store: restore and unknown outcomes ──────────────────── + + /// A pod whose registry holds the test issuer (so restores apply), sharing + /// `store` as production pods share Redis. + async fn store_pod( + capacity: usize, + store: Arc, + ) -> Arc { + let mut config = crate::config::Config::for_test(); + config.nip_fi.registry.insert(test_issuer_policy()); + let mut state = build_test_app_state(capacity, config).await; + state.nip_fi_command_replay = store; + Arc::new(state) + } + + /// Restart: a fresh pod is closed until it restores, then denies exactly + /// what other pods accepted. + #[tokio::test] + async fn restarted_pod_restores_denies_from_the_shared_store() { + let store: Arc = + Arc::new(buzz_auth::InMemoryCommandReplayGuard::default()); + let pod_a = store_pod(1000, Arc::clone(&store)).await; + let key = nostr::Keys::generate().public_key(); + let token = mint_token(&key.to_hex(), 300, serde_json::json!({})); + assert_eq!( + post_command(&pod_a, &token, &key.to_hex()).await.0, + StatusCode::OK + ); + + let pod_b = store_pod(1000, Arc::clone(&store)).await; + let deny_map = pod_b.nip_fi_deny_map.as_deref().unwrap(); + let generation = deny_map.begin_restore(); + let other = nostr::Keys::generate().public_key(); + assert!(is_denied(&pod_b, &other), "closed before restore"); + restore_nip_fi_denies(&pod_b, &[store]) + .await + .expect("restore"); + assert!(deny_map.finish_restore(generation)); + assert!(is_denied(&pod_b, &key), "restored deny"); + assert!(!is_denied(&pod_b, &other), "only restored keys are denied"); + } + + /// Redis down at startup: the subscription never confirms, so the + /// consumer never restores and admission stays closed. A store that + /// fails to load keeps it closed too. + #[tokio::test] + async fn unavailable_store_keeps_admission_closed() { + let pod = store_pod( + 1000, + Arc::new(buzz_auth::InMemoryCommandReplayGuard::default()), + ) + .await; + let key = nostr::Keys::generate().public_key(); + pod.nip_fi_deny_map.as_deref().unwrap().begin_restore(); + let (sub_tx, sub_rx) = + tokio::sync::watch::channel(buzz_pubsub::NipFiSubscription::default()); + let consumer = tokio::spawn(run_nip_fi_disconnect_consumer( + Arc::clone(&pod), + pod.pubsub.subscribe_nip_fi_disconnect(), + sub_rx, + vec![Arc::new(FailingReplayGuard { + load_fails: true, + ..Default::default() + })], + )); + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + assert!(is_denied(&pod, &key), "no subscription: closed"); + sub_tx.send_modify(|s| { + s.epoch += 1; + s.live = true; + }); + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + assert!(is_denied(&pod, &key), "store unreadable: closed"); + assert_eq!( + restore_nip_fi_denies( + &pod, + &[Arc::new(FailingReplayGuard { + load_fails: true, + ..Default::default() + })] + ) + .await, + Err("store") + ); + consumer.abort(); + } + + /// The consumer reopens admission once subscribed and restored, and + /// closes it again when the subscription is lost. + #[tokio::test] + async fn consumer_reopens_only_for_a_live_restored_subscription() { + let store: Arc = + Arc::new(buzz_auth::InMemoryCommandReplayGuard::default()); + let pod = store_pod(1000, Arc::clone(&store)).await; + let key = nostr::Keys::generate().public_key(); + pod.nip_fi_deny_map.as_deref().unwrap().begin_restore(); + let (sub_tx, sub_rx) = + tokio::sync::watch::channel(buzz_pubsub::NipFiSubscription::default()); + let consumer = tokio::spawn(run_nip_fi_disconnect_consumer( + Arc::clone(&pod), + pod.pubsub.subscribe_nip_fi_disconnect(), + sub_rx, + vec![store], + )); + let set = |live| { + sub_tx.send_modify(|s| { + s.epoch += 1; + s.live = live; + }) + }; + let settle = || tokio::time::sleep(std::time::Duration::from_millis(50)); + set(true); + settle().await; + assert!(!is_denied(&pod, &key), "open once restored"); + set(false); + settle().await; + assert!( + is_denied(&pod, &key), + "closed after losing the subscription" + ); + set(true); + settle().await; + assert!(!is_denied(&pod, &key), "open again after a fresh restore"); + consumer.abort(); + } + + /// A store whose first load misses `hidden` (a deny accepted while that + /// snapshot was being read), and which counts its loads. + struct StaleFirstLoad { + inner: Arc, + hidden: std::sync::Mutex>, + loads: tokio::sync::watch::Sender, + } + + impl StaleFirstLoad { + fn new( + inner: Arc, + hidden: Option, + ) -> Arc { + Arc::new(Self { + inner, + hidden: std::sync::Mutex::new(hidden), + loads: tokio::sync::watch::channel(0).0, + }) + } + + /// Waits until the consumer has started its `n`th restore load. + async fn loaded(&self, n: usize) { + let mut loads = self.loads.subscribe(); + tokio::time::timeout( + std::time::Duration::from_secs(10), + loads.wait_for(|loads| *loads >= n), + ) + .await + .expect("consumer progress") + .unwrap(); + } + } + + /// Waits until `pod`'s consumer has reopened admission. + async fn restored(pod: &AppState) { + let map = pod.nip_fi_deny_map.as_deref().unwrap(); + tokio::time::timeout(std::time::Duration::from_secs(10), async { + while !map.is_restored() { + tokio::task::yield_now().await; + } + }) + .await + .expect("restored"); + } + + impl buzz_auth::CommandReplayGuard for StaleFirstLoad { + fn try_claim<'a>( + &'a self, + claim: buzz_auth::CommandClaim<'a>, + ) -> std::pin::Pin< + Box< + dyn std::future::Future< + Output = Result, + > + Send + + 'a, + >, + > { + self.inner.try_claim(claim) + } + + fn load_denies<'a>( + &'a self, + issuer: &'a str, + now: chrono::DateTime, + ) -> buzz_auth::LoadDenies<'a> { + Box::pin(async move { + self.loads.send_modify(|loads| *loads += 1); + let hidden = self.hidden.lock().unwrap().take(); + let mut denies = self.inner.load_denies(issuer, now).await?; + denies.retain(|(key, _)| Some(*key) != hidden); + Ok(denies) + }) + } + } + + /// Records a deny for `target` in `store` as another pod's accept would. + async fn store_deny( + store: &buzz_auth::InMemoryCommandReplayGuard, + target: &nostr::PublicKey, + ) -> buzz_pubsub::NipFiDisconnect { + store_deny_for(store, TEST_ISS, target).await + } + + async fn store_deny_for( + store: &buzz_auth::InMemoryCommandReplayGuard, + issuer: &str, + target: &nostr::PublicKey, + ) -> buzz_pubsub::NipFiDisconnect { + use buzz_auth::CommandReplayGuard as _; + let until = chrono::Utc::now() + chrono::Duration::seconds(300); + let jti = uuid::Uuid::new_v4().to_string(); + let outcome = store + .try_claim(buzz_auth::CommandClaim { + issuer, + jti: &jti, + ttl_secs: 60, + target, + until, + capacity: 10, + now: chrono::Utc::now(), + }) + .await + .unwrap(); + assert_eq!(outcome, buzz_auth::ClaimOutcome::Claimed); + buzz_pubsub::NipFiDisconnect { + issuer: issuer.to_owned(), + pubkey_bytes: target.to_bytes().to_vec(), + until_unix: until.timestamp(), + until_unix_nanos: until.timestamp_subsec_nanos(), + } + } + + /// Runs the consumer for a capacity-one pod over `source`, fed by the + /// returned broadcast sender, with a live subscription. + async fn capacity_one_consumer( + source: Arc, + ) -> ( + Arc, + tokio::sync::broadcast::Sender, + tokio::sync::watch::Sender, + tokio::task::JoinHandle<()>, + ) { + let pod = store_pod(1, Arc::clone(&source)).await; + pod.nip_fi_deny_map.as_deref().unwrap().begin_restore(); + let (tx, rx) = tokio::sync::broadcast::channel(16); + let (sub_tx, sub_rx) = + tokio::sync::watch::channel(buzz_pubsub::NipFiSubscription::default()); + let consumer = tokio::spawn(run_nip_fi_disconnect_consumer( + Arc::clone(&pod), + rx, + sub_rx, + vec![source], + )); + (pod, tx, sub_tx, consumer) + } + + fn go_live(sub_tx: &tokio::sync::watch::Sender) { + sub_tx.send_modify(|s| { + s.epoch += 1; + s.live = true; + }); + } + + /// A partly unreadable load on a shadow pod applies the readable records + /// through the shadow close path, which closes no real session, and + /// still fails, so the generation never finishes. + #[tokio::test] + async fn shadow_partial_restore_observes_and_stays_unrestored() { + let source = Arc::new(FailingReplayGuard { + load_unreadable: true.into(), + ..Default::default() + }); + let key = nostr::Keys::generate().public_key(); + let message = store_deny(&source.inner, &key).await; + let mut config = crate::config::Config::for_test(); + config.nip_fi.mode = NipFiMode::Shadow; + config.nip_fi.registry.insert(test_issuer_policy()); + let mut state = build_test_app_state(10, config).await; + state.nip_fi_command_replay = Arc::clone(&source) as _; + let pod = Arc::new(state); + let deny_map = pod.nip_fi_deny_map.as_deref().unwrap(); + let session = IssuerSessions::register(&pod, TEST_ISS, &key); + deny_map.begin_restore(); + assert_eq!( + restore_nip_fi_denies(&pod, &[source as _]).await, + Err("unreadable") + ); + session.assert_open("shadow only observes"); + assert!( + !deny_map.is_restored(), + "a partial load leaves it restoring" + ); + assert_eq!( + merge_nip_fi_disconnect(&pod, &message, chrono::Utc::now()), + NipFiDisconnectApplyResult::Applied(buzz_auth::CrossPodMergeResult::Unchanged), + "the readable record was applied" + ); + } + + /// The consumer's own timer retries a partly unreadable restore: the + /// first attempt applies the readable record and stays closed; once the + /// bad record is gone the next attempt reopens. + #[tokio::test] + async fn consumer_retries_a_partly_unreadable_restore() { + let source = Arc::new(FailingReplayGuard { + load_unreadable: true.into(), + ..Default::default() + }); + let (revoked, bystander) = ( + nostr::Keys::generate().public_key(), + nostr::Keys::generate().public_key(), + ); + store_deny(&source.inner, &revoked).await; + let pod = store_pod(10, Arc::clone(&source) as _).await; + let deny_map = pod.nip_fi_deny_map.as_deref().unwrap(); + deny_map.begin_restore(); + let sessions = [&revoked, &bystander].map(|k| IssuerSessions::register(&pod, TEST_ISS, k)); + let (_tx, rx) = tokio::sync::broadcast::channel(16); + let (sub_tx, sub_rx) = + tokio::sync::watch::channel(buzz_pubsub::NipFiSubscription::default()); + let consumer = tokio::spawn(run_nip_fi_disconnect_consumer( + Arc::clone(&pod), + rx, + sub_rx, + vec![Arc::clone(&source) as _], + )); + tokio::time::pause(); + go_live(&sub_tx); + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + assert_eq!(source.loads.load(std::sync::atomic::Ordering::SeqCst), 1); + sessions[0].assert_closed("readable record past a bad one"); + sessions[1].assert_open("not revoked"); + assert!(!deny_map.is_restored(), "unreadable keeps admission closed"); + + source + .load_unreadable + .store(false, std::sync::atomic::Ordering::SeqCst); + tokio::time::sleep(std::time::Duration::from_millis(1000)).await; + assert_eq!(source.loads.load(std::sync::atomic::Ordering::SeqCst), 2); + assert!(deny_map.is_restored(), "the timer's retry reopens"); + assert!(!is_denied(&pod, &bystander)); + assert!(is_denied(&pod, &revoked)); + consumer.abort(); + } + + /// While restores keep failing, delivered disconnects still close their + /// sessions, admission stays closed, and steady traffic does not postpone + /// the next restore attempt. + #[tokio::test] + async fn failing_restore_still_closes_revoked_sessions() { + let store = Arc::new(buzz_auth::InMemoryCommandReplayGuard::default()); + let failing = Arc::new(FailingReplayGuard { + load_fails: true, + ..Default::default() + }); + let pod = store_pod(10, Arc::clone(&failing) as _).await; + pod.nip_fi_deny_map.as_deref().unwrap().begin_restore(); + let (tx, rx) = tokio::sync::broadcast::channel(16); + let (sub_tx, sub_rx) = + tokio::sync::watch::channel(buzz_pubsub::NipFiSubscription::default()); + let consumer = tokio::spawn(run_nip_fi_disconnect_consumer( + Arc::clone(&pod), + rx, + sub_rx, + vec![Arc::clone(&failing) as _], + )); + let (a, b, bystander, other) = ( + nostr::Keys::generate().public_key(), + nostr::Keys::generate().public_key(), + nostr::Keys::generate().public_key(), + nostr::Keys::generate().public_key(), + ); + let sessions = [&a, &b, &bystander].map(|k| IssuerSessions::register(&pod, TEST_ISS, k)); + // Controlled time from here on: the retry deadline, not scheduler + // pauses, decides how many loads happen. + tokio::time::pause(); + go_live(&sub_tx); + // Steady traffic, a message every 100ms for 2.5s, spanning two retry + // deadlines. + let messages = [store_deny(&store, &a).await, store_deny(&store, &b).await]; + let start = tokio::time::Instant::now(); + let mut i = 0; + while start.elapsed() < std::time::Duration::from_millis(2500) { + tx.send(messages[i % 2].clone()).unwrap(); + i += 1; + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + } + sessions[0].assert_closed("revoked during a failing restore"); + sessions[1].assert_closed("revoked during a failing restore"); + sessions[2].assert_open("not revoked"); + assert!(is_denied(&pod, &other), "admission stays closed"); + assert!( + failing.loads.load(std::sync::atomic::Ordering::SeqCst) >= 3, + "traffic must not postpone the retry" + ); + consumer.abort(); + } + + /// A deny that arrives during the restore and does not fit keeps the pod + /// closed: it restores again and finds the union over capacity. + #[tokio::test] + async fn capacity_miss_during_handoff_keeps_admission_closed() { + let store = Arc::new(buzz_auth::InMemoryCommandReplayGuard::default()); + let (a, b, other) = ( + nostr::Keys::generate().public_key(), + nostr::Keys::generate().public_key(), + nostr::Keys::generate().public_key(), + ); + store_deny(&store, &a).await; + let message = store_deny(&store, &b).await; + let source = StaleFirstLoad::new(Arc::clone(&store), Some(b)); + let (pod, tx, sub_tx, consumer) = capacity_one_consumer(source.clone()).await; + tx.send(message).unwrap(); + go_live(&sub_tx); + // The second load is the restore the missed deny forced. + source.loaded(2).await; + assert!( + !pod.nip_fi_deny_map.as_deref().unwrap().is_restored(), + "a missed deny never reopens admission" + ); + assert!(is_denied(&pod, &other)); + consumer.abort(); + } + + /// A live deny that does not fit after a successful restore closes + /// admission again until the active union fits. + #[tokio::test] + async fn capacity_miss_after_restore_closes_admission() { + let store = Arc::new(buzz_auth::InMemoryCommandReplayGuard::default()); + let (a, b, other) = ( + nostr::Keys::generate().public_key(), + nostr::Keys::generate().public_key(), + nostr::Keys::generate().public_key(), + ); + store_deny(&store, &a).await; + let source = StaleFirstLoad::new(Arc::clone(&store), None); + let (pod, tx, sub_tx, consumer) = capacity_one_consumer(source.clone()).await; + go_live(&sub_tx); + restored(&pod).await; + assert!(!is_denied(&pod, &other), "open once restored"); + tx.send(store_deny(&store, &b).await).unwrap(); + source.loaded(2).await; + assert!( + !pod.nip_fi_deny_map.as_deref().unwrap().is_restored(), + "closed after the miss" + ); + assert!(is_denied(&pod, &other)); + consumer.abort(); + } + + /// A Redis error before the script ran: 503, and the same signed command + /// succeeds on retry. + #[tokio::test] + async fn store_error_before_apply_returns_503_and_the_command_retries() { + let store = Arc::new(buzz_auth::InMemoryCommandReplayGuard::default()); + let failing = store_pod( + 1000, + Arc::new(FailingReplayGuard { + inner: Arc::clone(&store), + ..Default::default() + }), + ) + .await; + let healthy = store_pod(1000, store).await; + let key = nostr::Keys::generate().public_key(); + let token = mint_token(&key.to_hex(), 300, serde_json::json!({})); + assert_eq!( + post_command(&failing, &token, &key.to_hex()).await.0, + StatusCode::SERVICE_UNAVAILABLE + ); + assert!(!is_denied(&failing, &key)); + assert_eq!( + post_command(&healthy, &token, &key.to_hex()).await.0, + StatusCode::OK + ); + } + + /// The script ran but its reply was lost: 503; the same command is then a + /// replay (403), a fresh command succeeds, and the stored deny restores. + #[tokio::test] + async fn lost_reply_returns_503_and_needs_a_fresh_command() { + let store = Arc::new(buzz_auth::InMemoryCommandReplayGuard::default()); + let lossy = store_pod( + 1000, + Arc::new(FailingReplayGuard { + inner: Arc::clone(&store), + applies: true, + ..Default::default() + }), + ) + .await; + let healthy = store_pod( + 1000, + Arc::clone(&store) as Arc, + ) + .await; + let key = nostr::Keys::generate().public_key(); + let token = mint_token(&key.to_hex(), 300, serde_json::json!({})); + assert_eq!( + post_command(&lossy, &token, &key.to_hex()).await.0, + StatusCode::SERVICE_UNAVAILABLE + ); + assert_eq!( + post_command(&healthy, &token, &key.to_hex()).await.0, + StatusCode::FORBIDDEN, + "same jti is a replay" + ); + + let store: Arc = store; + let restarted = store_pod(1000, Arc::clone(&store)).await; + restore_nip_fi_denies(&restarted, std::slice::from_ref(&store)) + .await + .expect("restore"); + assert!(is_denied(&restarted, &key), "the applied deny was stored"); + + let fresh = mint_token(&key.to_hex(), 300, serde_json::json!({})); + assert_eq!( + post_command(&healthy, &fresh, &key.to_hex()).await.0, + StatusCode::OK + ); + } + + /// Capacity holds across pods: each pod's local map has room, but the + /// shared store refuses the second distinct key. + #[tokio::test] + async fn deny_set_capacity_is_enforced_across_pods() { + let store: Arc = + Arc::new(buzz_auth::InMemoryCommandReplayGuard::default()); + let pod_a = store_pod(1, Arc::clone(&store)).await; + let pod_b = store_pod(1, store).await; + let (a, b) = ( + nostr::Keys::generate().public_key(), + nostr::Keys::generate().public_key(), + ); + let token_a = mint_token(&a.to_hex(), 300, serde_json::json!({})); + let token_b = mint_token(&b.to_hex(), 300, serde_json::json!({})); + assert_eq!( + post_command(&pod_a, &token_a, &a.to_hex()).await.0, + StatusCode::OK + ); + assert_eq!( + post_command(&pod_b, &token_b, &b.to_hex()).await.0, + StatusCode::SERVICE_UNAVAILABLE + ); + assert!(!is_denied(&pod_b, &b), "a full shared set records nothing"); + } + + /// A restore that does not fit the local map is a failure, never a + /// truncated success. + #[tokio::test] + async fn over_capacity_restore_is_not_complete() { + let store: Arc = + Arc::new(buzz_auth::InMemoryCommandReplayGuard::default()); + let writer = store_pod(10, Arc::clone(&store)).await; + for _ in 0..2 { + let key = nostr::Keys::generate().public_key(); + let token = mint_token(&key.to_hex(), 300, serde_json::json!({})); + assert_eq!( + post_command(&writer, &token, &key.to_hex()).await.0, + StatusCode::OK + ); + } + let small = store_pod(1, Arc::clone(&store)).await; + assert_eq!( + restore_nip_fi_denies(&small, &[store]).await, + Err("capacity") + ); + } + + /// A restore closes sessions only for targets it added or extended; a + /// target whose held entry already covers the stored one stays open. + #[tokio::test] + async fn restore_closes_only_added_or_extended_targets() { + let store = Arc::new(buzz_auth::InMemoryCommandReplayGuard::default()); + let keys: Vec<_> = (0..3) + .map(|_| nostr::Keys::generate().public_key()) + .collect(); + let (held, extended) = (&keys[0], &keys[2]); + for key in &keys { + store_deny(&store, key).await; + } + let source: Arc = store; + let pod = store_pod(10, Arc::clone(&source)).await; + let map = pod.nip_fi_deny_map.as_deref().unwrap(); + let now = chrono::Utc::now(); + map.merge_cross_pod_deny(TEST_ISS, held, now + chrono::Duration::hours(1), now); + map.merge_cross_pod_deny(TEST_ISS, extended, now + chrono::Duration::seconds(5), now); + let sessions: Vec<_> = keys + .iter() + .map(|k| IssuerSessions::register(&pod, TEST_ISS, k)) + .collect(); + map.begin_restore(); + restore_nip_fi_denies(&pod, &[source]) + .await + .expect("restore"); + sessions[0].assert_open("held entry unchanged"); + sessions[1].assert_closed("entry added"); + sessions[2].assert_closed("entry extended"); + } + + /// A restore that fails part-way still closes every target it can reach: + /// a failure ends neither the pass over entries, nor over issuers and + /// sources, and the first failure still fails the restore. + #[tokio::test] + async fn failed_restore_still_closes_targets_it_added() { + let store = Arc::new(buzz_auth::InMemoryCommandReplayGuard::default()); + let keys = [(); 3].map(|()| nostr::Keys::generate().public_key()); + for key in &keys { + store_deny(&store, key).await; + } + let closed = |pod: &AppState| { + assert!( + is_denied(pod, &nostr::Keys::generate().public_key()), + "admission stays closed" + ); + }; + + // Capacity: the first entry fits, the next two miss. + let full = store_pod(1, Arc::clone(&store) as _).await; + let sessions = keys + .each_ref() + .map(|k| IssuerSessions::register(&full, TEST_ISS, k)); + full.nip_fi_deny_map.as_deref().unwrap().begin_restore(); + assert_eq!( + restore_nip_fi_denies(&full, &[Arc::clone(&store) as _]).await, + Err("capacity") + ); + for session in &sessions { + session.assert_closed("target past a capacity miss"); + } + closed(&full); + + // Store: a failing source, then a healthy one. + let pod = store_pod(10, Arc::clone(&store) as _).await; + let sessions = keys + .each_ref() + .map(|k| IssuerSessions::register(&pod, TEST_ISS, k)); + pod.nip_fi_deny_map.as_deref().unwrap().begin_restore(); + let failing = Arc::new(FailingReplayGuard { + load_fails: true, + ..Default::default() + }); + assert_eq!( + restore_nip_fi_denies(&pod, &[failing, Arc::clone(&store) as _]).await, + Err("store") + ); + for session in &sessions { + session.assert_closed("source after a store error"); + } + closed(&pod); + + // Store: the first issuer the map visits fails to load; the healthy + // issuer after it still closes. + const OTHER_ISS: &str = "https://other-issuer.example"; + let mut config = crate::config::Config::for_test(); + config.nip_fi.registry.insert(test_issuer_policy()); + config.nip_fi.registry.insert(issuer_policy(OTHER_ISS)); + let mut state = build_test_app_state(10, config).await; + let capacity = |issuer: &str| IssuerCapacity { + issuer: issuer.to_owned(), + capacity: 10, + }; + let map = NipFiDenyMap::new(10, vec![capacity(TEST_ISS), capacity(OTHER_ISS)]); + let mut order = map.issuers().into_iter(); + let (failed, healthy) = (order.next().unwrap(), order.next().unwrap()); + state.nip_fi_deny_map = Some(Arc::new(map)); + let pod = Arc::new(state); + let inner = Arc::new(buzz_auth::InMemoryCommandReplayGuard::default()); + let (a, b) = ( + nostr::Keys::generate().public_key(), + nostr::Keys::generate().public_key(), + ); + store_deny_for(&inner, &failed, &a).await; + store_deny_for(&inner, &healthy, &b).await; + let source = Arc::new(FailingReplayGuard { + inner, + fail_issuer: Some(failed), + ..Default::default() + }); + let session = IssuerSessions::register(&pod, &healthy, &b); + pod.nip_fi_deny_map.as_deref().unwrap().begin_restore(); + assert_eq!( + restore_nip_fi_denies(&pod, &[source as _]).await, + Err("store") + ); + session.assert_closed("issuer after a store error"); + closed(&pod); + + // Unreadable: a bad stored record is reported apart from an outage. + let pod = store_pod(10, Arc::clone(&store) as _).await; + let sessions = keys + .each_ref() + .map(|k| IssuerSessions::register(&pod, TEST_ISS, k)); + pod.nip_fi_deny_map.as_deref().unwrap().begin_restore(); + let unreadable = Arc::new(FailingReplayGuard { + load_unreadable: true.into(), + ..Default::default() + }); + assert_eq!( + restore_nip_fi_denies(&pod, &[unreadable, Arc::clone(&store) as _]).await, + Err("unreadable") + ); + for session in &sessions { + session.assert_closed("source after an unreadable record"); + } + closed(&pod); + } + + /// Live delivery still closes sessions when the entry is unchanged. + #[tokio::test] + async fn live_unchanged_delivery_closes_sessions() { + let store = Arc::new(buzz_auth::InMemoryCommandReplayGuard::default()); + let key = nostr::Keys::generate().public_key(); + let message = store_deny(&store, &key).await; + let pod = store_pod(10, store).await; + let now = chrono::Utc::now(); + pod.nip_fi_deny_map + .as_deref() + .unwrap() + .merge_cross_pod_deny(TEST_ISS, &key, now + chrono::Duration::hours(1), now); + let sessions = IssuerSessions::register(&pod, TEST_ISS, &key); + assert_eq!( + apply_nip_fi_disconnect(&pod, &message, now), + NipFiDisconnectApplyResult::Applied(buzz_auth::CrossPodMergeResult::Unchanged) + ); + sessions.assert_closed("unchanged live delivery"); + } + + /// A broadcast lag after a restore restores again: overflow the channel + /// with retained messages while a newer store entry no longer fits, and + /// the pod stays closed. + #[tokio::test] + async fn lag_after_restore_restores_again() { + let store = Arc::new(buzz_auth::InMemoryCommandReplayGuard::default()); + let a = nostr::Keys::generate().public_key(); + let message = store_deny(&store, &a).await; + let source = StaleFirstLoad::new(Arc::clone(&store), None); + let (pod, tx, sub_tx, consumer) = capacity_one_consumer(source.clone()).await; + go_live(&sub_tx); + restored(&pod).await; + store_deny(&store, &nostr::Keys::generate().public_key()).await; + for _ in 0..17 { + tx.send(message.clone()).unwrap(); + } + source.loaded(2).await; + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + assert!( + !pod.nip_fi_deny_map.as_deref().unwrap().is_restored(), + "a lag restores again" + ); + consumer.abort(); + } + + #[test] + fn subscribe_channels_and_restore_sources_follow_mode_and_bridge() { + use buzz_pubsub::conn_control::{ + NIP_FI_DISCONNECT_CHANNEL as E, NIP_FI_SHADOW_DISCONNECT_CHANNEL as S, + }; + let pool = || buzz_pubsub::redis_connection("redis://127.0.0.1:6379").expect("lazy pool"); + for (mode, bridge, channels) in [ + (NipFiMode::Enforce, false, &[E][..]), + (NipFiMode::Enforce, true, &[E, S][..]), + (NipFiMode::Shadow, false, &[E, S][..]), + ] { + assert_eq!( + disconnect_subscribe_channels(mode, bridge), + channels, + "{mode:?} {bridge}" + ); + assert_eq!( + restore_sources(pool(), mode, bridge).len(), + channels.len(), + "{mode:?} {bridge}" + ); + } + } + + /// Fails every claim. With `applies`, the claim is applied to `inner` + /// first and only the reply is lost. + #[derive(Default)] + struct FailingReplayGuard { + inner: Arc, + applies: bool, + load_fails: bool, + /// Fails loads as an undecodable stored record, still returning + /// `inner`'s records as the readable ones. + load_unreadable: std::sync::atomic::AtomicBool, + /// Fails loads for this issuer only. + fail_issuer: Option, + loads: std::sync::atomic::AtomicUsize, + } impl buzz_auth::CommandReplayGuard for FailingReplayGuard { fn try_claim<'a>( &'a self, - _issuer: &'a str, - _jti: &'a str, - _ttl_secs: u64, + claim: buzz_auth::CommandClaim<'a>, ) -> std::pin::Pin< - Box> + Send + 'a>, + Box< + dyn std::future::Future< + Output = Result, + > + Send + + 'a, + >, > { - Box::pin(async { + Box::pin(async move { + if self.applies { + self.inner.try_claim(claim).await?; + } Err(buzz_auth::AuthError::Internal( "simulated Redis outage".into(), )) }) } + + fn load_denies<'a>( + &'a self, + issuer: &'a str, + now: chrono::DateTime, + ) -> buzz_auth::LoadDenies<'a> { + self.loads.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + if self.load_fails || self.fail_issuer.as_deref() == Some(issuer) { + return Box::pin(async { + Err(buzz_auth::AuthError::Internal("simulated Redis outage".into()).into()) + }); + } + if self + .load_unreadable + .load(std::sync::atomic::Ordering::SeqCst) + { + return Box::pin(async move { + Err(buzz_auth::LoadDeniesError::Unreadable { + record: "simulated bad record".into(), + readable: self.inner.load_denies(issuer, now).await?, + }) + }); + } + self.inner.load_denies(issuer, now) + } } async fn guard_error_fails_closed_without_effect(observe_publishes: bool) { - let state = pod(1000, Arc::new(FailingReplayGuard)).await; + let state = pod(1000, Arc::new(FailingReplayGuard::default())).await; let key = nostr::Keys::generate().public_key(); let sessions = IssuerSessions::register(&state, TEST_ISS, &key); let token = mint_token(&key.to_hex(), 300, serde_json::json!({})); @@ -3606,12 +4708,26 @@ mod route_integration_tests { mod external_infra_redis { use super::*; - fn redis_guard() -> Arc { + /// A store on its own connection under `namespace`: pods built with + /// the same namespace share one store; other cases never share its + /// capacity. + fn redis_guard_in(namespace: &str) -> Arc { let url = std::env::var("BUZZ_TEST_REDIS_URL") .or_else(|_| std::env::var("REDIS_URL")) .unwrap_or_else(|_| "redis://127.0.0.1:6379".into()); let pool = buzz_pubsub::redis_connection(&url).expect("redis pool"); - Arc::new(buzz_pubsub::RedisCommandReplayGuard::new(pool)) + Arc::new(buzz_pubsub::RedisCommandReplayGuard::namespaced( + pool, namespace, + )) + } + + fn test_namespace() -> String { + format!("buzz:test:nip-fi:{}", uuid::Uuid::new_v4()) + } + + /// A store private to one case. + fn redis_guard() -> Arc { + redis_guard_in(&test_namespace()) } async fn pod_in(mode: NipFiMode) -> Arc { @@ -3650,6 +4766,7 @@ mod route_integration_tests { )]; config.nip_fi = NipFiRelayConfig { profile_policies: Vec::new(), + accept_shadow_disconnects: false, source: Default::default(), mode: NipFiMode::Shadow, registry: registry.clone(), @@ -3704,23 +4821,468 @@ mod route_integration_tests { assert!(verified.is_ok(), "shadow verifies commands: {verified:?}"); let jti = uuid::Uuid::new_v4().to_string(); - assert!(state - .nip_fi_command_replay - .try_claim(TEST_ISS, &jti, 60) - .await - .unwrap()); + let claim = buzz_auth::CommandClaim { + issuer: TEST_ISS, + jti: &jti, + ttl_secs: 60, + target: &target, + until: chrono::Utc::now() + chrono::Duration::seconds(60), + capacity: 100, + now: chrono::Utc::now(), + }; + use buzz_auth::ClaimOutcome::{Claimed, Replay}; + assert_eq!( + state.nip_fi_command_replay.try_claim(claim).await.unwrap(), + Claimed + ); let shadow = buzz_pubsub::RedisCommandReplayGuard::shadow(redis_pool.clone()); let enforce = buzz_pubsub::RedisCommandReplayGuard::new(redis_pool); - assert!( - !shadow.try_claim(TEST_ISS, &jti, 60).await.unwrap(), + assert_eq!( + shadow.try_claim(claim).await.unwrap(), + Replay, "claim is shadow-prefixed" ); - assert!( - enforce.try_claim(TEST_ISS, &jti, 60).await.unwrap(), + assert_eq!( + enforce.try_claim(claim).await.unwrap(), + Claimed, "enforce claim untouched" ); } + fn claim<'a>( + issuer: &'a str, + jti: &'a str, + target: &'a nostr::PublicKey, + until: chrono::DateTime, + capacity: usize, + ) -> buzz_auth::CommandClaim<'a> { + buzz_auth::CommandClaim { + issuer, + jti, + ttl_secs: 60, + target, + until, + capacity, + now: chrono::Utc::now(), + } + } + + /// An expired entry frees its slot, and a shorter later command never + /// lowers the index score, so a later prune keeps the longer deny. + #[tokio::test] + #[ignore = "requires Redis"] + async fn redis_store_prunes_expired_entries_and_never_lowers_a_score() { + use buzz_auth::ClaimOutcome::Claimed; + let store = redis_guard(); + let issuer = format!("https://{}.example", uuid::Uuid::new_v4()); + let keys: Vec<_> = (0..3) + .map(|_| nostr::Keys::generate().public_key()) + .collect(); + let (a, b, c) = (&keys[0], &keys[1], &keys[2]); + // A base an hour ahead: only the synthetic `now` expires entries, + // never Redis key TTLs on the wall clock. + let t = chrono::Utc::now() + chrono::Duration::hours(1); + let s = chrono::Duration::seconds; + let at = |jti: &'static str, target, until, capacity, now| buzz_auth::CommandClaim { + issuer: &issuer, + jti, + ttl_secs: 60, + target, + until, + capacity, + now, + }; + assert_eq!( + store.try_claim(at("p1", a, t + s(1), 1, t)).await.unwrap(), + Claimed + ); + assert_eq!( + store + .try_claim(at("p2", b, t + s(120), 1, t + s(2))) + .await + .unwrap(), + Claimed, + "an expired entry frees its slot" + ); + assert_eq!( + store + .try_claim(at("p3", b, t + s(30), 2, t + s(2))) + .await + .unwrap(), + Claimed + ); + // A later accept prunes entries whose score is below its now. + assert_eq!( + store + .try_claim(at("p4", c, t + s(90), 2, t + s(60))) + .await + .unwrap(), + Claimed + ); + let mut loaded = store.load_denies(&issuer, t + s(60)).await.unwrap(); + loaded.sort_by_key(|(k, _)| k.to_hex()); + let mut expected = vec![(*b, t + s(120)), (*c, t + s(90))]; + expected.sort_by_key(|(k, _)| k.to_hex()); + assert_eq!(loaded, expected, "the longer deny for b survives the prune"); + } + + /// A deny record restore cannot read fails the load, so the restore + /// fails and admission stays closed rather than dropping it. + #[tokio::test] + #[ignore = "requires Redis"] + async fn redis_store_load_fails_on_unreadable_record() { + let url = std::env::var("BUZZ_TEST_REDIS_URL") + .or_else(|_| std::env::var("REDIS_URL")) + .unwrap_or_else(|_| "redis://127.0.0.1:6379".into()); + let mut conn = buzz_pubsub::redis_connection(&url).expect("redis pool"); + let key = || nostr::Keys::generate().public_key().to_hex(); + let exact = |t: chrono::DateTime| { + format!("{}:{}", t.timestamp(), t.timestamp_subsec_nanos()) + }; + let now = chrono::Utc::now(); + let live = (key(), exact(now + chrono::Duration::seconds(120))); + let expired = (key(), exact(now - chrono::Duration::seconds(1))); + let bytes = |(k, v): (String, String)| (k.into_bytes(), v.into_bytes()); + let cases = [ + ("valid and expired", None, true), + ( + "invalid key", + Some(bytes(("not-a-key".to_owned(), live.1.clone()))), + false, + ), + ( + "invalid until", + Some(bytes((key(), "garbage".to_owned()))), + false, + ), + ( + "until with extra field", + Some(bytes((key(), format!("{}:x", live.1)))), + false, + ), + ( + "until not UTF-8", + Some((key().into_bytes(), vec![0xff, b':', b'0'])), + false, + ), + ( + "key not UTF-8", + Some((vec![0xff; 64], live.1.clone().into_bytes())), + false, + ), + ]; + for (case, extra, ok) in cases { + let namespace = test_namespace(); + let store = redis_guard_in(&namespace); + let issuer = format!("https://{}.example", uuid::Uuid::new_v4()); + let (_, hash) = buzz_pubsub::nip_fi_command_replay::deny_store_keys( + &format!("{namespace}:deny"), + &issuer, + ); + // Written first; HGETALL doesn't promise to return it first. + let mut fields: Vec<_> = extra.into_iter().collect(); + fields.extend([bytes(live.clone()), bytes(expired.clone())]); + // One transaction, so the fixture always expires. + let _: () = redis::pipe() + .atomic() + .cmd("HSET") + .arg(&hash) + .arg(&fields) + .ignore() + .cmd("EXPIRE") + .arg(&hash) + .arg(60) + .ignore() + .query_async(&mut conn) + .await + .unwrap(); + let loaded = match store.load_denies(&issuer, now).await { + Ok(loaded) => { + assert!(ok, "{case}: an unreadable record must fail the load"); + loaded + } + Err(buzz_auth::LoadDeniesError::Unreadable { readable, .. }) => { + assert!(!ok, "{case}: a readable hash must load"); + readable + } + Err(e) => panic!("{case}: an unreadable record is not a store error: {e}"), + }; + let keys: Vec<_> = loaded.into_iter().map(|(k, _)| k.to_hex()).collect(); + assert_eq!( + keys, + vec![live.0.clone()], + "{case}: every readable active record still loads" + ); + } + } + + /// One bad record does not hide the issuer's good ones: restore + /// applies the good record and closes its sessions, leaves unrelated + /// sessions open, and still fails as `unreadable`, so admission stays + /// closed until the bad record is removed and a retry restores. + #[tokio::test] + #[ignore = "requires Redis"] + async fn redis_restore_applies_readable_records_past_a_bad_one() { + let url = std::env::var("BUZZ_TEST_REDIS_URL") + .or_else(|_| std::env::var("REDIS_URL")) + .unwrap_or_else(|_| "redis://127.0.0.1:6379".into()); + let mut conn = buzz_pubsub::redis_connection(&url).expect("redis pool"); + let namespace = test_namespace(); + let store = redis_guard_in(&namespace); + let (revoked, bystander) = ( + nostr::Keys::generate().public_key(), + nostr::Keys::generate().public_key(), + ); + let now = chrono::Utc::now(); + let outcome = store + .try_claim(buzz_auth::CommandClaim { + issuer: TEST_ISS, + jti: "good", + ttl_secs: 60, + target: &revoked, + until: now + chrono::Duration::seconds(120), + capacity: 10, + now, + }) + .await + .unwrap(); + assert_eq!(outcome, buzz_auth::ClaimOutcome::Claimed); + let (_, hash) = buzz_pubsub::nip_fi_command_replay::deny_store_keys( + &format!("{namespace}:deny"), + TEST_ISS, + ); + let _: () = redis::cmd("HSET") + .arg(&hash) + .arg("not-a-key") + .arg("1:0") + .query_async(&mut conn) + .await + .unwrap(); + + let pod = store_pod(10, Arc::clone(&store)).await; + let deny_map = pod.nip_fi_deny_map.as_deref().unwrap(); + let revoked_session = IssuerSessions::register(&pod, TEST_ISS, &revoked); + let bystander_session = IssuerSessions::register(&pod, TEST_ISS, &bystander); + let generation = deny_map.begin_restore(); + assert_eq!( + restore_nip_fi_denies(&pod, &[Arc::clone(&store)]).await, + Err("unreadable") + ); + revoked_session.assert_closed("good record past a bad one"); + bystander_session.assert_open("unrelated key"); + assert_eq!( + deny_map.deny_status(TEST_ISS, &bystander, chrono::Utc::now()), + buzz_auth::DenyStatus::Unavailable, + "admission stays closed while a record is unreadable" + ); + + // The runbook's repair; the same generation's retry then reopens. + let _: () = redis::cmd("HDEL") + .arg(&hash) + .arg("not-a-key") + .query_async(&mut conn) + .await + .unwrap(); + assert_eq!(restore_nip_fi_denies(&pod, &[store]).await, Ok(())); + assert!(deny_map.finish_restore(generation)); + assert!(!is_denied(&pod, &bystander), "reopened after the repair"); + assert!(is_denied(&pod, &revoked), "the good record still denies"); + } + + /// A full revoke clears any cutoff stored for its target, whether the + /// stored `until` grows, stays equal or is kept over a shorter one, and + /// pruning an expired target clears its cutoff too. + #[tokio::test] + #[ignore = "requires Redis"] + async fn redis_store_accept_and_prune_clear_revoke_through() { + let url = std::env::var("BUZZ_TEST_REDIS_URL") + .or_else(|_| std::env::var("REDIS_URL")) + .unwrap_or_else(|_| "redis://127.0.0.1:6379".into()); + let conn = buzz_pubsub::redis_connection(&url).expect("redis pool"); + let namespace = test_namespace(); + let store = redis_guard_in(&namespace); + let issuer = format!("https://{}.example", uuid::Uuid::new_v4()); + let cutoffs = buzz_pubsub::nip_fi_command_replay::revoke_through_key( + &format!("{namespace}:deny"), + &issuer, + ); + let (a, b) = ( + nostr::Keys::generate().public_key(), + nostr::Keys::generate().public_key(), + ); + let t = chrono::Utc::now() + chrono::Duration::hours(1); + let s = chrono::Duration::seconds; + let claim = |jti, target, until, now| buzz_auth::CommandClaim { + issuer: &issuer, + jti, + ttl_secs: 60, + target, + until, + capacity: 10, + now, + }; + let seed = |key: &nostr::PublicKey| { + let mut conn = conn.clone(); + let (cutoffs, field) = (cutoffs.clone(), key.to_hex()); + async move { + let _: () = redis::pipe() + .atomic() + .cmd("HSET") + .arg(&cutoffs) + .arg(field) + .arg(1) + .ignore() + .cmd("EXPIRE") + .arg(&cutoffs) + .arg(60) + .ignore() + .query_async(&mut conn) + .await + .unwrap(); + } + }; + let held = |key: &nostr::PublicKey| { + let mut conn = conn.clone(); + let (cutoffs, field) = (cutoffs.clone(), key.to_hex()); + async move { + let held: bool = redis::cmd("HEXISTS") + .arg(cutoffs) + .arg(field) + .query_async(&mut conn) + .await + .unwrap(); + held + } + }; + store + .try_claim(claim("c0", &a, t + s(60), t)) + .await + .unwrap(); + for (jti, until, case) in [("c1", t + s(60), "equal"), ("c2", t + s(30), "shorter")] { + seed(&a).await; + store.try_claim(claim(jti, &a, until, t)).await.unwrap(); + assert!(!held(&a).await, "{case} until clears the cutoff"); + } + // b expires before the next accept's now and is pruned. + store.try_claim(claim("c3", &b, t + s(1), t)).await.unwrap(); + seed(&b).await; + store + .try_claim(claim("c4", &a, t + s(120), t + s(10))) + .await + .unwrap(); + assert!(!held(&b).await, "pruning clears the cutoff"); + } + + /// The Redis script checks replay and shared capacity before writing, + /// keeps the exact maximum `until`, and records no entry for a past + /// `until`. + #[tokio::test] + #[ignore = "requires Redis"] + async fn redis_store_checks_before_writing_and_keeps_exact_until() { + use buzz_auth::ClaimOutcome::{Claimed, Full, Replay}; + let store = redis_guard(); + let issuer = format!("https://{}.example", uuid::Uuid::new_v4()); + let (a, b) = ( + nostr::Keys::generate().public_key(), + nostr::Keys::generate().public_key(), + ); + let base = chrono::Utc::now() + chrono::Duration::seconds(120); + // Two deadlines inside the same millisecond: the later must win. + let later = base + chrono::Duration::nanoseconds(900); + let earlier = base + chrono::Duration::nanoseconds(100); + + assert_eq!( + store + .try_claim(claim(&issuer, "j1", &a, later, 1)) + .await + .unwrap(), + Claimed + ); + assert_eq!( + store + .try_claim(claim(&issuer, "j1", &a, later, 1)) + .await + .unwrap(), + Replay + ); + assert_eq!( + store + .try_claim(claim(&issuer, "j2", &a, earlier, 1)) + .await + .unwrap(), + Claimed, + "an existing key needs no new slot" + ); + assert_eq!( + store + .try_claim(claim(&issuer, "j3", &b, later, 1)) + .await + .unwrap(), + Full + ); + // `Full` wrote no claim: the same jti succeeds once there is room. + assert_eq!( + store + .try_claim(claim(&issuer, "j3", &b, later, 2)) + .await + .unwrap(), + Claimed + ); + let past = chrono::Utc::now() - chrono::Duration::seconds(1); + let c = nostr::Keys::generate().public_key(); + assert_eq!( + store + .try_claim(claim(&issuer, "j4", &c, past, 2)) + .await + .unwrap(), + Claimed + ); + assert_eq!( + store + .try_claim(claim(&issuer, "j4", &c, past, 2)) + .await + .unwrap(), + Replay + ); + + let mut loaded = store + .load_denies(&issuer, chrono::Utc::now()) + .await + .unwrap(); + loaded.sort_by_key(|(k, _)| k.to_hex()); + let mut expected = vec![(a, later), (b, later)]; + expected.sort_by_key(|(k, _)| k.to_hex()); + assert_eq!( + loaded, expected, + "exact maximum until; no entry for a past until" + ); + } + + /// The bridge: an enforce pod restores denies accepted by shadow pods + /// only with `BUZZ_NIP_FI_ACCEPT_SHADOW_DISCONNECTS`; without it the + /// shadow store is never read. + #[tokio::test] + #[ignore = "requires Redis"] + async fn bridge_restores_shadow_period_denies_on_enforce_pods() { + let shadow = pod_in(NipFiMode::Shadow).await; + let key = nostr::Keys::generate().public_key(); + let token = mint_token(&key.to_hex(), 300, serde_json::json!({})); + assert_eq!( + post_command(&shadow, &token, &key.to_hex()).await.0, + StatusCode::OK + ); + + for (bridge, denied) in [(false, false), (true, true)] { + let enforce = pod_in(NipFiMode::Enforce).await; + let sources = + restore_sources(enforce.redis_pool.clone(), NipFiMode::Enforce, bridge); + restore_nip_fi_denies(&enforce, &sources) + .await + .expect("restore"); + assert_eq!(is_denied(&enforce, &key), denied, "bridge={bridge}"); + } + } + /// Run `state`'s production disconnect subscriber and apply what it /// hears through the production consumer, like `main.rs`. Yields /// the target of each applied message. @@ -3728,7 +5290,7 @@ mod route_integration_tests { state: &Arc, ) -> tokio::sync::mpsc::UnboundedReceiver> { let mut rx = state.pubsub.subscribe_nip_fi_disconnect(); - let channels = disconnect_subscribe_channels(state.config.nip_fi.mode); + let channels = disconnect_subscribe_channels(state.config.nip_fi.mode, false); tokio::spawn(Arc::clone(&state.pubsub).run_nip_fi_disconnect_subscriber(channels)); let consumer = Arc::clone(state); let (seen_tx, seen) = tokio::sync::mpsc::unbounded_channel(); @@ -3858,9 +5420,10 @@ mod route_integration_tests { #[tokio::test] #[ignore = "requires Redis"] async fn redis_command_replay_on_second_pod_is_denied() { + let namespace = test_namespace(); command_replayed_on_second_pod_is_denied_without_effect( - redis_guard(), - redis_guard(), + redis_guard_in(&namespace), + redis_guard_in(&namespace), true, ) .await; diff --git a/crates/buzz-relay/src/audio/handler.rs b/crates/buzz-relay/src/audio/handler.rs index 7e37db56f7..9305b0a911 100644 --- a/crates/buzz-relay/src/audio/handler.rs +++ b/crates/buzz-relay/src/audio/handler.rs @@ -898,15 +898,31 @@ async fn run_active_audio_connection( crate::nip_fi_test_hooks::before_deny_set_check(tenant.community()).await; if let Some(assertion) = &nip_fi_assertion { if let Some(deny_map) = state.nip_fi_deny_map.as_deref() { - if crate::nip_fi_core::assertion_denied(deny_map, assertion, chrono::Utc::now()) { + if let Some(refusal) = + crate::nip_fi_core::assertion_denied(deny_map, assertion, chrono::Utc::now()) + { warn!( channel_id = %channel_id, pubkey = %pubkey_hex, - "NIP-FI deny-set hit at audio post-registration check — denying" + class = ?refusal.class, + "NIP-FI deny-set check refused audio post-registration — denying" ); - control.deny_nip_fi_enforce(crate::nip_fi_shadow::DENY_SET.by(Some(pubkey))); - auth_line.finish(AuthResult::Denied(crate::access::AuthReason::DenySet)); - deny_audio_authorization(&mut ws_send, &control, &mut terminal_ctrl_rx).await; + control.deny_nip_fi_enforce(refusal.by(Some(pubkey))); + auth_line.finish(AuthResult::Denied(match refusal.class { + buzz_auth::DenialClass::AuthorizationDenied => { + crate::access::AuthReason::DenySet + } + _ => crate::access::AuthReason::AuthorizationUnavailable, + })); + exit_authorization_refusal( + &mut ws_send, + &control, + &mut terminal_ctrl_rx, + true, + refusal.class, + serde_json::Value::Null, + ) + .await; return; } } @@ -4898,6 +4914,40 @@ mod tests { ); } + /// While the deny map restores, audio AUTH refuses as + /// `authorization unavailable` with a bare close, for a revoked key and + /// an unknown one, never `authorization denied`. + #[tokio::test] + async fn audio_restoring_deny_map_emits_authorization_unavailable() { + use tokio_tungstenite::tungstenite::Message; + let deadline = chrono::Utc::now() + chrono::Duration::hours(1); + let denied = nostr::Keys::generate(); + for (state_key, signer) in [(Some(denied.public_key()), &denied), (None, &denied)] { + let state = audio_deny_state(state_key.as_ref()).await; + state + .nip_fi_deny_map + .as_deref() + .expect("deny map") + .begin_restore(); + let assertion = + buzz_auth::VerifiedAssertion::for_test(Some(signer.public_key()), vec![deadline]); + let (wire, _) = run_audio_auth_wire(state, Some(assertion), signer, true).await; + assert_eq!( + wire.first(), + Some(&Message::Text( + audio_denial(buzz_auth::DenialClass::AuthorizationUnavailable).into() + )) + ); + assert!( + !wire.iter().any(|m| matches!( + m, + Message::Close(Some(f)) if f.code == tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode::Policy + )), + "a bare close, never the 1008 of a revocation: {wire:?}" + ); + } + } + /// Records every frame the denial writer emits for a registered audio /// control, then lets a registry scan race it in `scan_first` order. async fn audio_denial_with_concurrent_scan( diff --git a/crates/buzz-relay/src/config.rs b/crates/buzz-relay/src/config.rs index fd02bea605..f1c55a19d9 100644 --- a/crates/buzz-relay/src/config.rs +++ b/crates/buzz-relay/src/config.rs @@ -639,7 +639,7 @@ fn parse_operator_listener_delivery_urls( Ok(endpoints) } -fn parse_bool(name: &str, default: bool) -> Result { +pub(crate) fn parse_bool(name: &str, default: bool) -> Result { match std::env::var(name) { Err(std::env::VarError::NotPresent) => Ok(default), Err(error) => Err(ConfigError::InvalidValue(format!( diff --git a/crates/buzz-relay/src/handlers/auth.rs b/crates/buzz-relay/src/handlers/auth.rs index dd05a0ef24..b63fffd306 100644 --- a/crates/buzz-relay/src/handlers/auth.rs +++ b/crates/buzz-relay/src/handlers/auth.rs @@ -962,17 +962,27 @@ pub async fn handle_auth(event: nostr::Event, conn: Arc, state: // [FI-TRACE-DENY-SET] if let Some(assertion) = &conn.nip_fi_assertion { if let Some(deny_map) = state.nip_fi_deny_map.as_deref() { - if crate::nip_fi_core::assertion_denied(deny_map, assertion, chrono::Utc::now()) - { - attempt.log(AuthResult::Denied(crate::access::AuthReason::DenySet)); - metrics::counter!( - "buzz_nip_fi_admission_denied_total", - "reason" => "deny_set_post_registration" - ) - .increment(1); + if let Some(refusal) = crate::nip_fi_core::assertion_denied( + deny_map, + assertion, + chrono::Utc::now(), + ) { + let (auth_reason, reason) = match refusal.class { + buzz_auth::DenialClass::AuthorizationDenied => ( + crate::access::AuthReason::DenySet, + "deny_set_post_registration", + ), + _ => ( + crate::access::AuthReason::AuthorizationUnavailable, + "deny_set_restoring", + ), + }; + attempt.log(AuthResult::Denied(auth_reason)); + metrics::counter!("buzz_nip_fi_admission_denied_total", "reason" => reason) + .increment(1); conn.community_control - .deny_nip_fi_enforce(crate::nip_fi_shadow::DENY_SET.by(Some(pubkey))); - deny_nip_fi_auth(&conn, buzz_auth::DenialClass::AuthorizationDenied); + .deny_nip_fi_enforce(refusal.by(Some(pubkey))); + deny_nip_fi_auth(&conn, refusal.class); return; } } @@ -4824,6 +4834,53 @@ mod tests { } } + /// While the deny map restores, root AUTH refuses with the + /// `authorization unavailable` terminal frame and a bare close, never + /// `authorization denied`. + #[tokio::test] + #[ignore = "requires Postgres — runs in postgres-ci nextest lane"] + async fn fi_restoring_deny_map_emits_terminal_authorization_unavailable() { + let pool = sqlx::PgPool::connect(&crate::test_support::database_url()) + .await + .expect("PostgreSQL must be available"); + let mut state = (*state_with_pool(pool, |_| {}).await).clone(); + let deny_map = std::sync::Arc::new(buzz_auth::NipFiDenyMap::new( + 16, + vec![buzz_auth::IssuerCapacity { + issuer: "test-issuer".to_owned(), + capacity: 16, + }], + )); + deny_map.begin_restore(); + state.nip_fi_deny_map = Some(deny_map); + let state = std::sync::Arc::new(state); + let mut harness = AuthHarness::new(true); + let community = *harness.conn.tenant.community().as_uuid(); + sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") + .bind(community) + .bind(format!("fi-restoring-{}.example", community.simple())) + .execute(state.db.pool()) + .await + .expect("insert community"); + harness.run(harness.auth_event(), state).await; + assert_eq!( + harness + .terminal_rx + .try_recv() + .expect("terminal denial frame"), + crate::nip_fi_session::denial_frame( + crate::nip_fi_session::NipFiWsRoute::Root, + buzz_auth::DenialClass::AuthorizationUnavailable, + ), + ); + assert!(harness.conn.cancel.is_cancelled()); + assert_eq!( + *harness.conn.community_control.disconnect_reason().borrow(), + None, + "a bare close, never the 1008 of a revocation" + ); + } + /// Carl's coverage gap: a matching-key FI connection whose pubkey is /// banned gets the terminal `authorization denied` NOTICE and the /// socket closes; off mode keeps `OK false` on ctrl, then closes. diff --git a/crates/buzz-relay/src/main.rs b/crates/buzz-relay/src/main.rs index 2a7d508efe..71ea6c20e0 100644 --- a/crates/buzz-relay/src/main.rs +++ b/crates/buzz-relay/src/main.rs @@ -627,10 +627,13 @@ async fn run_relay_main(boot: BootTracker) -> anyhow::Result<()> { // command; every pod merges the deny entry and closes matching sessions. // Subscribe before the Redis subscriber starts so messages buffer (up to the // channel capacity) instead of being dropped until the consumer below runs. - let mut nip_fi_disconnect_rx = pubsub.subscribe_nip_fi_disconnect(); + let nip_fi_disconnect_rx = pubsub.subscribe_nip_fi_disconnect(); + let nip_fi_subscription = pubsub.watch_nip_fi_subscription(); let pubsub_for_nip_fi = Arc::clone(&pubsub); - let nip_fi_channels = - buzz_relay::api::nip_fi::disconnect_subscribe_channels(config.nip_fi.mode); + let nip_fi_channels = buzz_relay::api::nip_fi::disconnect_subscribe_channels( + config.nip_fi.mode, + config.nip_fi.accept_shadow_disconnects, + ); tokio::spawn(async move { pubsub_for_nip_fi .run_nip_fi_disconnect_subscriber(nip_fi_channels) @@ -709,6 +712,10 @@ async fn run_relay_main(boot: BootTracker) -> anyhow::Result<()> { &nip_fi.command_configs, ) .map_err(|e| anyhow::anyhow!("NIP-FI startup failed: {e}"))?; + // Closed until the consumer below restores it from Redis. + if let Some(deny_map) = app_state.nip_fi_deny_map.as_deref() { + deny_map.begin_restore(); + } } else if nip_fi.mode.evaluates() { return Err(anyhow::anyhow!( "NIP-FI: failed to construct JWKS key source \ @@ -1387,46 +1394,23 @@ async fn run_relay_main(boot: BootTracker) -> anyhow::Result<()> { tokio::spawn(Arc::clone(&state).run_conn_control_consumer(rx)); } - // Cross-pod NIP-FI disconnect consumer: receive deny entries from remote - // pods, merge them into the local deny map (same max(until) rule), and - // close any matching sessions. Every pod subscribes; the publishing pod - // also receives its own message and applies it — this is idempotent because - // the deny entry was already inserted locally before the publish. - // - // The consumer delegates to `apply_nip_fi_disconnect` which owns all - // validation, merge, and session-close logic. This keeps the loop body - // minimal and makes the exact production path testable end-to-end. + // NIP-FI deny restoration + cross-pod consumer. One task owns both: it + // keeps admission closed until the deny map is restored from Redis for + // the current subscription, applies remote deny entries (same max(until) + // rule, closing matching sessions), and restores again after any lost + // subscription or lag. See `run_nip_fi_disconnect_consumer`. { - let state_for_nip_fi = Arc::clone(&state); - let nip_fi_mode = state.config.nip_fi.mode; - tokio::spawn(async move { - loop { - match nip_fi_disconnect_rx.recv().await { - Ok(msg) => { - let now = chrono::Utc::now(); - buzz_relay::api::nip_fi::apply_nip_fi_disconnect( - &state_for_nip_fi, - &msg, - now, - ); - } - Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => { - buzz_relay::api::nip_fi::count_disconnect_event( - nip_fi_mode, - "buzz_nip_fi_disconnect_lag_total", - "cross_pod", - "lag", - n, - ); - tracing::warn!("NIP-FI disconnect consumer lagged by {n} messages"); - } - Err(tokio::sync::broadcast::error::RecvError::Closed) => { - tracing::error!("NIP-FI disconnect broadcast channel closed"); - break; - } - } - } - }); + let sources = buzz_relay::api::nip_fi::restore_sources( + state.redis_pool.clone(), + state.config.nip_fi.mode, + state.config.nip_fi.accept_shadow_disconnects, + ); + tokio::spawn(buzz_relay::api::nip_fi::run_nip_fi_disconnect_consumer( + Arc::clone(&state), + nip_fi_disconnect_rx, + nip_fi_subscription, + sources, + )); } let router = build_router(Arc::clone(&state)); diff --git a/crates/buzz-relay/src/nip_fi_config.rs b/crates/buzz-relay/src/nip_fi_config.rs index a6ed9c3280..fb359a9463 100644 --- a/crates/buzz-relay/src/nip_fi_config.rs +++ b/crates/buzz-relay/src/nip_fi_config.rs @@ -13,6 +13,7 @@ //! | `BUZZ_NIP_FI_ISSUERS` | If enforce | JSON array of issuer configs (see [`IssuerEnvConfig`]). | //! | `BUZZ_NIP_FI_COMMUNITIES` | If enforce | JSON array mapping each community's canonical URI to its authorized issuers (see [`CommunityEnvConfig`]). | //! | `BUZZ_NIP_FI_MAX_CONNECTION_LIFETIME_SECS` | If enforce | Per-partition limit on session lifetime. | +//! | `BUZZ_NIP_FI_ACCEPT_SHADOW_DISCONNECTS` | No | `true` lets an enforce pod honor disconnects accepted by shadow pods, for the deploy that switches shadow → enforce. Default `false`; rejected unless the mode is `enforce`. | //! | `BUZZ_NIP_FI_PROVISION_BINDING` | No | JSON `{"host_suffix", "authorized_issuers"}` binding communities created one label under the suffix; read in every mode (see [`buzz_auth::ProvisionBindingPolicy`]). | //! //! Each `BUZZ_NIP_FI_ISSUERS` entry also carries the S4 command-API fields. @@ -295,6 +296,9 @@ pub struct NipFiRelayConfig { pub command_configs: Vec<(String, crate::api::nip_fi::CommandIssuerEnvConfig)>, /// Output-only publication policies; independent of authorization capabilities. pub profile_policies: Vec, + /// `BUZZ_NIP_FI_ACCEPT_SHADOW_DISCONNECTS`: an enforce pod also receives + /// and restores disconnects accepted by shadow pods. Enforce mode only. + pub accept_shadow_disconnects: bool, } impl NipFiRelayConfig { @@ -304,6 +308,14 @@ impl NipFiRelayConfig { /// missing or invalid (fail-closed: no token is accepted until this passes). pub fn from_env() -> Result { let mode = parse_mode()?; + let accept_shadow_disconnects = + crate::config::parse_bool("BUZZ_NIP_FI_ACCEPT_SHADOW_DISCONNECTS", false)?; + if accept_shadow_disconnects && mode != NipFiMode::Enforce { + return Err(ConfigError::InvalidValue( + "BUZZ_NIP_FI_ACCEPT_SHADOW_DISCONNECTS requires BUZZ_NIP_FI_MODE=enforce" + .to_string(), + )); + } let source = parse_community_source()?; if source == CommunitySource::Database && !std::env::var("BUZZ_NIP_FI_COMMUNITIES") @@ -331,6 +343,7 @@ impl NipFiRelayConfig { max_connection_lifetime_secs: 0, command_configs: Vec::new(), profile_policies: Vec::new(), + accept_shadow_disconnects, }); } @@ -548,6 +561,7 @@ impl NipFiRelayConfig { max_connection_lifetime_secs, command_configs, profile_policies, + accept_shadow_disconnects, }) } } @@ -877,6 +891,7 @@ mod tests { "BUZZ_NIP_FI_COMMUNITIES", "BUZZ_NIP_FI_MAXIMUM_ASSERTION_AGE_SECS", "BUZZ_NIP_FI_MAX_CONNECTION_LIFETIME_SECS", + "BUZZ_NIP_FI_ACCEPT_SHADOW_DISCONNECTS", ]; /// Same-process witness (plain libtest, not nextest): a fixture's @@ -922,6 +937,32 @@ mod tests { assert!(matches!(mode, NipFiMode::Off)); } + #[test] + fn accept_shadow_disconnects_requires_enforce() { + let _guard = super::NIP_FI_ENV_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let _env = EnvGuard::new(NIP_FI_VARS); + + std::env::set_var("BUZZ_NIP_FI_ACCEPT_SHADOW_DISCONNECTS", "true"); + for mode in ["off", "shadow", "deny_protected"] { + std::env::set_var("BUZZ_NIP_FI_MODE", mode); + let err = NipFiRelayConfig::from_env().expect_err(mode); + assert!( + err.to_string() + .contains("BUZZ_NIP_FI_ACCEPT_SHADOW_DISCONNECTS"), + "{mode}: {err}" + ); + } + std::env::set_var("BUZZ_NIP_FI_ACCEPT_SHADOW_DISCONNECTS", "false"); + std::env::set_var("BUZZ_NIP_FI_MODE", "off"); + assert!( + !NipFiRelayConfig::from_env() + .unwrap() + .accept_shadow_disconnects + ); + } + #[test] fn off_mode_requires_no_other_config() { let _guard = super::NIP_FI_ENV_LOCK diff --git a/crates/buzz-relay/src/nip_fi_core.rs b/crates/buzz-relay/src/nip_fi_core.rs index fb536f9156..ef75663d47 100644 --- a/crates/buzz-relay/src/nip_fi_core.rs +++ b/crates/buzz-relay/src/nip_fi_core.rs @@ -216,18 +216,32 @@ pub(crate) fn asserted_key_matches( assertion.asserted_key() == Some(proven_pubkey) } -/// Whether the deny set holds `(iss, k)` or, for an agent assertion, -/// `(iss, owner)` (NIP-FI.md, admission step 7). +/// The deny-set step's refusal, if any (NIP-FI.md, admission step 7): +/// [`DENY_SET_RESTORING`](crate::nip_fi_shadow::DENY_SET_RESTORING) +/// (authorization unavailable) while the deny map is still restoring, else +/// [`DENY_SET`](crate::nip_fi_shadow::DENY_SET) when the deny set holds +/// `(iss, k)` or, for an agent assertion, `(iss, owner)`. pub(crate) fn assertion_denied( deny_map: &impl crate::nip_fi_http::HttpDenyMap, assertion: &VerifiedAssertion, now: chrono::DateTime, -) -> bool { +) -> Option { + use buzz_auth::DenyStatus; let issuer = assertion.identity().issuer(); - [assertion.asserted_key(), assertion.owner()] + // Each key's verdict is one read; an unavailable one wins over a + // revoked one, so a restore never reports as a revocation. + let mut refusal = None; + for key in [assertion.asserted_key(), assertion.owner()] .into_iter() .flatten() - .any(|key| deny_map.is_denied(issuer, &key, now)) + { + match deny_map.deny_status(issuer, &key, now) { + DenyStatus::Allowed => {} + DenyStatus::Denied => refusal = refusal.or(Some(crate::nip_fi_shadow::DENY_SET)), + DenyStatus::Unavailable => refusal = Some(crate::nip_fi_shadow::DENY_SET_RESTORING), + } + } + refusal.map(|refusal| refusal.by(assertion.asserted_key())) } /// The NIP-FI facts a live session is registered under: its admitting issuer @@ -559,6 +573,70 @@ pub(crate) mod tests { map } + #[test] + fn a_restoring_deny_map_refuses_as_unavailable_not_revoked() { + let key = nostr::Keys::generate().public_key(); + let assertion = agent_assertion(key, nostr::Keys::generate().public_key()); + let now = chrono::Utc::now(); + let map = deny_map_denying(&key); + map.begin_restore(); + let refusal = assertion_denied(&map, &assertion, now).expect("restoring refuses"); + assert_eq!( + refusal.class, + buzz_auth::DenialClass::AuthorizationUnavailable + ); + let generation = map.begin_restore(); + assert!(map.finish_restore(generation)); + let refusal = assertion_denied(&map, &assertion, now).expect("active entry refuses"); + assert_eq!(refusal.class, buzz_auth::DenialClass::AuthorizationDenied); + } + + /// Starts a restore right after its first lookup: a check that spans a + /// restore's start. + struct RestoresDuringCheck(buzz_auth::NipFiDenyMap); + + impl crate::nip_fi_http::sealed::Sealed for RestoresDuringCheck {} + impl crate::nip_fi_http::HttpDenyMap for RestoresDuringCheck { + fn is_denied( + &self, + _: &str, + _: &nostr::PublicKey, + _: chrono::DateTime, + ) -> bool { + unreachable!("admission reads deny_status only") + } + + fn deny_status( + &self, + issuer: &str, + pubkey: &nostr::PublicKey, + now: chrono::DateTime, + ) -> buzz_auth::DenyStatus { + let status = self.0.deny_status(issuer, pubkey, now); + self.0.begin_restore(); + status + } + } + + #[test] + fn a_restore_starting_during_the_check_refuses_as_unavailable() { + let (agent, owner) = ( + nostr::Keys::generate().public_key(), + nostr::Keys::generate().public_key(), + ); + let assertion = agent_assertion(agent, owner); + let now = chrono::Utc::now(); + for revoked in [agent, nostr::Keys::generate().public_key()] { + let map = RestoresDuringCheck(deny_map_denying(&revoked)); + let refusal = assertion_denied(&map, &assertion, now).expect("refused"); + assert_eq!( + refusal.class, + buzz_auth::DenialClass::AuthorizationUnavailable, + "never reported as a revocation" + ); + } + } + #[test] fn deny_entry_for_the_owner_denies_its_agent_assertion() { let agent = nostr::Keys::generate().public_key(); @@ -566,13 +644,9 @@ pub(crate) mod tests { let unrelated = nostr::Keys::generate().public_key(); let assertion = agent_assertion(agent, owner); let now = chrono::Utc::now(); - assert!(assertion_denied(&deny_map_denying(&owner), &assertion, now)); - assert!(assertion_denied(&deny_map_denying(&agent), &assertion, now)); - assert!(!assertion_denied( - &deny_map_denying(&unrelated), - &assertion, - now - )); + assert!(assertion_denied(&deny_map_denying(&owner), &assertion, now).is_some()); + assert!(assertion_denied(&deny_map_denying(&agent), &assertion, now).is_some()); + assert!(assertion_denied(&deny_map_denying(&unrelated), &assertion, now).is_none()); } #[test] @@ -583,11 +657,9 @@ pub(crate) mod tests { Some(key), vec![chrono::Utc::now() + chrono::Duration::seconds(300)], ); - assert!(!assertion_denied( - &deny_map_denying(&other), - &assertion, - chrono::Utc::now() - )); + assert!( + assertion_denied(&deny_map_denying(&other), &assertion, chrono::Utc::now()).is_none() + ); } #[test] diff --git a/crates/buzz-relay/src/nip_fi_http.rs b/crates/buzz-relay/src/nip_fi_http.rs index a7ef3620a9..797b0bbd25 100644 --- a/crates/buzz-relay/src/nip_fi_http.rs +++ b/crates/buzz-relay/src/nip_fi_http.rs @@ -186,6 +186,22 @@ pub(crate) trait HttpDenyMap: sealed::Sealed { /// `now` (`now < until`). Implementations fail closed: a poisoned or /// unavailable backing store returns `true` (deny). fn is_denied(&self, issuer: &str, pubkey: &PublicKey, now: DateTime) -> bool; + + /// The verdict for `(issuer, pubkey)` from one read, so a refusal keeps + /// its cause: unavailable while the deny set is restoring, else denied + /// or allowed. + fn deny_status( + &self, + issuer: &str, + pubkey: &PublicKey, + now: DateTime, + ) -> buzz_auth::DenyStatus { + if self.is_denied(issuer, pubkey, now) { + buzz_auth::DenyStatus::Denied + } else { + buzz_auth::DenyStatus::Allowed + } + } } pub(crate) mod sealed { @@ -199,6 +215,15 @@ impl HttpDenyMap for buzz_auth::NipFiDenyMap { fn is_denied(&self, issuer: &str, pubkey: &PublicKey, now: DateTime) -> bool { buzz_auth::NipFiDenyMap::is_denied(self, issuer, pubkey, now) } + + fn deny_status( + &self, + issuer: &str, + pubkey: &PublicKey, + now: DateTime, + ) -> buzz_auth::DenyStatus { + buzz_auth::NipFiDenyMap::deny_status(self, issuer, pubkey, now) + } } /// The deny map for a relay that has no `nip_fi_deny_map`. @@ -500,7 +525,9 @@ where } let reason = match deny.stage { Stage::Pairing => Some("nip_fi_http_key_mismatch"), - Stage::DenySet => Some("nip_fi_http_denied_pubkey"), + Stage::DenySet if deny.class == DenialClass::AuthorizationDenied => { + Some("nip_fi_http_denied_pubkey") + } _ => None, }; if let Some(reason) = reason { @@ -749,11 +776,12 @@ where // Step 7: deny-map check — (iss, pubkey) and, for an agent assertion, // (iss, owner) must not be in an active deny window. Private-state // denial. [FI-INV-14] [NIP-FI.md:624-627] - if assertion_denied(deny_map, &assertion, Utc::now()) { - return Err(denied( - crate::nip_fi_shadow::DENY_SET, - crate::access::AuthReason::DenySet, - )); + if let Some(refusal) = assertion_denied(deny_map, &assertion, Utc::now()) { + let reason = match refusal.class { + DenialClass::AuthorizationDenied => crate::access::AuthReason::DenySet, + _ => crate::access::AuthReason::AuthorizationUnavailable, + }; + return Err(denied(refusal, reason)); } Ok((proof, assertion)) @@ -2057,6 +2085,41 @@ mod tests { } } + /// A restoring deny map refuses protected HTTP 503 + /// `authorization unavailable`, never 403 `authorization denied`. + #[test] + fn restoring_deny_map_refuses_http_as_unavailable() { + use buzz_auth::{IssuerCapacity, NipFiDenyMap}; + let (agent, owner) = (any_pubkey(), any_pubkey()); + let verifier = AgentVerifier(crate::nip_fi_shadow_session::tests::owned_assertion( + agent, owner, + )); + let map = NipFiDenyMap::new( + 8, + vec![IssuerCapacity { + issuer: "test-issuer".to_owned(), + capacity: 8, + }], + ); + let now = Utc::now(); + map.merge_cross_pod_deny("test-issuer", &owner, now + chrono::Duration::hours(1), now); + map.begin_restore(); + let headers = bearer_headers("Bearer a.b.c"); + let refused = admit_stateless( + &headers, + || Ok(Nip98Proof::new(agent, ())), + &communities(), + Some(&verifier as &dyn VerifyAssertion), + NipFiMode::Enforce, + &map, + ) + .now_or_never() + .expect("env resolution never waits"); + let (status, body) = denial_parts(refused); + assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE); + assert_eq!(body, b"authorization unavailable\n"); + } + // Pins: step 7 reads the owner of an agent assertion. With the owner's // deny entry live, enforce denies the agent with the deny-map row and // shadow records the would-deny; without it, enforce admits and the diff --git a/crates/buzz-relay/src/nip_fi_shadow.rs b/crates/buzz-relay/src/nip_fi_shadow.rs index 1c5f4b815e..a3f087cd5e 100644 --- a/crates/buzz-relay/src/nip_fi_shadow.rs +++ b/crates/buzz-relay/src/nip_fi_shadow.rs @@ -127,6 +127,13 @@ pub(crate) const UNRESOLVED: &str = "community_unresolved"; /// The deny-set step's would-deny, before attribution. pub(crate) const DENY_SET: WouldDeny = WouldDeny::new(Stage::DenySet, DenialClass::AuthorizationDenied, "deny_set"); +/// The deny-set step while the deny map is still restoring: the deny set is +/// unknown, so authorization is unavailable rather than revoked. +pub(crate) const DENY_SET_RESTORING: WouldDeny = WouldDeny::new( + Stage::DenySet, + DenialClass::AuthorizationUnavailable, + "deny_set_restoring", +); /// The reason for a community binding that went stale before admission. pub(crate) const STALE: &str = "community_stale"; diff --git a/crates/buzz-relay/src/nip_fi_shadow_session.rs b/crates/buzz-relay/src/nip_fi_shadow_session.rs index 3b43f8fb88..9eeeb1720d 100644 --- a/crates/buzz-relay/src/nip_fi_shadow_session.rs +++ b/crates/buzz-relay/src/nip_fi_shadow_session.rs @@ -19,7 +19,7 @@ use nostr::PublicKey; use tokio_util::sync::CancellationToken; use crate::nip_fi_core::NipFiSession; -use crate::nip_fi_shadow::{Stage, WouldDeny, DENY_SET}; +use crate::nip_fi_shadow::{Stage, WouldDeny}; use crate::state::AppState; #[derive(Clone, Copy)] @@ -167,8 +167,8 @@ impl ShadowSession { self.sessions .registered() .insert(self.id, Arc::downgrade(self)); - if deny_listed(state, &self.assertion) { - self.decide(Err(DENY_SET.by(self.assertion.asserted_key()))); + if let Some(refusal) = deny_refusal(state, &self.assertion) { + self.decide(Err(refusal)); } } @@ -318,19 +318,20 @@ pub(crate) fn upgrade_denied( community: &metrics::SharedString, assertion: &VerifiedAssertion, ) -> bool { - let denied = deny_listed(state, assertion); - if denied { - let verdict = Err(DENY_SET.by(assertion.asserted_key())); - crate::nip_fi_shadow::record_for("ws", community.clone(), verdict); + let refusal = deny_refusal(state, assertion); + if let Some(refusal) = refusal { + crate::nip_fi_shadow::record_for("ws", community.clone(), Err(refusal)); } - denied + refusal.is_some() } -fn deny_listed(state: &AppState, assertion: &VerifiedAssertion) -> bool { +/// The deny-set step's would-deny: revoked for an active entry, unavailable +/// while the deny map is still restoring. +fn deny_refusal(state: &AppState, assertion: &VerifiedAssertion) -> Option { state .nip_fi_deny_map .as_deref() - .is_some_and(|map| crate::nip_fi_core::assertion_denied(map, assertion, chrono::Utc::now())) + .and_then(|map| crate::nip_fi_core::assertion_denied(map, assertion, chrono::Utc::now())) } #[cfg(test)] @@ -521,6 +522,29 @@ pub(crate) mod tests { assert_eq!(records, ["deny_set/denied"]); } + /// While the deny map restores, the shadow upgrade records the deny set + /// as unavailable, never revoked, for a listed key and an unknown one. + #[test] + fn restoring_deny_map_records_unavailable_not_revoked() { + let key = Keys::generate().public_key(); + let records = shadow_records(async move { + let state = shadow_state(Some(key)).await; + state.nip_fi_deny_map.as_deref().unwrap().begin_restore(); + for target in [key, Keys::generate().public_key()] { + let assertion = VerifiedAssertion::for_test( + Some(target), + vec![Utc::now() + Duration::hours(1)], + ); + assert!(upgrade_denied( + &state, + &crate::nip_fi_shadow::BOUND.into(), + &assertion + )); + } + }); + assert_eq!(records, ["deny_set/unavailable", "deny_set/unavailable"]); + } + /// Delivers a real cross-pod disconnect for `key` to a shadow pod. pub(crate) fn deliver(state: &AppState, key: &PublicKey) -> buzz_auth::CrossPodMergeResult { let msg = buzz_pubsub::NipFiDisconnect { diff --git a/crates/buzz-relay/src/router.rs b/crates/buzz-relay/src/router.rs index 1753d4281b..e427584351 100644 --- a/crates/buzz-relay/src/router.rs +++ b/crates/buzz-relay/src/router.rs @@ -944,13 +944,15 @@ async fn nip11_or_ws_handler( // [FI-TRACE-DENY-SET] if let Some(assertion) = &nip_fi_assertion { if let Some(deny_map) = state.nip_fi_deny_map.as_deref() { - if crate::nip_fi_core::assertion_denied(deny_map, assertion, chrono::Utc::now()) { + if let Some(refusal) = + crate::nip_fi_core::assertion_denied(deny_map, assertion, chrono::Utc::now()) + { crate::nip_fi_shadow::record_denial( "ws", crate::nip_fi_shadow::enforce_label(&state, raw_host), - crate::nip_fi_shadow::DENY_SET.by(assertion.asserted_key()), + refusal, ); - return http_denial(buzz_auth::DenialClass::AuthorizationDenied).into_response(); + return http_denial(refusal.class).into_response(); } } } @@ -2669,6 +2671,7 @@ mod tests { // a token-carrying request. config.nip_fi = NipFiRelayConfig { profile_policies: Vec::new(), + accept_shadow_disconnects: false, source: Default::default(), mode, registry: IssuerRegistry::new(), @@ -4533,6 +4536,7 @@ mod tests { config.nip_fi = NipFiRelayConfig { profile_policies: Vec::new(), + accept_shadow_disconnects: false, source: Default::default(), mode: NipFiMode::Enforce, registry: { @@ -4700,6 +4704,30 @@ mod tests { ); } + /// While the deny map restores, the upgrade is refused + /// 503 `authorization unavailable`, for a revoked key and an unknown one. + #[tokio::test] + async fn restoring_deny_map_refuses_ws_admission_as_unavailable() { + let denied_key = nostr::Keys::generate().public_key(); + for key in [denied_key, nostr::Keys::generate().public_key()] { + let state = nip_fi_deny_state(&denied_key).await; + state + .nip_fi_deny_map + .as_deref() + .expect("deny map") + .begin_restore(); + let bearer = format!("Bearer {}", mint_deny_test_token(&key.to_hex())); + let resp = + nip_fi_gate_response(state, "/", Some("Nostr-Federated-Identity"), Some(&bearer)) + .await; + assert_eq!(resp.status(), axum::http::StatusCode::SERVICE_UNAVAILABLE); + let body = axum::body::to_bytes(resp.into_body(), 64) + .await + .expect("body"); + assert_eq!(body.as_ref(), b"authorization unavailable\n"); + } + } + #[tokio::test] async fn deny_map_blocks_ws_admission_for_live_entry() { // A key with a live deny entry is refused 403 `authorization_denied` diff --git a/docs/nips/NIP-FI.md b/docs/nips/NIP-FI.md index 8409ed29ed..e776060f83 100644 --- a/docs/nips/NIP-FI.md +++ b/docs/nips/NIP-FI.md @@ -427,13 +427,18 @@ A disconnect call causes the relay to: MUST NOT be subsequently admitted. Connections registered under another issuer are not affected. -The deny set is held **in relay memory only** — no durable storage, no schema -changes. A relay restart MAY forget active deny entries. If the issuer stops +The relay holds the deny set in memory and MAY also keep it in shared storage +that outlives a relay process, with each entry expiring at its `until`. A +relay that keeps such storage MUST record an accepted command there before +reporting success, and MUST NOT admit protected connections or protected HTTP requests after a restart +until it has restored the active entries. A relay without such storage MAY +forget active deny entries on restart. In that case, if the issuer stops issuing assertions and re-push completes before any expired-entry reconnection attempt, the residual exposure after a restart is bounded by `max(0, min(exp, iat + maximum_assertion_age) - now)`. If the issuer continues issuing or re-push does not complete in time, that formula does not apply and -access may continue beyond it. [FI-TRACE-DENY-SET] +access may continue beyond it. Neither mode covers loss of the shared storage +itself. [FI-TRACE-DENY-SET] The relay MUST bound the deny set size **per issuer**. Capacity exhaustion under one issuer MUST NOT cause rejection of another issuer's commands; the `503` @@ -565,12 +570,13 @@ VerifyCommandJwt(token, request_method, request_path, request_body_pubkey): target_pubkey=target_k, until=until ) or DENY(authorization_denied) // replay: jti already reserved or REJECT(503) // capacity: deny set full; neither mutation applied + or REJECT(authorization_unavailable) // shared storage outcome unknown: jti and deny entry may be recorded; no sessions closed return CommandResult(target_pubkey=target_k, caller=(claims.iss, claims.sub)) ``` -Any failure at any step is fail-closed: no side effects occur and the relay -returns the appropriate error. +Any failure at any step is fail-closed: no sessions are closed and the relay +returns the appropriate error. Only an unknown shared-storage outcome, described below, can leave state behind. ### Request @@ -588,7 +594,7 @@ performs all pure authorization checks and then, as its single atomic admission mutation (step 7), simultaneously reserves the `(iss, jti)` replay identity and inserts the deny entry — both or neither. A capacity failure at that step rejects `503`; neither the jti nor the deny entry is recorded, and the caller may safely -retry the same signed command. On success, the relay MUST close every live connection +retry the same signed command. A relay that keeps the deny set in shared storage and cannot learn whether its write applied MUST reject `503` `authorization_unavailable` and close no sessions. The `jti` and deny entry may already be recorded, so the caller retries with a freshly signed command (new `jti`), not the same one. On success, the relay MUST close every live connection registered under the command's issuer (`claims.iss`) whose proven key equals `CommandResult.target_pubkey` or whose recorded owner equals `CommandResult.target_pubkey`, whether or not admission has completed. @@ -612,6 +618,7 @@ under the merge rule. | Missing or invalid command JWT | `401` / `403` | Per the rejection table | | Malformed request body or `until` exceeds ceiling | `400` | `bad request\n` | | Deny set at capacity | `503` | `deny set full\n` | +| Shared deny storage outcome unknown | `503` | `authorization unavailable\n` | ## HTTP ingress @@ -863,7 +870,7 @@ is unavailable. | assertion or proof absent | `missing_evidence` | `auth-required: authentication required` | `401`; `WWW-Authenticate: Nostr`; `Content-Type: text/plain; charset=utf-8`; body `authentication required\n` | | unknown or community-unauthorized issuer; malformed, invalid, or expired evidence | `evidence_rejected` | `restricted: evidence rejected` | `403`; `Content-Type: text/plain; charset=utf-8`; body `evidence rejected\n` | | assertion–key mismatch; unauthorized issuer principal, signed-target–body mismatch, or replayed `jti` on a signed command; active deny-set entry for pubkey | `authorization_denied` | `restricted: authorization denied` | `403`; `Content-Type: text/plain; charset=utf-8`; body `authorization denied\n` | -| required JWKS snapshot or community/Host resolution unavailable | `authorization_unavailable` | `restricted: authorization unavailable` | `503`; `Content-Type: text/plain; charset=utf-8`; body `authorization unavailable\n` | +| required JWKS snapshot, community/Host resolution, or restored deny set unavailable | `authorization_unavailable` | `restricted: authorization unavailable` | `503`; `Content-Type: text/plain; charset=utf-8`; body `authorization unavailable\n` | A denial decided on a WebSocket upgrade is the HTTP response in place of `101`. A denial decided on a protected HTTP request is the HTTP response. @@ -999,7 +1006,9 @@ longest still-live assertion it has issued to ensure no unexpired assertion slides through the expiry boundary; this is an operational recommendation, not a protocol invariant. -A relay restart clears the in-memory deny set. The issuer SHOULD re-push +A relay that holds the deny set only in memory clears it on restart; a relay +that keeps it in shared storage restores active entries before admitting +protected connections. For memory-only relays, the issuer SHOULD re-push still-active entries on observed restart, but re-push is not required and carries no specified completion bound. If the issuer stops issuing assertions and re-push completes before any expired-entry reconnection diff --git a/docs/operator-nip-fi-bindings.md b/docs/operator-nip-fi-bindings.md index 037bb727d6..b628c339a9 100644 --- a/docs/operator-nip-fi-bindings.md +++ b/docs/operator-nip-fi-bindings.md @@ -241,6 +241,97 @@ Ways out, in order: 2. If that cannot land quickly, set `BUZZ_NIP_FI_MODE=off`. `off` loads no snapshot, so pods boot and admit as they did before NIP-FI. +## Revocation during a deploy + +An accepted `POST /api/nip-fi/disconnect` is written to Redis before the relay +answers 200, and each entry expires at its `until`. A pod that starts, or that +loses its Redis subscription, restores every active entry before it admits a +NIP-FI assertion again. Until then it refuses every assertion-bearing +connection, so a key revoked just before a deploy can't come back in on a +fresh pod. + +What this covers, and what it does not: + +- **Covered:** pod restarts, and a pod that loses its Redis subscription or + falls behind on it. +- **Not covered:** a pod that stays healthy still learns of a disconnect only + through live pub/sub, which is best effort. If a publication never reaches + it, that pod neither closes the target's open sessions nor refuses the + target at its own admission check until its next restore. +- **Not covered:** losing Redis data. Run Redis with a non-evicting + `maxmemory-policy` of `noeviction`, with persistence if you need + revocations to survive a Redis restart. Every deny key carries an expiry, + so any `volatile-*` policy can evict it. +- **Redis down at startup:** if Redis is completely unreachable at boot, the + relay exits before it binds, and the process supervisor restarts it. If + Redis is reachable but the restore fails, the pod runs and refuses + assertion-bearing connections with `503` (authorization unavailable) until + it has restored. Watch `buzz_nip_fi_deny_restore_failures_total{reason}`. +- **Unreadable deny record:** `reason="unreadable"` means Redis answered but + a stored deny record could not be decoded: its field is not a hex pubkey, + or its value is not exactly `secs:nanos`. The pod still applies the + issuer's other records and closes their sessions, but stays closed until the + record is removed. The warning log names the record. Find it in the + issuer's deny hash, `buzz:nip-fi:deny-until:` + (`buzz:nip-fi:shadow-deny-until:…` in shadow mode), with `HGETALL`, then + `HDEL` that field. The pod retries on its own. Removing the record drops + that revocation, so send the disconnect again if it is still needed. +- **Deny set over capacity on a pod:** if a revocation this pod receives does + not fit its `deny_set_capacity`, the pod closes admission the same way and + restores until its active entries fit. + +### Disconnect responses + +- `403` is a replay: this command's `jti` was already used. +- `503 deny set full` means the issuer's shared deny set is full. Nothing was + recorded, so the same command can be retried. +- `503 authorization unavailable` after a Redis error means the outcome is + unknown. If Redis applied the command before the reply was lost, the deny is + already stored and its `jti` is used up, so a retry returns `403`. Send a + freshly signed command to get a `200`. + +### Capacity + +`deny_set_capacity` applies to each issuer across all pods, not per pod. If a +restore doesn't fit a pod's map, the pod stays closed and +`buzz_nip_fi_deny_restore_failures_total{reason="capacity"}` increases. This +can happen during the shadow → enforce switch below, when an enforce pod +restores both stores. To recover, either: + +- raise `deny_set_capacity` to at least the sum of the issuer's live entries + and roll out; or +- wait for entries to expire (at most one assertion lifetime). The pod retries + the restore on its own. + +Count live entries for an issuer with +`ZCOUNT buzz:nip-fi:deny: ( +inf` and +`ZCOUNT buzz:nip-fi:shadow-deny: ( +inf`, where +`` is the lowercase hex SHA-256 of the exact issuer URI. + +### Switching shadow → enforce + +Shadow pods write their accepts under `buzz:nip-fi:shadow-deny:*`, and enforce +pods normally never read them. For the deploy that switches modes, the bridge +setting `BUZZ_NIP_FI_ACCEPT_SHADOW_DISCONNECTS=true` makes enforce pods also +subscribe to and restore shadow accepts. It gives disconnects accepted by +shadow pods real effect on enforce pods, so keep the issuer configuration +identical across the switch. + +Let `L` be the largest `maximum_assertion_age_seconds + skew_seconds` across +configured issuers. + +1. Deploy this relay version while still in `shadow`. +2. Wait until the last pod of the previous version has been gone for at least + `L`. Older versions keep accepts only in memory, so this wait lets those + expire before anything relies on the store. +3. Deploy `BUZZ_NIP_FI_MODE=enforce` with + `BUZZ_NIP_FI_ACCEPT_SHADOW_DISCONNECTS=true`. +4. Keep the setting until both hold: + - the last shadow pod has been gone for at least `L`; + - `ZCOUNT buzz:nip-fi:shadow-deny: ( +inf` is `0` for + every configured issuer. +5. Deploy without the setting. + ## Assertion policy ID change This release changes every verified assertion's policy ID once, on purpose. diff --git a/scripts/run-tests.sh b/scripts/run-tests.sh index a7864569ba..496bc4b100 100755 --- a/scripts/run-tests.sh +++ b/scripts/run-tests.sh @@ -109,6 +109,11 @@ run_unit_tests() { cargo test -p buzz-pubsub --lib -- --exact --nocapture \ tests::queue_full_retain_does_not_wait_and_schedules_reconciliation + # NIP-FI deny-store keys and `until` rounding (infra-free). Mirrors + # `just test-unit`. + run_test_step "buzz-pubsub NIP-FI deny store tests" \ + cargo test -p buzz-pubsub --lib nip_fi_command_replay::tests:: -- --nocapture + run_test_step "buzz-voice tests" \ cargo test -p buzz-voice --lib -- --nocapture