diff --git a/crates/buzz-auth/src/lib.rs b/crates/buzz-auth/src/lib.rs index 626c0e2f85..cebf8c3b9e 100644 --- a/crates/buzz-auth/src/lib.rs +++ b/crates/buzz-auth/src/lib.rs @@ -79,14 +79,15 @@ pub use nip_fi::{ 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, + DenialClass, DenyEntry, DenyScope, 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/assertion.rs b/crates/buzz-auth/src/nip_fi/assertion.rs index 7431b50c15..915019c659 100644 --- a/crates/buzz-auth/src/nip_fi/assertion.rs +++ b/crates/buzz-auth/src/nip_fi/assertion.rs @@ -122,6 +122,7 @@ pub struct VerifiedAssertion { owner: Option, capabilities: CanonicalCapabilities, authority_deadlines: Vec>, + issued_at: DateTime, assertion_policy_id: AssertionPolicyId, transport_contract_id: TransportContractId, revalidation_dependencies: RevalidationDependencies, @@ -138,6 +139,7 @@ impl VerifiedAssertion { owner: Option, capabilities: CanonicalCapabilities, authority_deadlines: Vec>, + issued_at: DateTime, assertion_policy_id: AssertionPolicyId, transport_contract_id: TransportContractId, revalidation_dependencies: RevalidationDependencies, @@ -153,6 +155,7 @@ impl VerifiedAssertion { owner, capabilities, authority_deadlines, + issued_at, assertion_policy_id, transport_contract_id, revalidation_dependencies, @@ -209,6 +212,12 @@ impl VerifiedAssertion { .expect("authority_deadlines is non-empty by construction") } + /// The verified signed `iat`: the time-checked claim, never optional + /// profile evidence. A `revoke_through` cutoff compares against this. + pub const fn issued_at(&self) -> DateTime { + self.issued_at + } + /// The stable assertion-policy identity. pub const fn assertion_policy_id(&self) -> AssertionPolicyId { self.assertion_policy_id @@ -239,6 +248,7 @@ impl VerifiedAssertion { None, CanonicalCapabilities::from_pairs(vec![]), vec![Utc::now() + Duration::seconds(3600)], + Utc::now(), AssertionPolicyId::zero(), TransportContractId::zero(), RevalidationDependencies::new( @@ -287,6 +297,7 @@ impl VerifiedAssertion { owner: None, capabilities: CanonicalCapabilities::from_pairs(vec![]), authority_deadlines, + issued_at: Utc::now(), assertion_policy_id: AssertionPolicyId::zero(), transport_contract_id: TransportContractId::zero(), revalidation_dependencies: RevalidationDependencies { @@ -306,6 +317,13 @@ impl VerifiedAssertion { self.owner = Some(owner); self } + + /// Test-only: the same assertion with verified signed `iat` `issued_at`. + #[must_use] + pub fn with_issued_at_for_test(mut self, issued_at: DateTime) -> Self { + self.issued_at = issued_at; + self + } } impl RevalidationDependencies { diff --git a/crates/buzz-auth/src/nip_fi/command.rs b/crates/buzz-auth/src/nip_fi/command.rs index 0b16df0d6e..1e03623ca6 100644 --- a/crates/buzz-auth/src/nip_fi/command.rs +++ b/crates/buzz-auth/src/nip_fi/command.rs @@ -31,7 +31,7 @@ use super::command_replay::{ClaimOutcome, CommandClaim, CommandReplayGuard}; use super::config::{ IssuerPolicy, IssuerRegistry, MAX_JTI_BYTES, MAX_SUBJECT_BYTES, MAX_TOKEN_BYTES, }; -use super::deny_map::{NipFiDenyMap, Reservation, ReserveError}; +use super::deny_map::{DenyEntry, DenyScope, NipFiDenyMap, Reservation, ReserveError}; use super::verifier::{ enforce_compact_structure, enforce_signature_shape, parse_header, parse_numeric_date, parse_unique_claims, select_unique_jwk, validate_jwk, AssertionKeySet, IssuerKeySource, @@ -156,6 +156,8 @@ pub struct CommandResult { pub caller_sub: String, /// The `until` timestamp from the signed JWT. pub until: DateTime, + /// The command's scope: whole key, or `revoke_through` when present. + pub scope: DenyScope, } /// Errors from [`CommandVerifier::verify`]. @@ -295,6 +297,7 @@ impl CommandVerifier { ttl_secs: claim_ttl_secs(cmd.effective_expiry, now, cmd.skew_seconds), target: &cmd.target_pubkey, until: cmd.until, + scope: cmd.scope, capacity: cmd.capacity, now, }; @@ -304,7 +307,9 @@ impl CommandVerifier { Ok(ClaimOutcome::Full) => return Err(CommandError::DenySetFull), Err(_) => return Err(CommandError::AuthorizationUnavailable), } - Ok(Self::commit(&cmd, reservation)) + // Scope activity is judged at the deny mutation, after the await: an + // entry that expired meanwhile must contribute nothing. + Ok(Self::commit(&cmd, reservation, Utc::now)) } /// Verify against this pod's deny map only, with an injectable clock. @@ -324,7 +329,7 @@ impl CommandVerifier { ) -> Result { let cmd = self.authenticate_at(token, request_method, request_path, body_pubkey, now)?; let reservation = self.reserve(&cmd, now)?; - Ok(Self::commit(&cmd, reservation)) + Ok(Self::commit(&cmd, reservation, || now)) } /// Steps 1–5: authenticate and authorize the command with no side effects. @@ -447,6 +452,8 @@ impl CommandVerifier { // until: NumericDate. let until = numeric_date(&claims, "until")?; + // revoke_through: optional integral NumericDate; absent = whole key. + let scope = DenyScope::from_revoke_through(revoke_through(&claims)?); // Validate `until` ceiling: until <= now + skew + maximum_assertion_age. let max_assertion_age = @@ -484,6 +491,7 @@ impl CommandVerifier { // effective_expiry = min(exp, iat + maximum_command_age). effective_expiry: exp.min(iat_plus_cmd_age), until, + scope, skew_seconds: base_policy.skew_seconds(), capacity: cmd_policy.deny_set_capacity(), }) @@ -504,13 +512,22 @@ impl CommandVerifier { } /// Step 7: record the jti and deny entry; cannot fail. - fn commit(cmd: &AuthenticatedCommand, reservation: Reservation) -> CommandResult { - reservation.commit(cmd.effective_expiry, cmd.until); + fn commit( + cmd: &AuthenticatedCommand, + reservation: Reservation, + now: impl FnOnce() -> DateTime, + ) -> CommandResult { + let entry = DenyEntry { + until: cmd.until, + scope: cmd.scope, + }; + reservation.commit(cmd.effective_expiry, entry, now); CommandResult { target_pubkey: cmd.target_pubkey, caller_iss: cmd.issuer.clone(), caller_sub: cmd.sub.clone(), until: cmd.until, + scope: cmd.scope, } } } @@ -523,6 +540,7 @@ struct AuthenticatedCommand { jti: String, effective_expiry: DateTime, until: DateTime, + scope: DenyScope, skew_seconds: u64, capacity: usize, } @@ -542,6 +560,25 @@ fn claim_str<'a>(claims: &'a Map, key: &str) -> Option<&'a str> { claims.get(key)?.as_str().filter(|s| !s.is_empty()) } +/// The optional `revoke_through` claim. A present value must be an integral +/// NumericDate that is representable as a timestamp; `null`, nonnumeric, +/// fractional or out-of-range values are rejected. +fn revoke_through(claims: &Map) -> Result, CommandError> { + let Some(value) = claims.get("revoke_through") else { + return Ok(None); + }; + let secs = match (value.as_i64(), value.as_f64()) { + (Some(secs), _) => secs, + // `i64::MAX as f64` rounds up to 2^63, so the upper bound is exclusive. + (None, Some(f)) if f.fract() == 0.0 && f >= i64::MIN as f64 && f < i64::MAX as f64 => { + f as i64 + } + _ => return Err(CommandError::EvidenceRejected), + }; + DateTime::from_timestamp(secs, 0).ok_or(CommandError::EvidenceRejected)?; + Ok(Some(secs)) +} + fn numeric_date(claims: &Map, key: &str) -> Result, CommandError> { let value = claims.get(key).ok_or(CommandError::EvidenceRejected)?; parse_numeric_date(value).map_err(|_| CommandError::EvidenceRejected) @@ -1439,6 +1476,105 @@ mod tests { } } + /// A replay guard that accepts after sleeping, so a deny entry can expire + /// while the claim is in flight. + struct SlowAcceptGuard(std::time::Duration); + + impl CommandReplayGuard for SlowAcceptGuard { + fn try_claim<'a>( + &'a self, + _claim: CommandClaim<'a>, + ) -> std::pin::Pin< + Box< + dyn std::future::Future> + + Send + + 'a, + >, + > { + let wait = self.0; + Box::pin(async move { + tokio::time::sleep(wait).await; + Ok(ClaimOutcome::Claimed) + }) + } + + fn load_denies<'a>( + &'a self, + _issuer: &'a str, + _now: DateTime, + ) -> crate::nip_fi::LoadDenies<'a> { + Box::pin(async { Ok(Vec::new()) }) + } + } + + #[tokio::test] + async fn existing_whole_key_expiring_during_the_claim_leaves_cutoff_only() { + let cv = test_command_verifier(); + let target = target_key(); + let start = Utc::now(); + cv.deny_map().merge_cross_pod_deny( + ISS, + &target, + DenyEntry::whole_key(start + Duration::milliseconds(500)), + || start, + ); + let c = start.timestamp(); + let token = mint_cmd_jwt(&target, 300, serde_json::json!({ "revoke_through": c })); + let guard = SlowAcceptGuard(std::time::Duration::from_millis(1200)); + cv.verify(&token, METHOD, PATH, &target, &guard) + .await + .expect("accepted"); + let now = Utc::now(); + let fresh = DateTime::from_timestamp(c + 1, 0).unwrap(); + let old = DateTime::from_timestamp(c, 0).unwrap(); + assert!( + !cv.deny_map().denies(ISS, &target, fresh, now), + "fresh admitted" + ); + assert!(cv.deny_map().denies(ISS, &target, old, now), "old refused"); + assert_eq!( + cv.deny_map() + .close_scope(ISS, &target, DenyScope::IssuedThrough(c), now), + DenyScope::IssuedThrough(c), + "close scope stays cutoff-only" + ); + } + + #[tokio::test] + async fn incoming_whole_key_expiring_during_the_claim_does_not_widen_a_cutoff() { + let cv = test_command_verifier(); + let target = target_key(); + let start = Utc::now(); + let c = start.timestamp(); + cv.deny_map().merge_cross_pod_deny( + ISS, + &target, + DenyEntry { + until: start + Duration::seconds(300), + scope: DenyScope::IssuedThrough(c), + }, + || start, + ); + // `until` is at most one second away. + let token = mint_cmd_jwt(&target, 1, serde_json::json!({})); + let guard = SlowAcceptGuard(std::time::Duration::from_millis(1200)); + cv.verify(&token, METHOD, PATH, &target, &guard) + .await + .expect("accepted"); + let now = Utc::now(); + let fresh = DateTime::from_timestamp(c + 1, 0).unwrap(); + assert!( + !cv.deny_map().denies(ISS, &target, fresh, now), + "fresh admitted" + ); + assert_eq!( + cv.deny_map() + .close_scope(ISS, &target, DenyScope::IssuedThrough(c), now), + DenyScope::IssuedThrough(c), + "the expired whole-key command does not widen the cutoff" + ); + } + /// A verifier whose issuer shard holds exactly one deny entry. fn one_slot_verifier() -> CommandVerifier { use crate::nip_fi::verifier::{AssertionKeySet, StaticIssuerKeySource}; @@ -1681,4 +1817,99 @@ mod tests { "must be admitted past the fractional deadline" ); } + + // ── revoke_through ──────────────────────────────────────────────────────── + + #[test] + fn revoke_through_scopes_the_deny_to_assertions_issued_through_it() { + let cv = test_command_verifier(); + let target = target_key(); + let now = Utc::now(); + let c = now.timestamp(); + let token = mint_cmd_jwt(&target, 300, serde_json::json!({ "revoke_through": c })); + let result = cv + .verify_at(&token, METHOD, PATH, &target, now) + .expect("accepted"); + assert_eq!(result.scope, DenyScope::IssuedThrough(c)); + let later = now + Duration::seconds(1); + let old = DateTime::from_timestamp(c, 0).unwrap(); + let fresh = DateTime::from_timestamp(c + 1, 0).unwrap(); + assert!( + cv.deny_map().denies(ISS, &target, old, later), + "iat <= C is refused" + ); + assert!( + !cv.deny_map().denies(ISS, &target, fresh, later), + "iat > C is admitted" + ); + } + + #[test] + fn integral_float_revoke_through_matches_the_integer_cutoff() { + let cv = test_command_verifier(); + let target = target_key(); + let now = Utc::now(); + let c = now.timestamp(); + for value in [ + serde_json::json!(c as f64), + serde_json::from_str(&format!("{c}e0")).unwrap(), + ] { + let token = mint_cmd_jwt(&target, 300, serde_json::json!({ "revoke_through": value })); + let result = cv + .verify_at(&token, METHOD, PATH, &target, now) + .expect("accepted"); + assert_eq!(result.scope, DenyScope::IssuedThrough(c), "{value}"); + } + let token = mint_cmd_jwt(&target, 300, serde_json::json!({ "revoke_through": 1.8e9 })); + let result = cv + .verify_at(&token, METHOD, PATH, &target, now) + .expect("accepted"); + assert_eq!(result.scope, DenyScope::IssuedThrough(1_800_000_000)); + } + + #[test] + fn absent_revoke_through_denies_the_whole_key() { + let cv = test_command_verifier(); + let target = target_key(); + let now = Utc::now(); + let token = mint_cmd_jwt(&target, 300, serde_json::json!({})); + let result = cv + .verify_at(&token, METHOD, PATH, &target, now) + .expect("accepted"); + assert_eq!(result.scope, DenyScope::WholeKey); + let fresh = now + Duration::seconds(10); + assert!(cv + .deny_map() + .denies(ISS, &target, fresh, now + Duration::seconds(1))); + } + + #[test] + fn invalid_revoke_through_is_evidence_rejected_before_any_change() { + let cv = test_command_verifier(); + let target = target_key(); + let now = Utc::now(); + for bad in [ + serde_json::Value::Null, + serde_json::json!("1800000000"), + serde_json::json!(1_800_000_000.5), + serde_json::json!(1e-10), + serde_json::json!(1e300), + serde_json::json!(-1e300), + serde_json::json!(true), + serde_json::json!([1]), + serde_json::json!(u64::MAX), + serde_json::json!(i64::MAX), + ] { + let token = mint_cmd_jwt(&target, 300, serde_json::json!({ "revoke_through": bad })); + assert_eq!( + cv.verify_at(&token, METHOD, PATH, &target, now), + Err(CommandError::EvidenceRejected), + "{bad}" + ); + assert!( + !cv.deny_map().is_denied(ISS, &target, now), + "{bad}: a rejected command changes nothing" + ); + } + } } diff --git a/crates/buzz-auth/src/nip_fi/command_replay.rs b/crates/buzz-auth/src/nip_fi/command_replay.rs index a73db2cbf5..e03864b52a 100644 --- a/crates/buzz-auth/src/nip_fi/command_replay.rs +++ b/crates/buzz-auth/src/nip_fi/command_replay.rs @@ -21,6 +21,7 @@ use nostr::PublicKey; use sha2::{Digest, Sha256}; +use super::deny_map::{DenyEntry, DenyScope}; use crate::error::AuthError; /// One authenticated command, as presented to the shared store. @@ -36,6 +37,8 @@ pub struct CommandClaim<'a> { pub target: &'a PublicKey, /// The signed `until`, exact. pub until: DateTime, + /// The signed scope: the whole key or a `revoke_through` cutoff. + pub scope: DenyScope, /// This issuer's `deny_set_capacity`, enforced across every pod. pub capacity: usize, /// Verifier clock: entries with `until <= now` are expired. @@ -71,14 +74,13 @@ pub trait CommandReplayGuard: Send + Sync { ) -> Pin> + Send + 'a>>; /// Every recorded deny entry for `issuer` with `until > now`, at its exact - /// signed `until`. + /// merged `until` and scope. 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>, ->; +pub type LoadDenies<'a> = + Pin, LoadDeniesError>> + Send + 'a>>; /// Why [`CommandReplayGuard::load_denies`] failed. #[derive(Debug, thiserror::Error)] @@ -94,7 +96,7 @@ pub enum LoadDeniesError { /// The first record that could not be decoded. record: String, /// The active records that decoded. - readable: Vec<(PublicKey, DateTime)>, + readable: Vec<(PublicKey, DenyEntry)>, }, } @@ -138,7 +140,7 @@ pub struct InMemoryCommandReplayGuard(std::sync::Mutex); #[derive(Default)] struct InMemoryStore { claims: std::collections::HashSet, - denies: std::collections::HashMap>>, + denies: std::collections::HashMap>, } #[cfg(any(test, feature = "test-utils"))] @@ -154,13 +156,20 @@ impl CommandReplayGuard for InMemoryCommandReplayGuard { } else { let active = claim.until > claim.now; let denies = store.denies.entry(claim.issuer.to_owned()).or_default(); - denies.retain(|_, until| *until > claim.now); + denies.retain(|_, entry| entry.is_active(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); + let incoming = DenyEntry { + until: claim.until, + scope: claim.scope, + }; + let existing = denies.get(claim.target).copied(); + denies.insert( + *claim.target, + DenyEntry::merge(existing, incoming, claim.now), + ); } store.claims.insert(key); ClaimOutcome::Claimed @@ -178,8 +187,8 @@ impl CommandReplayGuard for InMemoryCommandReplayGuard { .get(issuer) .map(|d| { d.iter() - .filter(|(_, u)| **u > now) - .map(|(k, u)| (*k, *u)) + .filter(|(_, e)| e.is_active(now)) + .map(|(k, e)| (*k, *e)) .collect() }) .unwrap_or_default(); diff --git a/crates/buzz-auth/src/nip_fi/deny_map.rs b/crates/buzz-auth/src/nip_fi/deny_map.rs index aa27169edf..ee83f039db 100644 --- a/crates/buzz-auth/src/nip_fi/deny_map.rs +++ b/crates/buzz-auth/src/nip_fi/deny_map.rs @@ -1,8 +1,10 @@ //! In-memory NIP-FI deny set. //! -//! 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, +//! Holds `(iss, pubkey) → (until, scope)` entries. A [`DenyScope`] is the +//! whole key or, from a command's `revoke_through`, only assertions issued at +//! or before a cutoff. 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 @@ -12,13 +14,13 @@ //! //! ## Invariants //! -//! * **Merge rule**: inserting a new `until` for an existing key retains -//! `max(existing_until, new_until)` — an accepted disconnect MUST NOT shorten -//! an active deny. [FI-TRACE-DENY-SET] -//! * **Past-`until` commands**: close sessions but MUST NOT create or shorten -//! entries. Concretely, when `new_until < now` the merge still applies the -//! `max` rule, which preserves any active entry and lets a "no active entry" -//! case insert with an already-expired value (immediately inactive). [FI-TRACE-DENY-SET] +//! * **Merge rule** ([`DenyEntry::merge`]): two active entries keep +//! `max(until)`, whole-key scope beats a cutoff, and two cutoffs keep the +//! larger one — an accepted disconnect MUST NOT shorten or narrow an active +//! deny. An expired entry contributes nothing. [FI-TRACE-DENY-SET] +//! * **Past-`until` commands**: close sessions but MUST NOT create, shorten or +//! strengthen an active entry. With no active entry the expired value is +//! stored, immediately inactive. [FI-TRACE-DENY-SET] //! * **Per-issuer capacity cap**: each issuer has a hard ceiling on live entries. //! A capacity failure returns `Err(DenySetFull)` without inserting anything — //! the spec requires `503` here and neither the jti nor the deny entry is @@ -59,6 +61,110 @@ use std::sync::{Arc, Mutex}; #[error("deny set full for issuer")] pub struct DenySetFull; +// ── Deny entries ────────────────────────────────────────────────────────────── + +/// Which assertions naming a denied key an entry refuses. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DenyScope { + /// Every assertion: a command without `revoke_through`. + WholeKey, + /// Assertions whose verified signed `iat` is at or before this + /// NumericDate: a command's `revoke_through`. + IssuedThrough(i64), +} + +impl DenyScope { + /// The scope of a command's optional `revoke_through`. + pub fn from_revoke_through(revoke_through: Option) -> Self { + revoke_through.map_or(Self::WholeKey, Self::IssuedThrough) + } + + /// The `revoke_through` this scope carries, `None` for the whole key. + pub const fn revoke_through(self) -> Option { + match self { + Self::WholeKey => None, + Self::IssuedThrough(cutoff) => Some(cutoff), + } + } + + /// True when an assertion issued at `issued_at` is on the revoked side. + /// Compares the full instant, so a fractional `iat` just after C is not + /// covered. + pub fn covers(self, issued_at: DateTime) -> bool { + match self { + Self::WholeKey => true, + Self::IssuedThrough(cutoff) => match DateTime::from_timestamp(cutoff, 0) { + Some(cutoff) => issued_at <= cutoff, + // Beyond the representable range: past every instant, or before it. + None => cutoff > 0, + }, + } + } + + /// The stronger of two scopes: whole-key wins, else the later cutoff. + pub fn union(self, other: Self) -> Self { + match (self, other) { + (Self::IssuedThrough(a), Self::IssuedThrough(b)) => Self::IssuedThrough(a.max(b)), + _ => Self::WholeKey, + } + } +} + +/// One `(iss, pubkey)` deny: active while `now < until`, over `scope`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct DenyEntry { + /// End of the deny, exact. + pub until: DateTime, + /// The assertions it refuses. + pub scope: DenyScope, +} + +impl DenyEntry { + /// A whole-key deny until `until`. + pub const fn whole_key(until: DateTime) -> Self { + Self { + until, + scope: DenyScope::WholeKey, + } + } + + /// True while the entry is in force. + pub fn is_active(&self, now: DateTime) -> bool { + now < self.until + } + + /// True when the entry refuses an assertion issued at `issued_at`. + pub fn denies(&self, issued_at: DateTime, now: DateTime) -> bool { + self.is_active(now) && self.scope.covers(issued_at) + } + + /// `incoming` merged over `existing` at `now`. Two active entries keep + /// `max(until)` and the [`DenyScope::union`] of their scopes; an expired + /// entry contributes nothing, so an expired `incoming` leaves an active + /// `existing` unchanged and otherwise `incoming` replaces it. + pub fn merge(existing: Option, incoming: Self, now: DateTime) -> Self { + match existing { + Some(existing) if existing.is_active(now) => { + if !incoming.is_active(now) { + return existing; + } + Self { + until: existing.until.max(incoming.until), + scope: existing.scope.union(incoming.scope), + } + } + _ => incoming, + } + } +} + +/// A bare `until` is a whole-key deny. +impl From> for DenyEntry { + fn from(until: DateTime) -> Self { + Self::whole_key(until) + } +} + // ── Per-issuer shard ────────────────────────────────────────────────────────── /// One issuer's worth of deny entries and jti deduplication state. @@ -66,8 +172,8 @@ pub struct DenySetFull; /// Reserve and commit each take the shard mutex separately; the pending slot /// held between them keeps the jti and deny entry both-or-neither. struct IssuerShard { - /// Active deny entries: hex-encoded pubkey → until. - entries: HashMap>, + /// Deny entries: hex-encoded pubkey → entry. + entries: HashMap, /// Reserved jtis: jti string → effective_expiry. Expired jtis are evicted /// when the jti budget is full so the map never grows to replay-corpus size. jtis: HashMap>, @@ -125,7 +231,7 @@ impl IssuerShard { fn evict_expired(&mut self, now: DateTime) { let (pending_keys, pending_jtis) = (&self.pending_keys, &self.pending_jtis); self.entries - .retain(|k, until| *until > now || pending_keys.contains_key(k)); + .retain(|k, entry| entry.is_active(now) || pending_keys.contains_key(k)); self.jtis .retain(|j, exp| *exp > now || pending_jtis.contains(j)); } @@ -140,12 +246,21 @@ impl IssuerShard { full(self) } - /// True if `(iss, pubkey_hex)` has an active deny entry (`now < until`). - fn is_denied(&self, pubkey_hex: &str, now: DateTime) -> bool { + /// The active entry for `pubkey_hex`, if any. + fn active(&self, pubkey_hex: &str, now: DateTime) -> Option { self.entries .get(pubkey_hex) - .map(|until| now < *until) - .unwrap_or(false) + .copied() + .filter(|entry| entry.is_active(now)) + } + + /// Merge `entry` into the stored entry for `pubkey_hex`. Returns `true` + /// when the stored entry changed: new, extended, or widened in scope. + fn put(&mut self, pubkey_hex: &str, entry: DenyEntry, now: DateTime) -> bool { + let existing = self.entries.get(pubkey_hex).copied(); + let merged = DenyEntry::merge(existing, entry, now); + self.entries.insert(pubkey_hex.to_owned(), merged); + existing != Some(merged) } /// Run every fallible check and hold a pending slot for `(jti, key)`. @@ -208,18 +323,15 @@ impl IssuerShard { jti: &str, jti_effective_expiry: DateTime, pubkey_hex: &str, - until: DateTime, + entry: DenyEntry, + now: DateTime, ) { self.release(jti, pubkey_hex); - 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); + self.put(pubkey_hex, entry, now); self.jtis.insert(jti.to_owned(), jti_effective_expiry); } - /// Insert or `max(existing_until, until)`-merge a deny entry. + /// Insert or [`DenyEntry::merge`] a deny entry. /// /// Used directly for cross-pod propagation, where replay idempotency is /// achieved by the merge rule alone — no jti tracking needed. @@ -228,7 +340,7 @@ impl IssuerShard { fn merge_entry( &mut self, pubkey_hex: &str, - until: DateTime, + entry: DenyEntry, now: DateTime, ) -> Result { // Overwriting an existing (active or expired) entry never grows the @@ -239,15 +351,7 @@ impl IssuerShard { { return Err(CapacityExceeded); } - - // 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) - } - } + Ok(self.put(pubkey_hex, entry, now)) } } @@ -265,13 +369,22 @@ pub(crate) struct Reservation { } impl Reservation { - /// Record the jti and max-merge the deny entry. Cannot fail on capacity. - pub(crate) fn commit(mut self, jti_effective_expiry: DateTime, until: DateTime) { + /// Record the jti and merge the deny entry. Cannot fail on capacity. + pub(crate) fn commit( + mut self, + jti_effective_expiry: DateTime, + entry: DenyEntry, + now: impl FnOnce() -> DateTime, + ) { let pubkey_hex = self .pubkey_hex .take() .expect("reservation not yet committed"); - self.with_shard(|shard| shard.commit(&self.jti, jti_effective_expiry, &pubkey_hex, until)); + // `now` is read under the lock: an entry that expired while this + // commit waited must contribute nothing to the merge. + self.with_shard(|shard| { + shard.commit(&self.jti, jti_effective_expiry, &pubkey_hex, entry, now()) + }); } /// Shards are never removed, so the reserved shard exists. A poisoned @@ -417,7 +530,8 @@ impl NipFiDenyMap { self.shards.iter().map(|s| s.key().clone()).collect() } - /// Returns `true` when `(iss, pubkey)` has an active deny entry at `now`. + /// Returns `true` when `(iss, pubkey)` has an active deny entry at `now`, + /// whatever its scope. /// /// Used by S4 (WS admission step 6) and S5 (HTTP admission step 5). /// [FI-TRACE-DENY-SET] @@ -428,21 +542,45 @@ impl NipFiDenyMap { /// 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 { - self.deny_status(issuer, pubkey, now) != DenyStatus::Allowed + self.denies(issuer, pubkey, DateTime::::MIN_UTC, now) } - /// The deny-set verdict for `(iss, pubkey)` at `now`, read once: + /// Returns `true` when an active entry for `(iss, pubkey)` covers an + /// assertion with verified signed `iat` `issued_at`, or while a restore + /// is pending. Fails closed on a poisoned shard. + pub fn denies( + &self, + issuer: &str, + pubkey: &PublicKey, + issued_at: DateTime, + now: DateTime, + ) -> bool { + self.deny_status(issuer, pubkey, issued_at, now) != DenyStatus::Allowed + } + + /// The deny-set verdict for an assertion naming `(iss, pubkey)` with + /// verified signed `iat` `issued_at`, 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 { + /// [`DenyStatus::Denied`] for an active entry covering it or a poisoned + /// shard (fail closed), else [`DenyStatus::Allowed`]. [FI-TRACE-DENY-SET] + pub fn deny_status( + &self, + issuer: &str, + pubkey: &PublicKey, + issued_at: DateTime, + 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.to_hex(), now)) + .map(|guard| { + guard + .active(&pubkey.to_hex(), now) + .is_some_and(|entry| entry.scope.covers(issued_at)) + }) .unwrap_or(true), // poisoned shard → fail closed (deny) None => false, }; @@ -487,6 +625,26 @@ impl NipFiDenyMap { }) } + /// The scope a close scan for `(iss, pubkey)` applies after a command of + /// scope `command`: its union with any active stored entry, so a stronger + /// merged deny also closes. A poisoned shard closes the whole key. + pub fn close_scope( + &self, + issuer: &str, + pubkey: &PublicKey, + command: DenyScope, + now: DateTime, + ) -> DenyScope { + let stored = match self.shards.get(issuer) { + Some(shard) => match shard.lock() { + Ok(guard) => guard.active(&pubkey.to_hex(), now).map(|entry| entry.scope), + Err(_) => Some(DenyScope::WholeKey), + }, + None => None, + }; + stored.map_or(command, |stored| stored.union(command)) + } + /// Reserve and immediately commit, for tests of the local map alone. #[cfg(test)] pub(crate) fn atomic_reserve_and_insert( @@ -498,15 +656,18 @@ impl NipFiDenyMap { until: DateTime, now: DateTime, ) -> Result<(), ReserveError> { - self.reserve(issuer, jti, pubkey, now)? - .commit(jti_effective_expiry, until); + self.reserve(issuer, jti, pubkey, now)?.commit( + jti_effective_expiry, + DenyEntry::whole_key(until), + || now, + ); Ok(()) } /// Merge a cross-pod deny entry (e.g. from Redis propagation). /// - /// Idempotent: repeated delivery of the same `(issuer, pubkey, until)` is - /// a no-op due to the `max(until)` merge rule. No synthetic jti is + /// Idempotent: repeated delivery of the same `(issuer, pubkey, entry)` is + /// a no-op under the [`DenyEntry::merge`] rule. No synthetic jti is /// allocated — replay idempotency is structural, not tracked. /// /// Only merges into **locally-configured** issuer shards. An unknown @@ -521,9 +682,10 @@ impl NipFiDenyMap { &self, issuer: &str, pubkey: &PublicKey, - until: DateTime, - now: DateTime, + entry: impl Into, + now: impl FnOnce() -> DateTime, ) -> CrossPodMergeResult { + let entry = entry.into(); let pubkey_hex = pubkey.to_hex(); // Only operate on pre-configured shards — never allocate for unknown issuers. match self.shards.get(issuer) { @@ -536,7 +698,7 @@ impl NipFiDenyMap { // fail-closed without any explicit write. CrossPodMergeResult::ShardPoisoned } - Ok(mut guard) => match guard.merge_entry(&pubkey_hex, until, now) { + Ok(mut guard) => match guard.merge_entry(&pubkey_hex, entry, now()) { Ok(true) => CrossPodMergeResult::Merged, Ok(false) => CrossPodMergeResult::Unchanged, Err(CapacityExceeded) => { @@ -600,7 +762,7 @@ mod tests { "closed while restoring" ); assert_eq!( - m.deny_status("iss", &key, Utc::now()), + m.deny_status("iss", &key, DateTime::::MIN_UTC, Utc::now()), DenyStatus::Unavailable, "closed as unavailable, not revoked" ); @@ -982,12 +1144,12 @@ mod tests { // First merge: longer. assert_eq!( - m.merge_cross_pod_deny(iss(), &k, longer, now), + m.merge_cross_pod_deny(iss(), &k, longer, || now), CrossPodMergeResult::Merged ); // Second merge: shorter — must not shorten. assert_eq!( - m.merge_cross_pod_deny(iss(), &k, shorter, now), + m.merge_cross_pod_deny(iss(), &k, shorter, || now), CrossPodMergeResult::Unchanged ); // At 400s: still denied (longer wins). @@ -1013,11 +1175,11 @@ mod tests { // Deliver twice. assert_eq!( - m.merge_cross_pod_deny(iss(), &k, until, now), + m.merge_cross_pod_deny(iss(), &k, until, || now), CrossPodMergeResult::Merged ); assert_eq!( - m.merge_cross_pod_deny(iss(), &k, until, now), + m.merge_cross_pod_deny(iss(), &k, until, || now), CrossPodMergeResult::Unchanged ); // Still denied at 200s (no spurious second-insert count growth). @@ -1033,7 +1195,7 @@ mod tests { let k = key(); let until = Utc::now() + Duration::seconds(300); assert_eq!( - m.merge_cross_pod_deny("https://unknown.example.com", &k, until, Utc::now()), + m.merge_cross_pod_deny("https://unknown.example.com", &k, until, Utc::now), CrossPodMergeResult::UnknownIssuer, "unknown issuer must be rejected without allocating state" ); @@ -1076,14 +1238,14 @@ mod tests { let pending = m.reserve(iss(), "jti-local", &k, now).expect("slot free"); assert_eq!( - m.merge_cross_pod_deny(iss(), &k, until, now), + m.merge_cross_pod_deny(iss(), &k, until, || now), CrossPodMergeResult::Merged ); drop(pending); assert!(m.is_denied(iss(), &k, now), "the remote deny must survive"); assert_eq!( - m.merge_cross_pod_deny(iss(), &other, until, now), + m.merge_cross_pod_deny(iss(), &other, until, || now), CrossPodMergeResult::CapacityExceeded, "k still holds the only slot" ); @@ -1104,10 +1266,10 @@ mod tests { ); let pending = m.reserve(iss(), "jti-local", &k, now).expect("slot free"); assert_eq!( - m.merge_cross_pod_deny(iss(), &k, remote_until, now), + m.merge_cross_pod_deny(iss(), &k, remote_until, || now), CrossPodMergeResult::Merged ); - pending.commit(local_until, local_until); + pending.commit(local_until, DenyEntry::whole_key(local_until), || now); assert!( m.is_denied(iss(), &k, local_until + Duration::seconds(1)), @@ -1115,7 +1277,7 @@ mod tests { ); assert!(!m.is_denied(iss(), &k, remote_until)); assert_eq!( - m.merge_cross_pod_deny(iss(), &other, remote_until, now), + m.merge_cross_pod_deny(iss(), &other, remote_until, || now), CrossPodMergeResult::CapacityExceeded, "still one entry" ); @@ -1149,7 +1311,7 @@ mod tests { // Pod A map: has k_a, receives k_b cross-pod. let map_a = make_map(&k_a); - let result_a = map_a.merge_cross_pod_deny(iss(), &k_b, until, now); + let result_a = map_a.merge_cross_pod_deny(iss(), &k_b, until, || now); assert_eq!( result_a, CrossPodMergeResult::CapacityExceeded, @@ -1173,7 +1335,7 @@ mod tests { // Pod B map: has k_b, receives k_a cross-pod. let map_b = make_map(&k_b); - let result_b = map_b.merge_cross_pod_deny(iss(), &k_a, until, now); + let result_b = map_b.merge_cross_pod_deny(iss(), &k_a, until, || now); assert_eq!( result_b, CrossPodMergeResult::CapacityExceeded, @@ -1202,7 +1364,7 @@ mod tests { // must not alter the live entry or deny the expired target / unrelated key. let expired_until = now - Duration::seconds(1); let map_c = make_map(&k_a); // pre-filled with k_a active - let result_c = map_c.merge_cross_pod_deny(iss(), &k_b, expired_until, now); + let result_c = map_c.merge_cross_pod_deny(iss(), &k_b, expired_until, || now); // Expired remote entry is treated as a new (already-expired) entry; since // the shard is at capacity merge_cross_pod_deny returns CapacityExceeded. // The live k_a entry must remain; k_b and k_unrelated must not be denied. @@ -1250,7 +1412,7 @@ mod tests { .join(); assert_eq!( - m.merge_cross_pod_deny(iss, &k, until, Utc::now()), + m.merge_cross_pod_deny(iss, &k, until, Utc::now), CrossPodMergeResult::ShardPoisoned, "poisoned shard must return ShardPoisoned" ); @@ -1405,7 +1567,7 @@ mod tests { ); // The deny deadline must NOT have been extended (still t0+10s from // the last successful insert — the max-merge should not have applied X). - let stored_until = *guard.entries.get(&k.to_hex()).unwrap(); + let stored_until = guard.entries.get(&k.to_hex()).unwrap().until; assert_eq!( stored_until, deny_deadline, "deny deadline must not be extended by a rejected JTI-budget command" @@ -1552,7 +1714,7 @@ mod tests { let t_live = t0 + Duration::seconds(5); assert_eq!( - m.merge_cross_pod_deny(iss(), &k_b, t_live + Duration::seconds(60), t_live), + m.merge_cross_pod_deny(iss(), &k_b, t_live + Duration::seconds(60), || t_live), CrossPodMergeResult::CapacityExceeded, "full shard with a live entry must still reject a new key" ); @@ -1560,10 +1722,217 @@ mod tests { let t_expired = t0 + Duration::seconds(20); assert_eq!( - m.merge_cross_pod_deny(iss(), &k_b, t_expired + Duration::seconds(60), t_expired), + m.merge_cross_pod_deny(iss(), &k_b, t_expired + Duration::seconds(60), || t_expired), CrossPodMergeResult::Merged, "an expired entry must not hold the slot" ); assert!(m.is_denied(iss(), &k_b, t_expired), "k_b must be denied"); } + + // ── revoke_through scopes ──────────────────────────────────────────────── + + fn scoped_map() -> NipFiDenyMap { + NipFiDenyMap::new( + 100, + vec![IssuerCapacity { + issuer: iss().to_owned(), + capacity: 100, + }], + ) + } + + fn at(secs: i64) -> DateTime { + DateTime::from_timestamp(secs, 0).unwrap() + } + + fn cutoff(until: DateTime, c: i64) -> DenyEntry { + DenyEntry { + until, + scope: DenyScope::IssuedThrough(c), + } + } + + #[test] + fn cutoff_entry_refuses_old_assertions_and_admits_fresh_ones() { + let m = scoped_map(); + let k = key(); + let now = at(1_000); + m.merge_cross_pod_deny(iss(), &k, cutoff(at(2_000), 1_000), || now); + assert!(m.denies(iss(), &k, at(1_000), now), "iat == C is refused"); + assert!(m.denies(iss(), &k, at(999), now)); + assert!(!m.denies(iss(), &k, at(1_001), now), "iat > C is admitted"); + assert!( + !m.denies(iss(), &k, at(1_000), at(2_000)), + "now == until admits" + ); + } + + #[test] + fn fractional_iat_just_after_the_cutoff_is_not_covered() { + let scope = DenyScope::IssuedThrough(1_000); + assert!(scope.covers(at(1_000)), "iat == C is covered"); + let half = DateTime::from_timestamp(1_000, 500_000_000).unwrap(); + assert!(!scope.covers(half), "iat == C + 0.5 is not covered"); + let m = scoped_map(); + let k = key(); + m.merge_cross_pod_deny(iss(), &k, cutoff(at(2_000), 1_000), || at(1_000)); + assert!(m.denies(iss(), &k, at(1_000), at(1_001))); + assert!(!m.denies(iss(), &k, half, at(1_001))); + } + + #[test] + fn same_deadline_whole_key_overrides_a_cutoff_in_either_order() { + let now = at(1_000); + for whole_first in [true, false] { + let m = scoped_map(); + let k = key(); + let whole = DenyEntry::whole_key(at(2_000)); + let cut = cutoff(at(2_000), 1_000); + let (a, b) = if whole_first { + (whole, cut) + } else { + (cut, whole) + }; + m.merge_cross_pod_deny(iss(), &k, a, || now); + m.merge_cross_pod_deny(iss(), &k, b, || now); + assert!(m.denies(iss(), &k, at(1_500), now), "whole key wins"); + } + } + + #[test] + fn same_deadline_later_cutoff_wins_in_either_order() { + let now = at(1_000); + for later_first in [true, false] { + let m = scoped_map(); + let k = key(); + let (a, b) = (cutoff(at(2_000), 1_100), cutoff(at(2_000), 1_000)); + let (a, b) = if later_first { (a, b) } else { (b, a) }; + m.merge_cross_pod_deny(iss(), &k, a, || now); + m.merge_cross_pod_deny(iss(), &k, b, || now); + assert!(m.denies(iss(), &k, at(1_100), now)); + assert!(!m.denies(iss(), &k, at(1_101), now)); + } + } + + #[test] + fn entry_expiring_while_a_commit_waits_on_the_shard_lock_contributes_nothing() { + use std::sync::atomic::{AtomicI64, Ordering}; + use std::sync::mpsc; + let m = scoped_map(); + let k = key(); + m.merge_cross_pod_deny(iss(), &k, DenyEntry::whole_key(at(1_500)), || at(1_000)); + let clock = AtomicI64::new(1_000); + let reservation = m.reserve(iss(), "jti-lock", &k, at(1_000)).unwrap(); + let shard = m.shards.get(iss()).unwrap(); + let guard = shard.lock().unwrap(); + let (attempting_tx, attempting_rx) = mpsc::channel(); + let (read_tx, read_rx) = mpsc::channel(); + std::thread::scope(|scope| { + scope.spawn(|| { + attempting_tx.send(()).unwrap(); + reservation.commit(at(2_500), cutoff(at(2_500), 1_600), || { + read_tx.send(()).unwrap(); + at(clock.load(Ordering::SeqCst)) + }); + }); + // The worker is now attempting the held lock. A clock read before + // the lock would arrive here while the lock is still held. + attempting_rx.recv().unwrap(); + assert!( + read_rx + .recv_timeout(std::time::Duration::from_millis(200)) + .is_err(), + "the merge clock must not be read before the shard lock" + ); + // The old entry expires while the commit is still waiting. + clock.store(1_600, Ordering::SeqCst); + drop(guard); + }); + drop(shard); + let now = at(1_600); + assert!( + !m.denies(iss(), &k, at(1_601), now), + "expired whole-key not carried over" + ); + assert!(m.denies(iss(), &k, at(1_600), now)); + } + + #[test] + fn expired_whole_key_contributes_nothing_to_a_later_cutoff() { + let m = scoped_map(); + let k = key(); + m.merge_cross_pod_deny(iss(), &k, DenyEntry::whole_key(at(1_500)), || at(1_000)); + let now = at(1_600); + m.merge_cross_pod_deny(iss(), &k, cutoff(at(2_500), 1_600), || now); + assert!(!m.denies(iss(), &k, at(1_601), now), "fresh token admitted"); + assert!(m.denies(iss(), &k, at(1_600), now)); + } + + #[test] + fn past_until_cutoff_never_weakens_or_strengthens_an_active_entry() { + let m = scoped_map(); + let k = key(); + let now = at(1_000); + m.merge_cross_pod_deny(iss(), &k, cutoff(at(2_000), 900), || now); + m.merge_cross_pod_deny(iss(), &k, DenyEntry::whole_key(at(500)), || now); + assert!( + !m.denies(iss(), &k, at(901), now), + "expired whole key adds nothing" + ); + assert!(m.denies(iss(), &k, at(900), now)); + assert_eq!( + m.close_scope(iss(), &k, DenyScope::IssuedThrough(100), now), + DenyScope::IssuedThrough(900), + "close scope widens to the stronger active entry" + ); + } + + #[test] + fn poisoned_shard_close_scope_is_whole_key() { + let m = scoped_map(); + let k = key(); + let now = at(1_000); + m.merge_cross_pod_deny(iss(), &k, cutoff(at(2_000), 900), || now); + m.poison_shard_for_test(iss()); + assert_eq!( + m.close_scope(iss(), &k, DenyScope::IssuedThrough(100), now), + DenyScope::WholeKey, + "a poisoned shard fails closed to the whole key" + ); + } + + /// Widening the scope at the same `until` is a change, so a restore + /// closes the sessions it newly covers; the same entry again is not. + #[test] + fn same_until_scope_widening_is_merged_not_unchanged() { + let m = NipFiDenyMap::new( + 100, + vec![IssuerCapacity { + issuer: iss().to_owned(), + capacity: 100, + }], + ); + let k = key(); + let now = Utc::now(); + let until = now + Duration::seconds(600); + let scoped = |c| DenyEntry { + until, + scope: DenyScope::IssuedThrough(c), + }; + let merge = |entry: DenyEntry| m.merge_cross_pod_deny(iss(), &k, entry, || now); + assert_eq!(merge(scoped(10)), CrossPodMergeResult::Merged); + assert_eq!(merge(scoped(10)), CrossPodMergeResult::Unchanged); + assert_eq!(merge(scoped(5)), CrossPodMergeResult::Unchanged); + assert_eq!( + merge(scoped(20)), + CrossPodMergeResult::Merged, + "later cutoff" + ); + assert_eq!( + merge(DenyEntry::whole_key(until)), + CrossPodMergeResult::Merged, + "whole key" + ); + assert_eq!(merge(scoped(30)), CrossPodMergeResult::Unchanged); + } } diff --git a/crates/buzz-auth/src/nip_fi/mod.rs b/crates/buzz-auth/src/nip_fi/mod.rs index 3c73c44185..867d4a80f5 100644 --- a/crates/buzz-auth/src/nip_fi/mod.rs +++ b/crates/buzz-auth/src/nip_fi/mod.rs @@ -44,7 +44,10 @@ pub use config::{ NOSTR_OWNER_PUBKEY_CLAIM, NOSTR_PUBKEY_CLAIM, OAUTH_CLIENT_ID_CLAIM, }; pub use denial::DenialClass; -pub use deny_map::{CrossPodMergeResult, DenySetFull, DenyStatus, IssuerCapacity, NipFiDenyMap}; +pub use deny_map::{ + CrossPodMergeResult, DenyEntry, DenyScope, DenySetFull, DenyStatus, IssuerCapacity, + NipFiDenyMap, +}; pub use discovery::{ AssertionFreshnessDiscovery, FederatedIdentityDiscovery, FreshnessClassDiscovery, }; diff --git a/crates/buzz-auth/src/nip_fi/verifier.rs b/crates/buzz-auth/src/nip_fi/verifier.rs index ee5ba16139..717f056568 100644 --- a/crates/buzz-auth/src/nip_fi/verifier.rs +++ b/crates/buzz-auth/src/nip_fi/verifier.rs @@ -443,7 +443,8 @@ impl FederatedAssertionVerifier { let owner = parse_owner_claim(owner_rule, &claims, asserted_key)?; let now = Utc::now(); - let deadlines = self.check_time_and_deadlines(policy, &key_set, &claims, now)?; + let (issued_at, deadlines) = + self.check_time_and_deadlines(policy, &key_set, &claims, now)?; let capabilities = capture_capabilities(policy, &claims); // Offline validation (token-class, key, signature, audience, claims, @@ -504,6 +505,7 @@ impl FederatedAssertionVerifier { owner, capabilities, deadlines, + issued_at, policy.id_for_community(community.expected_aud()), self.transport_contract_id, RevalidationDependencies::new( @@ -527,7 +529,7 @@ impl FederatedAssertionVerifier { key_set: &AssertionKeySet, claims: &Map, now: DateTime, - ) -> Result>, VerifierError> { + ) -> Result<(DateTime, Vec>), VerifierError> { let iat = numeric_date(claims, "iat")?; let exp = numeric_date(claims, "exp")?; let skew = seconds(policy.skew_seconds()); @@ -564,7 +566,7 @@ impl FederatedAssertionVerifier { policy.freshness(), FreshnessClass::OfflineJwt | FreshnessClass::CurrentStatus )); - Ok(deadlines) + Ok((iat, deadlines)) } } diff --git a/crates/buzz-auth/src/nip_fi/verifier/tests.rs b/crates/buzz-auth/src/nip_fi/verifier/tests.rs index c5cafbcfa5..b8bb0b014c 100644 --- a/crates/buzz-auth/src/nip_fi/verifier/tests.rs +++ b/crates/buzz-auth/src/nip_fi/verifier/tests.rs @@ -911,6 +911,29 @@ fn fractional_iat_and_exp_within_bounds_verify() { assert!(verifier.verify_for_aud(&token, AUDIENCE).is_ok()); } +#[test] +fn signed_fractional_iat_reaches_the_cutoff_predicate_exactly() { + let verifier = verifier_with(dedicated_policy(ISSUER)); + let c = now() - 10; + let mint_at = |iat: f64| { + let token = mint( + Some("nip-fi+jwt"), + TEST_KID, + json!({ "sub": "u", "iat": iat, "exp": now() as f64 + 600.0 }), + ); + verifier.verify_for_aud(&token, AUDIENCE).expect("verifies") + }; + let scope = crate::nip_fi::DenyScope::IssuedThrough(c); + let at_c = mint_at(c as f64); + let after_c = mint_at(c as f64 + 0.5); + assert_eq!(after_c.issued_at().timestamp_subsec_millis(), 500); + assert!(scope.covers(at_c.issued_at()), "iat == C is revoked"); + assert!( + !scope.covers(after_c.issued_at()), + "iat == C + 0.5 is fresh" + ); +} + #[test] fn fractional_nbf_within_bounds_verifies() { let verifier = verifier_with(dedicated_policy(ISSUER)); diff --git a/crates/buzz-pubsub/src/conn_control.rs b/crates/buzz-pubsub/src/conn_control.rs index e850d81a54..3d5902cb74 100644 --- a/crates/buzz-pubsub/src/conn_control.rs +++ b/crates/buzz-pubsub/src/conn_control.rs @@ -68,6 +68,10 @@ pub struct NipFiDisconnect { /// the signed command JWT is preserved across pod boundaries. #[serde(default)] pub until_unix_nanos: u32, + /// The command's `revoke_through` cutoff in whole seconds since the Unix + /// epoch. Absent means the deny covers the whole key. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub revoke_through: Option, } /// State of this pod's NIP-FI disconnect subscription. Every confirmed @@ -586,6 +590,7 @@ mod tests { pubkey_bytes: vec![0xabu8; 32], until_unix: 9_999_999_999, until_unix_nanos: 500_000_000, + revoke_through: None, }; let json = serde_json::to_string(&cmd).unwrap(); let decoded: NipFiDisconnect = serde_json::from_str(&json).unwrap(); @@ -623,6 +628,7 @@ mod tests { pubkey_bytes: vec![1u8; 32], until_unix: 1_000_000, until_unix_nanos: 0, + revoke_through: None, }) .unwrap(); assert!(serde_json::from_str::(&good).is_ok()); diff --git a/crates/buzz-pubsub/src/nip_fi_command_replay.rs b/crates/buzz-pubsub/src/nip_fi_command_replay.rs index a798da9e66..427dafdc98 100644 --- a/crates/buzz-pubsub/src/nip_fi_command_replay.rs +++ b/crates/buzz-pubsub/src/nip_fi_command_replay.rs @@ -11,9 +11,12 @@ //! 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. +//! * `{deny}-revoke-through:{sha256(iss)}` — hash, field `pubkey_hex`, value +//! the merged `revoke_through` cutoff, present only while the entry is +//! scoped to it; a missing field is a whole-key deny. It lives outside the +//! exact-`until` hash so relays that predate cutoffs still decode that hash +//! and read the entry as a whole-key deny; those relays clear the field on +//! every write, so their full revokes are never narrowed. //! //! Only the issuer's hash is stored; readers map it back through configured //! issuers. @@ -22,8 +25,8 @@ use buzz_auth::nip_fi::{ namespaced_command_replay_key, COMMAND_REPLAY_PREFIX, SHADOW_COMMAND_REPLAY_PREFIX, }; use buzz_auth::{ - error::AuthError, ClaimOutcome, CommandClaim, CommandReplayGuard, LoadDeniesError, - DEFAULT_REPLAY_TTL_SECS, MAX_REPLAY_TTL_SECS, + error::AuthError, ClaimOutcome, CommandClaim, CommandReplayGuard, DenyEntry, DenyScope, + LoadDeniesError, DEFAULT_REPLAY_TTL_SECS, MAX_REPLAY_TTL_SECS, }; use chrono::{DateTime, Utc}; use nostr::PublicKey; @@ -37,17 +40,34 @@ pub const DENY_STORE_PREFIX: &str = "buzz:nip-fi:deny"; 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). +/// capacity, revoke_through ('' for the whole key). Whether the command and +/// the stored entry are still active is judged by Redis `TIME` as the script +/// runs, not by the clock the command was authenticated under. A stored +/// cutoff restore would reject returns 'unreadable' before any write. const ACCEPT_SCRIPT: &str = r" if redis.call('EXISTS', KEYS[1]) == 1 then return 'replay' end -local active = ARGV[8] == '1' +-- A stored cutoff restore would reject is refused here, before any write. +local stored = redis.call('HGET', KEYS[4], ARGV[2]) +if stored then + local c = string.match(stored, '^[+-]?%d+$') and tonumber(stored) + if not c or c < -8334601228800 or c > 8210266876799 then return 'unreadable' end +end +local t = redis.call('TIME') +local ts, tn = tonumber(t[1]), tonumber(t[2]) * 1000 +local now_ms = string.format('%.0f', ts * 1000 + math.floor(tn / 1000000)) +local function live(v) + local s, n = string.match(v, '^(%-?%d+):(%d+)$') + s, n = tonumber(s), tonumber(n) + return s > ts or (s == ts and n > tn) +end +local active = live(ARGV[4] .. ':' .. ARGV[5]) if active then - local expired = redis.call('ZRANGEBYSCORE', KEYS[2], '-inf', '(' .. ARGV[7]) + local expired = redis.call('ZRANGEBYSCORE', KEYS[2], '-inf', '(' .. now_ms) 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]) + redis.call('ZREMRANGEBYSCORE', KEYS[2], '-inf', '(' .. now_ms) if not redis.call('ZSCORE', KEYS[2], ARGV[2]) and redis.call('ZCARD', KEYS[2]) >= tonumber(ARGV[6]) then return 'full' @@ -65,7 +85,22 @@ if active then 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]) + -- Scope merge: an active stored entry without a cutoff is the whole key and + -- wins; two cutoffs keep the later one. An expired entry contributes none. + local cut = ARGV[7] + if cut ~= '' and cur and live(cur) then + local prior = redis.call('HGET', KEYS[4], ARGV[2]) + if not prior or not tonumber(prior) then + cut = '' + elseif tonumber(prior) > tonumber(cut) then + cut = prior + end + end + if cut == '' then + redis.call('HDEL', KEYS[4], ARGV[2]) + else + redis.call('HSET', KEYS[4], ARGV[2], cut) + end local top = redis.call('ZRANGE', KEYS[2], -1, -1, 'WITHSCORES') redis.call('PEXPIREAT', KEYS[2], top[2]) redis.call('PEXPIREAT', KEYS[3], top[2]) @@ -165,8 +200,12 @@ impl CommandReplayGuard for RedisCommandReplayGuard { .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)) + .arg( + claim + .scope + .revoke_through() + .map_or_else(String::new, |c| c.to_string()), + ) .invoke_async(&mut conn) .await .map_err(internal)?; @@ -174,6 +213,11 @@ impl CommandReplayGuard for RedisCommandReplayGuard { "claimed" => Ok(ClaimOutcome::Claimed), "replay" => Ok(ClaimOutcome::Replay), "full" => Ok(ClaimOutcome::Full), + "unreadable" => { + let record = format!("revoke_through for {}", claim.target.to_hex()); + tracing::warn!(record, "nip-fi command store: unreadable deny record"); + Err(internal(format!("unreadable deny record: {record}"))) + } other => Err(internal(format!("unexpected reply: {other}"))), } }) @@ -183,26 +227,22 @@ impl CommandReplayGuard for RedisCommandReplayGuard { 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) + // One script, so a cutoff is never paired with a deadline it was + // not written with. + let (entries, cutoffs): (RawHash, RawHash) = redis::Script::new(SNAPSHOT_SCRIPT) + .key(exact) + .key(revoke_through_key(&self.deny_prefix, issuer)) + .invoke_async(&mut conn) .await .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); - } - } - } + let entries = utf8_pairs(entries, &mut bad); + let cutoffs = utf8_pairs(cutoffs, &mut bad); + let untils = decode_untils(&entries, now, &mut bad); + let denies = join_cutoffs(untils, &entries, cutoffs, &mut bad); match bad { None => Ok(denies), Some(record) => Err(LoadDeniesError::Unreadable { @@ -214,25 +254,116 @@ impl CommandReplayGuard for RedisCommandReplayGuard { } } +/// A hash as `HGETALL` returns it: field and value bytes. +type RawHash = Vec<(Vec, Vec)>; + +/// Keeps the first unreadable record and logs every one. +fn note(bad: &mut Option, record: String) { + tracing::warn!(record, "nip-fi command store: unreadable deny record"); + bad.get_or_insert(record); +} + +/// A hash's fields and values as text; a record that isn't UTF-8 is +/// unreadable and left out. +fn utf8_pairs(raw: RawHash, bad: &mut Option) -> Vec<(String, String)> { + raw.into_iter() + .filter_map( + |(key, value)| match (String::from_utf8(key), String::from_utf8(value)) { + (Ok(key), Ok(value)) => Some((key, value)), + _ => { + note(bad, "deny record that is not UTF-8".into()); + None + } + }, + ) + .collect() +} + +/// KEYS: exact, cutoff. Both hashes as one snapshot. +const SNAPSHOT_SCRIPT: &str = r" +return {redis.call('HGETALL', KEYS[1]), redis.call('HGETALL', KEYS[2])} +"; + +/// The exact-`until` hash's active entries. This is the whole of the reader +/// in relays that predate cutoffs, which therefore read every entry as a +/// whole-key deny. An unreadable record is noted in `bad` and left out; the +/// others still decode. +fn decode_untils( + entries: &[(String, String)], + now: DateTime, + bad: &mut Option, +) -> Vec<(PublicKey, DateTime)> { + let mut denies = Vec::with_capacity(entries.len()); + for (key, until) in entries { + let Ok(pubkey) = PublicKey::from_hex(key) else { + note(bad, format!("deny key {key}")); + continue; + }; + match parse_until(until) { + Some(until) if until > now => denies.push((pubkey, until)), + Some(_) => {} + None => note(bad, format!("deny until {until} for {key}")), + } + } + denies +} + +/// Scope each active deny by its cutoff field; a missing field is the whole +/// key. A cutoff that doesn't decode, or that names no stored deny, is +/// noted in `bad`; a deny under an undecodable cutoff stays the whole key. +fn join_cutoffs( + untils: Vec<(PublicKey, DateTime)>, + entries: &[(String, String)], + cutoffs: Vec<(String, String)>, + bad: &mut Option, +) -> Vec<(PublicKey, DenyEntry)> { + let denied: std::collections::HashSet<&str> = entries.iter().map(|(k, _)| k.as_str()).collect(); + let mut scopes = std::collections::HashMap::with_capacity(cutoffs.len()); + for (key, cutoff) in cutoffs { + if !denied.contains(key.as_str()) { + note(bad, format!("revoke_through for {key} without a deny")); + continue; + } + match cutoff + .parse::() + .ok() + .filter(|c| DateTime::from_timestamp(*c, 0).is_some()) + { + Some(c) => { + scopes.insert(key, DenyScope::IssuedThrough(c)); + } + None => note(bad, format!("revoke_through {cutoff} for {key}")), + } + } + untils + .into_iter() + .map(|(key, until)| { + let scope = scopes + .get(&key.to_hex()) + .copied() + .unwrap_or(DenyScope::WholeKey); + (key, DenyEntry { until, scope }) + }) + .collect() +} + 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::*; + /// The accept script's cutoff bounds are restore's `from_timestamp` range. + #[test] + fn accept_cutoff_bounds_match_restore() { + for bound in [DateTime::::MIN_UTC, DateTime::::MAX_UTC] { + assert!(ACCEPT_SCRIPT.contains(&bound.timestamp().to_string())); + } + } + #[test] fn ceil_ms_never_rounds_down() { let t = DateTime::from_timestamp(10, 1).unwrap(); @@ -252,6 +383,70 @@ mod tests { ); } + /// A bad cutoff does not hide the others: a good one still scopes its + /// key, a malformed one leaves its deny the whole key, an orphan adds + /// nothing, and the first bad record is kept. + #[test] + fn cutoff_join_keeps_readable_records_past_bad_ones() { + let [good, malformed, orphan] = + std::array::from_fn(|i| PublicKey::from_hex(&format!("{:064x}", i + 1)).unwrap()); + let until = DateTime::from_timestamp(100, 0).unwrap(); + let entries: Vec<_> = [good, malformed] + .iter() + .map(|k| (k.to_hex(), "100:0".to_owned())) + .collect(); + let cutoffs = vec![ + (good.to_hex(), "10".to_owned()), + (malformed.to_hex(), "12.5".to_owned()), + (orphan.to_hex(), "10".to_owned()), + ]; + let mut bad = None; + let joined = join_cutoffs( + vec![(good, until), (malformed, until)], + &entries, + cutoffs, + &mut bad, + ); + assert_eq!( + joined, + vec![ + ( + good, + DenyEntry { + until, + scope: DenyScope::IssuedThrough(10) + } + ), + ( + malformed, + DenyEntry { + until, + scope: DenyScope::WholeKey + } + ), + ] + ); + assert_eq!( + bad, + Some(format!("revoke_through 12.5 for {}", malformed.to_hex())) + ); + } + + /// A full issuer at the default capacity joins every cutoff to its key. + #[test] + fn cutoff_join_handles_a_full_issuer() { + let entries: Vec<_> = (0..50_000) + .map(|i| (format!("{i:064x}"), "1:0".to_owned())) + .collect(); + let cutoffs = entries + .iter() + .map(|(k, _)| (k.clone(), "10".to_owned())) + .collect(); + let mut bad = None; + join_cutoffs(Vec::new(), &entries, cutoffs, &mut bad); + assert_eq!(bad, None); + } + #[test] fn exact_until_round_trips() { let t = DateTime::from_timestamp(1_795_000_000, 123_456_789).unwrap(); diff --git a/crates/buzz-relay/src/api/bridge.rs b/crates/buzz-relay/src/api/bridge.rs index aff105b70f..05b2925e15 100644 --- a/crates/buzz-relay/src/api/bridge.rs +++ b/crates/buzz-relay/src/api/bridge.rs @@ -8881,7 +8881,7 @@ pub(crate) mod postgres_tests { HANDLER_TEST_ISSUER, &actor.public_key(), now + chrono::Duration::minutes(5), - now + || now ), CrossPodMergeResult::Merged ); diff --git a/crates/buzz-relay/src/api/nip_fi.rs b/crates/buzz-relay/src/api/nip_fi.rs index 0bb32604ef..2809c215a4 100644 --- a/crates/buzz-relay/src/api/nip_fi.rs +++ b/crates/buzz-relay/src/api/nip_fi.rs @@ -138,17 +138,28 @@ pub async fn disconnect( // Issuer-scoped: the deny entry is keyed by (caller_iss, k), so only // sessions admitted under caller_iss are closed. [FI-TRACE-DENY-SET] // Shadow keeps the deny entry but closes nothing. + // The command's scope, widened by any stronger active entry. + let scope = state.nip_fi_deny_map.as_ref().map_or(cmd.scope, |map| { + map.close_scope( + &cmd.caller_iss, + &cmd.target_pubkey, + cmd.scope, + chrono::Utc::now(), + ) + }); let closed = if !state.config.nip_fi.mode.observes_only() { state .conn_manager - .disconnect_nip_fi(&cmd.caller_iss, &pubkey_bytes) - + state - .community_connections - .disconnect_nip_fi(&cmd.caller_iss, &pubkey_bytes) + .disconnect_nip_fi(&cmd.caller_iss, &pubkey_bytes, scope) + + state.community_connections.disconnect_nip_fi( + &cmd.caller_iss, + &pubkey_bytes, + scope, + ) } else { state .nip_fi_shadow_sessions - .would_close(&cmd.caller_iss, &pubkey_bytes); + .would_close(&cmd.caller_iss, &pubkey_bytes, scope); 0 }; if closed > 0 { @@ -327,14 +338,16 @@ async fn merge_stored_denies( readable } }; - for (key, until) in entries { + for (key, entry) 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(), + until_unix: entry.until.timestamp(), + until_unix_nanos: entry.until.timestamp_subsec_nanos(), + revoke_through: entry.scope.revoke_through(), }; - match merge_nip_fi_disconnect(state, &message, now) { + // Judge expiry at the merge, not at the read before it. + match merge_nip_fi_disconnect(state, &message, chrono::Utc::now) { NipFiDisconnectApplyResult::Applied(CrossPodMergeResult::Merged) => { changed.push(message) } @@ -405,7 +418,7 @@ pub async fn run_nip_fi_disconnect_consumer( () = &mut wait => break, msg = rx.recv() => match msg { Ok(msg) => { - if !retained(apply_nip_fi_disconnect(&state, &msg, chrono::Utc::now())) { + if !retained(apply_nip_fi_disconnect(&state, &msg, chrono::Utc::now)) { continue 'generation; } } @@ -425,7 +438,7 @@ pub async fn run_nip_fi_disconnect_consumer( loop { match rx.try_recv() { Ok(msg) => { - if !retained(apply_nip_fi_disconnect(&state, &msg, chrono::Utc::now())) { + if !retained(apply_nip_fi_disconnect(&state, &msg, chrono::Utc::now)) { continue 'generation; } } @@ -450,7 +463,7 @@ pub async fn run_nip_fi_disconnect_consumer( tokio::select! { msg = rx.recv() => match msg { Ok(msg) => { - if !retained(apply_nip_fi_disconnect(&state, &msg, chrono::Utc::now())) { + if !retained(apply_nip_fi_disconnect(&state, &msg, chrono::Utc::now)) { tracing::warn!("NIP-FI deny not retained; closing admission and restoring"); continue 'generation; } @@ -549,6 +562,7 @@ pub fn nip_fi_disconnect_message(cmd: &buzz_auth::CommandResult) -> buzz_pubsub: pubkey_bytes: cmd.target_pubkey.to_bytes().to_vec(), until_unix: cmd.until.timestamp(), until_unix_nanos: cmd.until.timestamp_subsec_nanos(), + revoke_through: cmd.scope.revoke_through(), } } @@ -568,7 +582,7 @@ pub fn nip_fi_disconnect_message(cmd: &buzz_auth::CommandResult) -> buzz_pubsub: pub fn apply_nip_fi_disconnect( state: &crate::state::AppState, message: &buzz_pubsub::NipFiDisconnect, - now: chrono::DateTime, + now: impl Fn() -> chrono::DateTime, ) -> NipFiDisconnectApplyResult { let result = merge_nip_fi_disconnect(state, message, now); if let NipFiDisconnectApplyResult::Applied(merge) = result { @@ -581,7 +595,7 @@ pub fn apply_nip_fi_disconnect( fn merge_nip_fi_disconnect( state: &crate::state::AppState, message: &buzz_pubsub::NipFiDisconnect, - now: chrono::DateTime, + now: impl Fn() -> chrono::DateTime, ) -> NipFiDisconnectApplyResult { let deny_map = match state.nip_fi_deny_map.as_deref() { Some(m) => m, @@ -623,6 +637,15 @@ fn merge_nip_fi_disconnect( return NipFiDisconnectApplyResult::Rejected; } }; + if let Some(c) = message.revoke_through { + if chrono::DateTime::from_timestamp(c, 0).is_none() { + tracing::warn!( + revoke_through = c, + "nip-fi cross-pod: unrepresentable revoke_through — rejected" + ); + return NipFiDisconnectApplyResult::Rejected; + } + } // Clamp `until` to this pod's ceiling rather than rejecting it. The origin // pod already verified `until` against its own clock and returned 200; a @@ -630,38 +653,56 @@ fn merge_nip_fi_disconnect( // at-ceiling command and leave the target's sessions open. let skew = chrono::Duration::seconds(policy.skew_seconds() as i64); let max_age = chrono::Duration::seconds(policy.maximum_assertion_age_seconds() as i64); - if let Some(ceiling) = now + if let Some(ceiling) = now() .checked_add_signed(skew) .and_then(|t| t.checked_add_signed(max_age)) { until = until.min(ceiling); } + let entry = buzz_auth::DenyEntry { + until, + scope: buzz_auth::DenyScope::from_revoke_through(message.revoke_through), + }; NipFiDisconnectApplyResult::Applied(deny_map.merge_cross_pod_deny( &message.issuer, &pubkey, - until, - now, + entry, + &now, )) } -/// Close (or, in shadow, record would-close for) every session of the -/// message's target. +/// Close (or, in shadow, record would-close for) the sessions of the +/// message's target that its scope covers, widened by any stronger active +/// entry the deny map holds for it. fn close_nip_fi_sessions( state: &crate::state::AppState, message: &buzz_pubsub::NipFiDisconnect, reason: &str, ) { + let command = buzz_auth::DenyScope::from_revoke_through(message.revoke_through); + let scope = match ( + state.nip_fi_deny_map.as_deref(), + nostr::PublicKey::from_slice(&message.pubkey_bytes), + ) { + (Some(deny_map), Ok(pubkey)) => { + deny_map.close_scope(&message.issuer, &pubkey, command, chrono::Utc::now()) + } + _ => command, + }; if state.config.nip_fi.mode.observes_only() { let sessions = &state.nip_fi_shadow_sessions; - return sessions.would_close(&message.issuer, &message.pubkey_bytes); + return sessions.would_close(&message.issuer, &message.pubkey_bytes, scope); } - let closed = state - .conn_manager - .disconnect_nip_fi(&message.issuer, &message.pubkey_bytes) - + state - .community_connections - .disconnect_nip_fi(&message.issuer, &message.pubkey_bytes); + let closed = + state + .conn_manager + .disconnect_nip_fi(&message.issuer, &message.pubkey_bytes, scope) + + state.community_connections.disconnect_nip_fi( + &message.issuer, + &message.pubkey_bytes, + scope, + ); if closed > 0 { tracing::debug!(closed, reason = reason, "nip-fi cross-pod: closed sessions"); } @@ -1542,8 +1583,9 @@ mod route_integration_tests { pubkey_bytes: k_a.to_bytes().to_vec(), until_unix, until_unix_nanos: 0, + revoke_through: None, }; - let result_a = apply_nip_fi_disconnect(&state, &msg_a, now); + let result_a = apply_nip_fi_disconnect(&state, &msg_a, || now); assert_eq!( result_a, NipFiDisconnectApplyResult::Applied(CrossPodMergeResult::Merged), @@ -1576,8 +1618,9 @@ mod route_integration_tests { pubkey_bytes: k_b.to_bytes().to_vec(), until_unix, until_unix_nanos: 0, + revoke_through: None, }; - let result_b = apply_nip_fi_disconnect(&state, &msg_b, now); + let result_b = apply_nip_fi_disconnect(&state, &msg_b, || now); assert_eq!( result_b, NipFiDisconnectApplyResult::Applied(CrossPodMergeResult::CapacityExceeded), @@ -1773,8 +1816,9 @@ mod route_integration_tests { pubkey_bytes: target.to_bytes().to_vec(), until_unix, until_unix_nanos: 0, + revoke_through: None, }; - let result = apply_nip_fi_disconnect(&state, &msg, now); + let result = apply_nip_fi_disconnect(&state, &msg, || now); assert_eq!( result, NipFiDisconnectApplyResult::Applied(CrossPodMergeResult::Merged), @@ -1828,8 +1872,9 @@ mod route_integration_tests { pubkey_bytes: filler.to_bytes().to_vec(), until_unix, until_unix_nanos: 0, + revoke_through: None, }; - let fill_result = apply_nip_fi_disconnect(&state, &msg_fill, now); + let fill_result = apply_nip_fi_disconnect(&state, &msg_fill, || now); assert_eq!( fill_result, NipFiDisconnectApplyResult::Applied(CrossPodMergeResult::Merged), @@ -1842,8 +1887,9 @@ mod route_integration_tests { pubkey_bytes: target2.to_bytes().to_vec(), until_unix, until_unix_nanos: 0, + revoke_through: None, }; - let result2 = apply_nip_fi_disconnect(&state, &msg2, now); + let result2 = apply_nip_fi_disconnect(&state, &msg2, || now); assert_eq!( result2, NipFiDisconnectApplyResult::Applied(CrossPodMergeResult::CapacityExceeded), @@ -1938,6 +1984,7 @@ mod route_integration_tests { caller_sub: TEST_SUB.to_owned(), target_pubkey: target, until: t_frac, + scope: buzz_auth::DenyScope::WholeKey, }; // Publisher seam → encode → decode. @@ -1954,7 +2001,7 @@ mod route_integration_tests { // Consumer seam: apply with now = t_frac - 1ns (just inside the deadline). let now_inside = t_frac - chrono::Duration::nanoseconds(1); - let result = apply_nip_fi_disconnect(&state, &decoded, now_inside); + let result = apply_nip_fi_disconnect(&state, &decoded, || now_inside); assert_eq!( result, NipFiDisconnectApplyResult::Applied(CrossPodMergeResult::Merged), @@ -2349,6 +2396,16 @@ mod route_integration_tests { impl IssuerSessions { fn register(state: &crate::state::AppState, issuer: &str, key: &nostr::PublicKey) -> Self { + Self::register_issued(state, issuer, key, chrono::Utc::now()) + } + + /// Sessions admitted by an assertion with verified `iat` `issued_at`. + fn register_issued( + state: &crate::state::AppState, + issuer: &str, + key: &nostr::PublicKey, + issued_at: chrono::DateTime, + ) -> Self { use crate::state::CommunityConnectionControl; use tokio::sync::mpsc; use tokio_util::sync::CancellationToken; @@ -2371,14 +2428,18 @@ mod route_integration_tests { state.conn_manager.set_authenticated_identity( conn_id, key.to_bytes().to_vec(), - Some(crate::nip_fi_core::NipFiSession::new(issuer, None)), + Some(crate::nip_fi_core::NipFiSession::issued_at( + issuer, None, issued_at, + )), ); let audio = CancellationToken::new(); let ctrl = CommunityConnectionControl::new(audio.clone()); crate::audio::handler::audio_post_auth_register( &ctrl, key.to_bytes().to_vec(), - Some(crate::nip_fi_core::NipFiSession::new(issuer, None)), + Some(crate::nip_fi_core::NipFiSession::issued_at( + issuer, None, issued_at, + )), ); let _audio_guard = state @@ -2432,6 +2493,180 @@ mod route_integration_tests { under_b.assert_open("issuer B"); } + // ── revoke_through: cutoff-scoped close scans ──────────────────────────── + + fn at(secs: i64) -> chrono::DateTime { + chrono::DateTime::from_timestamp(secs, 0).unwrap() + } + + fn cutoff_message(key: &nostr::PublicKey, c: i64) -> buzz_pubsub::NipFiDisconnect { + buzz_pubsub::NipFiDisconnect { + revoke_through: Some(c), + ..cross_pod_message(key) + } + } + + #[tokio::test] + async fn route_cutoff_closes_old_sessions_and_keeps_fresh_ones_across_redelivery() { + let state = build_test_state(1000).await; + let key = nostr::Keys::generate().public_key(); + let c = chrono::Utc::now().timestamp(); + let old = IssuerSessions::register_issued(&state, TEST_ISS, &key, at(c)); + let fresh = IssuerSessions::register_issued(&state, TEST_ISS, &key, at(c + 1)); + + let token = mint_token( + &key.to_hex(), + 300, + serde_json::json!({ "revoke_through": c }), + ); + let resp = do_request( + Arc::clone(&state), + "POST", + vec![ + ("Content-Type", "application/json".into()), + (CLIENT_ATTACHED_HEADER, format!("Bearer {token}")), + ], + Some(serde_json::json!({"pubkey": key.to_hex()})), + ) + .await; + assert_eq!(resp.status(), StatusCode::OK); + old.assert_closed("iat == C"); + fresh.assert_open("iat > C after the route"); + + // The issuer's periodic redelivery, and a restore replaying the same + // record, arrive as cross-pod messages: still cutoff-scoped. + for _ in 0..3 { + apply_nip_fi_disconnect(&state, &cutoff_message(&key, c), chrono::Utc::now); + } + fresh.assert_open("iat > C after redelivery"); + let deny_map = state.nip_fi_deny_map.as_ref().unwrap(); + assert!(deny_map.denies(TEST_ISS, &key, at(c), chrono::Utc::now())); + assert!(!deny_map.denies(TEST_ISS, &key, at(c + 1), chrono::Utc::now())); + } + + #[tokio::test] + async fn cross_pod_cutoff_closes_only_old_sessions_on_another_pod() { + let state = cross_pod_state(10).await; + let key = nostr::Keys::generate().public_key(); + let c = chrono::Utc::now().timestamp(); + let old = IssuerSessions::register_issued(&state, TEST_ISS, &key, at(c - 30)); + let fresh = IssuerSessions::register_issued(&state, TEST_ISS, &key, at(c + 1)); + let result = apply_nip_fi_disconnect(&state, &cutoff_message(&key, c), chrono::Utc::now); + assert_eq!( + result, + NipFiDisconnectApplyResult::Applied(buzz_auth::CrossPodMergeResult::Merged) + ); + old.assert_closed("old session"); + fresh.assert_open("fresh session"); + } + + #[tokio::test] + async fn cutoff_delivery_over_an_active_whole_key_entry_closes_every_session() { + let state = cross_pod_state(10).await; + let key = nostr::Keys::generate().public_key(); + let now = chrono::Utc::now(); + apply_nip_fi_disconnect(&state, &cross_pod_message(&key), || now); + let c = now.timestamp(); + let fresh = IssuerSessions::register_issued(&state, TEST_ISS, &key, at(c + 1)); + apply_nip_fi_disconnect(&state, &cutoff_message(&key, c), || now); + fresh.assert_closed("the stronger merged whole-key deny applies"); + } + + #[tokio::test] + async fn past_until_cutoff_still_closes_its_scope_without_changing_the_deny() { + let state = cross_pod_state(10).await; + let key = nostr::Keys::generate().public_key(); + let now = chrono::Utc::now(); + let c = now.timestamp(); + let old = IssuerSessions::register_issued(&state, TEST_ISS, &key, at(c)); + let fresh = IssuerSessions::register_issued(&state, TEST_ISS, &key, at(c + 1)); + let message = buzz_pubsub::NipFiDisconnect { + until_unix: c - 1, + ..cutoff_message(&key, c) + }; + apply_nip_fi_disconnect(&state, &message, || now); + old.assert_closed("scoped close still runs"); + fresh.assert_open("fresh session"); + let deny_map = state.nip_fi_deny_map.as_ref().unwrap(); + assert!( + !deny_map.is_denied(TEST_ISS, &key, now), + "no active deny created" + ); + } + + /// The route's published bus message carries the cutoff: another pod + /// that decodes it closes only `iat <= C` and keeps the fresh session. + #[tokio::test] + async fn published_cutoff_reaches_another_pod_cutoff_scoped() { + let key = nostr::Keys::generate().public_key(); + let c = chrono::Utc::now().timestamp(); + let cmd = buzz_auth::CommandResult { + caller_iss: TEST_ISS.to_owned(), + caller_sub: TEST_SUB.to_owned(), + target_pubkey: key, + until: chrono::Utc::now() + chrono::Duration::seconds(300), + scope: buzz_auth::DenyScope::IssuedThrough(c), + }; + let encoded = buzz_pubsub::encode_nip_fi_disconnect(&nip_fi_disconnect_message(&cmd)) + .expect("encode"); + let decoded = buzz_pubsub::decode_nip_fi_disconnect(&encoded).expect("decode"); + let other_pod = cross_pod_state(10).await; + let old = IssuerSessions::register_issued(&other_pod, TEST_ISS, &key, at(c)); + let fresh = IssuerSessions::register_issued(&other_pod, TEST_ISS, &key, at(c + 1)); + apply_nip_fi_disconnect(&other_pod, &decoded, chrono::Utc::now); + old.assert_closed("iat == C on the other pod"); + fresh.assert_open("iat > C on the other pod"); + } + + /// The route widens its close to a stronger active entry: a cutoff + /// command over an active whole-key deny closes a fresh session too. + #[tokio::test] + async fn route_cutoff_over_an_active_whole_key_entry_closes_every_session() { + let state = build_test_state(1000).await; + let key = nostr::Keys::generate().public_key(); + let now = chrono::Utc::now(); + let c = now.timestamp(); + state + .nip_fi_deny_map + .as_ref() + .unwrap() + .merge_cross_pod_deny( + TEST_ISS, + &key, + buzz_auth::DenyEntry::whole_key(now + chrono::Duration::seconds(300)), + || now, + ); + let fresh = IssuerSessions::register_issued(&state, TEST_ISS, &key, at(c + 1)); + let token = mint_token( + &key.to_hex(), + 300, + serde_json::json!({ "revoke_through": c }), + ); + let resp = do_request( + Arc::clone(&state), + "POST", + vec![ + ("Content-Type", "application/json".into()), + (CLIENT_ATTACHED_HEADER, format!("Bearer {token}")), + ], + Some(serde_json::json!({"pubkey": key.to_hex()})), + ) + .await; + assert_eq!(resp.status(), StatusCode::OK); + fresh.assert_closed("the stronger active whole-key deny applies on the route"); + } + + #[test] + fn legacy_bus_message_without_revoke_through_is_whole_key() { + let json = r#"{"issuer":"i","pubkey_bytes":[],"until_unix":1}"#; + let decoded: buzz_pubsub::NipFiDisconnect = serde_json::from_str(json).unwrap(); + assert_eq!(decoded.revoke_through, None); + assert_eq!( + buzz_auth::DenyScope::from_revoke_through(decoded.revoke_through), + buzz_auth::DenyScope::WholeKey + ); + } + /// State whose registry and deny map know only issuer A (`TEST_ISS`). async fn cross_pod_state(capacity: usize) -> Arc { let mut config = crate::config::Config::for_test(); @@ -2480,6 +2715,7 @@ mod route_integration_tests { pubkey_bytes: key.to_bytes().to_vec(), until_unix: (chrono::Utc::now() + chrono::Duration::seconds(300)).timestamp(), until_unix_nanos: 0, + revoke_through: None, } } @@ -2493,7 +2729,7 @@ mod route_integration_tests { let under_a = IssuerSessions::register(state, TEST_ISS, &key); let under_b = IssuerSessions::register(state, OTHER_ISS, &key); - let result = apply_nip_fi_disconnect(state, &cross_pod_message(&key), chrono::Utc::now()); + let result = apply_nip_fi_disconnect(state, &cross_pod_message(&key), chrono::Utc::now); assert_eq!(result, NipFiDisconnectApplyResult::Applied(expected)); under_a.assert_closed("issuer A"); @@ -2511,7 +2747,7 @@ mod route_integration_tests { let state = cross_pod_state(1).await; let filler = nostr::Keys::generate().public_key(); assert_eq!( - apply_nip_fi_disconnect(&state, &cross_pod_message(&filler), chrono::Utc::now()), + apply_nip_fi_disconnect(&state, &cross_pod_message(&filler), chrono::Utc::now), NipFiDisconnectApplyResult::Applied(buzz_auth::CrossPodMergeResult::Merged), ); assert_cross_pod_closes_only_issuer_a( @@ -2574,7 +2810,7 @@ mod route_integration_tests { let _guard = metrics::set_default_local_recorder(&recorder); for state in [&full, &full, &poisoned] { let key = nostr::Keys::generate().public_key(); - apply_nip_fi_disconnect(state, &cross_pod_message(&key), chrono::Utc::now()); + apply_nip_fi_disconnect(state, &cross_pod_message(&key), chrono::Utc::now); } let mut series: Vec = snapshotter .snapshot() @@ -2613,7 +2849,7 @@ mod route_integration_tests { let sessions = IssuerSessions::register(state, TEST_ISS, key); let now = cross_pod_now(); - let result = apply_nip_fi_disconnect(state, message, now); + let result = apply_nip_fi_disconnect(state, message, || now); assert_eq!(result, NipFiDisconnectApplyResult::Rejected); sessions.assert_open("rejected message"); @@ -2654,6 +2890,19 @@ mod route_integration_tests { assert_cross_pod_rejected(&state, &key, &message); } + #[tokio::test] + async fn cross_pod_unrepresentable_revoke_through_rejected() { + let state = cross_pod_state(10).await; + for c in [i64::MIN, i64::MAX] { + let key = nostr::Keys::generate().public_key(); + let message = buzz_pubsub::NipFiDisconnect { + revoke_through: Some(c), + ..cross_pod_message(&key) + }; + assert_cross_pod_rejected(&state, &key, &message); + } + } + #[tokio::test] async fn cross_pod_without_deny_map_is_disabled() { let mut config = crate::config::Config::for_test(); @@ -2663,7 +2912,7 @@ mod route_integration_tests { let key = nostr::Keys::generate().public_key(); let sessions = IssuerSessions::register(&state, TEST_ISS, &key); - let result = apply_nip_fi_disconnect(&state, &cross_pod_message(&key), cross_pod_now()); + let result = apply_nip_fi_disconnect(&state, &cross_pod_message(&key), cross_pod_now); assert_eq!(result, NipFiDisconnectApplyResult::Disabled); sessions.assert_open("disabled consumer"); @@ -2684,7 +2933,7 @@ mod route_integration_tests { ..cross_pod_message(&key) }; - let result = apply_nip_fi_disconnect(&state, &message, now); + let result = apply_nip_fi_disconnect(&state, &message, || now); assert_eq!( result, @@ -3990,6 +4239,105 @@ mod route_integration_tests { } } + /// Reads from `inner`, reports the read on `read`, then holds the answer + /// until `release`, so a test controls the time between read and merge. + struct GatedLoad { + inner: buzz_auth::InMemoryCommandReplayGuard, + read: tokio::sync::Notify, + release: tokio::sync::Notify, + } + + impl buzz_auth::CommandReplayGuard for GatedLoad { + 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 { + let denies = self.inner.load_denies(issuer, now).await; + self.read.notify_one(); + self.release.notified().await; + denies + }) + } + } + + /// Restore judges expiry when it merges, not when it started reading: a + /// whole key that lapses during a slow load no longer overrides the + /// stored cutoff. + #[tokio::test] + async fn restore_judges_expiry_at_the_merge() { + use buzz_auth::CommandReplayGuard as _; + let source = Arc::new(GatedLoad { + inner: buzz_auth::InMemoryCommandReplayGuard::default(), + read: tokio::sync::Notify::new(), + release: tokio::sync::Notify::new(), + }); + let key = nostr::Keys::generate().public_key(); + let now = chrono::Utc::now(); + let c = now.timestamp(); + let outcome = source + .try_claim(buzz_auth::CommandClaim { + issuer: TEST_ISS, + jti: "cutoff", + ttl_secs: 60, + target: &key, + until: now + chrono::Duration::seconds(120), + scope: buzz_auth::DenyScope::IssuedThrough(c), + capacity: 10, + now, + }) + .await + .unwrap(); + assert_eq!(outcome, buzz_auth::ClaimOutcome::Claimed); + let dyn_source: Arc = source.clone(); + let pod = store_pod(10, Arc::clone(&dyn_source)).await; + let deny_map = pod.nip_fi_deny_map.as_deref().unwrap(); + let lapse = chrono::Utc::now() + chrono::Duration::milliseconds(200); + deny_map.merge_cross_pod_deny( + TEST_ISS, + &key, + buzz_auth::DenyEntry::whole_key(lapse), + chrono::Utc::now, + ); + let generation = deny_map.begin_restore(); + let sources = [dyn_source]; + let restore = restore_nip_fi_denies(&pod, &sources); + tokio::pin!(restore); + tokio::select! { + _ = &mut restore => panic!("restore finished before the gated read"), + () = source.read.notified() => {} + } + assert!( + chrono::Utc::now() < lapse, + "the whole key is live at the read" + ); + let wait = (lapse - chrono::Utc::now()).to_std().unwrap_or_default(); + tokio::time::sleep(wait + std::time::Duration::from_millis(50)).await; + source.release.notify_one(); + assert_eq!(restore.await, Ok(())); + assert!(deny_map.finish_restore(generation)); + let after = chrono::DateTime::from_timestamp(c, 0).unwrap() + chrono::Duration::seconds(1); + assert!( + !deny_map.denies(TEST_ISS, &key, after, chrono::Utc::now()), + "the whole key lapsed before the merge and gave way to the cutoff" + ); + } + /// Records a deny for `target` in `store` as another pod's accept would. async fn store_deny( store: &buzz_auth::InMemoryCommandReplayGuard, @@ -4013,6 +4361,7 @@ mod route_integration_tests { ttl_secs: 60, target, until, + scope: buzz_auth::DenyScope::WholeKey, capacity: 10, now: chrono::Utc::now(), }) @@ -4024,6 +4373,7 @@ mod route_integration_tests { pubkey_bytes: target.to_bytes().to_vec(), until_unix: until.timestamp(), until_unix_nanos: until.timestamp_subsec_nanos(), + revoke_through: None, } } @@ -4088,7 +4438,7 @@ mod route_integration_tests { "a partial load leaves it restoring" ); assert_eq!( - merge_nip_fi_disconnect(&pod, &message, chrono::Utc::now()), + merge_nip_fi_disconnect(&pod, &message, chrono::Utc::now), NipFiDisconnectApplyResult::Applied(buzz_auth::CrossPodMergeResult::Unchanged), "the readable record was applied" ); @@ -4380,8 +4730,13 @@ mod route_integration_tests { 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); + 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)) @@ -4514,10 +4869,10 @@ mod route_integration_tests { pod.nip_fi_deny_map .as_deref() .unwrap() - .merge_cross_pod_deny(TEST_ISS, &key, now + chrono::Duration::hours(1), now); + .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), + apply_nip_fi_disconnect(&pod, &message, || now), NipFiDisconnectApplyResult::Applied(buzz_auth::CrossPodMergeResult::Unchanged) ); sessions.assert_closed("unchanged live delivery"); @@ -4827,6 +5182,7 @@ mod route_integration_tests { ttl_secs: 60, target: &target, until: chrono::Utc::now() + chrono::Duration::seconds(60), + scope: buzz_auth::DenyScope::WholeKey, capacity: 100, now: chrono::Utc::now(), }; @@ -4862,6 +5218,7 @@ mod route_integration_tests { ttl_secs: 60, target, until, + scope: buzz_auth::DenyScope::WholeKey, capacity, now: chrono::Utc::now(), } @@ -4879,23 +5236,28 @@ mod route_integration_tests { .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); + // Redis judges expiry on its own clock, so entries expire for real. + let t = chrono::Utc::now(); let s = chrono::Duration::seconds; + let ms = chrono::Duration::milliseconds; let at = |jti: &'static str, target, until, capacity, now| buzz_auth::CommandClaim { issuer: &issuer, jti, ttl_secs: 60, target, until, + scope: buzz_auth::DenyScope::WholeKey, capacity, now, }; assert_eq!( - store.try_claim(at("p1", a, t + s(1), 1, t)).await.unwrap(), + store + .try_claim(at("p1", a, t + ms(300), 1, t)) + .await + .unwrap(), Claimed ); + tokio::time::sleep(std::time::Duration::from_millis(400)).await; assert_eq!( store .try_claim(at("p2", b, t + s(120), 1, t + s(2))) @@ -4906,22 +5268,24 @@ mod route_integration_tests { ); assert_eq!( store - .try_claim(at("p3", b, t + s(30), 2, t + s(2))) + .try_claim(at("p3", b, t + s(1), 2, t + s(2))) .await .unwrap(), Claimed ); // A later accept prunes entries whose score is below its now. + tokio::time::sleep(std::time::Duration::from_millis(1200)).await; assert_eq!( store - .try_claim(at("p4", c, t + s(90), 2, t + s(60))) + .try_claim(at("p4", c, t + s(90), 2, t + s(2))) .await .unwrap(), Claimed ); - let mut loaded = store.load_denies(&issuer, t + s(60)).await.unwrap(); + let mut loaded = store.load_denies(&issuer, t + s(2)).await.unwrap(); loaded.sort_by_key(|(k, _)| k.to_hex()); - let mut expected = vec![(*b, t + s(120)), (*c, t + s(90))]; + let w = buzz_auth::DenyEntry::whole_key; + let mut expected = vec![(*b, w(t + s(120))), (*c, w(t + s(90)))]; expected.sort_by_key(|(k, _)| k.to_hex()); assert_eq!(loaded, expected, "the longer deny for b survives the prune"); } @@ -5041,6 +5405,7 @@ mod route_integration_tests { ttl_secs: 60, target: &revoked, until: now + chrono::Duration::seconds(120), + scope: buzz_auth::DenyScope::WholeKey, capacity: 10, now, }) @@ -5071,7 +5436,7 @@ mod route_integration_tests { 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()), + deny_map.deny_status(TEST_ISS, &bystander, chrono::Utc::now(), chrono::Utc::now()), buzz_auth::DenyStatus::Unavailable, "admission stays closed while a record is unreadable" ); @@ -5089,6 +5454,505 @@ mod route_integration_tests { assert!(is_denied(&pod, &revoked), "the good record still denies"); } + /// Past a bad record, restore applies a readable deny at its cutoff, + /// not as the whole key, and admission stays fenced. + #[tokio::test] + #[ignore = "requires Redis"] + async fn redis_partial_restore_keeps_a_readable_cutoff() { + 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 c = now.timestamp(); + let outcome = store + .try_claim(buzz_auth::CommandClaim { + issuer: TEST_ISS, + jti: "good", + ttl_secs: 60, + target: &revoked, + until: now + chrono::Duration::seconds(120), + scope: buzz_auth::DenyScope::IssuedThrough(c), + 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 at = |secs| chrono::DateTime::from_timestamp(secs, 0).unwrap(); + let after = at(c) + chrono::Duration::seconds(1); + let old = IssuerSessions::register_issued(&pod, TEST_ISS, &revoked, at(c)); + let fresh = IssuerSessions::register_issued(&pod, TEST_ISS, &revoked, after); + deny_map.begin_restore(); + assert_eq!( + restore_nip_fi_denies(&pod, &[store]).await, + Err("unreadable") + ); + assert!( + !deny_map.is_restored(), + "a partial load leaves it restoring" + ); + old.assert_closed("issued at the cutoff"); + fresh.assert_open("the readable deny is scoped to its cutoff, not the whole key"); + assert_eq!( + deny_map.deny_status(TEST_ISS, &bystander, after, chrono::Utc::now()), + buzz_auth::DenyStatus::Unavailable, + "admission stays fenced while a record is unreadable" + ); + } + + /// The deny-store writer and reader before cutoffs, from #9860's + /// `02627cce` (the script verbatim, the reader with its logging + /// dropped and errors as text): the code a rolled-back or + /// not-yet-upgraded pod runs. + mod pre_cutoff { + use chrono::{DateTime, Utc}; + use nostr::PublicKey; + + pub 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' +"; + + /// Writes a whole-key deny as the old writer's `try_claim` did. + pub async fn accept( + conn: &mut buzz_pubsub::RedisConnection, + prefix: &str, + issuer: &str, + jti: &str, + target: &PublicKey, + until: DateTime, + now: DateTime, + ) -> String { + let (index, exact) = + buzz_pubsub::nip_fi_command_replay::deny_store_keys(prefix, issuer); + let ceil_ms = until.timestamp_millis() + + i64::from(!until.timestamp_subsec_nanos().is_multiple_of(1_000_000)); + redis::Script::new(ACCEPT_SCRIPT) + .key(format!("{prefix}:claim:{issuer}:{jti}")) + .key(index) + .key(exact) + .key(buzz_pubsub::nip_fi_command_replay::revoke_through_key( + prefix, issuer, + )) + .arg(60) + .arg(target.to_hex()) + .arg(ceil_ms) + .arg(until.timestamp()) + .arg(until.timestamp_subsec_nanos()) + .arg(10) + .arg(now.timestamp_millis()) + .arg(u8::from(until > now)) + .invoke_async(conn) + .await + .unwrap() + } + + /// The old `load_denies` body: the exact-`until` hash only, applying + /// every record past a bad one but still failing. + pub async fn load_denies( + conn: &mut buzz_pubsub::RedisConnection, + exact: String, + now: DateTime, + ) -> Result)>, String> { + let entries: Vec<(Vec, Vec)> = redis::cmd("HGETALL") + .arg(exact) + .query_async(conn) + .await + .map_err(|e| e.to_string())?; + 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) => { + bad.get_or_insert(record); + } + } + } + match bad { + None => Ok(denies), + Some(record) => Err(record), + } + } + + 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)) + } + + fn parse_until(value: &str) -> Option> { + let (secs, nanos) = value.split_once(':')?; + DateTime::from_timestamp(secs.parse().ok()?, nanos.parse().ok()?) + } + } + + /// A cutoff a command stores in Redis survives a restart as a cutoff: + /// a restored pod refuses an assertion issued at C and admits one + /// issued after it, while the exact-`until` hash alone (the whole of + /// an older relay's reader) still decodes and reads it as a whole-key + /// deny. + #[tokio::test] + #[ignore = "requires Redis"] + async fn redis_cutoff_survives_restore_and_old_reader_sees_whole_key() { + 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 key = nostr::Keys::generate().public_key(); + let now = chrono::Utc::now(); + let until = now + chrono::Duration::seconds(120); + let c = now.timestamp(); + let outcome = store + .try_claim(buzz_auth::CommandClaim { + issuer: TEST_ISS, + jti: "cutoff", + ttl_secs: 60, + target: &key, + until, + scope: buzz_auth::DenyScope::IssuedThrough(c), + capacity: 10, + now, + }) + .await + .unwrap(); + assert_eq!(outcome, buzz_auth::ClaimOutcome::Claimed); + + let pod = store_pod(10, Arc::clone(&store)).await; + let deny_map = pod.nip_fi_deny_map.as_deref().unwrap(); + let generation = deny_map.begin_restore(); + assert_eq!(restore_nip_fi_denies(&pod, &[store]).await, Ok(())); + assert!(deny_map.finish_restore(generation)); + let at = |secs| chrono::DateTime::from_timestamp(secs, 0).unwrap(); + let fraction = at(c) + chrono::Duration::milliseconds(500); + assert!(deny_map.denies(TEST_ISS, &key, at(c), chrono::Utc::now())); + assert!( + !deny_map.denies(TEST_ISS, &key, fraction, chrono::Utc::now()), + "restored as a cutoff, not a whole-key deny" + ); + + let (_, exact) = buzz_pubsub::nip_fi_command_replay::deny_store_keys( + &format!("{namespace}:deny"), + TEST_ISS, + ); + let old = pre_cutoff::load_denies(&mut conn, exact, now) + .await + .expect("the old reader decodes new data"); + assert_eq!(old, vec![(key, until)], "read as a whole-key deny"); + } + + /// The Redis merge matches [`buzz_auth::DenyEntry::merge`] in both + /// write orders: a whole key beats a cutoff, two cutoffs keep the + /// later C even under a shorter `until`, and an expired entry + /// contributes no scope. + #[tokio::test] + #[ignore = "requires Redis"] + async fn redis_scope_merge_matches_the_deny_map() { + use buzz_auth::{DenyEntry, DenyScope}; + let s = chrono::Duration::seconds; + let cut = DenyScope::IssuedThrough; + let whole = DenyScope::WholeKey; + // (first, second, milliseconds between the writes) + let cases = [ + ((s(60), cut(10)), (s(60), whole), 0, "whole over cutoff"), + ((s(60), whole), (s(60), cut(10)), 0, "cutoff over whole"), + ( + (s(60), cut(10)), + (s(30), cut(20)), + 0, + "shorter later cutoff", + ), + ( + (s(60), cut(20)), + (s(90), cut(10)), + 0, + "longer earlier cutoff", + ), + ( + (chrono::Duration::milliseconds(300), whole), + (s(60), cut(10)), + 400, + "expired whole key", + ), + ]; + for ((d1, s1), (d2, s2), wait, case) in cases { + let store = redis_guard(); + let key = nostr::Keys::generate().public_key(); + let t = chrono::Utc::now(); + let claim = |jti, until, scope| buzz_auth::CommandClaim { + issuer: TEST_ISS, + jti, + ttl_secs: 60, + target: &key, + until, + scope, + capacity: 10, + now: t, + }; + let first = DenyEntry { + until: t + d1, + scope: s1, + }; + let second = DenyEntry { + until: t + d2, + scope: s2, + }; + store.try_claim(claim("a", first.until, s1)).await.unwrap(); + tokio::time::sleep(std::time::Duration::from_millis(wait)).await; + store.try_claim(claim("b", second.until, s2)).await.unwrap(); + let now = chrono::Utc::now(); + let expected = DenyEntry::merge(Some(first), second, now); + let loaded = store.load_denies(TEST_ISS, now).await.unwrap(); + assert_eq!(loaded, vec![(key, expected)], "{case}"); + } + } + + /// A pod that predates cutoffs writes over a cutoff with an equal or + /// shorter `until`, and a fresh upgraded pod restores what it wrote as a whole-key deny. + #[tokio::test] + #[ignore = "requires Redis"] + async fn redis_pre_cutoff_writer_then_fresh_restore_is_whole_key() { + 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 prefix = format!("{namespace}:deny"); + let store = redis_guard_in(&namespace); + let [equal, shorter, fresh] = + std::array::from_fn(|_| nostr::Keys::generate().public_key()); + let now = chrono::Utc::now(); + let until = now + chrono::Duration::seconds(120); + let c = now.timestamp(); + for (jti, target) in [("cutoff-a", &equal), ("cutoff-b", &shorter)] { + let outcome = store + .try_claim(buzz_auth::CommandClaim { + issuer: TEST_ISS, + jti, + ttl_secs: 60, + target, + until, + scope: buzz_auth::DenyScope::IssuedThrough(c), + capacity: 10, + now, + }) + .await + .unwrap(); + assert_eq!(outcome, buzz_auth::ClaimOutcome::Claimed); + } + let short = until - chrono::Duration::seconds(60); + for (jti, target, old_until) in [ + ("old-a", &equal, until), + ("old-b", &shorter, short), + ("old-c", &fresh, until), + ] { + let reply = + pre_cutoff::accept(&mut conn, &prefix, TEST_ISS, jti, target, old_until, now) + .await; + assert_eq!(reply, "claimed"); + } + + let pod = store_pod(10, Arc::clone(&store)).await; + let deny_map = pod.nip_fi_deny_map.as_deref().unwrap(); + let generation = deny_map.begin_restore(); + assert_eq!(restore_nip_fi_denies(&pod, &[store]).await, Ok(())); + assert!(deny_map.finish_restore(generation)); + let after = + chrono::DateTime::from_timestamp(c, 0).unwrap() + chrono::Duration::seconds(1); + for key in [equal, shorter, fresh] { + assert!( + deny_map.denies(TEST_ISS, &key, after, chrono::Utc::now()), + "the old writer's full revoke, equal or shorter, restores as the whole key" + ); + } + } + + /// Expiry is judged by Redis as the script runs, not by the clock the + /// command was authenticated under: a full revoke whose `until` passes + /// before its write changes nothing, and a stored full revoke that + /// expired meanwhile no longer overrides a cutoff. + #[tokio::test] + #[ignore = "requires Redis"] + async fn redis_accept_judges_expiry_at_the_write() { + use buzz_auth::{DenyEntry, DenyScope}; + let store = redis_guard(); + let (key, other) = ( + nostr::Keys::generate().public_key(), + nostr::Keys::generate().public_key(), + ); + let authenticated = chrono::Utc::now(); + let ms = chrono::Duration::milliseconds; + let claim = |jti, target, until, scope| buzz_auth::CommandClaim { + issuer: TEST_ISS, + jti, + ttl_secs: 60, + target, + until, + scope, + capacity: 10, + now: authenticated, + }; + let until = authenticated + chrono::Duration::seconds(60); + let cut = DenyScope::IssuedThrough(10); + let lapsing = authenticated + ms(300); + store + .try_claim(claim("cutoff", &key, until, cut)) + .await + .unwrap(); + store + .try_claim(claim("lapsing", &other, lapsing, DenyScope::WholeKey)) + .await + .unwrap(); + tokio::time::sleep(std::time::Duration::from_millis(400)).await; + store + .try_claim(claim("lapsed", &key, lapsing, DenyScope::WholeKey)) + .await + .unwrap(); + store + .try_claim(claim("over", &other, until, cut)) + .await + .unwrap(); + let mut loaded = store + .load_denies(TEST_ISS, chrono::Utc::now()) + .await + .unwrap(); + loaded.sort_by_key(|(k, _)| k.to_hex()); + let mut expected = vec![ + (key, DenyEntry { until, scope: cut }), + (other, DenyEntry { until, scope: cut }), + ]; + expected.sort_by_key(|(k, _)| k.to_hex()); + assert_eq!( + loaded, expected, + "an expired full revoke neither widens nor overrides a cutoff" + ); + } + + /// A cutoff that doesn't decode, or names no stored deny, fails the + /// load as unreadable. + #[tokio::test] + #[ignore = "requires Redis"] + async fn redis_store_load_fails_on_unreadable_cutoff() { + 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(); + let now = chrono::Utc::now(); + let until = now + chrono::Duration::seconds(120); + for (case, field, cutoff) in [ + ("not a number", key.to_hex(), "soon".to_owned()), + ("out of range", key.to_hex(), i64::MAX.to_string()), + ( + "no deny", + nostr::Keys::generate().public_key().to_hex(), + "10".to_owned(), + ), + ] { + let namespace = test_namespace(); + let store = redis_guard_in(&namespace); + let prefix = format!("{namespace}:deny"); + let (_, exact) = + buzz_pubsub::nip_fi_command_replay::deny_store_keys(&prefix, TEST_ISS); + let cutoffs = + buzz_pubsub::nip_fi_command_replay::revoke_through_key(&prefix, TEST_ISS); + let _: () = redis::pipe() + .atomic() + .cmd("HSET") + .arg(&exact) + .arg(key.to_hex()) + .arg(format!( + "{}:{}", + until.timestamp(), + until.timestamp_subsec_nanos() + )) + .ignore() + .cmd("HSET") + .arg(&cutoffs) + .arg(field) + .arg(cutoff) + .ignore() + .cmd("EXPIRE") + .arg(&exact) + .arg(60) + .ignore() + .cmd("EXPIRE") + .arg(&cutoffs) + .arg(60) + .ignore() + .query_async(&mut conn) + .await + .unwrap(); + assert!( + matches!( + store.load_denies(TEST_ISS, now).await, + Err(buzz_auth::LoadDeniesError::Unreadable { .. }) + ), + "{case}" + ); + } + } + /// 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. @@ -5110,7 +5974,7 @@ mod route_integration_tests { nostr::Keys::generate().public_key(), nostr::Keys::generate().public_key(), ); - let t = chrono::Utc::now() + chrono::Duration::hours(1); + let t = chrono::Utc::now(); let s = chrono::Duration::seconds; let claim = |jti, target, until, now| buzz_auth::CommandClaim { issuer: &issuer, @@ -5118,6 +5982,7 @@ mod route_integration_tests { ttl_secs: 60, target, until, + scope: buzz_auth::DenyScope::WholeKey, capacity: 10, now, }; @@ -5163,9 +6028,32 @@ mod route_integration_tests { 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; + // b's entry already expired when the next accept runs, so it is pruned. + let (index, exact) = buzz_pubsub::nip_fi_command_replay::deny_store_keys( + &format!("{namespace}:deny"), + &issuer, + ); + let mut seed_conn = conn.clone(); + let _: () = redis::pipe() + .atomic() + .cmd("ZADD") + .arg(&index) + .arg(1) + .arg(b.to_hex()) + .ignore() + .cmd("HSET") + .arg(&exact) + .arg(b.to_hex()) + .arg("0:1000000") + .ignore() + .cmd("HSET") + .arg(&cutoffs) + .arg(b.to_hex()) + .arg(1) + .ignore() + .query_async(&mut seed_conn) + .await + .unwrap(); store .try_claim(claim("c4", &a, t + s(120), t + s(10))) .await @@ -5173,6 +6061,116 @@ mod route_integration_tests { assert!(!held(&b).await, "pruning clears the cutoff"); } + /// A disconnect over an active deny whose stored cutoff restore would + /// reject is refused with nothing written: the claim stays unused and the deny state is + /// unchanged. + #[tokio::test] + #[ignore = "requires Redis"] + async fn redis_accept_refuses_an_unreadable_stored_cutoff() { + /// Index members with scores, then the exact and cutoff hashes. + type DenyStoreSnapshot = ( + Vec<(String, f64)>, + Vec<(String, String)>, + Vec<(String, String)>, + ); + 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 prefix = format!("{namespace}:deny"); + let store = redis_guard_in(&namespace); + let issuer = format!("https://{}.example", uuid::Uuid::new_v4()); + let (index, exact) = + buzz_pubsub::nip_fi_command_replay::deny_store_keys(&prefix, &issuer); + let cutoffs = buzz_pubsub::nip_fi_command_replay::revoke_through_key(&prefix, &issuer); + let now = chrono::Utc::now(); + for (case, bad) in [ + ("fractional", "12.5"), + ("out of range", "9223372036854775807"), + ] { + let key = nostr::Keys::generate().public_key(); + let base = buzz_auth::CommandClaim { + issuer: &issuer, + jti: "base", + ttl_secs: 60, + target: &key, + until: now + chrono::Duration::seconds(120), + scope: buzz_auth::DenyScope::IssuedThrough(now.timestamp()), + capacity: 10, + now, + }; + let base_jti = format!("base-{key}"); + let outcome = store + .try_claim(buzz_auth::CommandClaim { + jti: &base_jti, + ..base + }) + .await + .unwrap(); + assert_eq!(outcome, buzz_auth::ClaimOutcome::Claimed); + let _: () = redis::cmd("HSET") + .arg(&cutoffs) + .arg(key.to_hex()) + .arg(bad) + .query_async(&mut conn) + .await + .unwrap(); + let snapshot = |conn: &mut buzz_pubsub::RedisConnection| { + let mut conn = conn.clone(); + let (index, exact, cutoffs) = (index.clone(), exact.clone(), cutoffs.clone()); + async move { + let state: DenyStoreSnapshot = redis::pipe() + .cmd("ZRANGE") + .arg(&index) + .arg(0) + .arg(-1) + .arg("WITHSCORES") + .cmd("HGETALL") + .arg(&exact) + .cmd("HGETALL") + .arg(&cutoffs) + .query_async(&mut conn) + .await + .unwrap(); + state + } + }; + let before = snapshot(&mut conn).await; + let jti = format!("bad-cutoff-{key}"); + let claim = buzz_auth::CommandClaim { + issuer: &issuer, + jti: &jti, + ttl_secs: 60, + target: &key, + until: now + chrono::Duration::seconds(60), + scope: buzz_auth::DenyScope::IssuedThrough(now.timestamp()), + capacity: 10, + now, + }; + assert!( + store.try_claim(claim).await.is_err(), + "{case} cutoff is refused" + ); + assert_eq!( + snapshot(&mut conn).await, + before, + "{case} leaves the deny state" + ); + let _: () = redis::cmd("HDEL") + .arg(&cutoffs) + .arg(key.to_hex()) + .query_async(&mut conn) + .await + .unwrap(); + assert_eq!( + store.try_claim(claim).await.unwrap(), + buzz_auth::ClaimOutcome::Claimed, + "{case} left the claim unused" + ); + } + } + /// The Redis script checks replay and shared capacity before writing, /// keeps the exact maximum `until`, and records no entry for a past /// `until`. @@ -5250,7 +6248,8 @@ mod route_integration_tests { .await .unwrap(); loaded.sort_by_key(|(k, _)| k.to_hex()); - let mut expected = vec![(a, later), (b, later)]; + let w = buzz_auth::DenyEntry::whole_key; + let mut expected = vec![(a, w(later)), (b, w(later))]; expected.sort_by_key(|(k, _)| k.to_hex()); assert_eq!( loaded, expected, @@ -5296,7 +6295,7 @@ mod route_integration_tests { let (seen_tx, seen) = tokio::sync::mpsc::unbounded_channel(); tokio::spawn(async move { while let Ok(msg) = rx.recv().await { - apply_nip_fi_disconnect(&consumer, &msg, chrono::Utc::now()); + apply_nip_fi_disconnect(&consumer, &msg, chrono::Utc::now); let _ = seen_tx.send(msg.pubkey_bytes); } }); diff --git a/crates/buzz-relay/src/audio/handler.rs b/crates/buzz-relay/src/audio/handler.rs index 9305b0a911..cf83eb5e22 100644 --- a/crates/buzz-relay/src/audio/handler.rs +++ b/crates/buzz-relay/src/audio/handler.rs @@ -4968,11 +4968,14 @@ mod tests { let mut wire = Vec::new(); if scan_first { - assert_eq!(registry.disconnect_nip_fi("test-issuer", &key), 1); + assert_eq!( + registry.disconnect_nip_fi("test-issuer", &key, buzz_auth::DenyScope::WholeKey), + 1 + ); } deny_audio_authorization(&mut wire, &control, &mut terminal_rx).await; if !scan_first { - registry.disconnect_nip_fi("test-issuer", &key); + registry.disconnect_nip_fi("test-issuer", &key, buzz_auth::DenyScope::WholeKey); } (wire, terminal_rx) } @@ -6895,8 +6898,7 @@ mod tests { if let Some(key) = denied_key { let until = chrono::Utc::now() + chrono::Duration::seconds(3600); - let result = - deny_map.merge_cross_pod_deny("test-issuer", key, until, chrono::Utc::now()); + let result = deny_map.merge_cross_pod_deny("test-issuer", key, until, chrono::Utc::now); assert!( matches!(result, buzz_auth::CrossPodMergeResult::Merged), "audio_deny_state: deny entry must be inserted for test setup" @@ -7181,7 +7183,7 @@ mod tests { // - `after_deny_set_check_passed` hook holds the handler AFTER the terminal // sender is registered and the deny-set check has passed (so the direct // map-denial branch is not what produces the frame). - // - Test calls `registry.disconnect_nip_fi("test-issuer", &pubkey)` while the hook holds. + // - Test calls `registry.disconnect_nip_fi("test-issuer", &pubkey, buzz_auth::DenyScope::WholeKey)` while the hook holds. // `CommunityConnectionControl::disconnect_nip_fi` enqueues the denial frame // on `terminal_frame_tx`, publishes `AuthorizationDenied`, then cancels. // - Hook is released; handler observes cancellation, drains the denial @@ -7345,9 +7347,11 @@ mod tests { // CommunityConnectionControl::disconnect_nip_fi enqueues the denial frame on // the registered terminal sender, publishes AuthorizationDenied, then cancels. let pubkey_bytes = key.public_key().to_bytes().to_vec(); - let closed = state - .community_connections - .disconnect_nip_fi("test-issuer", &pubkey_bytes); + let closed = state.community_connections.disconnect_nip_fi( + "test-issuer", + &pubkey_bytes, + buzz_auth::DenyScope::WholeKey, + ); assert_eq!( closed, 1, "W_admin_disconnect: registry scan must find exactly 1 audio session \ @@ -7423,13 +7427,34 @@ mod tests { // B) Remove `set_terminal_frame_sender` entirely → same outcome as (A). #[tokio::test] async fn w_admin_disconnect_at_deny_check_delivers_payload_then_terminates() { + w_admin_disconnect_at_deny_check_body(false).await; + } + + // Cutoff variants: the session registers through production + // `from_assertion` with a signed `iat` two minutes before registration. + // `iat == C` is seen by the scan, cancelled and never admitted; + // `iat == C + 0.5` is skipped, admitted and survives redelivery. + #[tokio::test] + async fn w_cutoff_disconnect_at_deny_check_cancels_old_token() { + w_admin_disconnect_at_deny_check_body(true).await; + } + + async fn w_admin_disconnect_at_deny_check_body(cutoff: bool) { use buzz_auth::VerifiedAssertion; use chrono::{Duration, Utc}; use std::sync::Arc; let key = nostr::Keys::generate(); let deadline = Utc::now() + Duration::hours(1); - let assertion = VerifiedAssertion::for_test(Some(key.public_key()), vec![deadline]); + let c = Utc::now().timestamp() - 120; + let mut assertion = VerifiedAssertion::for_test(Some(key.public_key()), vec![deadline]); + let mut scope = buzz_auth::DenyScope::WholeKey; + if cutoff { + // iat == C: on the revoked side of the cutoff. + assertion = + assertion.with_issued_at_for_test(chrono::DateTime::from_timestamp(c, 0).unwrap()); + scope = buzz_auth::DenyScope::IssuedThrough(c); + } // State with deny map; key is absent (not denied) — the check must pass. let state = audio_deny_state(None).await; @@ -7554,12 +7579,21 @@ mod tests { // Simulate admin-disconnect at the exact old-gap position. let pubkey_bytes = key.public_key().to_bytes().to_vec(); - let closed = state - .community_connections - .disconnect_nip_fi("test-issuer", &pubkey_bytes); + if cutoff { + let entry = buzz_auth::DenyEntry { + until: Utc::now() + Duration::hours(1), + scope, + }; + let deny_map = state.nip_fi_deny_map.as_ref().unwrap(); + deny_map.merge_cross_pod_deny("test-issuer", &key.public_key(), entry, Utc::now); + } + let closed = + state + .community_connections + .disconnect_nip_fi("test-issuer", &pubkey_bytes, scope); assert_eq!( closed, 1, - "W_addc: registry scan must find exactly 1 audio session \ + "W_addc: registry scan must find exactly the revoked-side audio session \ (proves audio_post_auth_register ran before the hook)" ); @@ -8131,7 +8165,7 @@ mod tests { // Insert the deny entry — handler is between registration and check. let until = Utc::now() + Duration::seconds(3600); let merge = - deny_map_for_insert.merge_cross_pod_deny("test-issuer", &target, until, Utc::now()); + deny_map_for_insert.merge_cross_pod_deny("test-issuer", &target, until, Utc::now); assert!( matches!(merge, buzz_auth::CrossPodMergeResult::Merged), "W_audio_deny_straddle: deny entry must be inserted during hook window" @@ -8148,9 +8182,11 @@ mod tests { // disconnect_nip_fi returns 0 (not yet registered) → assertion panics. // Causally falsifies the registration-before-check invariant. let pubkey_bytes = target.to_bytes().to_vec(); - let closed = state - .community_connections - .disconnect_nip_fi("test-issuer", &pubkey_bytes); + let closed = state.community_connections.disconnect_nip_fi( + "test-issuer", + &pubkey_bytes, + buzz_auth::DenyScope::WholeKey, + ); assert_eq!( closed, 1, "W_audio_deny_straddle: close scan must find exactly 1 registered audio session \ @@ -8197,6 +8233,177 @@ mod tests { mod postgres_tests { use super::*; + /// iat > C straddling a cutoff at the deny check: the scan skips it, the + /// handler completes a real audio join, and redelivery never closes it. + #[tokio::test] + #[ignore = "requires Postgres — runs in postgres-ci nextest lane"] + async fn w_cutoff_disconnect_at_deny_check_keeps_fresh_token_across_redelivery() { + use buzz_auth::{DenyEntry, DenyScope, VerifiedAssertion}; + use chrono::{Duration, Utc}; + use std::sync::Arc; + + let mut state = (*audio_test_state_real_db() + .await + .expect("W_cutoff: PostgreSQL must be available")) + .clone(); + let deny_map = Arc::new(buzz_auth::NipFiDenyMap::new( + 16, + vec![buzz_auth::IssuerCapacity { + issuer: "test-issuer".to_owned(), + capacity: 16, + }], + )); + state.nip_fi_deny_map = Some(Arc::clone(&deny_map)); + let state = Arc::new(state); + let (tenant, channel_id, key) = seed_audio_fixture(&state.db.pool().clone()).await; + let community = tenant.community(); + let relay_url = format!("ws://{}", tenant.host()); + + let c = Utc::now().timestamp() - 120; + let scope = DenyScope::IssuedThrough(c); + let assertion = VerifiedAssertion::for_test( + Some(key.public_key()), + vec![Utc::now() + Duration::hours(1)], + ) + .with_issued_at_for_test(chrono::DateTime::from_timestamp(c, 500_000_000).unwrap()); + + let conn_cancel = CancellationToken::new(); + let control = crate::state::CommunityConnectionControl::new(conn_cancel.clone()); + let _conn_guard = state.community_connections.register( + uuid::Uuid::new_v4(), + community, + control.clone(), + ); + + let listener = TcpListener::bind("127.0.0.1:0") + .await + .expect("W_cutoff: bind"); + let addr = listener.local_addr().expect("W_cutoff: addr"); + let state_c = Arc::clone(&state); + let server = tokio::spawn(async move { + let app = Router::new().route( + "/", + get(move |ws: WebSocketUpgrade| async move { + ws.on_upgrade(move |socket| { + handle_active_audio_connection( + socket, + state_c, + tenant, + channel_id, + control, + Some(assertion), + Utc::now(), + None, + ) + }) + }), + ); + axum::serve(listener, app).await.expect("W_cutoff: server"); + }); + + let (mut client, _) = connect_async(format!("ws://{addr}/")) + .await + .expect("W_cutoff: connect"); + let (hook_arrived_rx, hook_release) = + crate::nip_fi_test_hooks::deny_set_check_hook::arm(community); + + let challenge = + match tokio::time::timeout(std::time::Duration::from_secs(2), client.next()) + .await + .expect("W_cutoff: challenge timeout") + .expect("W_cutoff: challenge item") + .expect("W_cutoff: challenge message") + { + tokio_tungstenite::tungstenite::Message::Text(t) => { + serde_json::from_str::(&t) + .expect("W_cutoff: challenge JSON")["challenge"] + .as_str() + .expect("W_cutoff: challenge field") + .to_string() + } + other => panic!("W_cutoff: expected text challenge; got {other:?}"), + }; + let auth_event = nostr::EventBuilder::new(nostr::Kind::Authentication, "") + .tag(nostr::Tag::parse(["relay", &relay_url]).unwrap()) + .tag(nostr::Tag::parse(["challenge", &challenge]).unwrap()) + .sign_with_keys(&key) + .unwrap(); + let auth_msg = serde_json::json!({ + "type": "auth", + "event": auth_event, + "parent_channel_id": null, + "protocol_version": 2, + }) + .to_string(); + client + .send(tokio_tungstenite::tungstenite::Message::Text( + auth_msg.into(), + )) + .await + .expect("W_cutoff: send auth"); + + tokio::time::timeout(std::time::Duration::from_secs(5), hook_arrived_rx) + .await + .expect("W_cutoff: handler must reach before_deny_set_check within 5s") + .expect("W_cutoff: hook arrived channel closed"); + let entry = DenyEntry { + until: Utc::now() + Duration::hours(1), + scope, + }; + assert!(matches!( + deny_map.merge_cross_pod_deny("test-issuer", &key.public_key(), entry, Utc::now), + buzz_auth::CrossPodMergeResult::Merged + )); + let pubkey_bytes = key.public_key().to_bytes().to_vec(); + assert_eq!( + state + .community_connections + .disconnect_nip_fi("test-issuer", &pubkey_bytes, scope), + 0, + "W_cutoff: the scan must skip iat > C" + ); + hook_release.notify_one(); + + // Sync point: the handler's own `joined` proves the audio join completed. + let joined = loop { + match tokio::time::timeout(std::time::Duration::from_secs(10), client.next()) + .await + .expect("W_cutoff: `joined` must arrive within 10s") + .expect("W_cutoff: stream closed before `joined`") + .expect("W_cutoff: ws error") + { + tokio_tungstenite::tungstenite::Message::Text(t) => break t.to_string(), + _ => continue, + } + }; + let joined: serde_json::Value = serde_json::from_str(&joined).expect("W_cutoff: JSON"); + assert_eq!( + joined["type"], "joined", + "W_cutoff: iat > C must join: {joined}" + ); + assert_eq!( + joined["pubkey"].as_str(), + Some(key.public_key().to_hex().as_str()) + ); + + for _ in 0..3 { + assert_eq!( + state.community_connections.disconnect_nip_fi( + "test-issuer", + &pubkey_bytes, + scope + ), + 0, + "W_cutoff: redelivery must skip iat > C" + ); + } + assert!( + !conn_cancel.is_cancelled(), + "W_cutoff: iat > C must stay open after redelivery" + ); + server.abort(); + } + /// Joining a huddle is a write. For an ephemeral huddle the joiner /// needs a writing role in the huddle itself and in its lifecycle /// parent, at the pre-join check and again at commit. @@ -16401,9 +16608,11 @@ mod tests { if issuer_first { assert_eq!( - state - .community_connections - .disconnect_nip_fi("test-issuer", &member_bytes), + state.community_connections.disconnect_nip_fi( + "test-issuer", + &member_bytes, + buzz_auth::DenyScope::WholeKey + ), 1 ); } diff --git a/crates/buzz-relay/src/handlers/auth.rs b/crates/buzz-relay/src/handlers/auth.rs index b63fffd306..2cb597d45b 100644 --- a/crates/buzz-relay/src/handlers/auth.rs +++ b/crates/buzz-relay/src/handlers/auth.rs @@ -1833,7 +1833,11 @@ mod tests { Some(crate::nip_fi_core::NipFiSession::new("test-issuer", None)), ); assert_eq!( - state.conn_manager.disconnect_nip_fi("test-issuer", &pubkey), + state.conn_manager.disconnect_nip_fi( + "test-issuer", + &pubkey, + buzz_auth::DenyScope::WholeKey + ), 1 ); let admin_disconnect = harness.wire_frames().await; @@ -3814,7 +3818,7 @@ mod tests { // the deny check. Insert the deny entry into the live map. let until = Utc::now() + Duration::seconds(3600); let merge = - deny_map_for_insert.merge_cross_pod_deny("test-issuer", &target, until, Utc::now()); + deny_map_for_insert.merge_cross_pod_deny("test-issuer", &target, until, Utc::now); assert!( matches!(merge, buzz_auth::CrossPodMergeResult::Merged), "W_deny_straddle: deny entry must be inserted during the hook window" @@ -3826,9 +3830,11 @@ mod tests { // With the deny entry live, the scan finds exactly one session matching this // pubkey and closes it. let pubkey_bytes = target.to_bytes().to_vec(); - let closed = state - .conn_manager - .disconnect_nip_fi("test-issuer", &pubkey_bytes); + let closed = state.conn_manager.disconnect_nip_fi( + "test-issuer", + &pubkey_bytes, + buzz_auth::DenyScope::WholeKey, + ); assert_eq!( closed, 1, "W_deny_straddle: close scan must find exactly 1 registered session \ @@ -4008,17 +4014,20 @@ mod tests { ISSUER_A, &key.public_key(), Utc::now() + Duration::seconds(3600), - Utc::now(), + Utc::now, ), buzz_auth::CrossPodMergeResult::Merged )); let pubkey_bytes = key.public_key().to_bytes().to_vec(); - let closed = state - .conn_manager - .disconnect_nip_fi(ISSUER_A, &pubkey_bytes) - + state - .community_connections - .disconnect_nip_fi(ISSUER_A, &pubkey_bytes); + let closed = state.conn_manager.disconnect_nip_fi( + ISSUER_A, + &pubkey_bytes, + buzz_auth::DenyScope::WholeKey, + ) + state.community_connections.disconnect_nip_fi( + ISSUER_A, + &pubkey_bytes, + buzz_auth::DenyScope::WholeKey, + ); assert_eq!( closed, 0, "issuer A's close scan must not match a session admitted under B" @@ -4052,6 +4061,170 @@ mod tests { assert!(ok_true, "B session must receive OK(true)"); } + // ── W_cutoff_straddle: a cutoff disconnect lands between registration + // and the deny check. The session registers through production + // `from_assertion`, with a signed `iat` far from registration time. + // `iat == C`: the scan sees and cancels it, and it is never admitted. + // `iat == C + 0.5`: the scan skips it, it is admitted, and redelivery + // leaves it open. Mutation: recording registration time, or flooring + // the signed `iat`, flips one case. [FI-TRACE-DENY-SET] + #[tokio::test] + #[ignore = "requires Postgres"] + async fn w_cutoff_straddle_old_token_is_cancelled_and_never_admitted() { + w_cutoff_straddle_body(false).await; + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn w_cutoff_straddle_fresh_token_is_admitted_and_survives_redelivery() { + w_cutoff_straddle_body(true).await; + } + + async fn w_cutoff_straddle_body(fresh: bool) { + use buzz_auth::{ + DenyEntry, DenyScope, IssuerCapacity, NipFiDenyMap, VerifiedAssertion, + }; + use chrono::{Duration, Utc}; + use std::collections::HashMap; + use std::sync::Arc; + use tokio::sync::mpsc; + use tokio_util::sync::CancellationToken; + use uuid::Uuid; + + let key = Keys::generate(); + let deadline = Utc::now() + Duration::hours(1); + let c = Utc::now().timestamp() - 120; + let iat = + chrono::DateTime::from_timestamp(c, if fresh { 500_000_000 } else { 0 }).unwrap(); + let assertion = VerifiedAssertion::for_test(Some(key.public_key()), vec![deadline]) + .with_issued_at_for_test(iat); + + let challenge = "w-cutoff-straddle-challenge".to_string(); + let (send_tx, mut send_rx) = mpsc::channel::(8); + let (ctrl_tx, _ctrl_rx) = mpsc::channel::(8); + let (terminal_ctrl_tx, mut terminal_ctrl_rx) = mpsc::channel::(1); + let cancel = CancellationToken::new(); + let gate = crate::nip_fi_gate::SessionAdmissionGate::new(deadline, cancel.clone()); + let community = buzz_core::tenant::CommunityId::from_uuid(Uuid::new_v4()); + let conn = Arc::new(crate::connection::ConnectionState { + refusal_budget: Default::default(), + conn_id: Uuid::new_v4(), + tenant: buzz_core::tenant::TenantContext::resolved( + community, + "test.local".to_string(), + ), + remote_addr: "127.0.0.1:1234".parse().unwrap(), + auth_state: std::sync::Mutex::new(AuthState::Pending { + challenge: challenge.clone(), + started_at: std::time::Instant::now(), + }), + subscriptions: Arc::new(tokio::sync::Mutex::new(HashMap::new())), + send_tx, + ctrl_tx, + terminal_ctrl_tx, + cancel: cancel.clone(), + backpressure_count: Arc::new(std::sync::atomic::AtomicU8::new(0)), + grace_limit: 3, + nip_fi_assertion: Some(assertion), + session_deadline: Some(deadline), + nip_fi_gate: gate, + community_control: crate::state::CommunityConnectionControl::new(cancel.clone()), + }); + + let mut state = Arc::try_unwrap(auth_test_state_real_db_expect().await) + .unwrap_or_else(|arc| (*arc).clone()); + let deny_map = Arc::new(NipFiDenyMap::new( + 16, + vec![IssuerCapacity { + issuer: "test-issuer".to_owned(), + capacity: 16, + }], + )); + state.nip_fi_deny_map = Some(Arc::clone(&deny_map)); + let state = Arc::new(state); + state.conn_manager.register( + conn.conn_id, + conn.send_tx.clone(), + conn.ctrl_tx.clone(), + conn.terminal_ctrl_tx.clone(), + None, + cancel.clone(), + community, + Arc::clone(&conn.backpressure_count), + Arc::clone(&conn.subscriptions), + conn.grace_limit, + conn.community_control.clone(), + ); + + let auth_event = nostr::EventBuilder::new(nostr::Kind::Authentication, "") + .tag(nostr::Tag::parse(["relay", "ws://test.local"]).unwrap()) + .tag(nostr::Tag::parse(["challenge", &challenge]).unwrap()) + .sign_with_keys(&key) + .unwrap(); + let (arrived_rx, release) = + crate::nip_fi_test_hooks::deny_set_check_hook::arm(community); + let handle = tokio::spawn(handle_auth( + auth_event, + Arc::clone(&conn), + Arc::clone(&state), + )); + tokio::time::timeout(std::time::Duration::from_secs(5), arrived_rx) + .await + .expect("handler must reach before_deny_set_check within 5s") + .expect("arrived channel closed"); + + let scope = DenyScope::IssuedThrough(c); + let entry = DenyEntry { + until: Utc::now() + Duration::seconds(3600), + scope, + }; + assert!(matches!( + deny_map.merge_cross_pod_deny("test-issuer", &key.public_key(), entry, Utc::now), + buzz_auth::CrossPodMergeResult::Merged + )); + let pubkey_bytes = key.public_key().to_bytes().to_vec(); + let closed = state + .conn_manager + .disconnect_nip_fi("test-issuer", &pubkey_bytes, scope); + assert_eq!(closed, usize::from(!fresh), "the scan sees only iat <= C"); + + release.notify_one(); + tokio::time::timeout(std::time::Duration::from_secs(5), handle) + .await + .expect("handle_auth must return within 5s after hook release") + .expect("handle_auth task must not panic"); + + // `AuthState` turns Authenticated before the barrier; admission + // is `mark_admitted`, i.e. the admitted index entry. + let admitted = state + .conn_manager + .has_admitted_connection(community, &pubkey_bytes); + let mut ok_true = false; + while let Ok(WsMessage::Text(t)) = send_rx.try_recv() { + ok_true |= is_ok_true(t.as_str()); + } + if fresh { + assert!(admitted && ok_true, "iat > C must be admitted"); + for _ in 0..3 { + assert_eq!( + state + .conn_manager + .disconnect_nip_fi("test-issuer", &pubkey_bytes, scope), + 0 + ); + } + assert!(!cancel.is_cancelled(), "iat > C survives redelivery"); + } else { + assert!(cancel.is_cancelled(), "iat == C must be cancelled"); + assert!(!admitted, "iat == C must never reach mark_admitted"); + assert!(!ok_true, "iat == C must never get OK(true)"); + assert!( + terminal_ctrl_rx.try_recv().is_ok(), + "iat == C must get a terminal denial" + ); + } + } + /// True iff `frame` is a NIP-01 `["OK", , true, ...]` acceptance. fn is_ok_true(frame: &str) -> bool { serde_json::from_str::(frame) @@ -4163,7 +4336,7 @@ mod tests { "test-issuer", &denied_key, Utc::now() + Duration::hours(1), - Utc::now(), + Utc::now, ); assert!(matches!(merge, buzz_auth::CrossPodMergeResult::Merged)); state.nip_fi_deny_map = Some(deny_map); @@ -4188,9 +4361,11 @@ mod tests { // The close scan runs while the connection is still unproven: it // must miss it, leaving the handler's check as the only defence. - let closed = state - .conn_manager - .disconnect_nip_fi("test-issuer", &key.public_key().to_bytes()); + let closed = state.conn_manager.disconnect_nip_fi( + "test-issuer", + &key.public_key().to_bytes(), + buzz_auth::DenyScope::WholeKey, + ); assert_eq!(closed, 0, "close scan must miss the unproven connection"); assert!(!cancel.is_cancelled()); diff --git a/crates/buzz-relay/src/nip_fi_core.rs b/crates/buzz-relay/src/nip_fi_core.rs index ef75663d47..f37b2f2fdd 100644 --- a/crates/buzz-relay/src/nip_fi_core.rs +++ b/crates/buzz-relay/src/nip_fi_core.rs @@ -219,8 +219,10 @@ pub(crate) fn asserted_key_matches( /// 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)`. +/// [`DENY_SET`](crate::nip_fi_shadow::DENY_SET) when an active deny entry for +/// `(iss, k)` or, for an agent assertion, `(iss, owner)` covers this +/// assertion's verified signed `iat`; each key is checked independently and +/// either denial wins. pub(crate) fn assertion_denied( deny_map: &impl crate::nip_fi_http::HttpDenyMap, assertion: &VerifiedAssertion, @@ -235,7 +237,7 @@ pub(crate) fn assertion_denied( .into_iter() .flatten() { - match deny_map.deny_status(issuer, &key, now) { + match deny_map.deny_status(issuer, &key, assertion.issued_at(), 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), @@ -244,33 +246,56 @@ pub(crate) fn assertion_denied( refusal.map(|refusal| refusal.by(assertion.asserted_key())) } -/// The NIP-FI facts a live session is registered under: its admitting issuer -/// and, for an agent assertion, the verified owner. +/// The NIP-FI facts a live session is registered under: its admitting issuer, +/// for an agent assertion the verified owner, and the assertion's verified +/// signed `iat`. #[derive(Clone)] pub(crate) struct NipFiSession { issuer: String, owner: Option<[u8; 32]>, + issued_at: chrono::DateTime, } impl NipFiSession { + #[cfg(test)] pub(crate) fn new(issuer: impl Into, owner: Option<[u8; 32]>) -> Self { + Self::issued_at(issuer, owner, chrono::Utc::now()) + } + + #[cfg(test)] + pub(crate) fn issued_at( + issuer: impl Into, + owner: Option<[u8; 32]>, + issued_at: chrono::DateTime, + ) -> Self { Self { issuer: issuer.into(), owner, + issued_at, } } pub(crate) fn from_assertion(assertion: &VerifiedAssertion) -> Self { - Self::new( - assertion.identity().issuer(), - assertion.owner().map(|owner| owner.to_bytes()), - ) + Self { + issuer: assertion.identity().issuer().to_owned(), + owner: assertion.owner().map(|owner| owner.to_bytes()), + issued_at: assertion.issued_at(), + } } - /// An admin disconnect of `(issuer, target)` reaches this session when - /// its proven key or its recorded owner is `target`. - pub(crate) fn matches(&self, issuer: &str, proven: &[u8], target: &[u8]) -> bool { + /// An admin disconnect of `(issuer, target)` with close `scope` reaches + /// this session when its proven key or its recorded owner is `target` + /// and `scope` covers the session's verified `iat`. The one close + /// predicate for every socket registry and shadow accounting. + pub(crate) fn matches( + &self, + issuer: &str, + proven: &[u8], + target: &[u8], + scope: buzz_auth::DenyScope, + ) -> bool { self.issuer == issuer + && scope.covers(self.issued_at) && (proven == target || self.owner.is_some_and(|owner| owner[..] == *target)) } } @@ -569,7 +594,12 @@ pub(crate) mod tests { }], ); let now = chrono::Utc::now(); - map.merge_cross_pod_deny("test-issuer", key, now + chrono::Duration::seconds(60), now); + map.merge_cross_pod_deny( + "test-issuer", + key, + now + chrono::Duration::seconds(60), + || now, + ); map } @@ -602,6 +632,7 @@ pub(crate) mod tests { _: &str, _: &nostr::PublicKey, _: chrono::DateTime, + _: chrono::DateTime, ) -> bool { unreachable!("admission reads deny_status only") } @@ -610,9 +641,10 @@ pub(crate) mod tests { &self, issuer: &str, pubkey: &nostr::PublicKey, + issued_at: chrono::DateTime, now: chrono::DateTime, ) -> buzz_auth::DenyStatus { - let status = self.0.deny_status(issuer, pubkey, now); + let status = self.0.deny_status(issuer, pubkey, issued_at, now); self.0.begin_restore(); status } @@ -649,6 +681,83 @@ pub(crate) mod tests { assert!(assertion_denied(&deny_map_denying(&unrelated), &assertion, now).is_none()); } + fn deny_map_with( + key: &nostr::PublicKey, + entry: buzz_auth::DenyEntry, + ) -> buzz_auth::NipFiDenyMap { + let map = deny_map_denying(&nostr::Keys::generate().public_key()); + map.merge_cross_pod_deny("test-issuer", key, entry, chrono::Utc::now); + map + } + + #[test] + fn cutoff_deny_refuses_old_agent_tokens_and_admits_fresh_ones() { + let (agent, owner) = ( + nostr::Keys::generate().public_key(), + nostr::Keys::generate().public_key(), + ); + let now = chrono::Utc::now(); + let c = now.timestamp(); + let map = deny_map_with( + &agent, + buzz_auth::DenyEntry { + until: now + chrono::Duration::seconds(60), + scope: buzz_auth::DenyScope::IssuedThrough(c), + }, + ); + let issued = |secs| chrono::DateTime::from_timestamp(secs, 0).unwrap(); + let old = agent_assertion(agent, owner).with_issued_at_for_test(issued(c)); + let fresh = agent_assertion(agent, owner).with_issued_at_for_test(issued(c + 1)); + assert!(assertion_denied(&map, &old, now).is_some()); + assert!(assertion_denied(&map, &fresh, now).is_none()); + } + + #[test] + fn owner_whole_key_deny_still_blocks_a_fresh_agent_token() { + let (agent, owner) = ( + nostr::Keys::generate().public_key(), + nostr::Keys::generate().public_key(), + ); + let now = chrono::Utc::now(); + let map = deny_map_with( + &owner, + buzz_auth::DenyEntry::whole_key(now + chrono::Duration::seconds(60)), + ); + map.merge_cross_pod_deny( + "test-issuer", + &agent, + buzz_auth::DenyEntry { + until: now + chrono::Duration::seconds(60), + scope: buzz_auth::DenyScope::IssuedThrough(now.timestamp() - 10), + }, + || now, + ); + let fresh = agent_assertion(agent, owner).with_issued_at_for_test(now); + assert!( + assertion_denied(&map, &fresh, now).is_some(), + "either denial wins" + ); + } + + #[test] + fn close_predicate_skips_sessions_issued_after_the_cutoff() { + let (agent, owner) = ([1u8; 32], [2u8; 32]); + let issued = |secs| chrono::DateTime::from_timestamp(secs, 0).unwrap(); + let old = NipFiSession::issued_at("test-issuer", Some(owner), issued(100)); + let fresh = NipFiSession::issued_at("test-issuer", Some(owner), issued(101)); + let scope = buzz_auth::DenyScope::IssuedThrough(100); + for target in [agent, owner] { + assert!(old.matches("test-issuer", &agent, &target, scope)); + assert!(!fresh.matches("test-issuer", &agent, &target, scope)); + assert!(fresh.matches( + "test-issuer", + &agent, + &target, + buzz_auth::DenyScope::WholeKey + )); + } + } + #[test] fn owner_deny_entry_does_not_reach_an_ownerless_assertion() { let key = nostr::Keys::generate().public_key(); @@ -666,12 +775,37 @@ pub(crate) mod tests { fn session_matches_disconnect_of_its_key_or_owner_under_its_issuer() { let (agent, owner, other) = ([1u8; 32], [2u8; 32], [3u8; 32]); let session = NipFiSession::new("test-issuer", Some(owner)); - assert!(session.matches("test-issuer", &agent, &agent)); - assert!(session.matches("test-issuer", &agent, &owner)); - assert!(!session.matches("test-issuer", &agent, &other)); - assert!(!session.matches("other-issuer", &agent, &owner)); + assert!(session.matches( + "test-issuer", + &agent, + &agent, + buzz_auth::DenyScope::WholeKey + )); + assert!(session.matches( + "test-issuer", + &agent, + &owner, + buzz_auth::DenyScope::WholeKey + )); + assert!(!session.matches( + "test-issuer", + &agent, + &other, + buzz_auth::DenyScope::WholeKey + )); + assert!(!session.matches( + "other-issuer", + &agent, + &owner, + buzz_auth::DenyScope::WholeKey + )); let human = NipFiSession::new("test-issuer", None); - assert!(!human.matches("test-issuer", &agent, &owner)); + assert!(!human.matches( + "test-issuer", + &agent, + &owner, + buzz_auth::DenyScope::WholeKey + )); } /// Verifier returning a fixed result and counting calls. diff --git a/crates/buzz-relay/src/nip_fi_http.rs b/crates/buzz-relay/src/nip_fi_http.rs index 797b0bbd25..5d312a4c98 100644 --- a/crates/buzz-relay/src/nip_fi_http.rs +++ b/crates/buzz-relay/src/nip_fi_http.rs @@ -182,21 +182,29 @@ use crate::nip_fi_shadow::{Stage, WouldDeny}; /// /// Sealed: only implementations in this crate are accepted. pub(crate) trait HttpDenyMap: sealed::Sealed { - /// Returns `true` when `(issuer, pubkey)` has an active deny entry at - /// `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; + /// Returns `true` when an entry for `(issuer, pubkey)` active at `now` + /// (`now < until`) covers an assertion whose verified signed `iat` is + /// `issued_at`. Implementations fail closed: a poisoned or unavailable + /// backing store returns `true` (deny). + fn is_denied( + &self, + issuer: &str, + pubkey: &PublicKey, + issued_at: DateTime, + 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. + /// The verdict for `(issuer, pubkey)` and `issued_at` 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, + issued_at: DateTime, now: DateTime, ) -> buzz_auth::DenyStatus { - if self.is_denied(issuer, pubkey, now) { + if self.is_denied(issuer, pubkey, issued_at, now) { buzz_auth::DenyStatus::Denied } else { buzz_auth::DenyStatus::Allowed @@ -210,19 +218,26 @@ pub(crate) mod sealed { impl sealed::Sealed for buzz_auth::NipFiDenyMap {} impl HttpDenyMap for buzz_auth::NipFiDenyMap { - /// Delegates to [`buzz_auth::NipFiDenyMap::is_denied`], which is issuer- + /// Delegates to [`buzz_auth::NipFiDenyMap::denies`], which is issuer- /// scoped and returns `true` on a poisoned shard. - fn is_denied(&self, issuer: &str, pubkey: &PublicKey, now: DateTime) -> bool { - buzz_auth::NipFiDenyMap::is_denied(self, issuer, pubkey, now) + fn is_denied( + &self, + issuer: &str, + pubkey: &PublicKey, + issued_at: DateTime, + now: DateTime, + ) -> bool { + self.denies(issuer, pubkey, issued_at, now) } fn deny_status( &self, issuer: &str, pubkey: &PublicKey, + issued_at: DateTime, now: DateTime, ) -> buzz_auth::DenyStatus { - buzz_auth::NipFiDenyMap::deny_status(self, issuer, pubkey, now) + buzz_auth::NipFiDenyMap::deny_status(self, issuer, pubkey, issued_at, now) } } @@ -240,7 +255,7 @@ impl HttpDenyMap for buzz_auth::NipFiDenyMap { struct NoDenyMapConfigured; impl sealed::Sealed for NoDenyMapConfigured {} impl HttpDenyMap for NoDenyMapConfigured { - fn is_denied(&self, _issuer: &str, _pubkey: &PublicKey, _now: DateTime) -> bool { + fn is_denied(&self, _: &str, _: &PublicKey, _: DateTime, _: DateTime) -> bool { false } } @@ -899,7 +914,7 @@ mod tests { struct AlwaysAdmitStubDenyMap; impl sealed::Sealed for AlwaysAdmitStubDenyMap {} impl HttpDenyMap for AlwaysAdmitStubDenyMap { - fn is_denied(&self, _issuer: &str, _pubkey: &PublicKey, _now: DateTime) -> bool { + fn is_denied(&self, _: &str, _: &PublicKey, _: DateTime, _: DateTime) -> bool { false } } @@ -1119,7 +1134,13 @@ mod tests { struct FixedDenyMap(bool); impl sealed::Sealed for FixedDenyMap {} impl HttpDenyMap for FixedDenyMap { - fn is_denied(&self, _: &str, _: &PublicKey, _: DateTime) -> bool { + fn is_denied( + &self, + _: &str, + _: &PublicKey, + _: DateTime, + _: DateTime, + ) -> bool { self.0 } } @@ -2102,7 +2123,12 @@ mod tests { }], ); let now = Utc::now(); - map.merge_cross_pod_deny("test-issuer", &owner, now + chrono::Duration::hours(1), 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( @@ -2160,7 +2186,12 @@ mod tests { assert_eq!(admission.assertion().and_then(|a| a.owner()), Some(owner)); let now = Utc::now(); - map.merge_cross_pod_deny("test-issuer", &owner, now + chrono::Duration::hours(1), now); + map.merge_cross_pod_deny( + "test-issuer", + &owner, + now + chrono::Duration::hours(1), + || now, + ); let (status, body) = denial_parts(admit(NipFiMode::Enforce, &map)); assert_eq!(status, StatusCode::FORBIDDEN); assert_eq!(body, b"authorization denied\n"); diff --git a/crates/buzz-relay/src/nip_fi_resolver/tests/router_tests.rs b/crates/buzz-relay/src/nip_fi_resolver/tests/router_tests.rs index ef2e67db11..48439cb9c6 100644 --- a/crates/buzz-relay/src/nip_fi_resolver/tests/router_tests.rs +++ b/crates/buzz-relay/src/nip_fi_resolver/tests/router_tests.rs @@ -576,7 +576,7 @@ async fn key_disconnected_before_its_community_exists_is_denied_there() { let (k_keys, control_keys) = (nostr::Keys::generate(), nostr::Keys::generate()); let (k, control) = (k_keys.public_key(), control_keys.public_key()); let now = chrono::Utc::now(); - let merged = deny_map.merge_cross_pod_deny(ISS, &k, now + chrono::Duration::hours(1), now); + let merged = deny_map.merge_cross_pod_deny(ISS, &k, now + chrono::Duration::hours(1), || now); assert!(matches!(merged, buzz_auth::CrossPodMergeResult::Merged)); let h = host("after"); assert_eq!( diff --git a/crates/buzz-relay/src/nip_fi_shadow_session.rs b/crates/buzz-relay/src/nip_fi_shadow_session.rs index 9eeeb1720d..6fbf4d5c6e 100644 --- a/crates/buzz-relay/src/nip_fi_shadow_session.rs +++ b/crates/buzz-relay/src/nip_fi_shadow_session.rs @@ -53,7 +53,7 @@ impl ShadowSessions { /// [`NipFiSession`] matches, at once if admitted or at its admit if still /// pending; a session already ended records nothing, so re-sent denies /// are idempotent. - pub(crate) fn would_close(&self, issuer: &str, pubkey: &[u8]) { + pub(crate) fn would_close(&self, issuer: &str, pubkey: &[u8], scope: buzz_auth::DenyScope) { let live: Vec<_> = self .registered() .values() @@ -62,7 +62,12 @@ impl ShadowSessions { for session in live { let assertion = &session.assertion; if assertion.asserted_key().is_some_and(|key| { - NipFiSession::from_assertion(assertion).matches(issuer, &key.to_bytes(), pubkey) + NipFiSession::from_assertion(assertion).matches( + issuer, + &key.to_bytes(), + pubkey, + scope, + ) }) { session.revoke(); } @@ -428,7 +433,7 @@ pub(crate) mod tests { "test-issuer", &key, Utc::now() + Duration::hours(1), - Utc::now(), + Utc::now, ); } state.nip_fi_deny_map = Some(Arc::new(map)); @@ -466,9 +471,11 @@ pub(crate) mod tests { } fn revoke(state: &AppState, key: &PublicKey) { - state - .nip_fi_shadow_sessions - .would_close("test-issuer", &key.to_bytes()); + state.nip_fi_shadow_sessions.would_close( + "test-issuer", + &key.to_bytes(), + buzz_auth::DenyScope::WholeKey, + ); } // Mutation: recording on a repeated AUTH, or letting the re-sent deny @@ -482,15 +489,53 @@ pub(crate) mod tests { auth(&s, &state, key); auth(&s, &state, key); revoke(&state, &Keys::generate().public_key()); - state - .nip_fi_shadow_sessions - .would_close("other-issuer", &key.to_bytes()); + state.nip_fi_shadow_sessions.would_close( + "other-issuer", + &key.to_bytes(), + buzz_auth::DenyScope::WholeKey, + ); revoke(&state, &key); revoke(&state, &key); }); assert_eq!(records, ["admit/admit", "end/revoked"]); } + // Mutation: dropping the scope from the shadow match ends the fresh + // session too. + #[test] + fn cutoff_would_close_ends_only_sessions_issued_through_it() { + let records = shadow_records(async { + let state = shadow_state(None).await; + let key = Keys::generate().public_key(); + let c = Utc::now().timestamp(); + let issued = |secs| chrono::DateTime::from_timestamp(secs, 0).unwrap(); + let mut live = Vec::new(); + for iat in [c, c + 1] { + let assertion = + VerifiedAssertion::for_test(Some(key), vec![Utc::now() + Duration::hours(1)]) + .with_issued_at_for_test(issued(iat)); + let s = ShadowSession::start( + &state, + "ws", + crate::nip_fi_shadow::BOUND.into(), + assertion, + Utc::now(), + ); + auth(&s, &state, key); + live.push(s); + } + state.nip_fi_shadow_sessions.would_close( + "test-issuer", + &key.to_bytes(), + buzz_auth::DenyScope::IssuedThrough(c), + ); + let ended = |s: &ShadowSession| matches!(*s.phase.lock().unwrap(), Phase::Ended); + assert!(ended(&live[0]), "the session issued at C ends"); + assert!(!ended(&live[1]), "the session issued at C + 1 stays open"); + }); + assert_eq!(records, ["admit/admit", "admit/admit", "end/revoked"]); + } + // Mismatched and claimless keys are both pairing denials; nothing after a // denial records, because enforce would have closed the connection. #[test] @@ -552,8 +597,9 @@ pub(crate) mod tests { pubkey_bytes: key.to_bytes().to_vec(), until_unix: (Utc::now() + Duration::minutes(5)).timestamp(), until_unix_nanos: 0, + revoke_through: None, }; - match crate::api::nip_fi::apply_nip_fi_disconnect(state, &msg, Utc::now()) { + match crate::api::nip_fi::apply_nip_fi_disconnect(state, &msg, Utc::now) { crate::api::nip_fi::NipFiDisconnectApplyResult::Applied(merged) => merged, other => panic!("disconnect not applied: {other:?}"), } @@ -669,9 +715,11 @@ pub(crate) mod tests { s.observe_pairing(agent); s.observe_deny_set(&state); } - state - .nip_fi_shadow_sessions - .would_close("other-issuer", &owner.to_bytes()); + state.nip_fi_shadow_sessions.would_close( + "other-issuer", + &owner.to_bytes(), + buzz_auth::DenyScope::WholeKey, + ); for s in &admitted { assert!(matches!(*s.phase.lock().unwrap(), Phase::Admitted)); } diff --git a/crates/buzz-relay/src/router.rs b/crates/buzz-relay/src/router.rs index e427584351..fecdea1109 100644 --- a/crates/buzz-relay/src/router.rs +++ b/crates/buzz-relay/src/router.rs @@ -4623,7 +4623,7 @@ mod tests { )); let until = chrono::Utc::now() + chrono::Duration::seconds(3600); let merge_result = - deny_map.merge_cross_pod_deny(DENY_TEST_ISS, denied_key, until, chrono::Utc::now()); + deny_map.merge_cross_pod_deny(DENY_TEST_ISS, denied_key, until, chrono::Utc::now); assert!( matches!(merge_result, buzz_auth::CrossPodMergeResult::Merged), "deny entry must be inserted for test setup" diff --git a/crates/buzz-relay/src/state.rs b/crates/buzz-relay/src/state.rs index 5d281a9aab..80e78af9f3 100644 --- a/crates/buzz-relay/src/state.rs +++ b/crates/buzz-relay/src/state.rs @@ -103,10 +103,10 @@ struct ProvenIdentity { } impl ProvenIdentity { - fn matches(&self, issuer: &str, pubkey: &[u8]) -> bool { + fn matches(&self, issuer: &str, pubkey: &[u8], scope: buzz_auth::DenyScope) -> bool { self.nip_fi .as_ref() - .is_some_and(|session| session.matches(issuer, &self.pubkey, pubkey)) + .is_some_and(|session| session.matches(issuer, &self.pubkey, pubkey, scope)) } } @@ -555,7 +555,12 @@ impl CommunityConnectionRegistry { /// and then runs the deny-set check, so such a socket is rejected there. /// /// Returns the number of connections closed. - pub fn disconnect_nip_fi(&self, issuer: &str, pubkey: &[u8]) -> usize { + pub fn disconnect_nip_fi( + &self, + issuer: &str, + pubkey: &[u8], + scope: buzz_auth::DenyScope, + ) -> usize { let mut closed = 0; for entry in self.connections.iter() { let matches = entry @@ -564,7 +569,7 @@ impl CommunityConnectionRegistry { .proven_identity .read() .ok() - .and_then(|v| v.as_ref().map(|id| id.matches(issuer, pubkey))) + .and_then(|v| v.as_ref().map(|id| id.matches(issuer, pubkey, scope))) .unwrap_or(false); if matches { let control = &entry.value().1; @@ -1110,7 +1115,12 @@ impl ConnectionManager { /// ordinary control buffer is full. /// /// Returns the number of connections closed. - pub fn disconnect_nip_fi(&self, issuer: &str, pubkey: &[u8]) -> usize { + pub fn disconnect_nip_fi( + &self, + issuer: &str, + pubkey: &[u8], + scope: buzz_auth::DenyScope, + ) -> usize { let mut closed = 0usize; for entry in self.connections.iter() { let matches = entry @@ -1122,7 +1132,7 @@ impl ConnectionManager { entry.nip_fi.read().is_ok_and(|session| { session .as_ref() - .is_some_and(|s| s.matches(issuer, proven, pubkey)) + .is_some_and(|s| s.matches(issuer, proven, pubkey, scope)) }) }) }) @@ -3229,7 +3239,7 @@ pub(crate) mod tests { ); // No set_authenticated_pubkey — simulates pre-NIP-42 state. - let closed = mgr.disconnect_nip_fi("test-issuer", &pubkey); + let closed = mgr.disconnect_nip_fi("test-issuer", &pubkey, buzz_auth::DenyScope::WholeKey); assert_eq!(closed, 0, "unproven connection must not be closed"); assert!(!cancel.is_cancelled(), "unproven connection must stay live"); @@ -3277,7 +3287,14 @@ pub(crate) mod tests { let (cancel_b, mut frames_b) = register(Some("https://issuer-b.example")); let (cancel_none, mut frames_none) = register(None); - assert_eq!(mgr.disconnect_nip_fi("https://issuer-a.example", &key), 1); + assert_eq!( + mgr.disconnect_nip_fi( + "https://issuer-a.example", + &key, + buzz_auth::DenyScope::WholeKey + ), + 1 + ); assert!(cancel_a.is_cancelled(), "A session must be closed"); assert!( @@ -3339,7 +3356,7 @@ pub(crate) mod tests { Some(NipFiSession::new("test-issuer", None)), ); - let closed = mgr.disconnect_nip_fi("test-issuer", &pubkey); + let closed = mgr.disconnect_nip_fi("test-issuer", &pubkey, buzz_auth::DenyScope::WholeKey); assert_eq!(closed, 1, "one matching connection must be closed"); assert!(cancel.is_cancelled(), "connection token must be cancelled"); @@ -3383,7 +3400,11 @@ pub(crate) mod tests { let (cancel_none, mut frames_none, _gn) = register(None); assert_eq!( - registry.disconnect_nip_fi("https://issuer-a.example", &key), + registry.disconnect_nip_fi( + "https://issuer-a.example", + &key, + buzz_auth::DenyScope::WholeKey + ), 1 ); @@ -3425,7 +3446,14 @@ pub(crate) mod tests { ); let _guard = registry.register(Uuid::new_v4(), community, control); - assert_eq!(registry.disconnect_nip_fi("test-issuer", &target_pubkey), 1); + assert_eq!( + registry.disconnect_nip_fi( + "test-issuer", + &target_pubkey, + buzz_auth::DenyScope::WholeKey + ), + 1 + ); assert!(cancel.is_cancelled(), "audio socket must be cancelled"); assert_eq!( *reason_rx.borrow(), @@ -3473,8 +3501,14 @@ pub(crate) mod tests { audio.set_proven_identity(agent.clone(), owned); let _guard = registry.register(Uuid::new_v4(), community, audio); - assert_eq!(mgr.disconnect_nip_fi("test-issuer", &owner), 1); - assert_eq!(registry.disconnect_nip_fi("test-issuer", &owner), 1); + assert_eq!( + mgr.disconnect_nip_fi("test-issuer", &owner, buzz_auth::DenyScope::WholeKey), + 1 + ); + assert_eq!( + registry.disconnect_nip_fi("test-issuer", &owner, buzz_auth::DenyScope::WholeKey), + 1 + ); assert!(root_owned.is_cancelled() && audio_cancel.is_cancelled()); assert!(!root_other_issuer.is_cancelled()); assert!(!root_ownerless.is_cancelled()); @@ -3501,7 +3535,14 @@ pub(crate) mod tests { peer_control.set_proven_identity(peer_pubkey, Some(NipFiSession::new("test-issuer", None))); let _peer_guard = registry.register(Uuid::new_v4(), community, peer_control); - assert_eq!(registry.disconnect_nip_fi("test-issuer", &target_pubkey), 1); + assert_eq!( + registry.disconnect_nip_fi( + "test-issuer", + &target_pubkey, + buzz_auth::DenyScope::WholeKey + ), + 1 + ); assert!( target_cancel.is_cancelled(), "target audio socket must be cancelled" @@ -3526,7 +3567,14 @@ pub(crate) mod tests { control.set_proven_identity(other_pubkey, Some(NipFiSession::new("test-issuer", None))); let _guard = registry.register(Uuid::new_v4(), community, control); - assert_eq!(registry.disconnect_nip_fi("test-issuer", &target_pubkey), 0); + assert_eq!( + registry.disconnect_nip_fi( + "test-issuer", + &target_pubkey, + buzz_auth::DenyScope::WholeKey + ), + 0 + ); assert!( !cancel.is_cancelled(), "different-key socket must not be touched" @@ -3546,7 +3594,14 @@ pub(crate) mod tests { // Intentionally skip set_proven_pubkey — simulates pre-auth state. let _guard = registry.register(Uuid::new_v4(), community, control); - assert_eq!(registry.disconnect_nip_fi("test-issuer", &target_pubkey), 0); + assert_eq!( + registry.disconnect_nip_fi( + "test-issuer", + &target_pubkey, + buzz_auth::DenyScope::WholeKey + ), + 0 + ); assert!( !cancel.is_cancelled(), "pre-auth socket must not be touched" diff --git a/docs/nips/NIP-FI.md b/docs/nips/NIP-FI.md index e776060f83..5482140d72 100644 --- a/docs/nips/NIP-FI.md +++ b/docs/nips/NIP-FI.md @@ -351,8 +351,9 @@ On WebSocket upgrade: this registered connection before step 8; cancellation is terminal, so a cancelled connection MUST NOT be admitted. 7. Check the deny set for `(iss, k)` and, if `verified.owner` is present, for - `(iss, verified.owner)`. Either active entry (`now < until`) denies - `authorization_denied`. + `(iss, verified.owner)`. Either entry denies `authorization_denied` when + it covers the assertion (see Deny scope); each key is checked + independently and either denial wins. [FI-TRACE-DENY-SET] 8. Admit the connection only if it remains live and uncancelled. The session's authority deadline is the minimum of all `authority_deadlines`; see Session @@ -411,22 +412,69 @@ A disconnect call causes the relay to: 1. Insert a **deny entry** keyed by `(iss, target_pubkey)` into the relay's in-memory deny set, with an absolute expiry of `until` (a Unix timestamp - carried in the signed command JWT; see Command JWT). If an entry for - `(iss, target_pubkey)` already exists, the relay MUST retain - `max(existing_until, command.until)` — an accepted disconnect MUST NOT - shorten an active deny. A past-`until` command still closes sessions but - MUST NOT clear or shorten an independently active entry. Any subsequent - connection or admission attempt for that pubkey under the same issuer is - denied `authorization_denied` until `now >= until`. If the deny set is at + carried in the signed command JWT; see Command JWT) and the command's scope + (see Deny scope). If an entry for `(iss, target_pubkey)` already exists, the relay + MUST merge them under the Deny scope merge rule — an accepted disconnect + MUST NOT shorten an active deny. A past-`until` command still performs its + scoped close but MUST NOT clear, shorten or strengthen an independently + active entry. Any subsequent connection or admission attempt for that + pubkey under the same issuer whose assertion the entry covers is denied + `authorization_denied` until `now >= until`. If the deny set is at capacity and a new entry cannot be inserted, the relay MUST reject the command `503`; no sessions are closed and no replay state is consumed. 2. Close all live WebSocket connections registered under the command's issuer whose proven `k` equals the target pubkey or whose recorded owner equals - the target pubkey, whether or not admission has completed, synchronously. + the target pubkey, whether or not admission has completed, synchronously, + limited to the close scope (see Deny scope). Disconnect cancellation is terminal: a cancelled in-progress connection MUST NOT be subsequently admitted. Connections registered under another issuer are not affected. +### Deny scope + +A command MAY carry `revoke_through` (C). Without C, its deny entry covers +the whole key. With C, it covers only assertions whose verified signed `iat` +is at or before C. + +- **Admission.** An entry `(iss, key, until, C?)` denies an otherwise-valid + assertion exactly when `now < until` and either C is absent or the + assertion's verified signed `iat <= C`. The `iat` is the verified claim, + never optional profile evidence. This holds for WebSocket and HTTP + admission, for `(iss, k)` and `(iss, verified.owner)` alike. Every other + authorization check still applies. +- **Close scope.** A command with C closes only matching sessions whose + admitting assertion's verified `iat <= C`, including in-progress ones; a + command without C closes all matching sessions. The close scope is the + union of the command's scope and the scope of any active entry for the + same key after merging, so a stronger active denial also applies. A + session registers its verified `iat` before the post-registration deny + check, so a session straddling a disconnect is caught by the close scan or + the deny check. A past-`until` command still performs its scoped close but + MUST NOT create, shorten or strengthen an active entry. +- **Comparison.** `iat <= C` compares the full verified instant, including + any fractional part, against the integral C. +- **Merging.** Merging an incoming entry into an active one takes the later + `until`; a whole-key scope beats a cutoff; two cutoffs merge to the larger + C. An expired entry contributes nothing: an active entry ignores an + expired incoming one, and an incoming entry replaces an expired one. + Activity is judged at the instant the merge is applied. These rules hold + identically for local state, any shared or durable store, inter-process + propagation and restore. +- **Records.** A stored or propagated entry without C means whole-key. + Unreadable revocation state MUST NOT be treated as allowed. +- **Issuer duty.** An issuer that sends C MUST ensure that every still-valid + assertion it released under the revoked authority has `iat <= C`. While + a cutoff is active, it MUST NOT release a recovery assertion for that key + whose `iat <= C`. It MUST record the revocation, C and the queued + delivery atomically, and retries MUST resend the recorded policy rather + than a new one. + +Oracle: with an active entry `(iss, k, until, C)`, an assertion for `k` +signed with `iat = C` is denied and closed by every disconnect for `k`, an +assertion signed with `iat = C + 0.5` is admitted and survives every +redelivery of that command, and a whole-key entry for its owner still denies +it. [FI-TRACE-DENY-SET] + 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 @@ -504,6 +552,7 @@ The command JWT MUST carry the following claims: | `cmd` | Exactly `"disconnect"` (literal string). Operation selector. | | `target_pubkey` | Lowercase hexadecimal encoding of the target 32-byte Nostr public key — the same encoding required for the assertion `nostr_pubkey` claim. | | `until` | Unix timestamp (NumericDate) at which the deny entry expires. MUST NOT exceed `now + skew + maximum_assertion_age` for this issuer policy. The relay validates this ceiling; a value that exceeds it rejects `400`. | +| `revoke_through` | OPTIONAL. Integral NumericDate C limiting the deny to assertions with `iat <= C` (see Deny scope). Absent means the whole key. A present value that is `null`, nonnumeric, fractional or unrepresentable rejects `evidence_rejected` before any state changes. | The `maximum_command_age` policy knob is a required positive finite configuration per authorized issuer, with a normative upper bound of @@ -536,6 +585,14 @@ VerifyCommandJwt(token, request_method, request_path, request_body_pubkey): assert claims.cmd == "disconnect" or DENY(evidence_rejected) target_k := ParseHexKey(claims.target_pubkey) or DENY(evidence_rejected) until := claims.until or DENY(evidence_rejected) + // Optional cutoff: absent → whole key. Present but null, nonnumeric, + // fractional or unrepresentable → deny before any state changes. + if "revoke_through" in claims: + assert IsIntegralRepresentableNumericDate(claims.revoke_through) + or DENY(evidence_rejected) + scope := IssuedThrough(claims.revoke_through) + else: + scope := WholeKey // 4. Validate until ceiling deny_ceiling := now + policy.skew + policy.maximum_assertion_age @@ -560,19 +617,21 @@ VerifyCommandJwt(token, request_method, request_path, request_body_pubkey): // capacity failure, making the 503 contract unimplementable. Capacity // is checked against the per-issuer bound for claims.iss; a different // issuer's capacity exhaustion does not produce a 503 here. - // On same-key collision: retain max(existing_until, until) — never shorten - // an active deny. A past-until command merges as max(existing, past) which - // preserves any active entry; a fresh entry with a past-until inserts with - // an already-expired value (immediately inactive for future admissions). + // On same-key collision: merge under the Deny scope merge rule, judging + // activity at the moment of this mutation — never shorten an active deny. + // A past-until command leaves any active entry unchanged; a fresh entry + // with a past-until inserts an already-expired value (immediately inactive + // for future admissions). effective_expiry := min(claims.exp, claims.iat + policy.maximum_command_age) AtomicReserveJtiAndDenyEntry( iss=claims.iss, jti=claims.jti, effective_expiry=effective_expiry, - target_pubkey=target_k, until=until + target_pubkey=target_k, until=until, scope=scope ) 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)) + return CommandResult(target_pubkey=target_k, caller=(claims.iss, claims.sub), + until=until, scope=scope) ``` Any failure at any step is fail-closed: no sessions are closed and the relay @@ -597,7 +656,8 @@ inserts the deny entry — both or neither. A capacity failure at that step rej 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. +`CommandResult.target_pubkey`, and whose admitting assertion falls in the +close scope (see Deny scope), whether or not admission has completed. Disconnect cancellation is terminal: a cancelled in-progress connection MUST NOT be subsequently admitted. This close scan matches the deny entry's `target_pubkey` against each connection's proven key and recorded @@ -606,7 +666,7 @@ another issuer are not affected. The `until` expiry is taken exclusively from the signed command JWT claim; the request body carries no `until` field. An unknown or unprovable pubkey is not an error; the relay responds `200` with `{"disconnected": true}`. An `until` value in the past is not an error; -sessions are closed. Absent an active same-key deny entry the past-`until` +sessions in the close scope are closed. Absent an active same-key deny entry the past-`until` creates no future denial; if an active entry already exists it remains unchanged under the merge rule. @@ -826,8 +886,9 @@ On each protected HTTP request: 5. Assert `verified.asserted_key == k`; mismatch → deny `authorization_denied`. [FI-TRACE-ASSERTION-KEY-MISMATCH] 6. Check the deny set for `(iss, k)` and, if `verified.owner` is present, for - `(iss, verified.owner)`. Either active entry (`now < until`) denies - `authorization_denied`. + `(iss, verified.owner)`. Either entry denies `authorization_denied` when + it covers the assertion (see Deny scope); each key is checked + independently and either denial wins. [FI-TRACE-DENY-SET] 7. Admit the request. @@ -958,8 +1019,8 @@ deployment-local identifiers. [FI-TRACE-DISCOVERY-PRIVATE] | `FI-TRACE-JWKS-REMOVE` | Connections verified under a removed key deny on next revalidation or reconnect. | | `FI-TRACE-DEPENDENCY-FAIL-CLOSED` | An unreadable JWKS snapshot denies `authorization_unavailable`; no degraded Nostr-only access. | | `FI-TRACE-LEASE-BOUND` | A session closes at its earliest deadline; equality at any deadline is expired. | -| `FI-TRACE-DENY-SET` | A pubkey in the deny set is denied `authorization_denied` on admission until `now >= until`; an expired or absent entry does not deny; a past-`until` command closes sessions — absent an active same-key entry it creates no future denial, while an active entry remains unchanged under the merge rule; a deny-set-full command is rejected `503` without closing sessions and without removing any existing entry; capacity is evaluated per issuer — one issuer's capacity exhaustion MUST NOT reject another issuer's command; a connection that passes the deny-set check before a concurrent deny-entry insertion but completes admission after MUST still be terminated (the session's proven `k` and admitting issuer are registered before the deny-set check, ensuring the close scan catches it); a registered-but-not-admitted connection caught by the close scan MUST be cancelled terminally and MUST NOT later be admitted; a disconnect command from one issuer MUST NOT close a same-key connection registered under a different issuer, whether or not admission has completed; two overlapping commands for the same `(iss, pubkey)` in either delivery order result in `until = max(until_A, until_B)` — delivery order does not shorten the longer deny; a past-`until` command arriving over an active entry leaves the active entry's `until` unchanged; a successful disconnect responds `{"disconnected": true}` regardless of how many sessions were closed; the deny entry applies across all communities served by the relay under that issuer. | -| `FI-TRACE-HTTP-INGRESS` | A protected HTTP request with both valid headers and matching pubkeys is admitted; absent, mismatched, or invalid assertion or NIP-98 event denies; a request presenting only one of the two denies; an active deny-set entry denies; a route that cannot be classified as exempt is treated as protected; repeated, comma-combined, wrong-scheme, or alternative-credential `Authorization` fields deny `evidence_rejected`; a missing `Authorization` field denies `missing_evidence`; an authorization-relevant body without exactly one matching `payload` tag denies; the NIP-FI administrative API is not a protected surface. For kind-24242 (Blossom) proofs on media routes: a `t=upload` proof with valid `x`, `server`, `expiration`, and freshness is admitted on `PUT /upload`; a `t=get` proof with valid `server`, `expiration`, and freshness is admitted on `GET\|HEAD /media/{hash…}`; a kind-24242 proof on any other route denies; an upload proof with absent or mismatched `server` tag denies; a read proof with absent or mismatched `server` tag denies; a proof with a duplicate, missing, or out-of-range `expiration` tag denies; a proof dated more than 120 seconds in the future denies; a proof older than 120 seconds denies; key mismatch between assertion `nostr_pubkey` and the kind-24242 event pubkey denies; an active deny-set entry denies. | +| `FI-TRACE-DENY-SET` | A pubkey in the deny set is denied `authorization_denied` on admission until `now >= until` when the entry covers the assertion — a whole-key entry covers every assertion, a cutoff entry only those with verified `iat <= C`, so `iat = C` denies and `iat = C + 0.5` admits; an expired or absent entry does not deny; a disconnect with C closes only sessions with `iat <= C`, and a session with `iat > C` survives every redelivery unless a stronger active merged entry widens the close scope (see Deny scope); a whole-key entry beats a same-deadline cutoff and the later of two cutoffs wins, in either order; an entry that expires before a merge is applied contributes nothing to it; a past-`until` command performs its scoped close — absent an active same-key entry it creates no future denial, while an active entry remains unchanged under the merge rule; a deny-set-full command is rejected `503` without closing sessions and without removing any existing entry; capacity is evaluated per issuer — one issuer's capacity exhaustion MUST NOT reject another issuer's command; a connection within the effective close scope that passes the deny-set check before a concurrent deny-entry insertion but completes admission after MUST still be terminated (the session's proven `k` and admitting issuer are registered before the deny-set check, ensuring the close scan catches it); a registered-but-not-admitted connection caught by the close scan MUST be cancelled terminally and MUST NOT later be admitted; a disconnect command from one issuer MUST NOT close a same-key connection registered under a different issuer, whether or not admission has completed; two overlapping commands for the same `(iss, pubkey)` in either delivery order result in `until = max(until_A, until_B)` — delivery order does not shorten the longer deny; a past-`until` command arriving over an active entry leaves the active entry's `until` unchanged; a successful disconnect responds `{"disconnected": true}` regardless of how many sessions were closed; the deny entry applies across all communities served by the relay under that issuer. | +| `FI-TRACE-HTTP-INGRESS` | A protected HTTP request with both valid headers and matching pubkeys is admitted; absent, mismatched, or invalid assertion or NIP-98 event denies; a request presenting only one of the two denies; an active deny-set entry that covers the assertion denies; a route that cannot be classified as exempt is treated as protected; repeated, comma-combined, wrong-scheme, or alternative-credential `Authorization` fields deny `evidence_rejected`; a missing `Authorization` field denies `missing_evidence`; an authorization-relevant body without exactly one matching `payload` tag denies; the NIP-FI administrative API is not a protected surface. For kind-24242 (Blossom) proofs on media routes: a `t=upload` proof with valid `x`, `server`, `expiration`, and freshness is admitted on `PUT /upload`; a `t=get` proof with valid `server`, `expiration`, and freshness is admitted on `GET\|HEAD /media/{hash…}`; a kind-24242 proof on any other route denies; an upload proof with absent or mismatched `server` tag denies; a read proof with absent or mismatched `server` tag denies; a proof with a duplicate, missing, or out-of-range `expiration` tag denies; a proof dated more than 120 seconds in the future denies; a proof older than 120 seconds denies; key mismatch between assertion `nostr_pubkey` and the kind-24242 event pubkey denies; an active deny-set entry that covers the assertion denies. | | `FI-TRACE-DENIAL-ORACLE` | Each public-class row produces its exact fixed bytes; all private-state rows compare byte-identical. | | `FI-TRACE-DISCOVERY-PRIVATE` | Complete discovery bytes do not expose issuer, audience, or deployment-private state. | | `FI-TRACE-CROSS-DOMAIN-COLLISION` | Equal `sub` values under different `iss` values remain distinct identities. | @@ -989,15 +1050,18 @@ assertions. If the issuer continues issuing assertions, access continues. For the deny-until-TTL disconnect model (issuer issues a successful disconnect call with an `until` timestamp), the relay inserts a deny entry for the target -pubkey with expiry `until` and then closes all matching connections synchronously. +pubkey with expiry `until` and the command's scope, then closes all matching +connections synchronously. Here, matching means connections registered under that issuer whose proven `k` equals that target pubkey or whose recorded owner equals the target pubkey, -whether or not admission has completed; disconnect +and whose admitting assertion falls in the close scope, whether or not +admission has completed; disconnect cancellation is terminal, so a cancelled in-progress connection MUST NOT be subsequently admitted. Connections registered under another issuer are not affected. Any subsequent admission attempt for that pubkey under the same issuer -is denied `authorization_denied` -until `now >= until`. The `until` ceiling enforced by the relay is +whose assertion the entry covers is denied `authorization_denied` +until `now >= until`. A cutoff entry lets assertions issued after C in at +once; its security rests on the issuer duty in Deny scope. The `until` ceiling enforced by the relay is `now + skew + maximum_assertion_age`; this limits how long a deny entry may last — it does not ensure denial outlasts all live assertions. A short or past `until` is valid, and if the issuer continues issuing after the entry diff --git a/docs/operator-nip-fi-bindings.md b/docs/operator-nip-fi-bindings.md index b628c339a9..15a2278b0b 100644 --- a/docs/operator-nip-fi-bindings.md +++ b/docs/operator-nip-fi-bindings.md @@ -276,6 +276,20 @@ What this covers, and what it does not: (`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. + A disconnect with `revoke_through` stores its cutoff in a second hash, + `buzz:nip-fi:deny-revoke-through:`, under the same + field (`buzz:nip-fi:shadow-deny-revoke-through:…` in shadow mode). A + cutoff is also unreadable when it is not an integer, or when its field has + no entry in the deny hash. Recover with `HDEL` on the cutoff hash, but the + two cases differ: + - The cutoff is malformed and its field is also in the deny hash: after + the `HDEL`, that entry still refuses every token for the key until its + `until`. + - The cutoff is orphaned (its field is not in the deny hash): there is no + deny underneath it, so after the `HDEL` that key is not revoked at all. + Send the disconnect again if the revocation is still needed. + A new disconnect for a key whose stored cutoff is unreadable also fails + with `503` and records nothing until that `HDEL`; then send it again. - **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.