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
9 changes: 9 additions & 0 deletions js/qmux/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
173 changes: 169 additions & 4 deletions js/qmux/src/session.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Uint8Array | ArrayBuffer | string>;
writable: WritableStream<Uint8Array>;
Expand All @@ -41,6 +43,14 @@ class FakePeer {
constructor(url: string, options?: { protocol?: string }) {
const protocol = options?.protocol ?? "qmux-01";
this.url = url;
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<Uint8Array | ArrayBuffer | string>({
start: (c) => {
Expand All @@ -51,6 +61,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: "" });
Expand Down Expand Up @@ -86,7 +97,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) {
Expand All @@ -104,8 +115,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 (Frame.usesRecords(this.version)) 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<Frame.Any> {
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);
}
Expand Down Expand Up @@ -220,8 +249,12 @@ function peerParams(overrides: Partial<TransportParams> = {}): 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", {
Expand Down Expand Up @@ -553,6 +586,138 @@ describe("Session integration (scripted peer)", () => {
await waitFor(() => sentCloseCode(peer) === 1002);
});

describe("send-control stream state", () => {
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;
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]) {
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, 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);
if (version !== "webtransport") peer.send({ type: "max_stream_data", id, max: 10n });
await writer.write(new Uint8Array([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);
await sync(0n);
expect(peer.has("connection_close")).toBe(false);
session.close();
});
}

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);
});
}
}
}
});

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();
}
}
});

test("draft-01 tolerates the legacy zero final_size after data", async () => {
const { session, peer } = connect();
await session.ready;
Expand Down
20 changes: 15 additions & 5 deletions js/qmux/src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down Expand Up @@ -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.)
Expand Down Expand Up @@ -908,11 +910,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") {
Expand Down Expand Up @@ -1505,7 +1503,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;
Expand Down
1 change: 0 additions & 1 deletion quest/a0/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,4 @@ The Required list is ordered by priority. Independent children may proceed concu
- [Quiche lifecycle](/quest/a0/quiche/README.md) - deterministic harness and retirement handling
- [QMux socket teardown](/quest/a0/qmux-socket-teardown.md) - release retained stats descriptors
- [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 session and reader lifetime](/quest/a0/node-session-lifetime.md) - `closed` rejects on an abnormal end, and an abandoned reader releases its stream
4 changes: 0 additions & 4 deletions quest/a0/qmux-max-streams-param.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
17 changes: 0 additions & 17 deletions quest/a0/qmux-stream-state.md

This file was deleted.

9 changes: 9 additions & 0 deletions rs/qmux/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,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.
5 changes: 5 additions & 0 deletions rs/qmux/src/credit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Loading
Loading