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/subscription-id-utf16-length.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
---

fix(relay): measure a subscription id in UTF-16 code units, as the capture does

The frame decoder counted a `REQ` or `COUNT` subscription id in characters against its bound of 256, and both handlers counted it in UTF-8 bytes against `maxSubscriptionIdLength`. The capture counts UTF-16 code units (JavaScript's `length`) in all three, and so does the port now, as ADR 0002 already does for filter lengths. An id of 100 CJK characters (300 bytes) is now accepted under the shipped limit of 256, and an id of 200 emoji (400 units) is now refused at decode, with the `NOTICE` `invalid: String must contain at most 256 character(s)`. A deliberate limit: the bounds and refusals stay the capture's, not NIP-01's 64-character maximum or the `CLOSED` refusal NIP-01 and NIP-45 ask for.
2 changes: 1 addition & 1 deletion crates/nostream-core/src/messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,7 @@ fn decode_request(items: &[Value], verb: &str) -> Result<(String, Vec<Filter>),
return Err(invalid("Invalid input"));
};

let length = subscription_id.chars().count();
let length = subscription_id.encode_utf16().count();

if length == 0 {
return Err(invalid("String must contain at least 1 character(s)"));
Expand Down
30 changes: 30 additions & 0 deletions crates/nostream-core/tests/wire_codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,36 @@ fn decode_reports_the_capture_notice_strings() {
}
}

#[test]
fn decode_bounds_the_subscription_id_in_utf16_code_units() {
// 128 astral characters: 256 UTF-16 code units, but 128 chars and 512 bytes.
let at_bound = "\u{1F600}".repeat(128);
let over_bound = format!("{at_bound}x");

for verb in ["REQ", "COUNT"] {
let decoded_id = |id: &str| {
decode(&format!(r#"["{verb}","{id}",{{"kinds":[1]}}]"#)).map(|message| {
match (verb, message) {
("REQ", ClientMessage::Subscribe(message)) => message.subscription_id,
("COUNT", ClientMessage::Count(message)) => message.subscription_id,
(_, other) => panic!("{verb} decoded as {other:?}"),
}
})
};

assert_eq!(
(decoded_id(&at_bound), decoded_id(&over_bound)),
(
Ok(at_bound.clone()),
Err(WireError::Validation(
"String must contain at most 256 character(s)".to_owned()
))
),
"{verb}"
);
}
}

#[test]
fn decode_reports_json_syntax_failure_as_a_tolerated_detail() {
let error = decode("{\"kind\":").unwrap_err();
Expand Down
2 changes: 1 addition & 1 deletion crates/nostream-relay/src/handlers/count.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ fn can_count(query_id: &str, filters: &[Filter], context: &HandlerContext) -> Op
}

if let Some(max_id_length) = limits.and_then(|limits| limits.max_subscription_id_length)
&& query_id.len() as u64 > max_id_length
&& query_id.encode_utf16().count() as u64 > max_id_length
{
return Some(format!(
"Query ID too long: Query ID must be less than or equal to {max_id_length}"
Expand Down
2 changes: 1 addition & 1 deletion crates/nostream-relay/src/handlers/subscribe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -622,7 +622,7 @@ fn can_subscribe(
}

if let Some(max_id_length) = limits.and_then(|limits| limits.max_subscription_id_length)
&& subscription_id.len() as u64 > max_id_length
&& subscription_id.encode_utf16().count() as u64 > max_id_length
{
return Some(format!(
"Subscription ID too long: Subscription ID must be less or equal to {max_id_length}"
Expand Down
94 changes: 94 additions & 0 deletions crates/nostream-relay/tests/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,18 @@ fn event_limits(event: EventLimits) -> Limits {
}
}

fn subscription_id_limit(max: u64) -> Limits {
Limits {
client: Some(ClientLimits {
subscription: Some(ClientSubscriptionLimits {
max_subscription_id_length: Some(max),
..Default::default()
}),
}),
..Default::default()
}
}

/// Starts a relay with the test key source.
async fn start(fixture: Fixture) -> Server {
Server::start_with(fixture, relay_keys(), common::fast_config()).await
Expand Down Expand Up @@ -1054,6 +1066,31 @@ async fn the_filter_limits_carry_the_captures_strings_and_typos() {
);
}

#[tokio::test]
async fn the_subscription_id_limit_counts_utf16_code_units() {
let server = start(Fixture::new(settings_with(subscription_id_limit(4)))).await;
let (mut client, _challenge) = server.connect().await;
// Two astral characters: 4 UTF-16 code units, but 2 chars and 8 bytes.
let at_limit = "\u{1F600}\u{1F600}";
let over_limit = format!("{at_limit}x");

let mut frames = Vec::new();
for id in [at_limit, over_limit.as_str()] {
client
.send(&format!(r#"["REQ","{id}",{{"kinds":[1]}}]"#))
.await;
frames.push(client.expect_frame().await);
}

assert_eq!(
frames,
[
format!(r#"["EOSE","{at_limit}"]"#),
r#"["NOTICE","Subscription rejected: Subscription ID too long: Subscription ID must be less or equal to 4"]"#.to_owned(),
]
);
}

#[tokio::test]
async fn a_restricted_only_req_from_an_unauthenticated_client_is_closed() {
let mut settings = settings();
Expand Down Expand Up @@ -1899,6 +1936,63 @@ async fn count_limits_are_the_capture_strings() {
);
}

#[tokio::test]
async fn the_query_id_limit_counts_utf16_code_units() {
let server = start(Fixture::new(settings_with(subscription_id_limit(4)))).await;
let (mut client, _challenge) = server.connect().await;
let at_limit = "\u{1F600}\u{1F600}";
let over_limit = format!("{at_limit}x");

let mut frames = Vec::new();
for id in [at_limit, over_limit.as_str()] {
client
.send(&format!(r#"["COUNT","{id}",{{"kinds":[1]}}]"#))
.await;
frames.push(client.expect_frame().await);
}

assert_eq!(
frames,
[
format!(r#"["COUNT","{at_limit}",{{"count":0}}]"#),
format!(
r#"["CLOSED","{over_limit}","Query ID too long: Query ID must be less than or equal to 4"]"#
),
]
);
}

#[tokio::test]
async fn an_id_is_bounded_in_utf16_code_units_at_the_shipped_limit() {
let server = start(Fixture::new(settings_with(subscription_id_limit(256)))).await;
let (mut client, _challenge) = server.connect().await;
// 100 BMP ideographs: 100 UTF-16 code units, but 300 bytes.
let within = "\u{4E2D}".repeat(100);
// 257 UTF-16 code units, but 129 chars.
let over = format!("{}x", "\u{1F600}".repeat(128));

let mut frames = Vec::new();
for verb in ["REQ", "COUNT"] {
for id in [&within, &over] {
client
.send(&format!(r#"["{verb}","{id}",{{"kinds":[1]}}]"#))
.await;
frames.push(client.expect_frame().await);
}
}

let refused = r#"["NOTICE","invalid: String must contain at most 256 character(s)"]"#;
assert_eq!(
frames,
[
format!(r#"["EOSE","{within}"]"#),
refused.to_owned(),
format!(r#"["COUNT","{within}",{{"count":0}}]"#),
refused.to_owned(),
]
);
}

#[tokio::test]
async fn a_count_repository_failure_is_generic() {
let fixture = Fixture::new(settings());
Expand Down
10 changes: 10 additions & 0 deletions docs/rewrite/decisions/0002-core-crypto-and-negentropy.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,16 @@ character is two units, so 600 emoji are 1200 units and are rejected by both pat
the catchall type check, where zod's `superRefine` only sees parsed keys: the Rust output can
be a superset of zod's on a document that is invalid either way, never on a valid one.

A `REQ` or `COUNT` subscription id is counted in UTF-16 code units too, at both of its bounds:
the frame schema's 256 (`src/schemas/message-schema.ts:11`, `:34`) and `maxSubscriptionIdLength`
(`src/handlers/subscribe-message-handler.ts:297`, `src/handlers/count-message-handler.ts:69`).
Both bounds and their refusals stay the capture's, not NIP-01's `max length 64 chars` and
`CLOSED` (`01.md:121`, `:180`) or NIP-45's `CLOSED` (`45.md:30`; NIPs at `bec0fc8`). Over 256
units an otherwise valid frame gets
`NOTICE "invalid: String must contain at most 256 character(s)"`; over a lower configured limit
the handler answers a `NOTICE` on `REQ` and a `CLOSED` on `COUNT`. Changing that is a decision
for both implementations.

## Decision — negentropy crate and its divergences

NIP-77 is the `negentropy` crate 0.5.2 behind a seam (`negentropy.rs` re-exports the
Expand Down
4 changes: 2 additions & 2 deletions docs/rewrite/fuzz.md
Original file line number Diff line number Diff line change
Expand Up @@ -247,8 +247,8 @@ including PRs that change `crates/**`.

## The four targets, one line each

- `client_frame`: `decode` never panics; an accepted REQ/COUNT carries a 1..=256-character
subscription id and 1..=10 filters.
- `client_frame`: `decode` never panics; an accepted REQ/COUNT carries a subscription id of
1..=256 UTF-16 code units and 1..=10 filters.
- `filter`: `validate_filter` never panics; an accepted filter's `ids`/`authors` are 4..=64
lowercase-hex characters and its tag keys are `#` plus one ASCII letter; a refusal carries at
least one issue.
Expand Down
10 changes: 5 additions & 5 deletions fuzz/fuzz_targets/client_frame.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
//! Invariants, on every input with no early return:
//!
//! - no input panics: `decode` is total, and libFuzzer's own report is the assertion;
//! - an accepted `Subscribe`/`Count` carries a subscription id of `1..=256` `char`s and
//! - an accepted `Subscribe`/`Count` carries a subscription id of `1..=256` UTF-16 code units and
//! `1..=10` filters — the bounds `decode_request` enforces
//! (`crates/nostream-core/src/messages.rs:465-506`), so a change that lets a 257-character
//! id or an eleventh filter through is a finding here.
//! (`crates/nostream-core/src/messages.rs:465-506`), so a change that lets a 257-unit id or
//! an eleventh filter through is a finding here.

#![no_main]

Expand All @@ -28,11 +28,11 @@ fuzz_target!(|data: &[u8]| {

/// The bounds a REQ/COUNT frame's parts must satisfy once `decode` accepted it.
fn check(subscription_id: &str, filters: usize) {
let length = subscription_id.chars().count();
let length = subscription_id.encode_utf16().count();

assert!(
(1..=256).contains(&length),
"accepted subscription id of {length} chars: {subscription_id:?}"
"accepted subscription id of {length} UTF-16 code units: {subscription_id:?}"
);
assert!(
(1..=10).contains(&filters),
Expand Down
Loading