From 1b8d03be24b01d7eb64f095329d554f0d837c22c Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 7 Nov 2026 00:21:37 -0800 Subject: [PATCH 1/3] chore(quest): claim quest/a0/qmux-stream-state.md Quest-Claim: 79a141d26c829864 From e31aa82d9b1dcf413c241ad679adb5db94a2ba3a Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 7 Nov 2026 00:32:09 -0800 Subject: [PATCH 2/3] fix(qmux): reject send controls for unopened local streams Validate send-control stream IDs against direction-specific allocation counters before looking up active state. Preserve retired and peer-initiated stream behavior, and apply the missing TypeScript STOP_SENDING direction check. Co-Authored-By: GPT-6.1 Sol --- js/qmux/README.md | 9 ++ js/qmux/src/session.test.ts | 126 +++++++++++++++- js/qmux/src/session.ts | 18 ++- quest/a0/README.md | 1 - quest/a0/qmux-max-streams-param.md | 4 - quest/a0/qmux-stream-state.md | 17 --- rs/qmux/README.md | 9 ++ rs/qmux/src/credit.rs | 5 + rs/qmux/src/session.rs | 232 ++++++++++++++++++++++++++--- 9 files changed, 368 insertions(+), 53 deletions(-) delete mode 100644 quest/a0/qmux-stream-state.md diff --git a/js/qmux/README.md b/js/qmux/README.md index b61c70d0..32b409df 100644 --- a/js/qmux/README.md +++ b/js/qmux/README.md @@ -119,6 +119,15 @@ install() const transport = new WebTransport("https://example.com/endpoint") ``` +## Stream control validation + +MAX_STREAM_DATA and STOP_SENDING close the session when they name a receive-only +stream or a locally initiated stream that has not been allocated. Late controls +for previously opened and closed streams are ignored. These checks follow +[RFC 9000 §19.5](https://www.rfc-editor.org/rfc/rfc9000.html#section-19.5) and +[§19.10](https://www.rfc-editor.org/rfc/rfc9000.html#section-19.10); detected +violations use the existing CONNECTION_CLOSE code 1002. + ## License Licensed under either of [Apache License, Version 2.0](LICENSE-APACHE) or [MIT license](LICENSE-MIT) at your option. diff --git a/js/qmux/src/session.test.ts b/js/qmux/src/session.test.ts index f8211a82..23a2bd92 100644 --- a/js/qmux/src/session.test.ts +++ b/js/qmux/src/session.test.ts @@ -17,6 +17,8 @@ class FakePeer { static last: FakePeer | undefined; readonly url: string; + readonly version: Frame.WireFormat; + #frameWaiters = new Set<() => void>(); readonly opened: Promise<{ readable: ReadableStream; writable: WritableStream; @@ -41,6 +43,11 @@ class FakePeer { constructor(url: string, options?: { protocol?: string }) { const protocol = options?.protocol ?? "qmux-01"; this.url = url; + this.version = protocol.startsWith("qmux-00") + ? "qmux-00" + : protocol.startsWith("qmux-02") + ? "qmux-02" + : "qmux-01"; FakePeer.last = this; const readable = new ReadableStream({ start: (c) => { @@ -51,6 +58,7 @@ class FakePeer { write: async (chunk) => { await this.#writeBlocked; this.sent.push(chunk); + for (const notify of this.#frameWaiters) notify(); }, }); this.opened = Promise.resolve({ readable, writable, protocol, extensions: "" }); @@ -86,7 +94,7 @@ class FakePeer { // --- test controls --- /** Inject a frame as if sent by the peer. */ send(frame: Frame.Any) { - this.#recv.enqueue(Frame.encode(frame, "qmux-01")); + this.#recv.enqueue(Frame.encode(frame, this.version)); } /** Inject a raw text frame (invalid for QMux). */ sendText(text: string) { @@ -104,8 +112,26 @@ class FakePeer { } /** All frames the Session has written so far, decoded. */ received(): Frame.Any[] { - return this.sent.flatMap((b) => Frame.decodeRecord(b)); + return this.sent.flatMap((b) => { + if (this.version !== "qmux-00") return Frame.decodeRecord(b); + const frame = Frame.decode(b, this.version); + return frame ? [frame] : []; + }); + } + /** Wait for observable peer output without timers or fixed microtask drains. */ + waitForFrame(predicate: (frame: Frame.Any) => boolean): Promise { + return new Promise((resolve) => { + const check = () => { + const frame = this.received().find(predicate); + if (!frame) return; + this.#frameWaiters.delete(check); + resolve(frame); + }; + this.#frameWaiters.add(check); + check(); + }); } + has(type: Frame.Any["type"]): boolean { return this.received().some((f) => f.type === type); } @@ -220,8 +246,12 @@ function peerParams(overrides: Partial = {}): TransportParams { }; } -function connect(config?: Config): { session: Session; peer: FakePeer } { - (globalThis as { WebSocketStream?: unknown }).WebSocketStream = FakePeer; +function connect(config?: Config, version: Frame.WireFormat = "qmux-01"): { session: Session; peer: FakePeer } { + (globalThis as { WebSocketStream?: unknown }).WebSocketStream = class extends FakePeer { + constructor(url: string) { + super(url, { protocol: version }); + } + }; // Idle timer off so a stray interval can't interfere with the test. // Bare version ALPNs are offered by default (requireProtocol defaults to false). const session = new Session("https://example/test", { @@ -553,6 +583,94 @@ describe("Session integration (scripted peer)", () => { await waitFor(() => sentCloseCode(peer) === 1002); }); + describe("send-control stream state", () => { + const controls = (id: Stream.Id): Frame.Any[] => [ + { type: "max_stream_data", id, max: 10n }, + { type: "stop_sending", id, code: VarInt.from(42) }, + ]; + + for (const version of ["qmux-00", "qmux-01", "qmux-02"] as const) { + for (const isServer of [false, true]) { + const setup = async () => { + const { session, peer } = isServer ? accept({ protocol: version }) : connect(undefined, version); + await session.ready; + peer.send({ + type: "transport_parameters", + params: peerParams({ initialMaxStreamDataUni: 0n, initialMaxStreamDataBidiRemote: 0n }), + }); + return { session, peer }; + }; + + for (const dir of [Stream.Dir.Uni, Stream.Dir.Bi]) { + const open = async (session: Session) => + dir === Stream.Dir.Uni + ? { writable: await session.createUnidirectionalStream(), readable: undefined } + : session.createBidirectionalStream(); + for (const opened of [0n, 2n]) { + for (const index of [opened, opened + 10n]) { + for (const frame of controls(Stream.Id.create(index, dir, isServer))) { + test(`${version} role=${isServer} dir=${dir} opened=${opened} index=${index} ${frame.type} rejects unopened local stream`, async () => { + const { session, peer } = await setup(); + // The allocation counters are independent in each direction. + for (let i = 0; i < 3; i++) { + if (dir === Stream.Dir.Uni) await session.createBidirectionalStream(); + else await session.createUnidirectionalStream(); + } + for (let i = 0n; i < opened; i++) await open(session); + peer.send(frame); + await expectSessionFailure(session); + const close = (await peer.waitForFrame( + (f) => f.type === "connection_close", + )) as Frame.ConnectionClose; + expect(close.code.value).toBe(1002n); + }); + } + } + } + + test(`${version} role=${isServer} dir=${dir} accepts controls on opened and retired streams`, async () => { + const { session, peer } = await setup(); + const stream = await open(session); + const writer = stream.writable.getWriter(); + const stopped = settleTo(writer.closed); + const id = Stream.Id.create(0n, dir, isServer); + peer.send(controls(id)[0]); + await writer.write(new Uint8Array([1])); + peer.send(controls(id)[1]); + expect(await stopped).toMatchObject({ streamErrorCode: 42 }); + await peer.waitForFrame( + (f) => f.type === "reset_stream" && f.id.value.value === id.value.value, + ); + if (stream.readable) await stream.readable.cancel(); + for (const frame of controls(id)) peer.send(frame); + peer.send({ type: "ping_request", sequence: 0n }); + await peer.waitForFrame((f) => f.type === "ping_response" && f.sequence === 0n); + expect(peer.has("connection_close")).toBe(false); + session.close(); + }); + } + + test(`${version} role=${isServer} preserves peer bidi controls and rejects receive-only STOP_SENDING`, async () => { + const { session, peer } = await setup(); + for (const frame of controls(Stream.Id.create(10n, Stream.Dir.Bi, !isServer))) peer.send(frame); + peer.send({ type: "ping_request", sequence: 0n }); + await peer.waitForFrame((f) => f.type === "ping_response" && f.sequence === 0n); + expect(peer.has("connection_close")).toBe(false); + peer.send({ + type: "stop_sending", + id: Stream.Id.create(0n, Stream.Dir.Uni, !isServer), + code: VarInt.from(42), + }); + await expectSessionFailure(session); + const close = (await peer.waitForFrame( + (f) => f.type === "connection_close", + )) as Frame.ConnectionClose; + expect(close.code.value).toBe(1002n); + }); + } + } + }); + test("draft-01 tolerates the legacy zero final_size after data", async () => { const { session, peer } = connect(); await session.ready; diff --git a/js/qmux/src/session.ts b/js/qmux/src/session.ts index 0a0bc641..947daa12 100644 --- a/js/qmux/src/session.ts +++ b/js/qmux/src/session.ts @@ -908,11 +908,7 @@ export default class Session implements WebTransport { } else if (frame.type === "max_data") { this.#connCredit.increaseMax(frame.max); } else if (frame.type === "max_stream_data") { - // RFC 9000 §19.10: MAX_STREAM_DATA for a receive-only stream is a - // STREAM_STATE_ERROR. - if (!frame.id.canSend(this.#isServer)) { - throw new Error("MAX_STREAM_DATA on a receive-only stream"); - } + this.#validateSendId(frame.id, "MAX_STREAM_DATA"); const flow = this.#streamFlow.get(frame.id.value.value); if (flow) flow.sendCredit.increaseMax(frame.max); } else if (frame.type === "max_streams_bidi") { @@ -1505,7 +1501,19 @@ export default class Session implements WebTransport { this.#maybeDeleteStreamFlow(streamId); } + // RFC 9000 §19.5/§19.10 permit retired local IDs, but not unallocated IDs. + #validateSendId(id: Stream.Id, frame: "MAX_STREAM_DATA" | "STOP_SENDING") { + if (!id.canSend(this.#isServer)) { + throw new Error(`${frame} on a receive-only stream`); + } + if (id.serverInitiated === this.#isServer) { + const next = id.dir === Stream.Dir.Uni ? this.#nextUniStreamId : this.#nextBiStreamId; + if (id.index >= next) throw new Error(`${frame} on an unopened local stream`); + } + } + #handleStopSending(frame: Frame.StopSending) { + this.#validateSendId(frame.id, "STOP_SENDING"); const streamId = frame.id.value.value; const stream = this.#sendStreams.get(streamId); if (!stream) return; diff --git a/quest/a0/README.md b/quest/a0/README.md index 26ce85f5..f64a90c3 100644 --- a/quest/a0/README.md +++ b/quest/a0/README.md @@ -15,6 +15,5 @@ The Required list is ordered by priority. Independent children may proceed concu - [QMux socket teardown](/quest/a0/qmux-socket-teardown.md) - release retained stats descriptors - [WebSocket handshake timeout](/quest/a0/qmux-ws-handshake-timeout.md) - close sessions whose peer never sends parameters - [QMux initial stream-count bound](/quest/a0/qmux-max-streams-param.md) - refuse initial_max_streams parameters above 2^60 -- [QMux stream-state checks](/quest/a0/qmux-stream-state.md) - refuse MAX_STREAM_DATA and STOP_SENDING for unopened local streams - [Node Server.close()](/quest/a0/node-server-close.md) - close completes while an accept is pending - [Node session and reader lifetime](/quest/a0/node-session-lifetime.md) - `closed` rejects on an abnormal end, and an abandoned reader releases its stream diff --git a/quest/a0/qmux-max-streams-param.md b/quest/a0/qmux-max-streams-param.md index ec1c33fd..353934cb 100644 --- a/quest/a0/qmux-max-streams-param.md +++ b/quest/a0/qmux-max-streams-param.md @@ -9,7 +9,3 @@ Rust and TypeScript QMux close the session with a transport-parameter error when Validate in the transport-parameter decoders, next to the existing parameter checks: Rust `proto/params.rs` returns the existing `Error::TransportParameter`, and TypeScript `frame.ts` throws like its other TRANSPORT_PARAMETER_ERROR cases. Do not add a public error variant. Both languages already send every detected violation as CONNECTION_CLOSE code 1002, and this quest keeps that path; per-error RFC 9000 wire codes are out of scope. Reuse the 2^60 bound that the MAX_STREAMS frame decoders already apply rather than defining a second constant. Cover exactly 2^60 (accepted) and 2^60 + 1 (refused) for both parameters in both languages, plus a session-level test showing the connect fails. No wire encoding changes; well-behaved peers are unaffected. - -## Related - -- [QMux stream-state checks](/quest/a0/qmux-stream-state.md) - the other RFC 9000 peer-input check planned alongside this one diff --git a/quest/a0/qmux-stream-state.md b/quest/a0/qmux-stream-state.md deleted file mode 100644 index 0975f833..00000000 --- a/quest/a0/qmux-stream-state.md +++ /dev/null @@ -1,17 +0,0 @@ -# [S] Refuse QMux control frames for unopened local streams - -## Goal - -Rust and TypeScript QMux close the session when the peer sends MAX_STREAM_DATA or STOP_SENDING for a locally initiated stream that has not been opened yet, as RFC 9000 §19.5 and §19.10 require (STREAM_STATE_ERROR). Today both implementations drop these frames silently. TypeScript also gains the STOP_SENDING direction check (refuse it for a receive-only stream) that Rust already has. - -## Plan - -A locally initiated stream is unopened when its index is at or beyond the next index this side will allocate in that direction. Frames for streams that were opened and have since closed stay ignored, and handling of peer-initiated streams is unchanged. Use the existing errors: Rust returns `Error::InvalidStreamId`, matching the receive-only MAX_STREAM_DATA and STOP_SENDING direction checks; TypeScript throws like its existing receive-only check. Do not add a public error variant. The close keeps the existing CONNECTION_CLOSE code 1002 that every detected violation uses; per-error RFC 9000 wire codes are out of scope. - -Read the next-index state without introducing a new lock order; the frame handlers already take the streams lock. Cover uni and bidi, opened, closed and unopened streams, and the TypeScript direction check with scripted-peer session tests in both languages. - -This is RFC-mandated validation that well-behaved peers never trigger. It is separate from the draft-02 receive-offset and terminal-size tolerance owned by [QMux draft readiness](/quest/a2/qmux-draft-readiness.md). - -## Related - -- [QMux initial stream-count bound](/quest/a0/qmux-max-streams-param.md) - the other RFC 9000 peer-input check planned alongside this one diff --git a/rs/qmux/README.md b/rs/qmux/README.md index 57baf91f..5471226d 100644 --- a/rs/qmux/README.md +++ b/rs/qmux/README.md @@ -68,6 +68,15 @@ grow a response queue by sending more pings; inbound stream processing continues while the writer is blocked. Pending responses are discarded during teardown, and a close frame ends the writer's output. +## Stream control validation + +MAX_STREAM_DATA and STOP_SENDING close the session when they name a receive-only +stream or a locally initiated stream that has not been allocated. Late controls +for previously opened and closed streams are ignored. These checks follow +[RFC 9000 §19.5](https://www.rfc-editor.org/rfc/rfc9000.html#section-19.5) and +[§19.10](https://www.rfc-editor.org/rfc/rfc9000.html#section-19.10); detected +violations use the existing CONNECTION_CLOSE code 1002. + ## License Licensed under either of [Apache License, Version 2.0](LICENSE-APACHE) or [MIT license](LICENSE-MIT) at your option. diff --git a/rs/qmux/src/credit.rs b/rs/qmux/src/credit.rs index 6f8c80c3..1e422498 100644 --- a/rs/qmux/src/credit.rs +++ b/rs/qmux/src/credit.rs @@ -84,6 +84,11 @@ impl Credit { } } + /// Return the next index for credit allocated with `claim_index`. + pub(crate) fn used(&self) -> u64 { + self.inner.lock().unwrap().state.used + } + /// Snapshot the two distinct stream-count credits while both locks are held. pub(crate) fn available_pair(bidi: &Self, uni: &Self) -> (u64, u64) { let bidi = bidi.inner.lock().unwrap(); diff --git a/rs/qmux/src/session.rs b/rs/qmux/src/session.rs index 7b9827a9..4ebf4734 100644 --- a/rs/qmux/src/session.rs +++ b/rs/qmux/src/session.rs @@ -1476,6 +1476,25 @@ impl SessionState { } } + // RFC 9000 §19.5/§19.10 forbid send controls for receive-only streams + // and local IDs we have not allocated. Retired IDs remain valid. + fn validate_send_id(&self, id: StreamId) -> Result<(), Error> { + if !id.can_send(self.is_server) { + return Err(Error::InvalidStreamId); + } + if id.server_initiated() == self.is_server { + // Read before taking the streams lock, preserving the lock order. + let next = match id.dir() { + StreamDir::Bi => self.open_bi_credit.used(), + StreamDir::Uni => self.open_uni_credit.used(), + }; + if id.index() >= next { + return Err(Error::InvalidStreamId); + } + } + Ok(()) + } + async fn recv_frame(&mut self, frame: Frame) -> Result<(), Error> { // Draft-02: QX_TRANSPORT_PARAMETERS MUST be the first frame, and only the // first. A non-params frame before params, or a second params frame, is a @@ -1808,9 +1827,7 @@ impl SessionState { } } Frame::StopSending(stop) => { - if !stop.id.can_send(self.is_server) { - return Err(Error::InvalidStreamId); - } + self.validate_send_id(stop.id)?; if let Some(send) = self.streams.lock().unwrap().send.get(&stop.id) { send.inbound_signal.send(SendSignal::Stopped(stop)).ok(); @@ -1844,11 +1861,7 @@ impl SessionState { self.conn_send_credit.increase_max(max); } Frame::MaxStreamData { id, max } => { - // RFC 9000 §19.10: MAX_STREAM_DATA for a receive-only stream is a - // STREAM_STATE_ERROR. - if !id.can_send(self.is_server) { - return Err(Error::InvalidStreamId); - } + self.validate_send_id(id)?; if let Some(send) = self.streams.lock().unwrap().send.get(&id) { if let Some(credit) = &send.stream_credit { credit.increase_max(max); @@ -5261,8 +5274,9 @@ mod credit_update_tests { use web_transport_trait::{SendStream as _, Session as _}; use super::{Reader, Session, Transport, Writer}; - use crate::proto::{Frame, TransportParams}; + use crate::proto::{Frame, StopSending, TransportParams}; use crate::{Config, Error, StreamDir, StreamId, Version}; + use web_transport_proto::VarInt; const VERSIONS: [Version; 3] = [Version::QMux00, Version::QMux01, Version::QMux02]; @@ -5330,19 +5344,42 @@ mod credit_update_tests { .unwrap(); } - /// Payload bytes the session has written on stream `id`. - fn sent_on(&self, id: StreamId) -> usize { + fn received(&self) -> Vec { self.outbound .lock() .unwrap() .iter() - .flat_map(|record| match self.version { - Version::QMux00 => Frame::decode(record.clone(), self.version) - .unwrap() - .into_iter() - .collect(), - _ => Frame::decode_record(record.clone()).unwrap(), + .flat_map(|record| { + if self.version.uses_records() { + Frame::decode_record(record.clone()).unwrap() + } else { + Frame::decode(record.clone(), self.version) + .unwrap() + .into_iter() + .collect() + } }) + .collect() + } + + async fn sync(&self, session: &Session, sequence: u64) { + // A peer stream is an input barrier supported by every QMux draft. + self.send(Frame::Stream(crate::Stream { + id: StreamId::new(sequence, StreamDir::Uni, !session.is_server), + offset: 0, + data: Bytes::new(), + fin: true, + })); + tokio::time::timeout(Duration::from_secs(1), session.accept_uni()) + .await + .expect("peer input was not processed") + .unwrap(); + } + + /// Payload bytes the session has written on stream `id`. + fn sent_on(&self, id: StreamId) -> usize { + self.received() + .into_iter() .map(|frame| match frame { Frame::Stream(stream) if stream.id == id => stream.data.len(), _ => 0, @@ -5351,8 +5388,12 @@ mod credit_update_tests { } } - /// A client session opposite a scripted server that has announced `params`. - fn scripted_session(version: Version, params: TransportParams) -> (Session, Peer) { + /// A session opposite a scripted peer that has announced `params`. + fn scripted_session( + version: Version, + params: TransportParams, + is_server: bool, + ) -> (Session, Peer) { let (tx, rx) = mpsc::unbounded_channel(); let outbound = Arc::new(Mutex::new(Vec::new())); let session = Session::new( @@ -5360,7 +5401,7 @@ mod credit_update_tests { incoming: rx, outgoing: outbound.clone(), }, - false, + is_server, Config::new(version), ); let peer = Peer { @@ -5387,7 +5428,7 @@ mod credit_update_tests { #[tokio::test(start_paused = true)] async fn stale_limits_are_ignored() { for version in VERSIONS { - let (session, peer) = scripted_session(version, small_params(version)); + let (session, peer) = scripted_session(version, small_params(version), false); let mut send = session.open_uni().await.unwrap(); let id = StreamId::new(0, StreamDir::Uni, false); @@ -5433,7 +5474,7 @@ mod credit_update_tests { async fn closed_with(frame: Frame) -> Vec { let mut errors = Vec::new(); for version in VERSIONS { - let (session, peer) = scripted_session(version, small_params(version)); + let (session, peer) = scripted_session(version, small_params(version), false); peer.send(frame.clone()); let err = tokio::time::timeout(Duration::from_secs(10), session.closed()) .await @@ -5463,4 +5504,151 @@ mod credit_update_tests { assert!(matches!(err, Error::InvalidStreamId), "got {err:?}"); } } + fn send_controls(id: StreamId) -> [Frame; 2] { + [ + Frame::MaxStreamData { id, max: 10 }, + Frame::StopSending(StopSending { + id, + code: VarInt::from_u32(42), + }), + ] + } + + #[tokio::test(start_paused = true)] + async fn send_controls_on_unopened_local_streams_are_rejected() { + for version in VERSIONS { + for is_server in [false, true] { + for dir in [StreamDir::Uni, StreamDir::Bi] { + for opened in [0, 2] { + for index in [opened, opened + 10] { + for frame in send_controls(StreamId::new(index, dir, is_server)) { + let params = Config::new(version).to_transport_params(); + let (session, peer) = scripted_session(version, params, is_server); + // Advancing the other direction must not open this ID. + for _ in 0..3 { + match dir { + StreamDir::Bi => { + session.open_uni().await.unwrap(); + } + StreamDir::Uni => { + session.open_bi().await.unwrap(); + } + } + } + for _ in 0..opened { + match dir { + StreamDir::Uni => { + session.open_uni().await.unwrap(); + } + StreamDir::Bi => { + session.open_bi().await.unwrap(); + } + } + } + peer.send(frame.clone()); + let error = + tokio::time::timeout(Duration::from_secs(1), session.closed()) + .await + .unwrap_or_else(|_| { + panic!("{version:?} {frame:?} was accepted") + }); + assert!(matches!(error, Error::InvalidStreamId), "{error:?}"); + tokio::time::timeout(Duration::from_secs(1), async { + loop { + if let Some(close) = + peer.received().into_iter().find_map(|f| match f { + Frame::ConnectionClose(close) => Some(close), + _ => None, + }) + { + assert_eq!(close.code.into_inner(), 1002); + break; + } + tokio::task::yield_now().await; + } + }) + .await + .expect("missing CONNECTION_CLOSE"); + } + } + } + } + } + } + } + + #[tokio::test(start_paused = true)] + async fn send_controls_on_opened_and_retired_local_streams_are_allowed() { + for version in VERSIONS { + for is_server in [false, true] { + for dir in [StreamDir::Uni, StreamDir::Bi] { + let mut params = Config::new(version).to_transport_params(); + params.initial_max_stream_data_uni = 0; + params.initial_max_stream_data_bidi_remote = 0; + let (session, peer) = scripted_session(version, params, is_server); + let (mut send, recv) = match dir { + StreamDir::Uni => (session.open_uni().await.unwrap(), None), + StreamDir::Bi => { + let (send, recv) = session.open_bi().await.unwrap(); + (send, Some(recv)) + } + }; + let id = StreamId::new(0, dir, is_server); + peer.send(send_controls(id)[0].clone()); + assert_eq!( + tokio::time::timeout(Duration::from_secs(1), send.write(b"x")) + .await + .expect("MAX_STREAM_DATA did not grant credit") + .unwrap(), + 1 + ); + peer.send(send_controls(id)[1].clone()); + peer.sync(&session, 0).await; + assert!( + matches!(tokio::time::timeout(Duration::from_secs(1), send.closed()) + .await.expect("STOP_SENDING was ignored"), Err(Error::StreamStop(code)) if code.into_inner() == 42) + ); + drop(send); + drop(recv); + tokio::time::timeout(Duration::from_secs(1), async { + while session.streams.lock().unwrap().send.contains_key(&id) { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + for frame in send_controls(id) { + peer.send(frame); + } + peer.sync(&session, 1).await; + assert!(!peer + .received() + .iter() + .any(|f| matches!(f, Frame::ConnectionClose(_)))); + } + } + } + } + + #[tokio::test(start_paused = true)] + async fn send_controls_on_peer_initiated_streams_keep_their_behavior() { + for version in VERSIONS { + for is_server in [false, true] { + let params = Config::new(version).to_transport_params(); + let (session, peer) = scripted_session(version, params, is_server); + let id = StreamId::new(10, StreamDir::Bi, !is_server); + for frame in send_controls(id) { + peer.send(frame); + } + peer.sync(&session, 0).await; + assert!(session.streams.lock().unwrap().send.is_empty()); + let id = StreamId::new(0, StreamDir::Uni, !is_server); + peer.send(send_controls(id)[1].clone()); + let error = tokio::time::timeout(Duration::from_secs(1), session.closed()) + .await + .expect("receive-only STOP_SENDING was accepted"); + assert!(matches!(error, Error::InvalidStreamId), "{error:?}"); + } + } + } } From 160ce1b016225af001ccd7aa45bb950383976890 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 7 Nov 2026 00:42:40 -0800 Subject: [PATCH 3/3] fix(qmux): address stream-state review findings Ignore late TypeScript input after session closure. Replace paused-time spin waits with output notifications and cover legacy STOP_SENDING plus server receive-only MAX_STREAM_DATA. Co-Authored-By: GPT-6.1 Sol --- js/qmux/src/session.test.ts | 123 ++++++++++++++++++++++----------- js/qmux/src/session.ts | 2 + rs/qmux/src/session.rs | 132 ++++++++++++++++++++++-------------- 3 files changed, 167 insertions(+), 90 deletions(-) diff --git a/js/qmux/src/session.test.ts b/js/qmux/src/session.test.ts index 23a2bd92..748df944 100644 --- a/js/qmux/src/session.test.ts +++ b/js/qmux/src/session.test.ts @@ -43,11 +43,14 @@ class FakePeer { constructor(url: string, options?: { protocol?: string }) { const protocol = options?.protocol ?? "qmux-01"; this.url = url; - this.version = protocol.startsWith("qmux-00") - ? "qmux-00" - : protocol.startsWith("qmux-02") - ? "qmux-02" - : "qmux-01"; + this.version = + protocol === "webtransport" + ? "webtransport" + : protocol.startsWith("qmux-00") + ? "qmux-00" + : protocol.startsWith("qmux-02") + ? "qmux-02" + : "qmux-01"; FakePeer.last = this; const readable = new ReadableStream({ start: (c) => { @@ -113,7 +116,7 @@ class FakePeer { /** All frames the Session has written so far, decoded. */ received(): Frame.Any[] { return this.sent.flatMap((b) => { - if (this.version !== "qmux-00") return Frame.decodeRecord(b); + if (Frame.usesRecords(this.version)) return Frame.decodeRecord(b); const frame = Frame.decode(b, this.version); return frame ? [frame] : []; }); @@ -584,21 +587,34 @@ describe("Session integration (scripted peer)", () => { }); describe("send-control stream state", () => { - const controls = (id: Stream.Id): Frame.Any[] => [ - { type: "max_stream_data", id, max: 10n }, - { type: "stop_sending", id, code: VarInt.from(42) }, - ]; - - for (const version of ["qmux-00", "qmux-01", "qmux-02"] as const) { + for (const version of ["webtransport", "qmux-00", "qmux-01", "qmux-02"] as const) { + const controls = (id: Stream.Id): Frame.Any[] => [ + ...(version === "webtransport" ? [] : [{ type: "max_stream_data" as const, id, max: 10n }]), + { type: "stop_sending", id, code: VarInt.from(42) }, + ]; for (const isServer of [false, true]) { const setup = async () => { const { session, peer } = isServer ? accept({ protocol: version }) : connect(undefined, version); await session.ready; - peer.send({ - type: "transport_parameters", - params: peerParams({ initialMaxStreamDataUni: 0n, initialMaxStreamDataBidiRemote: 0n }), - }); - return { session, peer }; + if (version !== "webtransport") + peer.send({ + type: "transport_parameters", + params: peerParams({ initialMaxStreamDataUni: 0n, initialMaxStreamDataBidiRemote: 0n }), + }); + const sync = async (sequence: bigint) => { + peer.send({ + type: "stream", + id: Stream.Id.create(sequence, Stream.Dir.Uni, !isServer), + data: new Uint8Array(), + fin: true, + }); + const incoming = session.incomingUnidirectionalStreams.getReader(); + const { value } = await incoming.read(); + incoming.releaseLock(); + expect(value).toBeDefined(); + await value?.cancel(); + }; + return { session, peer, sync }; }; for (const dir of [Stream.Dir.Uni, Stream.Dir.Bi]) { @@ -629,44 +645,75 @@ describe("Session integration (scripted peer)", () => { } test(`${version} role=${isServer} dir=${dir} accepts controls on opened and retired streams`, async () => { - const { session, peer } = await setup(); + const { session, peer, sync } = await setup(); const stream = await open(session); const writer = stream.writable.getWriter(); const stopped = settleTo(writer.closed); const id = Stream.Id.create(0n, dir, isServer); - peer.send(controls(id)[0]); + if (version !== "webtransport") peer.send({ type: "max_stream_data", id, max: 10n }); await writer.write(new Uint8Array([1])); - peer.send(controls(id)[1]); + peer.send({ type: "stop_sending", id, code: VarInt.from(42) }); expect(await stopped).toMatchObject({ streamErrorCode: 42 }); await peer.waitForFrame( (f) => f.type === "reset_stream" && f.id.value.value === id.value.value, ); if (stream.readable) await stream.readable.cancel(); for (const frame of controls(id)) peer.send(frame); - peer.send({ type: "ping_request", sequence: 0n }); - await peer.waitForFrame((f) => f.type === "ping_response" && f.sequence === 0n); + await sync(0n); expect(peer.has("connection_close")).toBe(false); session.close(); }); } - test(`${version} role=${isServer} preserves peer bidi controls and rejects receive-only STOP_SENDING`, async () => { - const { session, peer } = await setup(); - for (const frame of controls(Stream.Id.create(10n, Stream.Dir.Bi, !isServer))) peer.send(frame); - peer.send({ type: "ping_request", sequence: 0n }); - await peer.waitForFrame((f) => f.type === "ping_response" && f.sequence === 0n); - expect(peer.has("connection_close")).toBe(false); - peer.send({ - type: "stop_sending", - id: Stream.Id.create(0n, Stream.Dir.Uni, !isServer), - code: VarInt.from(42), + for (const frame of controls(Stream.Id.create(0n, Stream.Dir.Uni, !isServer))) { + test(`${version} role=${isServer} preserves peer bidi controls and rejects receive-only ${frame.type}`, async () => { + const { session, peer, sync } = await setup(); + for (const frame of controls(Stream.Id.create(10n, Stream.Dir.Bi, !isServer))) peer.send(frame); + await sync(0n); + expect(peer.has("connection_close")).toBe(false); + peer.send(frame); + await expectSessionFailure(session); + const close = (await peer.waitForFrame( + (f) => f.type === "connection_close", + )) as Frame.ConnectionClose; + expect(close.code.value).toBe(1002n); }); - await expectSessionFailure(session); - const close = (await peer.waitForFrame( - (f) => f.type === "connection_close", - )) as Frame.ConnectionClose; - expect(close.code.value).toBe(1002n); - }); + } + } + } + }); + + test("send controls after local or peer close are ignored", async () => { + for (const local of [false, true]) { + const { session, peer } = connect(); + await session.ready; + peer.send({ type: "transport_parameters", params: peerParams() }); + await session.createUnidirectionalStream(); + const errors = spyOn(console, "error"); + const timers = spyOn(globalThis, "setTimeout"); + try { + const close: Frame.ApplicationClose = { + type: "application_close", + code: VarInt.from(42), + reason: "done", + }; + const frames: Frame.Any[] = [ + { type: "stop_sending", id: Stream.Id.create(1n, Stream.Dir.Uni, false), code: VarInt.from(0) }, + { type: "stop_sending", id: Stream.Id.create(0n, Stream.Dir.Uni, true), code: VarInt.from(0) }, + { type: "max_stream_data", id: Stream.Id.create(1n, Stream.Dir.Bi, false), max: 10n }, + ]; + if (local) session.close({ closeCode: 42, reason: "done" }); + const timersBefore = timers.mock.calls.length; + const record = (local ? frames : [close, ...frames]).flatMap((f) => [...Frame.encode(f, "qmux-01")]); + peer.sendRaw(Uint8Array.from(record)); + expect(await session.closed).toEqual({ closeCode: 42, reason: "done" }); + await flushMicrotasks(); + expect(errors).not.toHaveBeenCalled(); + expect(timers.mock.calls.length).toBe(timersBefore); + expect(peer.has("connection_close")).toBe(false); + } finally { + errors.mockRestore(); + timers.mockRestore(); } } }); diff --git a/js/qmux/src/session.ts b/js/qmux/src/session.ts index 947daa12..2f98c53b 100644 --- a/js/qmux/src/session.ts +++ b/js/qmux/src/session.ts @@ -838,6 +838,7 @@ export default class Session implements WebTransport { } #onData(data: Uint8Array) { + if (this.#closed) return; this.#lastRecvAt = Date.now(); try { if (usesRecords(this.#version)) { @@ -874,6 +875,7 @@ export default class Session implements WebTransport { } #recvFrame(frame: Frame.Any) { + if (this.#closed) return; // Draft-02: QX_TRANSPORT_PARAMETERS MUST be the first frame, and only the // first. A non-params frame before params, or a second params frame, is a // PROTOCOL_VIOLATION. (decodeRecord drops leading PADDING before we get here.) diff --git a/rs/qmux/src/session.rs b/rs/qmux/src/session.rs index 4ebf4734..99007808 100644 --- a/rs/qmux/src/session.rs +++ b/rs/qmux/src/session.rs @@ -5270,7 +5270,7 @@ mod credit_update_tests { use std::time::Duration; use bytes::Bytes; - use tokio::sync::mpsc; + use tokio::sync::{mpsc, Notify}; use web_transport_trait::{SendStream as _, Session as _}; use super::{Reader, Session, Transport, Writer}; @@ -5280,15 +5280,24 @@ mod credit_update_tests { const VERSIONS: [Version; 3] = [Version::QMux00, Version::QMux01, Version::QMux02]; + const CONTROL_VERSIONS: [Version; 4] = [ + Version::WebTransport, + Version::QMux00, + Version::QMux01, + Version::QMux02, + ]; + /// A transport whose inbound frames are scripted and whose outbound records /// are kept for inspection. struct ScriptedTransport { incoming: mpsc::UnboundedReceiver, outgoing: Arc>>, + written: Arc, } struct ScriptedWriter { outgoing: Arc>>, + written: Arc, } struct ScriptedReader { @@ -5303,6 +5312,7 @@ mod credit_update_tests { ( ScriptedWriter { outgoing: self.outgoing, + written: self.written, }, ScriptedReader { incoming: self.incoming, @@ -5314,6 +5324,7 @@ mod credit_update_tests { impl Writer for ScriptedWriter { async fn send(&mut self, data: Bytes) -> Result<(), Error> { self.outgoing.lock().unwrap().push(data); + self.written.notify_one(); Ok(()) } @@ -5335,6 +5346,7 @@ mod credit_update_tests { version: Version, inbound: mpsc::UnboundedSender, outbound: Arc>>, + written: Arc, } impl Peer { @@ -5362,6 +5374,19 @@ mod credit_update_tests { .collect() } + async fn wait_for(&self, predicate: impl Fn(&Frame) -> bool) -> Frame { + tokio::time::timeout(Duration::from_secs(1), async { + loop { + if let Some(frame) = self.received().into_iter().find(&predicate) { + return frame; + } + self.written.notified().await; + } + }) + .await + .expect("expected frame was not written") + } + async fn sync(&self, session: &Session, sequence: u64) { // A peer stream is an input barrier supported by every QMux draft. self.send(Frame::Stream(crate::Stream { @@ -5396,10 +5421,12 @@ mod credit_update_tests { ) -> (Session, Peer) { let (tx, rx) = mpsc::unbounded_channel(); let outbound = Arc::new(Mutex::new(Vec::new())); + let written = Arc::new(Notify::new()); let session = Session::new( ScriptedTransport { incoming: rx, outgoing: outbound.clone(), + written: written.clone(), }, is_server, Config::new(version), @@ -5408,8 +5435,11 @@ mod credit_update_tests { version, inbound: tx, outbound, + written, }; - peer.send(Frame::TransportParameters(params)); + if version.is_qmux() { + peer.send(Frame::TransportParameters(params)); + } (session, peer) } @@ -5504,24 +5534,28 @@ mod credit_update_tests { assert!(matches!(err, Error::InvalidStreamId), "got {err:?}"); } } - fn send_controls(id: StreamId) -> [Frame; 2] { - [ - Frame::MaxStreamData { id, max: 10 }, - Frame::StopSending(StopSending { - id, - code: VarInt::from_u32(42), - }), - ] + fn send_controls(version: Version, id: StreamId) -> Vec { + let mut frames = Vec::new(); + if version.is_qmux() { + frames.push(Frame::MaxStreamData { id, max: 10 }); + } + frames.push(Frame::StopSending(StopSending { + id, + code: VarInt::from_u32(42), + })); + frames } #[tokio::test(start_paused = true)] async fn send_controls_on_unopened_local_streams_are_rejected() { - for version in VERSIONS { + for version in CONTROL_VERSIONS { for is_server in [false, true] { for dir in [StreamDir::Uni, StreamDir::Bi] { for opened in [0, 2] { for index in [opened, opened + 10] { - for frame in send_controls(StreamId::new(index, dir, is_server)) { + for frame in + send_controls(version, StreamId::new(index, dir, is_server)) + { let params = Config::new(version).to_transport_params(); let (session, peer) = scripted_session(version, params, is_server); // Advancing the other direction must not open this ID. @@ -5553,22 +5587,13 @@ mod credit_update_tests { panic!("{version:?} {frame:?} was accepted") }); assert!(matches!(error, Error::InvalidStreamId), "{error:?}"); - tokio::time::timeout(Duration::from_secs(1), async { - loop { - if let Some(close) = - peer.received().into_iter().find_map(|f| match f { - Frame::ConnectionClose(close) => Some(close), - _ => None, - }) - { - assert_eq!(close.code.into_inner(), 1002); - break; - } - tokio::task::yield_now().await; - } - }) - .await - .expect("missing CONNECTION_CLOSE"); + let close = peer + .wait_for(|f| matches!(f, Frame::ConnectionClose(_))) + .await; + let Frame::ConnectionClose(close) = close else { + unreachable!() + }; + assert_eq!(close.code.into_inner(), 1002); } } } @@ -5579,7 +5604,7 @@ mod credit_update_tests { #[tokio::test(start_paused = true)] async fn send_controls_on_opened_and_retired_local_streams_are_allowed() { - for version in VERSIONS { + for version in CONTROL_VERSIONS { for is_server in [false, true] { for dir in [StreamDir::Uni, StreamDir::Bi] { let mut params = Config::new(version).to_transport_params(); @@ -5594,7 +5619,9 @@ mod credit_update_tests { } }; let id = StreamId::new(0, dir, is_server); - peer.send(send_controls(id)[0].clone()); + if version.is_qmux() { + peer.send(Frame::MaxStreamData { id, max: 10 }); + } assert_eq!( tokio::time::timeout(Duration::from_secs(1), send.write(b"x")) .await @@ -5602,7 +5629,10 @@ mod credit_update_tests { .unwrap(), 1 ); - peer.send(send_controls(id)[1].clone()); + peer.send(Frame::StopSending(StopSending { + id, + code: VarInt::from_u32(42), + })); peer.sync(&session, 0).await; assert!( matches!(tokio::time::timeout(Duration::from_secs(1), send.closed()) @@ -5610,14 +5640,10 @@ mod credit_update_tests { ); drop(send); drop(recv); - tokio::time::timeout(Duration::from_secs(1), async { - while session.streams.lock().unwrap().send.contains_key(&id) { - tokio::task::yield_now().await; - } - }) - .await - .unwrap(); - for frame in send_controls(id) { + peer.wait_for(|f| matches!(f, Frame::ResetStream(reset) if reset.id == id)) + .await; + assert!(!session.streams.lock().unwrap().send.contains_key(&id)); + for frame in send_controls(version, id) { peer.send(frame); } peer.sync(&session, 1).await; @@ -5632,22 +5658,24 @@ mod credit_update_tests { #[tokio::test(start_paused = true)] async fn send_controls_on_peer_initiated_streams_keep_their_behavior() { - for version in VERSIONS { + for version in CONTROL_VERSIONS { for is_server in [false, true] { - let params = Config::new(version).to_transport_params(); - let (session, peer) = scripted_session(version, params, is_server); - let id = StreamId::new(10, StreamDir::Bi, !is_server); - for frame in send_controls(id) { + let id = StreamId::new(0, StreamDir::Uni, !is_server); + for frame in send_controls(version, id) { + let params = Config::new(version).to_transport_params(); + let (session, peer) = scripted_session(version, params, is_server); + let id = StreamId::new(10, StreamDir::Bi, !is_server); + for frame in send_controls(version, id) { + peer.send(frame); + } + peer.sync(&session, 0).await; + assert!(session.streams.lock().unwrap().send.is_empty()); peer.send(frame); + let error = tokio::time::timeout(Duration::from_secs(1), session.closed()) + .await + .expect("receive-only send control was accepted"); + assert!(matches!(error, Error::InvalidStreamId), "{error:?}"); } - peer.sync(&session, 0).await; - assert!(session.streams.lock().unwrap().send.is_empty()); - let id = StreamId::new(0, StreamDir::Uni, !is_server); - peer.send(send_controls(id)[1].clone()); - let error = tokio::time::timeout(Duration::from_secs(1), session.closed()) - .await - .expect("receive-only STOP_SENDING was accepted"); - assert!(matches!(error, Error::InvalidStreamId), "{error:?}"); } } }