|
| 1 | +//! NIP-98 replay protection — shared, community-scoped, atomic seen-set. |
| 2 | +//! |
| 3 | +//! NIP-98 verification ([`crate::nip98::verify_nip98_event`]) is structurally |
| 4 | +//! complete: it checks signature, kind, timestamp window, URL, method, and |
| 5 | +//! optional body hash. It does **not** check whether the same event id has |
| 6 | +//! already been used — that requires shared state. With multiple relay pods |
| 7 | +//! ("any pod, any connection" per the rewrite §4 architecture), an in-process |
| 8 | +//! cache (moka, DashMap) does not carry the freshness proof across pods, so |
| 9 | +//! replay protection is a §5 hard gate. |
| 10 | +//! |
| 11 | +//! The required shape (§5): |
| 12 | +//! |
| 13 | +//! - shared state (Redis), atomic set-if-absent, TTL ≥ 120s |
| 14 | +//! - community-scoped key — see [`nip98_replay_key`] |
| 15 | +//! |
| 16 | +//! ## Usage shape |
| 17 | +//! |
| 18 | +//! Verify first, then mark. Burning a seen-set slot on a forgery would let an |
| 19 | +//! attacker who knows a future event id of a victim DoS the legitimate event. |
| 20 | +//! |
| 21 | +//! ```ignore |
| 22 | +//! let pubkey = buzz_auth::verify_nip98_event(json, url, method, body)?; |
| 23 | +//! if !replay.try_mark(&ctx, &event_id).await? { |
| 24 | +//! return Err(AuthError::Nip98Replay); |
| 25 | +//! } |
| 26 | +//! // safe to honor the request as `pubkey` |
| 27 | +//! ``` |
| 28 | +//! |
| 29 | +//! The TTL must cover the verifier's clock-skew tolerance (currently ±60s, so |
| 30 | +//! the window over which a duplicate event id is even plausible is 2×60 = 120s). |
| 31 | +//! [`DEFAULT_REPLAY_TTL_SECS`] is the floor; deployments may raise it. |
| 32 | +
|
| 33 | +use buzz_core::TenantContext; |
| 34 | +use nostr::EventId; |
| 35 | + |
| 36 | +use crate::error::AuthError; |
| 37 | + |
| 38 | +/// Floor for the replay-prevention window, in seconds. |
| 39 | +/// |
| 40 | +/// Matches the §5 gate ("TTL ≥ 120s") and the doubled NIP-98 timestamp |
| 41 | +/// tolerance (±60s window → 120s span). Implementations MAY use a larger TTL |
| 42 | +/// for safety margin; they MUST NOT use a smaller one. |
| 43 | +pub const DEFAULT_REPLAY_TTL_SECS: u64 = 120; |
| 44 | + |
| 45 | +/// Shared seen-set for NIP-98 event ids, scoped per community. |
| 46 | +/// |
| 47 | +/// The production implementation lives in `buzz-pubsub` (Redis `SET NX EX`). |
| 48 | +/// A test impl is provided behind `cfg(any(test, feature = "test-utils"))`. |
| 49 | +pub trait Nip98ReplayGuard: Send + Sync { |
| 50 | + /// Atomically claim `event_id` for `ctx`'s community. |
| 51 | + /// |
| 52 | + /// Returns `Ok(true)` when the id is newly inserted (proceed) and |
| 53 | + /// `Ok(false)` when an entry already exists (the caller MUST reject the |
| 54 | + /// request as replay). |
| 55 | + /// |
| 56 | + /// On `Err` (Redis unreachable, etc.) callers MUST fail closed — reject |
| 57 | + /// the request rather than admitting it. The shared seen-set is a |
| 58 | + /// correctness fence; degrading to "best effort, allow on error" forfeits |
| 59 | + /// the freshness proof. |
| 60 | + /// |
| 61 | + /// Implementations MUST use an atomic set-if-absent operation; a |
| 62 | + /// read-then-write sequence loses to concurrent inserts and forfeits the |
| 63 | + /// freshness proof. |
| 64 | + /// |
| 65 | + /// `ttl_secs` MUST be at least [`DEFAULT_REPLAY_TTL_SECS`]. Implementations |
| 66 | + /// MAY clamp a smaller value up to the floor rather than reject; they MUST |
| 67 | + /// NOT honor it as-given. |
| 68 | + fn try_mark( |
| 69 | + &self, |
| 70 | + ctx: &TenantContext, |
| 71 | + event_id: &EventId, |
| 72 | + ttl_secs: u64, |
| 73 | + ) -> impl std::future::Future<Output = Result<bool, AuthError>> + Send; |
| 74 | +} |
| 75 | + |
| 76 | +/// Redis key for a NIP-98 replay marker: |
| 77 | +/// `buzz:{community}:nip98:{event_id_hex}`. |
| 78 | +/// |
| 79 | +/// The community prefix is the S1 isolation fence at the replay layer. |
| 80 | +/// Event ids are content-addressed (SHA-256 of the canonical event tuple) so |
| 81 | +/// natural cross-community collision is zero, but the gate is fail-closed |
| 82 | +/// isolation: a same-id replay across communities must consult two distinct |
| 83 | +/// seen-set rows, not one shared row. |
| 84 | +pub fn nip98_replay_key(ctx: &TenantContext, event_id: &EventId) -> String { |
| 85 | + format!("buzz:{}:nip98:{}", ctx.community(), event_id.to_hex()) |
| 86 | +} |
| 87 | + |
| 88 | +/// Always-fresh seen-set for unit tests — every `try_mark` returns `Ok(true)`. |
| 89 | +/// |
| 90 | +/// Use only in test code that does not exercise the replay path itself. |
| 91 | +#[cfg(any(test, feature = "test-utils"))] |
| 92 | +pub struct AlwaysFreshReplayGuard; |
| 93 | + |
| 94 | +#[cfg(any(test, feature = "test-utils"))] |
| 95 | +impl Nip98ReplayGuard for AlwaysFreshReplayGuard { |
| 96 | + async fn try_mark( |
| 97 | + &self, |
| 98 | + _ctx: &TenantContext, |
| 99 | + _event_id: &EventId, |
| 100 | + _ttl_secs: u64, |
| 101 | + ) -> Result<bool, AuthError> { |
| 102 | + Ok(true) |
| 103 | + } |
| 104 | +} |
| 105 | + |
| 106 | +#[cfg(test)] |
| 107 | +mod tests { |
| 108 | + use super::*; |
| 109 | + use buzz_core::CommunityId; |
| 110 | + use nostr::{EventBuilder, Keys, Kind}; |
| 111 | + use sha2::{Digest, Sha256}; |
| 112 | + use uuid::Uuid; |
| 113 | + |
| 114 | + fn fixture_ctx(host: &str) -> TenantContext { |
| 115 | + let bytes = Sha256::digest(host.as_bytes()); |
| 116 | + let mut uuid_bytes = [0u8; 16]; |
| 117 | + uuid_bytes.copy_from_slice(&bytes[..16]); |
| 118 | + let id = CommunityId::from_uuid(Uuid::from_bytes(uuid_bytes)); |
| 119 | + TenantContext::resolved(id, host) |
| 120 | + } |
| 121 | + |
| 122 | + fn fixture_event_id() -> EventId { |
| 123 | + let keys = Keys::generate(); |
| 124 | + EventBuilder::new(Kind::HttpAuth, "") |
| 125 | + .sign_with_keys(&keys) |
| 126 | + .expect("sign") |
| 127 | + .id |
| 128 | + } |
| 129 | + |
| 130 | + #[test] |
| 131 | + fn key_includes_community_prefix() { |
| 132 | + let ctx = fixture_ctx("relay-a.example"); |
| 133 | + let eid = fixture_event_id(); |
| 134 | + let key = nip98_replay_key(&ctx, &eid); |
| 135 | + let expected_prefix = format!("buzz:{}:nip98:", ctx.community()); |
| 136 | + assert!( |
| 137 | + key.starts_with(&expected_prefix), |
| 138 | + "key {key} should start with {expected_prefix}" |
| 139 | + ); |
| 140 | + assert!(key.ends_with(&eid.to_hex())); |
| 141 | + } |
| 142 | + |
| 143 | + #[test] |
| 144 | + fn key_isolates_communities_for_same_event_id() { |
| 145 | + // Belt-and-suspenders: even if a same-id event surfaces in two |
| 146 | + // communities (which content-addressing makes implausible), the |
| 147 | + // seen-set MUST consult two distinct rows. |
| 148 | + let eid = fixture_event_id(); |
| 149 | + let ctx_a = fixture_ctx("relay-a.example"); |
| 150 | + let ctx_b = fixture_ctx("relay-b.example"); |
| 151 | + let key_a = nip98_replay_key(&ctx_a, &eid); |
| 152 | + let key_b = nip98_replay_key(&ctx_b, &eid); |
| 153 | + assert_ne!( |
| 154 | + key_a, key_b, |
| 155 | + "same event id in two communities must not share a seen-set key" |
| 156 | + ); |
| 157 | + } |
| 158 | + |
| 159 | + #[test] |
| 160 | + fn default_ttl_meets_gate_floor() { |
| 161 | + // §5 gate: TTL ≥ 120s. Drift this constant down and the gate breaks. |
| 162 | + assert!(DEFAULT_REPLAY_TTL_SECS >= 120); |
| 163 | + } |
| 164 | + |
| 165 | + #[tokio::test] |
| 166 | + async fn always_fresh_returns_true() { |
| 167 | + let guard = AlwaysFreshReplayGuard; |
| 168 | + let ctx = fixture_ctx("relay-a.example"); |
| 169 | + let eid = fixture_event_id(); |
| 170 | + assert!(guard |
| 171 | + .try_mark(&ctx, &eid, DEFAULT_REPLAY_TTL_SECS) |
| 172 | + .await |
| 173 | + .unwrap()); |
| 174 | + } |
| 175 | +} |
0 commit comments