Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/message-limiter-frame-class.md
Original file line number Diff line number Diff line change
@@ -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.
96 changes: 91 additions & 5 deletions crates/nostream-relay/src/limits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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<Option<u64>, 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<Option<u64>, RelayError> {
let Some(message) = &self.message else {
return Ok(None);
};
Expand All @@ -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)));
Expand Down
10 changes: 5 additions & 5 deletions crates/nostream-relay/src/relay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -672,10 +672,10 @@ impl Relay {
context: &Arc<HandlerContext>,
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);

Expand Down
38 changes: 38 additions & 0 deletions crates/nostream-relay/tests/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Loading
Loading