diff --git a/.changeset/message-limiter-frame-class.md b/.changeset/message-limiter-frame-class.md new file mode 100644 index 000000000..853d7c8fe --- /dev/null +++ b/.changeset/message-limiter-frame-class.md @@ -0,0 +1,6 @@ +--- +--- + +fix(relay): key the message limiter by the frame's type + +The message level bucketed `{address}:message:60000`, so an EVENT burst spent the REQ budget and refused mixed traffic the capture allows. The key now carries the frame's class, read before decoding from the first 32 bytes against the capture's closed set, with one shared `OTHER` bucket. No published package changes. diff --git a/crates/nostream-relay/src/limits.rs b/crates/nostream-relay/src/limits.rs index 9b20f0715..2b9f12ccc 100644 --- a/crates/nostream-relay/src/limits.rs +++ b/crates/nostream-relay/src/limits.rs @@ -61,6 +61,87 @@ impl From<&EventRateLimit> for RateLimitConfig { } } +/// The frame class the message limiter buckets by (`web-socket-adapter.ts:48-68`): the +/// capture's closed set plus the one bucket everything unrecognised shares. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MessageClass { + Req, + Event, + Count, + Close, + Auth, + NegOpen, + NegMsg, + NegClose, + Other, +} + +impl MessageClass { + /// The class a raw frame belongs to, read from its first 32 bytes before decoding + /// (`web-socket-adapter.ts:59-68`): leading whitespace, `[`, optional whitespace, then a + /// quoted 1–8 character `[A-Za-z-]` word, upper-cased. Anything else is + /// [`MessageClass::Other`] — including `NEG-CLOSE`, whose nine characters exceed the + /// capture's eight-character bound. + pub fn from_frame(frame: &str) -> Self { + let mut end = frame.len().min(32); + + while !frame.is_char_boundary(end) { + end -= 1; + } + + let mut chars = frame[..end].chars().skip_while(|c| c.is_whitespace()); + + if chars.next() != Some('[') { + return Self::Other; + } + + let mut chars = chars.skip_while(|c| c.is_whitespace()); + + if chars.next() != Some('"') { + return Self::Other; + } + + let mut word = String::new(); + + loop { + match chars.next() { + Some('"') if !word.is_empty() => break, + Some(c) if word.len() < 8 && (c.is_ascii_alphabetic() || c == '-') => { + word.push(c.to_ascii_uppercase()); + } + _ => return Self::Other, + } + } + + match word.as_str() { + "REQ" => Self::Req, + "EVENT" => Self::Event, + "COUNT" => Self::Count, + "CLOSE" => Self::Close, + "AUTH" => Self::Auth, + "NEG-OPEN" => Self::NegOpen, + "NEG-MSG" => Self::NegMsg, + "NEG-CLOSE" => Self::NegClose, + _ => Self::Other, + } + } + + /// The token this class contributes to the limiter key. + pub fn as_str(&self) -> &'static str { + match self { + Self::Req => "REQ", + Self::Event => "EVENT", + Self::Count => "COUNT", + Self::Close => "CLOSE", + Self::Auth => "AUTH", + Self::NegOpen => "NEG-OPEN", + Self::NegMsg => "NEG-MSG", + Self::NegClose => "NEG-CLOSE", + Self::Other => "OTHER", + } + } +} + /// One sliding-window hit: the instant it was recorded and the weight it carries. #[derive(Debug, Clone, Copy, PartialEq, Eq)] struct SlidingEntry { @@ -514,10 +595,15 @@ impl RateLimits { Ok(limited) } - /// `limits.message.rateLimits` with its `ipWhitelist` bypass - /// (`web-socket-adapter.ts:264-282`). `Ok(Some(backoff))` is the message not being - /// handled; `Ok(None)` is allowed. - pub fn message_backoff(&self, address: &str) -> Result, RelayError> { + /// `limits.message.rateLimits` with its `ipWhitelist` bypass (`web-socket-adapter.ts:278-310`). + /// Each window keys `{address}:message:{class}:{period_ms}`, the class read from the raw + /// frame before decoding (`web-socket-adapter.ts:59-68`; key at `:354`). + /// `Ok(Some(backoff))` is the message not being handled; `Ok(None)` is allowed. + pub fn message_backoff( + &self, + address: &str, + class: MessageClass, + ) -> Result, RelayError> { let Some(message) = &self.message else { return Ok(None); }; @@ -540,7 +626,7 @@ impl RateLimits { for window in rate_limits { let config = RateLimitConfig::from(window); - let key = format!("{address}:message:{}", config.period_ms); + let key = format!("{address}:message:{}:{}", class.as_str(), config.period_ms); if self.message_limiter.hit(&key, 1, &config)? { return Ok(Some(backoff_ms(&config))); diff --git a/crates/nostream-relay/src/relay.rs b/crates/nostream-relay/src/relay.rs index dc2726ab5..7b2fca9a7 100644 --- a/crates/nostream-relay/src/relay.rs +++ b/crates/nostream-relay/src/relay.rs @@ -32,7 +32,7 @@ use crate::connection_cap::ConnectionCap; use crate::dispatch::{HttpFallback, Protocol, classify_socket}; use crate::handlers::{self, HandlerContext, Stores}; use crate::hidden_content::{DEFAULT_REFRESH_INTERVAL, HiddenContentCache}; -use crate::limits::RateLimits; +use crate::limits::{MessageClass, RateLimits}; use crate::metrics::RelayMetrics; use crate::relay_key::RelayKeySource; use crate::sink::{FrameBudget, FrameSink, Refusal}; @@ -672,10 +672,10 @@ impl Relay { context: &Arc, handlers: &mut JoinSet<()>, ) { - match self - .limits - .message_backoff(&context.connection.remote_address) - { + match self.limits.message_backoff( + &context.connection.remote_address, + MessageClass::from_frame(text), + ) { Ok(Some(backoff)) => { let frame = rate_limited_frame(text, backoff, &context.connection); diff --git a/crates/nostream-relay/tests/handlers.rs b/crates/nostream-relay/tests/handlers.rs index 6483ae321..dbee299e0 100644 --- a/crates/nostream-relay/tests/handlers.rs +++ b/crates/nostream-relay/tests/handlers.rs @@ -2252,6 +2252,44 @@ async fn a_whitelisted_ip_bypasses_the_message_limiter() { assert_eq!(client.expect_frame().await, r#"["EOSE","s1"]"#); } +#[tokio::test] +async fn an_event_burst_leaves_the_req_window_intact() { + let limits = Limits { + message: Some(MessageLimits { + rate_limits: Some(vec![MessageRateLimit { + description: None, + message_type: None, + period: 60_000, + rate: 1, + }]), + ip_whitelist: None, + }), + ..Default::default() + }; + let server = start(Fixture::new(settings_with(limits))).await; + let (mut client, _challenge) = server.connect().await; + + let event = signed_event(&CLIENT_SECRET, 1, vec![], "", NOW_SECS); + client.send(&event_frame(&event)).await; + assert_eq!( + client.expect_frame().await, + format!(r#"["OK","{}",true,""]"#, event.id) + ); + + client.send(r#"["REQ","s1",{"kinds":[2]}]"#).await; + assert_eq!( + client.expect_frame().await, + r#"["EOSE","s1"]"#, + "the EVENT spent the REQ window" + ); + + client.send(r#"["REQ","s2",{"kinds":[2]}]"#).await; + assert_eq!( + client.expect_frame().await, + r#"["CLOSED","s2","rate-limited: slow down","60000"]"# + ); +} + #[tokio::test] async fn the_connection_limiter_terminates_the_upgrade() { let limits = Limits { diff --git a/crates/nostream-relay/tests/limits.rs b/crates/nostream-relay/tests/limits.rs index 646220fd1..ac6ab1bd1 100644 --- a/crates/nostream-relay/tests/limits.rs +++ b/crates/nostream-relay/tests/limits.rs @@ -12,7 +12,7 @@ mod common; -use std::sync::Arc; +use std::sync::{Arc, Mutex}; use common::{CLIENT_SECRET, NOW_MS, NOW_SECS, relay_keys, signed_event}; use nostream_config::settings::{ @@ -21,8 +21,9 @@ use nostream_config::settings::{ }; use nostream_core::clock::{Clock, TestClock}; use nostream_core::{Event, Kind, KindSelector, Pubkey}; +use nostream_relay::error::RelayError; use nostream_relay::limits::{ - EwmaRateLimiter, Limiter, MAX_STORE_KEYS, RateLimitConfig, RateLimits, + EwmaRateLimiter, Limiter, MAX_STORE_KEYS, MessageClass, RateLimitConfig, RateLimits, SlidingWindowRateLimiter, backoff_ms, kind_selector_matches, }; use nostream_relay::testing::{FailingLimiter, Fixture, settings}; @@ -187,7 +188,10 @@ fn one_level_s_flood_cannot_refuse_another_level_s_clients() { // Fill the message store past its ceiling with distinct addresses. for index in 0..(2 * MAX_STORE_KEYS) { limits - .message_backoff(&format!("10.1.{}.{}", index / 256, index % 256)) + .message_backoff( + &format!("10.1.{}.{}", index / 256, index % 256), + MessageClass::Other, + ) .expect("a verdict"); } @@ -688,6 +692,184 @@ fn the_connection_level_uses_addr_connection_period_and_its_whitelist() { assert!(!limits.connection_limited("10.0.0.1").expect("store")); } +#[test] +fn the_message_class_is_read_from_the_frame_prefix() { + let cases = [ + (r#"["REQ","s1",{}]"#, MessageClass::Req), + (r#"["EVENT",{}]"#, MessageClass::Event), + (r#"["COUNT","c1",{}]"#, MessageClass::Count), + (r#"["CLOSE","s1"]"#, MessageClass::Close), + (r#"["AUTH",{}]"#, MessageClass::Auth), + (r#"["NEG-OPEN","s1",{}]"#, MessageClass::NegOpen), + (r#"["NEG-MSG","s1","00"]"#, MessageClass::NegMsg), + (r#"["req"]"#, MessageClass::Req), + (r#"["Req"]"#, MessageClass::Req), + (r#"[ "REQ","s1"]"#, MessageClass::Req), + (" [\"REQ\"]", MessageClass::Req), + ("\t[\"REQ\"]", MessageClass::Req), + ("\n[\"REQ\"]", MessageClass::Req), + (r#"["AAAA"]"#, MessageClass::Other), + (r#"["BBBB"]"#, MessageClass::Other), + ("not json", MessageClass::Other), + (r#"["REQ"#, MessageClass::Other), + ]; + + for (frame, class) in cases { + assert_eq!(MessageClass::from_frame(frame), class, "frame {frame:?}"); + } + + // The 32-byte prefix reaches the closing quote after 26 spaces and stops one byte + // short of it after 27. + assert_eq!( + MessageClass::from_frame(&format!("{}[\"REQ\"]", " ".repeat(26))), + MessageClass::Req + ); + assert_eq!( + MessageClass::from_frame(&format!("{}[\"REQ\"]", " ".repeat(27))), + MessageClass::Other + ); + + let tokens = [ + (MessageClass::Req, "REQ"), + (MessageClass::Event, "EVENT"), + (MessageClass::Count, "COUNT"), + (MessageClass::Close, "CLOSE"), + (MessageClass::Auth, "AUTH"), + (MessageClass::NegOpen, "NEG-OPEN"), + (MessageClass::NegMsg, "NEG-MSG"), + (MessageClass::NegClose, "NEG-CLOSE"), + (MessageClass::Other, "OTHER"), + ]; + + for (class, token) in tokens { + assert_eq!(class.as_str(), token); + } +} + +#[test] +fn the_nine_character_neg_close_falls_to_other() { + assert_eq!( + MessageClass::from_frame(r#"["NEG-CLOSE","s1"]"#), + MessageClass::Other, + "the eight-character bound excludes the nine-character word" + ); + assert_eq!(MessageClass::NegClose.as_str(), "NEG-CLOSE"); +} + +#[test] +fn a_mid_codepoint_cut_at_32_bytes_does_not_panic() { + // Byte 32 splits the two-byte `é`, so the prefix must round down to byte 31. + let frame = format!("{}é[\"REQ\"]", " ".repeat(31)); + + assert_eq!(MessageClass::from_frame(&frame), MessageClass::Other); +} + +/// Records every key the message level hands the store. +#[derive(Debug, Default)] +struct RecordingLimiter { + keys: Mutex>, +} + +impl Limiter for RecordingLimiter { + fn hit(&self, key: &str, _step: u64, _config: &RateLimitConfig) -> Result { + self.keys.lock().expect("recorder").push(key.to_owned()); + + Ok(false) + } + + fn strategy(&self) -> RateLimiterStrategy { + RateLimiterStrategy::Ewma + } +} + +#[test] +fn the_message_key_carries_the_class_and_the_period() { + let recorder = Arc::new(RecordingLimiter::default()); + let settings = settings_with(Limits { + message: Some(MessageLimits { + rate_limits: Some(vec![MessageRateLimit { + description: None, + message_type: None, + period: 60_000, + rate: 240, + }]), + ip_whitelist: None, + }), + ..Default::default() + }); + let limiter: Arc = recorder.clone(); + let limits = RateLimits::with_limiter(limiter, &settings); + + limits + .message_backoff("192.0.2.1", MessageClass::from_frame(r#"["REQ","s1",{}]"#)) + .expect("store"); + limits + .message_backoff("192.0.2.1", MessageClass::from_frame(r#"["AAAA"]"#)) + .expect("store"); + + assert_eq!( + *recorder.keys.lock().expect("recorder"), + vec![ + "192.0.2.1:message:REQ:60000".to_owned(), + "192.0.2.1:message:OTHER:60000".to_owned(), + ] + ); + assert_eq!(MessageClass::from_frame(r#"["BBBB"]"#), MessageClass::Other); +} + +#[test] +fn one_class_s_window_leaves_another_intact() { + let clock = Arc::new(TestClock::new(BASE)); + let settings = settings_with(Limits { + message: Some(MessageLimits { + rate_limits: Some(vec![MessageRateLimit { + description: None, + message_type: None, + period: 60_000, + rate: 1, + }]), + ip_whitelist: None, + }), + ..Default::default() + }); + let limits = limits_from(&settings, clock); + let address = "192.0.2.1"; + + assert_eq!( + limits + .message_backoff(address, MessageClass::Event) + .expect("store"), + None + ); + assert_eq!( + limits + .message_backoff(address, MessageClass::Req) + .expect("store"), + None, + "the EVENT did not spend the REQ window" + ); + assert_eq!( + limits + .message_backoff(address, MessageClass::Req) + .expect("store"), + Some(60_000), + "REQ still enforces its own rate" + ); + assert_eq!( + limits + .message_backoff(address, MessageClass::from_frame(r#"["AAAA"]"#)) + .expect("store"), + None + ); + assert_eq!( + limits + .message_backoff(address, MessageClass::from_frame(r#"["BBBB"]"#)) + .expect("store"), + Some(60_000), + "both invented frames share OTHER" + ); +} + #[test] fn the_message_level_reports_the_period_as_the_backoff() { let clock = Arc::new(TestClock::new(BASE)); @@ -705,9 +887,16 @@ fn the_message_level_reports_the_period_as_the_backoff() { }); let limits = limits_from(&settings, clock); - assert_eq!(limits.message_backoff("192.0.2.1").expect("store"), None); assert_eq!( - limits.message_backoff("192.0.2.1").expect("store"), + limits + .message_backoff("192.0.2.1", MessageClass::Req) + .expect("store"), + None + ); + assert_eq!( + limits + .message_backoff("192.0.2.1", MessageClass::Req) + .expect("store"), Some(2_500) ); assert_eq!( @@ -740,7 +929,7 @@ fn the_message_level_with_no_windows_never_limits() { assert_eq!( limits_from(&settings, clock) - .message_backoff("192.0.2.1") + .message_backoff("192.0.2.1", MessageClass::Other) .expect("store"), None ); @@ -947,7 +1136,11 @@ fn a_failing_store_reports_an_error_at_every_level() { let pubkey = nostream_core::crypto::public_key(&CLIENT_SECRET).expect("pubkey"); assert!(limits.connection_limited("192.0.2.1").is_err()); - assert!(limits.message_backoff("192.0.2.1").is_err()); + assert!( + limits + .message_backoff("192.0.2.1", MessageClass::Other) + .is_err() + ); assert!( limits .event_backoff(&event_at(1, pubkey), "192.0.2.1", None) diff --git a/docs/rewrite/decisions/0004-wire-transport.md b/docs/rewrite/decisions/0004-wire-transport.md index 23090dd72..42c018824 100644 --- a/docs/rewrite/decisions/0004-wire-transport.md +++ b/docs/rewrite/decisions/0004-wire-transport.md @@ -171,7 +171,7 @@ Two limits worth recording rather than discovering in production: | --- | --- | --- | --- | | connection | 2 — `{address}:connection:{period}`, windows 1 s and 60 s | 32,768 addresses | ≤ 61 s | | event | **1 to 7** — one 60 s key per kind window the event matches, plus the global hour key | **9,400–65,536 authors** (see below) | **depends on the kind** (see below) | - | message | 1 — `{address}:message:60000` | 65,536 addresses | ≤ 61 s | + | message | **1 to 8** — one `{address}:message:{type}:{period}` per class (seven reachable types plus `OTHER`) | **8,192–65,536 addresses** | ≤ 61 s | | invite | 1 — `{pubkey}:invites:3600000` | 65,536 pubkeys | **≤ 1 h + 1 s** | Each cell is window **+ up to one sweep interval**, not the window alone: a lapsed key is @@ -205,6 +205,23 @@ Two limits worth recording rather than discovering in production: logs that at `debug`, so a deployment that wants to see it must run with `debug` enabled; one that wants the limiter must set a key. +## The message limiter keys by the frame's type + +The message level keys one bucket per address **per frame class** per period, at +`{address}:message:{type}:{period}` — for example `192.0.2.1:message:REQ:60000` for a REQ +under the shipped 60 s window. The class is read from the raw frame before decoding, the way +the capture does it (`src/adapters/web-socket-adapter.ts:278-284`): the first 32 bytes, +rounded down to a UTF-8 boundary, matched against `/^\s*\[\s*"([A-Za-z-]{1,8})"/` and +upper-cased, then checked against the closed set +`REQ, EVENT, COUNT, CLOSE, AUTH, NEG-OPEN, NEG-MSG, NEG-CLOSE`, with `OTHER` for everything +unrecognised — one shared bucket, so a client cannot rotate invented types (`["AAAA"]`, +`["BBBB"]`, …) to keep every bucket empty. `NEG-CLOSE` is named in the set but its nine +characters exceed the eight-character bound, so a frame carrying it lands in `OTHER`; the +variant exists to name the capture's set, not to be reachable through this parser. The +earlier one-key-per-address shape (`{address}:message:60000`) was a port gap, not a decision +against the capture: under it an EVENT burst spent the REQ budget and vice versa, refusing +mixed traffic the capture allowed. + ## The accept loop lives in the relay, and serving cannot fail Spec R1 says the acceptor hands the accepted socket to the relay; this job hands the