From cbcad876e2058d2dc19fdea530f5cdba650d027d Mon Sep 17 00:00:00 2001 From: saket0187 Date: Sat, 5 Dec 2026 14:25:31 +0530 Subject: [PATCH] fix(relay): measure a subscription id in UTF-16 code units, as the capture does (cherry picked from commit 0f5a2d8b7c5adc23ad5c0682b5f2d56aee096c7b) --- .changeset/subscription-id-utf16-length.md | 6 ++ crates/nostream-core/src/messages.rs | 2 +- crates/nostream-core/tests/wire_codec.rs | 30 ++++++ crates/nostream-relay/src/handlers/count.rs | 2 +- .../nostream-relay/src/handlers/subscribe.rs | 2 +- crates/nostream-relay/tests/handlers.rs | 94 +++++++++++++++++++ .../0002-core-crypto-and-negentropy.md | 10 ++ docs/rewrite/fuzz.md | 4 +- fuzz/fuzz_targets/client_frame.rs | 10 +- 9 files changed, 150 insertions(+), 10 deletions(-) create mode 100644 .changeset/subscription-id-utf16-length.md diff --git a/.changeset/subscription-id-utf16-length.md b/.changeset/subscription-id-utf16-length.md new file mode 100644 index 000000000..0c9ab8134 --- /dev/null +++ b/.changeset/subscription-id-utf16-length.md @@ -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. diff --git a/crates/nostream-core/src/messages.rs b/crates/nostream-core/src/messages.rs index a9738c225..63e0b5296 100644 --- a/crates/nostream-core/src/messages.rs +++ b/crates/nostream-core/src/messages.rs @@ -467,7 +467,7 @@ fn decode_request(items: &[Value], verb: &str) -> Result<(String, Vec), 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)")); diff --git a/crates/nostream-core/tests/wire_codec.rs b/crates/nostream-core/tests/wire_codec.rs index 2d926428a..9b08a0b4a 100644 --- a/crates/nostream-core/tests/wire_codec.rs +++ b/crates/nostream-core/tests/wire_codec.rs @@ -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(); diff --git a/crates/nostream-relay/src/handlers/count.rs b/crates/nostream-relay/src/handlers/count.rs index da9ccfefc..d115f4a87 100644 --- a/crates/nostream-relay/src/handlers/count.rs +++ b/crates/nostream-relay/src/handlers/count.rs @@ -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}" diff --git a/crates/nostream-relay/src/handlers/subscribe.rs b/crates/nostream-relay/src/handlers/subscribe.rs index c910db164..d2be2ba9d 100644 --- a/crates/nostream-relay/src/handlers/subscribe.rs +++ b/crates/nostream-relay/src/handlers/subscribe.rs @@ -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}" diff --git a/crates/nostream-relay/tests/handlers.rs b/crates/nostream-relay/tests/handlers.rs index dbee299e0..63f5b35b7 100644 --- a/crates/nostream-relay/tests/handlers.rs +++ b/crates/nostream-relay/tests/handlers.rs @@ -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 @@ -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(); @@ -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()); diff --git a/docs/rewrite/decisions/0002-core-crypto-and-negentropy.md b/docs/rewrite/decisions/0002-core-crypto-and-negentropy.md index 5c825ea48..0532c211f 100644 --- a/docs/rewrite/decisions/0002-core-crypto-and-negentropy.md +++ b/docs/rewrite/decisions/0002-core-crypto-and-negentropy.md @@ -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 diff --git a/docs/rewrite/fuzz.md b/docs/rewrite/fuzz.md index a265b46ef..c68808291 100644 --- a/docs/rewrite/fuzz.md +++ b/docs/rewrite/fuzz.md @@ -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. diff --git a/fuzz/fuzz_targets/client_frame.rs b/fuzz/fuzz_targets/client_frame.rs index 447a684a1..eebc454fc 100644 --- a/fuzz/fuzz_targets/client_frame.rs +++ b/fuzz/fuzz_targets/client_frame.rs @@ -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] @@ -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),