Skip to content

Commit a2a9ef4

Browse files
npub17jjz49l9jjmhhk7cac63j8yt9z555n9cw8vk7v5jz4vzw4ppld5qgj57ccTyler Longwell
andcommitted
feat(auth): NIP-98 replay seen-set — shared, community-scoped, atomic
Adds the §5 pre-build gate for multi-tenant replay protection. buzz-auth gains a Nip98ReplayGuard trait plus the nip98_replay_key(ctx, event_id) helper. The trait's try_mark contract requires atomic set-if-absent semantics; an in-process cache (moka, DashMap) does not carry the freshness proof across pods under the "any pod, any connection" architecture (§4B), so the production implementation MUST be shared state. The Redis-backed impl lives in buzz-pubsub as RedisNip98ReplayGuard and uses a single SET key 1 NX EX <ttl> per claim. Key shape: buzz:{community}:nip98:{event_id_hex}. Event ids are content-addressed so natural cross-community collision is zero, but the gate is fail-closed isolation — a same-id replay across communities must consult two distinct seen-set rows, not one shared row. Tests pin both the prefix and the cross-community isolation guarantee. TTL floor is DEFAULT_REPLAY_TTL_SECS = 120, matching the §5 gate requirement and the doubled NIP-98 ±60s timestamp tolerance. Implementations MAY clamp sub-floor TTLs up to the floor; they MUST NOT honor smaller values. The Redis impl clamps. Caller contract documented in the trait: verify first, then mark. Burning a seen-set slot on a forgery would let an attacker who learns a future event id DoS the legitimate event. On Err (Redis unreachable) callers MUST fail closed. Not wired into a call site in this commit — there is no NIP-98 HTTP handler in Lane 0 yet. Eva's relay-wiring lane will consume the trait when the HTTP path lands; the contract is documented for that integration. Validation: - cargo test -p buzz-auth --lib ✅ 40 passed (4 new in nip98_replay). - cargo test -p buzz-pubsub --lib ✅ 3 passed, 9 Redis-required ignored (3 new in nip98_replay). - cargo test -p buzz-pubsub --lib nip98_replay -- --ignored against local Redis ✅ 3 passed: first-claim/replay, cross-community isolation, sub-floor TTL lifted to floor. - Workspace check not run locally (sqlx 0.9.0 / rustc 1.94 vs local 1.89); CI catches it. Co-authored-by: Tyler Longwell <[email protected]> Signed-off-by: Tyler Longwell <[email protected]>
1 parent 6a92f0b commit a2a9ef4

5 files changed

Lines changed: 339 additions & 0 deletions

File tree

‎crates/buzz-auth/src/error.rs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,12 @@ pub enum AuthError {
3030
#[error("NIP-98 HTTP Auth verification failed: {0}")]
3131
Nip98Invalid(String),
3232

33+
/// A NIP-98 event with the same id has already been observed within the
34+
/// replay-prevention window. The event itself was structurally valid; the
35+
/// rejection is on freshness, not validity.
36+
#[error("NIP-98 replay: event id already seen within window")]
37+
Nip98Replay,
38+
3339
/// The pubkey in the auth event does not match the expected identity.
3440
#[error("pubkey mismatch: event pubkey does not match authenticated identity")]
3541
PubkeyMismatch,

‎crates/buzz-auth/src/lib.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ pub mod error;
2323
pub mod nip42;
2424
/// NIP-98 HTTP Auth verification (kind:27235).
2525
pub mod nip98;
26+
/// NIP-98 replay protection — shared, community-scoped, atomic seen-set.
27+
pub mod nip98_replay;
2628
/// Per-connection rate limiting.
2729
pub mod rate_limit;
2830
/// OAuth scope parsing and enforcement.
@@ -32,6 +34,7 @@ pub use access::{check_read_access, check_write_access, require_scope, ChannelAc
3234
pub use error::AuthError;
3335
pub use nip42::{generate_challenge, verify_nip42_event};
3436
pub use nip98::verify_nip98_event;
37+
pub use nip98_replay::{nip98_replay_key, Nip98ReplayGuard, DEFAULT_REPLAY_TTL_SECS};
3538
pub use rate_limit::{
3639
ip_rate_limit_key, rate_limit_key, LimitType, RateLimitConfig, RateLimitResult, RateLimiter,
3740
};
@@ -40,6 +43,8 @@ pub use scope::{parse_scopes, Scope};
4043
#[cfg(any(test, feature = "test-utils"))]
4144
pub use access::MockAccessChecker;
4245
#[cfg(any(test, feature = "test-utils"))]
46+
pub use nip98_replay::AlwaysFreshReplayGuard;
47+
#[cfg(any(test, feature = "test-utils"))]
4348
pub use rate_limit::AlwaysAllowRateLimiter;
4449

4550
/// How the connection was authenticated.
Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
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+
}

‎crates/buzz-pubsub/src/lib.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@
2525
pub mod cache_invalidation;
2626
/// Error types for pub/sub operations.
2727
pub mod error;
28+
/// Redis-backed NIP-98 replay seen-set.
29+
pub mod nip98_replay;
2830
/// Online/offline presence tracking in Redis.
2931
pub mod presence;
3032
/// Redis PUBLISH for channel event fan-out.
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
//! Redis-backed NIP-98 replay seen-set.
2+
//!
3+
//! Implements the [`Nip98ReplayGuard`] trait from `buzz-auth`. Uses Redis
4+
//! `SET NX EX` for an atomic set-if-absent with TTL — the §5 pre-build gate
5+
//! for multi-tenant HA replay protection.
6+
7+
use buzz_auth::{
8+
error::AuthError,
9+
nip98_replay::{nip98_replay_key, Nip98ReplayGuard, DEFAULT_REPLAY_TTL_SECS},
10+
};
11+
use buzz_core::TenantContext;
12+
use nostr::EventId;
13+
14+
/// Redis-backed NIP-98 replay seen-set.
15+
///
16+
/// Each `try_mark(ctx, event_id, ttl)` issues a single
17+
/// `SET buzz:{community}:nip98:{event_id_hex} 1 NX EX <ttl>` against Redis.
18+
/// `NX` makes the operation atomic set-if-absent — the freshness proof comes
19+
/// from Redis returning `OK` only on the first claim. Subsequent claims within
20+
/// the TTL window return `nil`, which we surface as `Ok(false)` so the caller
21+
/// rejects the request as replay.
22+
pub struct RedisNip98ReplayGuard {
23+
pool: deadpool_redis::Pool,
24+
}
25+
26+
impl RedisNip98ReplayGuard {
27+
/// Create a new replay guard backed by the given Redis connection pool.
28+
pub fn new(pool: deadpool_redis::Pool) -> Self {
29+
Self { pool }
30+
}
31+
}
32+
33+
impl Nip98ReplayGuard for RedisNip98ReplayGuard {
34+
async fn try_mark(
35+
&self,
36+
ctx: &TenantContext,
37+
event_id: &EventId,
38+
ttl_secs: u64,
39+
) -> Result<bool, AuthError> {
40+
// §5 gate floor — never accept a sub-floor TTL silently.
41+
let ttl = ttl_secs.max(DEFAULT_REPLAY_TTL_SECS);
42+
43+
let mut conn = self
44+
.pool
45+
.get()
46+
.await
47+
.map_err(|e| AuthError::Internal(format!("Redis pool: {e}")))?;
48+
49+
let key = nip98_replay_key(ctx, event_id);
50+
51+
// SET key 1 NX EX <ttl>. redis-rs typed return: Some("OK") on first
52+
// claim, None on existing key. Any other value would be a Redis-side
53+
// bug; treat it as internal error.
54+
let result: Option<String> = redis::cmd("SET")
55+
.arg(&key)
56+
.arg("1")
57+
.arg("NX")
58+
.arg("EX")
59+
.arg(ttl)
60+
.query_async(&mut *conn)
61+
.await
62+
.map_err(|e| AuthError::Internal(format!("Redis SET NX EX: {e}")))?;
63+
64+
match result.as_deref() {
65+
Some("OK") => Ok(true),
66+
None => Ok(false),
67+
Some(other) => Err(AuthError::Internal(format!(
68+
"unexpected SET NX EX reply: {other}"
69+
))),
70+
}
71+
}
72+
}
73+
74+
#[cfg(test)]
75+
mod tests {
76+
use super::*;
77+
use buzz_core::{CommunityId, TenantContext};
78+
use deadpool_redis::{Config, Runtime};
79+
use nostr::{EventBuilder, Keys, Kind};
80+
use uuid::Uuid;
81+
82+
fn redis_pool() -> deadpool_redis::Pool {
83+
let url = std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379".into());
84+
Config::from_url(url)
85+
.create_pool(Some(Runtime::Tokio1))
86+
.expect("create pool")
87+
}
88+
89+
fn fresh_ctx() -> TenantContext {
90+
TenantContext::resolved(CommunityId::from_uuid(Uuid::new_v4()), "test.example")
91+
}
92+
93+
fn fresh_event_id() -> EventId {
94+
EventBuilder::new(Kind::HttpAuth, "")
95+
.sign_with_keys(&Keys::generate())
96+
.expect("sign")
97+
.id
98+
}
99+
100+
#[tokio::test]
101+
#[ignore = "requires Redis"]
102+
async fn first_claim_succeeds_replay_fails() {
103+
let guard = RedisNip98ReplayGuard::new(redis_pool());
104+
let ctx = fresh_ctx();
105+
let eid = fresh_event_id();
106+
107+
assert!(guard
108+
.try_mark(&ctx, &eid, DEFAULT_REPLAY_TTL_SECS)
109+
.await
110+
.expect("first mark"));
111+
assert!(!guard
112+
.try_mark(&ctx, &eid, DEFAULT_REPLAY_TTL_SECS)
113+
.await
114+
.expect("replay mark"));
115+
}
116+
117+
#[tokio::test]
118+
#[ignore = "requires Redis"]
119+
async fn isolation_between_communities() {
120+
let guard = RedisNip98ReplayGuard::new(redis_pool());
121+
let ctx_a = fresh_ctx();
122+
let ctx_b = fresh_ctx();
123+
let eid = fresh_event_id();
124+
125+
assert!(guard
126+
.try_mark(&ctx_a, &eid, DEFAULT_REPLAY_TTL_SECS)
127+
.await
128+
.expect("mark in A"));
129+
// Same event id under ctx_b is still a first claim — communities are
130+
// independent seen-sets.
131+
assert!(guard
132+
.try_mark(&ctx_b, &eid, DEFAULT_REPLAY_TTL_SECS)
133+
.await
134+
.expect("mark in B"));
135+
}
136+
137+
#[tokio::test]
138+
#[ignore = "requires Redis"]
139+
async fn sub_floor_ttl_is_lifted_to_default() {
140+
let guard = RedisNip98ReplayGuard::new(redis_pool());
141+
let ctx = fresh_ctx();
142+
let eid = fresh_event_id();
143+
144+
// Caller asks for 30s; impl lifts to ≥ DEFAULT_REPLAY_TTL_SECS.
145+
// Smoke-test the path: pass sub-floor TTL, claim once, then expect
146+
// replay rejection — the TTL lift kept the marker alive past 30s and
147+
// the contract holds.
148+
assert!(guard.try_mark(&ctx, &eid, 30).await.expect("mark"));
149+
assert!(!guard.try_mark(&ctx, &eid, 30).await.expect("replay"));
150+
}
151+
}

0 commit comments

Comments
 (0)