diff --git a/doc/concept/standard.md b/doc/concept/standard.md index c166cb2ec2a..073fea9d300 100644 --- a/doc/concept/standard.md +++ b/doc/concept/standard.md @@ -29,8 +29,8 @@ subset drops. What a peer actually observes against this implementation: - **History is one group.** In Rust, Object ID gaps must be marked by Prior Object ID Gap properties for a group to be fetchable. A `FETCH` returns one group from the cache, or on drafts 14 through 19 the saved prefix of the group a new subscription just joined. A range of groups is refused, as is a draft 20+ `LOCATION_FILTER` that ends at Largest Object rather than an absolute End Location. On draft 20 and later, `FETCH_OK`'s End Location is the requested end, capped at Largest Object: a range holding no objects gets an empty fetch stream, and only a start past Largest Object is refused, with `INVALID_RANGE`. A relay's copy with no upstream subscription can't know Largest Object short of the track's end, so it echoes the requested end instead. JavaScript publishing refuses every `FETCH`. Datagrams are never fetchable. A Rust reader that only fetches learns the track from `TRACK_STATUS` instead of subscribing, so a finished track stays fetchable; draft 17 still subscribes, since its `TRACK_STATUS` answer cannot say whether the track is timed, and so does a reader whose publisher refuses `TRACK_STATUS` as `NOT_SUPPORTED`. - **Timing.** A track whose `SUBSCRIBE_OK` declares no `TIMESCALE` is untimed, as is every track on drafts 14 through 16. A Rust reader that never subscribed takes the units from `TRACK_STATUS` on draft 18 and later. - **Strict SETUP and parameters.** Repeated unknown `SETUP` options, GREASE included, are accepted if well-formed; a repeated known option is rejected. On draft 17 and later, a `GROUP_ORDER` other than Ascending (1) or Descending (2) closes the session. Message parameters follow the negotiated draft's lists: drafts 14 and 15 ignore an unknown or misplaced parameter, draft 16 ignores one defined only for another message but closes the session on an unknown one, and draft 17 and later close it on both. -- **One `SETUP` credential**, forwarded to the [auth server](/bin/relay/auth#the-contract) unverified. A second `SETUP` token closes the session. We advertise no token cache, so an alias reference in `SETUP` closes it with `PROTOCOL_VIOLATION`, one on a request with `UNKNOWN_AUTH_TOKEN_ALIAS`, and a registration on a request with `AUTH_TOKEN_CACHE_OVERFLOW`. Where the Rust side authorizes the peer or verifies tokens, a token on a `SUBSCRIBE` or `PUBLISH_NAMESPACE` is verified like an in-band session token and authorizes that one request alone, even where that authorization already covers it; it never widens the session. It is refused with `NOT_SUPPORTED` when nothing verifies it, when it is empty, or when its Token Type is anything but 0 (out of band). A side that does neither, JavaScript included, ignores the token. Rust refuses a request carrying more than one distinct token with `NOT_SUPPORTED`, since it verifies one; JavaScript, which verifies none, ignores them all. A token-authorized `SUBSCRIBE` still stays within the grant the peer gave us. A token-authorized `PUBLISH_NAMESPACE` needs a grant covering everything beneath the namespace, and the tracks we subscribe under it rely on that announce instead of our limit, ending with it. An update renews the token, except on a drafts 14 and 15 `PUBLISH_NAMESPACE`, which has no update, and a refused renewal ends only that request. A token on any other request is decoded and grants nothing, and a request repeating one is refused with `MALFORMED_AUTH_TOKEN`. `SUBSCRIBE_TRACKS` is refused unread, so its token is not decoded. On draft 17 and later, the negotiated [MoQ Auth extension](/concept/moq-lite#authorization) accepts additional session tokens in band. -- **Refused, not fatal.** A legal request this stack does not serve is rejected on its own and the session stays up: `FORWARD=0`, range filters, `SUBSCRIBE_TRACKS`, and the fetch forms above. On draft 19 and later, and in Rust on drafts 14 through 16, a subscription update may change only priority or renew a request token; any other update ends that subscription. +- **One `SETUP` credential**, forwarded to the [auth server](/bin/relay/auth#the-contract) unverified. A second `SETUP` token closes the session. We advertise no token cache, so an alias reference in `SETUP` closes it with `PROTOCOL_VIOLATION`, one on a request with `UNKNOWN_AUTH_TOKEN_ALIAS`, and a registration on a request with `AUTH_TOKEN_CACHE_OVERFLOW`. Where the Rust side authorizes the peer or verifies tokens, a token on a `SUBSCRIBE` or `PUBLISH_NAMESPACE` is verified like an in-band session token and authorizes that one request alone, even where that authorization already covers it; it never widens the session. It is refused with `NOT_SUPPORTED` when nothing verifies it, when it is empty, or when its Token Type is anything but 0 (out of band). A side that does neither, JavaScript included, ignores the token. Rust refuses a request carrying more than one distinct token with `NOT_SUPPORTED`, since it verifies one; JavaScript, which verifies none, ignores them all. A token-authorized `SUBSCRIBE` still stays within the grant the peer gave us. A token-authorized `PUBLISH_NAMESPACE` needs a grant covering everything beneath the namespace, and the tracks we subscribe under it rely on that announce instead of our limit, ending with it. An update renews the token, except on a drafts 14 and 15 `PUBLISH_NAMESPACE`, which has no update, and a refused renewal ends only that request. A token on any other request is decoded and grants nothing, and a request repeating one is refused with `MALFORMED_AUTH_TOKEN`. `SUBSCRIBE_TRACKS` reads its namespace before refusal; its token is not decoded. On draft 17 and later, the negotiated [MoQ Auth extension](/concept/moq-lite#authorization) accepts additional session tokens in band. +- **Refused, not fatal.** A legal request this stack does not serve is rejected on its own and the session stays up: `FORWARD=0`, `SUBSCRIBE_TRACKS`, and the fetch forms above get `NOT_SUPPORTED`. Range Filters get `INVALID_FILTER` on draft 19 and later because the advertised filter limit is zero. On draft 21 and later, namespaces whose first tuple field is exactly `.` or `.session` get `DOES_NOT_EXIST` before application lookup; other dot prefixes still reach the application. Subscription updates accept priority and delivery timeouts; Rust also renews request tokens. Other supported-but-unimplemented preferences end that subscription; a `TRACK_PROPERTY_FILTER` there closes the session with `PROTOCOL_VIOLATION`, since it belongs only to `SUBSCRIBE_TRACKS`. On draft 18 and later a namespace update may change its prefix; suffixes after the acknowledgement are relative to that new prefix. - **Objects and datagrams.** Rust relays preserve Object IDs, gaps, object properties, FIRST\_OBJECT, and END\_OF\_GROUP status objects between moq-transport peers for subgroup 0. Datagrams retain their IDs, properties, priority, and status. Plain Rust readers and moq-lite peers see consecutive frames and normal datagram payloads; JavaScript supports only normal datagrams at Object ID 0. A malformed datagram closes the session; a relayed one the downstream draft cannot carry is dropped. A relayed Timestamp leaves in the units the downstream response declares, and is dropped where it declares none (drafts 14 through 16), as for a plain frame; an immutable one that would change or vanish is refused. Property 0x06 is a draft-ietf-moq-loc-03 Timestamp only before draft 19, which reassigns it to SUBGROUP\_DELIVERY\_TIMEOUT, so it is dropped across that boundary, or refused when immutable. From draft 15, a status object carrying properties is refused, and one relayed from draft 14 leaves without them. A `FETCH` carries the END\_OF\_GROUP object on drafts 14 and 15; later drafts have no FETCH status, so their response ends at the last frame. A group cannot resume across route changes by frame ordinal once Object IDs skip ahead of the ordinals on either route; recovery refuses it instead of splicing different objects. - **Priority.** Higher is served first. The IETF default of 128 is this stack's 127, and a track that never sets one is 127. - **Size.** An object extension block larger than 64 KiB ends that subgroup stream. The session stays up. This cap is ours, not the draft's. @@ -52,8 +52,8 @@ See [Encryption](/concept/hang#encryption). ### Deliberate deviations -These four answers differ from the draft on purpose. They are the -product's model, not bugs, and the relay does not change them. +These answers deliberately differ from the draft or exercise its implementation +choices. They follow the product model. - **One publisher per path.** A broadcast path names one piece of content, so a `SUBSCRIBE` goes to one route, not to every publisher whose namespace matches. @@ -61,6 +61,7 @@ product's model, not bugs, and the relay does not change them. requires the relay to send that `SUBSCRIBE` to all matching publishers. See [publisher epochs](/concept/moq-lite#publisher-epochs) for how that one route is chosen. + - **Plain readers leave object properties out.** [Draft 18 §2.5](https://www.ietf.org/archive/id/draft-ietf-moq-transport-18.html#section-2.5) says a relay that does not understand a property still forwards and caches @@ -69,6 +70,7 @@ product's model, not bugs, and the relay does not change them. Immutable property blocks retain their bytes. Forwarding is refused when the negotiated drafts use incompatible key or integer encodings, or when the block holds a Timestamp in units the response does not declare. + - **`SUBSCRIBE_OK` before an old source answers.** moq-lite 01 through 04 have no track stream, so the relay cannot learn from that source whether the track exists before answering. A moq-transport subscriber gets `SUBSCRIBE_OK` @@ -78,12 +80,28 @@ product's model, not bugs, and the relay does not change them. requires an established upstream subscription before `SUBSCRIBE_OK`. From moq-lite 05 the track stream answers first, and a missing track is refused before `SUBSCRIBE_OK`. + - **An unknown token alias closes the session.** No alias is ever registered, so a `DELETE` or `USE_ALIAS` token on a request names one that does not exist. [Draft 21 §8.9](https://www.ietf.org/archive/id/draft-ietf-moq-transport-21.html#section-8.9) rejects the message, but `UNKNOWN_AUTH_TOKEN_ALIAS` exists only as a session termination code, so we close the session with it. +- **Deduplicated subscriptions and discovery.** Shared subscriptions and overlapping + namespace prefixes are coalesced internally, so `DUPLICATE_SUBSCRIPTION` and + `PREFIX_OVERLAP` are never sent. + +- **Delivery timeouts are advisory.** `OBJECT_DELIVERY_TIMEOUT` and + `SUBGROUP_DELIVERY_TIMEOUT` are accepted on subscriptions and their updates, + but do not drop objects or reset subgroups. Latency enforcement uses + presentation time instead of wall-clock delivery deadlines. + +- **Rendezvous waits are capped at zero.** A `SUBSCRIBE` with a positive + `RENDEZVOUS_TIMEOUT` gets `TIMEOUT` immediately if no publisher exists; + absent or zero still gets `DOES_NOT_EXIST`. + [Draft 21 §9.20.7](https://www.ietf.org/archive/id/draft-ietf-moq-transport-21.html#section-9.20.7) + permits the publisher to cap the wait. + ## MSF The MoQ Streaming Format is a catalog, playing the role HLS playlists and SDP diff --git a/js/net/bench/requests.ts b/js/net/bench/requests.ts index 1055b239f39..0daf1b294ed 100644 --- a/js/net/bench/requests.ts +++ b/js/net/bench/requests.ts @@ -1,8 +1,19 @@ /** Sweep request restart and cancellation over independent origin and waiter dimensions. */ import { Producer as Broadcast } from "../src/broadcast"; import * as Epoch from "../src/epoch"; +import { NativeSession } from "../src/ietf/adapter"; +import { Publisher as IetfPublisher } from "../src/ietf/publisher"; +import { RequestOk } from "../src/ietf/request"; +import { + SubscribeNamespace, + SubscribeNamespaceEntry, + SubscribeNamespaceEntryDone, +} from "../src/ietf/subscribe_namespace"; +import { ALPN, Version } from "../src/ietf/version"; +import { createMockTransportPair } from "../src/mock"; import { Producer } from "../src/origin"; import * as Path from "../src/path"; +import { Stream } from "../src/stream"; import { wireOf } from "../src/wire"; const settle = () => new Promise((resolve) => setImmediate(resolve)); @@ -248,3 +259,83 @@ for (const survivor of [false, true]) settled.sort((a, b) => a - b); console.log(`${survivor},${routes},${cancelled},${active[3].toFixed(2)},${settled[3].toFixed(2)}`); } + +// Prefix updates withdraw the old set and replay the new set. Sweep both the +// namespaces per prefix and the concurrent requesting peers, including wire encoding. +console.log("namespace_update,draft,namespaces,subscribers,update_us"); +for (const [version, alpn] of [ + [Version.DRAFT_18, ALPN.DRAFT_18], + [Version.DRAFT_21, ALPN.DRAFT_21], +] as const) + for (const namespaces of [1, 32, 128]) + for (const subscribers of [1, 8]) { + const origin = new Producer(); + const sources = []; + for (const prefix of ["a", "b"]) + for (let i = 0; i < namespaces; i++) { + const source = origin.createBroadcast(Path.from(`${prefix}/${i}`)); + source.announce(); + sources.push(source); + } + const peers = await Promise.all( + Array.from({ length: subscribers }, async () => { + const pair = createMockTransportPair(alpn); + const pub = new IetfPublisher({ + quic: pair.server, + session: new NativeSession(pair.server, version, false), + publish: origin.consume(), + requiresSolicitation: true, + }); + const client = await Stream.open(pair.client, { version }); + const server = await Stream.accept(pair.server, version); + if (!server) throw new Error("missing namespace stream"); + const running = pub.runSubscribeNamespace( + new SubscribeNamespace({ requestId: 0n, namespace: Path.from("a") }), + server, + ); + if ((await client.reader.u53()) !== RequestOk.id) throw new Error("missing initial OK"); + await RequestOk.decode(client.reader, version); + for (let i = 0; i < namespaces; i++) { + if ((await client.reader.u53()) !== SubscribeNamespaceEntry.id) + throw new Error("missing initial namespace"); + await SubscribeNamespaceEntry.decode(client.reader, version); + } + return { client, running }; + }), + ); + const samples: number[] = []; + try { + for (let round = 0; round < 7; round++) { + const start = performance.now(); + await Promise.all( + peers.map(async ({ client }) => { + await client.writer.write( + Uint8Array.from([0x02, 0, 6, (round + 1) * 2, 1, 0x34, 1, 1, round % 2 ? 97 : 98]), + ); + for (let i = 0; i < namespaces; i++) { + if ((await client.reader.u53()) !== SubscribeNamespaceEntryDone.id) + throw new Error("missing old withdrawal"); + await SubscribeNamespaceEntryDone.decode(client.reader, version); + } + if ((await client.reader.u53()) !== RequestOk.id) throw new Error("missing update OK"); + await RequestOk.decode(client.reader, version); + for (let i = 0; i < namespaces; i++) { + if ((await client.reader.u53()) !== SubscribeNamespaceEntry.id) + throw new Error("missing replay namespace"); + await SubscribeNamespaceEntry.decode(client.reader, version); + } + }), + ); + if (round > 1) samples.push((performance.now() - start) * 1000); + } + samples.sort((a, b) => a - b); + console.log( + `namespace_update,${version === Version.DRAFT_18 ? 18 : 21},${namespaces},${subscribers},${samples[2].toFixed(2)}`, + ); + } finally { + for (const peer of peers) peer.client.close(); + await Promise.all(peers.map((peer) => peer.running)); + for (const source of sources) source.close(); + origin.close(); + } + } diff --git a/js/net/src/ietf/connection.ts b/js/net/src/ietf/connection.ts index 009a41f2f9c..bc9546cd385 100644 --- a/js/net/src/ietf/connection.ts +++ b/js/net/src/ietf/connection.ts @@ -19,6 +19,7 @@ import { type RequestKind, toRequestCode } from "./error.ts"; import { Fetch, FetchError, FetchHeader } from "./fetch.ts"; import { GoAway } from "./goaway.ts"; import * as Message from "./message.ts"; +import * as Namespace from "./namespace.ts"; import { Group } from "./object.ts"; import { Publish, PublishError } from "./publish.ts"; import { PublishNamespace, PublishNamespaceError } from "./publish_namespace.ts"; @@ -401,13 +402,14 @@ export class Connection implements Established { if (this.#session.version < Version.DRAFT_18) { throw new ProtocolViolation("SUBSCRIBE_TRACKS before draft-18"); } - const requestId = await Message.decode(stream.reader, async (reader) => { - const id = await reader.u62(); + const request = await Message.decode(stream.reader, async (reader) => { + const requestId = await reader.u62(); + const namespace = await Namespace.decode(reader); await reader.readAll(); - return id; + return { requestId, namespace }; }); - this.#session.spendRequest(requestId); - await this.#publisher.runSubscribeTracks(stream); + this.#session.spendRequest(request.requestId); + await this.#publisher.runSubscribeTracks(stream, request.namespace); break; } case BigInt(TrackStatusRequest.id): { diff --git a/js/net/src/ietf/error.test.ts b/js/net/src/ietf/error.test.ts index 5e51ecf68c9..e938891316e 100644 --- a/js/net/src/ietf/error.test.ts +++ b/js/net/src/ietf/error.test.ts @@ -32,6 +32,7 @@ const CONDITIONS: RequestCondition[] = [ "not_supported", "does_not_exist", "invalid_range", + "invalid_filter", "invalid_joining_request_id", "uninterested", "malformed_track", @@ -214,3 +215,12 @@ test("stream reset codes are shared only where the draft agrees", () => { expect(sharedStreamCode(StreamCode.MalformedTrack, Version.DRAFT_15)).toBe(false); expect(sharedStreamCode(StreamCode.MalformedTrack, Version.DRAFT_16)).toBe(true); }); + +test("INVALID_FILTER is registered from draft 19", () => { + for (const version of ALL) { + expect(toRequestCode("invalid_filter", "subscribe", version)).toBe(version >= Version.DRAFT_19 ? 0x36 : 0); + expect(fromRequestCode(0x36, "fetch", version)).toBe( + version >= Version.DRAFT_19 ? "invalid_filter" : undefined, + ); + } +}); diff --git a/js/net/src/ietf/error.ts b/js/net/src/ietf/error.ts index f19449b5866..cf32400bf37 100644 --- a/js/net/src/ietf/error.ts +++ b/js/net/src/ietf/error.ts @@ -93,6 +93,7 @@ export type RequestCondition = | "not_supported" /** The broadcast or track the peer asked for is not here. */ | "invalid_range" + | "invalid_filter" | "invalid_joining_request_id" | "does_not_exist" /** The content the peer offered is not wanted here, so it should stop offering it. */ @@ -188,6 +189,8 @@ function goingAway(version: IetfVersion): number | undefined { */ export function toRequestCode(condition: RequestCondition, kind: RequestKind, version: IetfVersion): number { switch (condition) { + case "invalid_filter": + return version >= Version.DRAFT_19 ? 0x36 : INTERNAL_ERROR; case "internal": return INTERNAL_ERROR; case "unauthorized": @@ -236,6 +239,7 @@ export function fromRequestCode(code: number, kind: RequestKind, version: IetfVe return "not_supported"; } + if (code === 0x36 && version >= Version.DRAFT_19) return "invalid_filter"; if (code === doesNotExist(kind, version)) return "does_not_exist"; if (code === invalidRange(kind, version)) return "invalid_range"; if (code === invalidJoiningRequestId(kind, version)) return "invalid_joining_request_id"; diff --git a/js/net/src/ietf/fetch.ts b/js/net/src/ietf/fetch.ts index 3db0412c98a..dc82e1cbf47 100644 --- a/js/net/src/ietf/fetch.ts +++ b/js/net/src/ietf/fetch.ts @@ -1,3 +1,4 @@ +import type * as Path from "../path.ts"; import type { Reader, Writer } from "../stream.ts"; import { hasRangeFilters, isDraft20 } from "./filter.ts"; import * as Message from "./message.ts"; @@ -39,9 +40,19 @@ export class Fetch { static id = 0x16; requestId: bigint; + /** Whether the decoded request carried Range Filters. */ + rangeFilters: boolean; + /** The decoded standalone namespace, absent for a joining fetch. */ + trackNamespace?: Path.Valid; - constructor({ requestId }: { requestId: bigint }) { + constructor({ + requestId, + rangeFilters = false, + trackNamespace, + }: { requestId: bigint; rangeFilters?: boolean; trackNamespace?: Path.Valid }) { this.requestId = requestId; + this.rangeFilters = rangeFilters; + this.trackNamespace = trackNamespace; } async #encode(_w: Writer): Promise { @@ -67,15 +78,16 @@ export class Fetch { await r.u8(); // group_order } + let trackNamespace: Path.Valid | undefined; if (isDraft20(version)) { // Draft-20 names the track up front and moves the range into LOCATION_FILTER. - await Namespace.decode(r); + trackNamespace = await Namespace.decode(r); await r.string(); } else { const fetchType = await r.u53(); switch (fetchType) { case 0x1: // Standalone: namespace, name, start and end Locations - await Namespace.decode(r); + trackNamespace = await Namespace.decode(r); await r.string(); for (let i = 0; i < 4; i++) await r.u62(); break; @@ -97,7 +109,7 @@ export class Fetch { throw new Error("TRACK_PROPERTY_FILTER is not allowed on FETCH"); } - return new Fetch({ requestId }); + return new Fetch({ requestId, rangeFilters: params.rangeFilters, trackNamespace }); } } diff --git a/js/net/src/ietf/namespace.test.ts b/js/net/src/ietf/namespace.test.ts new file mode 100644 index 00000000000..656fb31c736 --- /dev/null +++ b/js/net/src/ietf/namespace.test.ts @@ -0,0 +1,21 @@ +import { expect, test } from "bun:test"; +import { fromTuple, reserved } from "./namespace.ts"; +import { Version } from "./version.ts"; + +test("reserved namespaces preserve tuple fields and draft boundaries", () => { + for (const [fields, expected] of [ + [["."], true], + [[".", "child"], true], + [[".session"], true], + [[".session", "extension"], true], + [[".session/extension"], false], + [["", ".session"], false], + [[".application"], false], + [[".sessionish"], false], + ] as [string[], boolean][]) { + const path = fromTuple(fields); + expect(reserved(path, Version.DRAFT_21)).toBe(expected); + expect(reserved(path, Version.DRAFT_22)).toBe(expected); + expect(reserved(path, Version.DRAFT_20)).toBe(false); + } +}); diff --git a/js/net/src/ietf/namespace.ts b/js/net/src/ietf/namespace.ts index f779bbf41d4..1c256f0c8e6 100644 --- a/js/net/src/ietf/namespace.ts +++ b/js/net/src/ietf/namespace.ts @@ -1,5 +1,6 @@ import * as Path from "../path.ts"; import type { Reader, Writer } from "../stream.ts"; +import { type IetfVersion, Version } from "./version.ts"; /** Convert the escaped moq-net path representation into IETF namespace tuple fields. */ export function toTuple(namespace: Path.Valid): string[] { @@ -55,3 +56,10 @@ export async function decode(r: Reader): Promise { } return fromTuple(parts); } + +/** Whether a request names an unimplemented session namespace or the forbidden period field. */ +export function reserved(namespace: Path.Valid, version: IetfVersion): boolean { + if (version < Version.DRAFT_21) return false; + const first = toTuple(namespace)[0]; + return first === "." || first === ".session"; +} diff --git a/js/net/src/ietf/parameters.ts b/js/net/src/ietf/parameters.ts index 24c6e299e28..dd51b8f3877 100644 --- a/js/net/src/ietf/parameters.ts +++ b/js/net/src/ietf/parameters.ts @@ -1,7 +1,9 @@ import { ProtocolViolation } from "../error.ts"; +import type * as Path from "../path.ts"; import type { Reader, Writer } from "../stream.ts"; import * as Varint from "../varint.ts"; import * as Filter from "./filter.ts"; +import * as Namespace from "./namespace.ts"; import { AUTHORIZATION_TOKEN, type Token, tokenFromRequest, unique } from "./token.ts"; import { type IetfVersion, Version } from "./version.ts"; @@ -247,7 +249,8 @@ type ControlMessage = | "fetch" | "request-ok" | "request-update" - | "namespace"; + | "namespace" + | "namespace-update"; function draft20(version: IetfVersion): boolean { return version >= Version.DRAFT_20; @@ -313,6 +316,8 @@ function allows(message: ControlMessage, version: IetfVersion, id: bigint): bool trackRange || newGroup ); + case "namespace-update": + return from18 && (auth || id === 0x34n); case "subscribe-namespace": return auth || (forward && legacyForward) || id === MSG_PARAM_HIDDEN; case "publish": @@ -367,12 +372,14 @@ const MSG_PARAM_REPEATABLE: readonly bigint[] = [ MSG_PARAM_TRACK_PROPERTY_FILTER, ]; -type MessageParamKind = "varint" | "uint8" | "bool" | "location" | "filter" | "bytes"; +type MessageParamKind = "varint" | "uint8" | "bool" | "location" | "filter" | "bytes" | "namespace"; /** A `{Group, Object}` pair carried by a message parameter, such as LARGEST_OBJECT. */ export type MessageLocation = { groupId: bigint; objectId: bigint }; function getMessageParamKind(id: bigint): MessageParamKind { switch (id) { + case 0x34n: + return "namespace"; case MSG_PARAM_DELIVERY_TIMEOUT: case MSG_PARAM_FILL_TIMEOUT: case MSG_PARAM_NEW_GROUP_REQUEST: @@ -431,6 +438,8 @@ function encodeLocation({ groupId, objectId }: MessageLocation): Uint8Array { export class Parameters { vars: Map; bytes: Map; + /** TRACK_NAMESPACE_PREFIX on a namespace update, decoded only. */ + namespacePrefix: Path.Valid | undefined; #locations: Map; /** LOCATION_FILTER, kept decoded because its framing depends on the draft. */ #filter: Filter.Filter | undefined; @@ -808,7 +817,13 @@ export class Parameters { } const filter = id === MSG_PARAM_SUBSCRIPTION_FILTER && params.#filter !== undefined; - if (params.vars.has(id) || params.bytes.has(id) || params.#locations.has(id) || filter) { + if ( + params.vars.has(id) || + params.bytes.has(id) || + params.#locations.has(id) || + filter || + (id === 0x34n && params.namespacePrefix !== undefined) + ) { throw new Error(`duplicate message parameter id: ${id.toString()}`); } @@ -839,6 +854,9 @@ export class Parameters { params.#locations.set(id, { groupId, objectId }); break; } + case "namespace": + params.namespacePrefix = await Namespace.decode(r); + break; case "filter": params.#filter = await Filter.decodeParam(r, version); break; diff --git a/js/net/src/ietf/publisher.test.ts b/js/net/src/ietf/publisher.test.ts index d6b0e9e703d..2142d9b5212 100644 --- a/js/net/src/ietf/publisher.test.ts +++ b/js/net/src/ietf/publisher.test.ts @@ -3,7 +3,7 @@ import { Signal } from "@moq/signals"; import type { Grant } from "../auth.ts"; import { Producer as BroadcastProducer } from "../broadcast.ts"; import * as Epoch from "../epoch.ts"; -import { error, StreamCode } from "../error.ts"; +import { error, ProtocolViolation, StreamCode } from "../error.ts"; import { Producer as GroupProducer, MAX_GROUP_FRAMES } from "../group.ts"; import { type Hop, HopSchema } from "../hop.ts"; import { createMockTransportPair } from "../mock.ts"; @@ -401,6 +401,111 @@ test("FETCH and a non-forwarding SUBSCRIBE get NOT_SUPPORTED", async () => { } }); +test("Range Filters over MAX_FILTER_RANGES zero get INVALID_FILTER", async () => { + for (const version of [Version.DRAFT_19, Version.DRAFT_21, Version.DRAFT_22]) { + const pair = createMockTransportPair(ALPNS[version]); + const { pub, origin } = publisher(pair.server, { session: new NativeSession(pair.server, version, true) }); + for (const fetch of [false, true]) { + const request = requestStream(version); + try { + const name = [1, 4, ...new TextEncoder().encode("test"), 5, ...new TextEncoder().encode("video")]; + const fields = [ + 7, + ...(fetch && version === Version.DRAFT_19 ? [1] : []), + ...name, + ...(fetch && version === Version.DRAFT_19 ? [0, 0, 0, 0] : []), + 1, + 0x25, + 0, + ]; + const encoded = new Reader(undefined, Uint8Array.from([0, fields.length, ...fields]), version); + if (fetch) await pub.runFetch(await Fetch.decode(encoded, version), request.stream); + else await pub.runSubscribe(await Subscribe.decode(encoded, version), request.stream); + await request.stream.writer.closed; + const wire = request.wire(); + expect(await wire.u53()).toBe(RequestError.id); + expect((await RequestError.decode(wire, version)).errorCode).toBe(0x36); + } finally { + request.cancel(); + } + } + origin.close(); + } +}); + +test("RENDEZVOUS_TIMEOUT has a zero cap with TIMEOUT for a requested wait", async () => { + for (const version of [Version.DRAFT_18, Version.DRAFT_21, Version.DRAFT_22]) { + // A wait applies only to a missing publisher; a missing track on a live one does not exist. + for (const [namespace, trackName, live] of [ + ["missing", "video", false], + ["room", "audio", true], + ] as const) { + for (const millis of [undefined, 0, 7]) { + const pair = createMockTransportPair(ALPNS[version]); + const { pub, origin } = publisher(pair.server, { + session: new NativeSession(pair.server, version, true), + }); + const broadcast = live ? publish(origin, Path.from(namespace)) : undefined; + const track = broadcast?.createTrack("video", { timescale: Timescale.MILLI }); + const request = requestStream(version); + const fields = [ + 7, + 1, + namespace.length, + ...new TextEncoder().encode(namespace), + trackName.length, + ...new TextEncoder().encode(trackName), + ...(millis === undefined ? [0] : [1, 0x04, millis]), + ]; + const msg = await Subscribe.decode( + new Reader(undefined, Uint8Array.from([0, fields.length, ...fields]), version), + version, + ); + try { + await pub.runSubscribe(msg, request.stream); + await request.stream.writer.closed; + const wire = request.wire(); + expect(await wire.u53()).toBe(RequestError.id); + expect((await RequestError.decode(wire, version)).errorCode).toBe(millis && !live ? 0x02 : 0x10); + } finally { + track?.close(); + broadcast?.close(); + origin.close(); + request.cancel(); + } + } + } + } +}); + +test("reserved namespace requests get DOES_NOT_EXIST while other dot namespaces are served", async () => { + for (const version of [Version.DRAFT_21, Version.DRAFT_22]) { + for (const path of [".", "./child", ".session", ".session/extension", ".application", ".sessionish"]) { + const pair = createMockTransportPair(ALPNS[version]); + const { pub, origin } = publisher(pair.server, { session: new NativeSession(pair.server, version, true) }); + const broadcast = publish(origin, Path.from(path)); + const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const request = requestStream(version); + try { + await pub.runTrackStatusRequest(trackStatus(path), request.stream); + await request.stream.writer.closed; + const wire = request.wire(); + if (path.split("/")[0] === "." || path.split("/")[0] === ".session") { + expect(await wire.u53()).toBe(RequestError.id); + expect((await RequestError.decode(wire, version)).errorCode).toBe(0x10); + } else { + expect(await wire.u53()).toBe(TrackStatusOk.id(version)); + } + } finally { + request.cancel(); + track.close(); + broadcast.close(); + origin.close(); + } + } + } +}); + /** A request's USE_VALUE token decodes but grants nothing yet, so a SUBSCRIBE outside the grant is still refused. */ test("a request token does not widen the grant", async () => { for (const version of [Version.DRAFT_14, Version.DRAFT_22] as const) { @@ -2889,6 +2994,66 @@ test("REQUEST_UPDATE applies priority and preserves it when omitted", async () = } }); +test("REQUEST_UPDATE accepts delivery timeouts without changing the subscription", async () => { + const fx = fixture(Version.DRAFT_19); + const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const { client } = await runSubscribe( + fx, + new Subscribe({ + requestId: 0n, + trackNamespace: Path.from("test"), + trackName: "video", + subscriberPriority: 128, + }), + ); + try { + const before = track.subscription.peek(); + await client.writer.write(new Uint8Array([0x02, 0, 6, 2, 2, 0x02, 7, 0x04, 9])); + expect(await client.reader.u53()).toBe(RequestOk.id); + await RequestOk.decode(client.reader, fx.version); + expect(track.subscription.peek()).toEqual(before); + } finally { + client.close(); + track.close(); + fx.close(); + } +}); + +test("TRACK_PROPERTY_FILTER on a subscription update closes with PROTOCOL_VIOLATION", async () => { + const fx = fixture(Version.DRAFT_19); + const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const client = await Stream.open(fx.pair.client, { version: fx.version }); + const server = await Stream.accept(fx.pair.server, fx.version); + if (!server) throw new Error("missing subscribe stream"); + const serving = fx.pub + .runSubscribe( + new Subscribe({ + requestId: 0n, + trackNamespace: Path.from("test"), + trackName: "video", + subscriberPriority: 128, + }), + server, + ) + .then( + () => undefined, + (err: unknown) => err, + ); + try { + expect(await client.reader.u53()).toBe(SubscribeOk.id); + await SubscribeOk.decode(client.reader, fx.version); + await client.writer.write(new Uint8Array([0x02, 0, 6, 2, 1, 0x29, 2, 0, 0])); + const failure = await serving; + expect(failure).toBeInstanceOf(ProtocolViolation); + expect(Number((failure as ProtocolViolation).code)).toBe(0x03); + } finally { + client.close(); + track.close(); + fx.close(); + await serving; + } +}); + test("unsupported REQUEST_UPDATE is refused and ends with UPDATE_FAILED", async () => { const fx = fixture(Version.DRAFT_19); const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); @@ -2942,3 +3107,49 @@ test("namespace subscription survives requester FIN and stops on STOP_SENDING", origin.close(); } }); + +test("namespace updates move the prefix after acknowledgement", async () => { + for (const version of [Version.DRAFT_18, Version.DRAFT_21, Version.DRAFT_22]) { + const pair = createMockTransportPair(ALPNS[version]); + const { pub, origin } = publisher(pair.server, { + session: new NativeSession(pair.server, version, false), + requiresSolicitation: true, + }); + const old = publish(origin, Path.from("old/first")); + const fresh = publish(origin, Path.from("new/second")); + const client = await Stream.open(pair.client, { version }); + const server = await Stream.accept(pair.server, version); + if (!server) throw new Error("missing namespace stream"); + const running = pub.runSubscribeNamespace( + new SubscribeNamespace({ requestId: 0n, namespace: Path.from("old") }), + server, + ); + try { + expect(await client.reader.u53()).toBe(RequestOk.id); + await RequestOk.decode(client.reader, version); + expect(await client.reader.u53()).toBe(SubscribeNamespaceEntry.id); + expect((await SubscribeNamespaceEntry.decode(client.reader, version)).suffix).toBe(Path.from("first")); + await client.writer.write(Uint8Array.from([0x02, 0, 8, 2, 1, 0x34])); + // Finishing the same frame must apply it exactly once. + await client.writer.write(Uint8Array.from([1, 3, 110, 101, 119])); + expect(await client.reader.u53()).toBe(SubscribeNamespaceEntryDone.id); + expect((await SubscribeNamespaceEntryDone.decode(client.reader, version)).suffix).toBe(Path.from("first")); + expect(await client.reader.u53()).toBe(RequestOk.id); + await RequestOk.decode(client.reader, version); + expect(await client.reader.u53()).toBe(SubscribeNamespaceEntry.id); + expect((await SubscribeNamespaceEntry.decode(client.reader, version)).suffix).toBe(Path.from("second")); + if (version >= Version.DRAFT_21) { + await client.writer.write(Uint8Array.from([0x02, 0, 6, 4, 1, 0x34, 1, 1, 46])); + expect(await client.reader.u53()).toBe(RequestError.id); + expect((await RequestError.decode(client.reader, version)).errorCode).toBe(0x10); + await running; + } + } finally { + client.close(); + origin.close(); + old.close(); + fresh.close(); + await running; + } + } +}); diff --git a/js/net/src/ietf/publisher.ts b/js/net/src/ietf/publisher.ts index fe31d5beb97..5d51da90e76 100644 --- a/js/net/src/ietf/publisher.ts +++ b/js/net/src/ietf/publisher.ts @@ -35,6 +35,7 @@ import { type RequestKind, requestReason, toRequestCode } from "./error.ts"; import { type Fetch, FetchError, FetchHeader } from "./fetch.ts"; import * as Filter from "./filter.ts"; import * as Message from "./message.ts"; +import * as Namespace from "./namespace.ts"; import { FetchFrame, Frame, Group as GroupMessage } from "./object.ts"; import { Parameters } from "./parameters.ts"; import { fromWire, toWire } from "./priority.ts"; @@ -47,7 +48,7 @@ import { PublishNamespaceUpdate, } from "./publish_namespace.ts"; import { RequestError, RequestOk } from "./request.ts"; -import { cancelled, finCancels } from "./request_stream.ts"; +import { cancelled, finCancels, namespaceUpdate, refuseReserved } from "./request_stream.ts"; import { GroupOrder, type Subscribe, SubscribeError, SubscribeOk, SubscribeUpdate } from "./subscribe.ts"; import { type SubscribeNamespace, @@ -354,6 +355,10 @@ export class Publisher { * @internal */ async runSubscribe(msg: Subscribe, stream: Stream) { + if (Namespace.reserved(msg.trackNamespace, this.#session.version)) { + await refuseReserved(stream, this.#session.version); + return; + } // Only a subscription we would serve holds a slot, as in Rust: a refused one ends at // once. A peer past the cap loses the session. const charged = msg.forward && !msg.rangeFilters && !this.#denied(msg.trackNamespace); @@ -388,7 +393,14 @@ export class Publisher { : undefined; if (unsupported) { - refusal = { errorCode: toRequestCode("not_supported", "subscribe", version), reasonPhrase: unsupported }; + refusal = { + errorCode: toRequestCode( + msg.rangeFilters && msg.forward ? "invalid_filter" : "not_supported", + "subscribe", + version, + ), + reasonPhrase: unsupported, + }; } else if (this.#denied(name)) { // Serve only what our grant lets us publish. Checked before resolving, so a denied // request never reaches the origin. @@ -402,7 +414,7 @@ export class Publisher { stream.abort(cancel); return; } - refusal = this.#failed(err, "subscribe"); + refusal = this.#failed(err, "subscribe", msg.rendezvous); } } @@ -428,7 +440,26 @@ export class Publisher { let ranking: Priority | undefined; try { - const info = await untilAborted(track.info(), left.signal); + let info: Awaited>; + try { + info = await untilAborted(track.info(), left.signal); + } catch (err) { + const failed = error(err); + if ( + !(failed instanceof StreamError) || + (failed.code !== StreamCode.NotFound && failed.code !== StreamCode.Unroutable) + ) + throw err; + // The broadcast resolved, so only a vanished route still means a missing publisher; + // a missing track is the publisher's answer. + await this.#refuse( + stream, + msg.requestId, + SubscribeError.id, + this.#failed(err, "subscribe", msg.rendezvous && failed.code === StreamCode.Unroutable), + ); + return; + } // A Timestamp goes out only when this SUBSCRIBE_OK actually carries TIMESCALE. // Drafts 14-16 never write that property, so their objects stay unstamped. const timescale = @@ -570,12 +601,17 @@ export class Publisher { if (err instanceof MalformedAuthToken) throw await refuse("malformed_auth_token", err.message); throw err; } + if (params.trackPropertyFilter) + throw new ProtocolViolation( + "TRACK_PROPERTY_FILTER is only allowed on SUBSCRIBE_TRACKS updates", + ); const unsupported = params.forward === false || params.bytes.size > 0 || params.rangeFilters || - params.trackPropertyFilter || - [...params.vars.keys()].some((key) => key !== 0x10n && key !== 0x20n); + [...params.vars.keys()].some( + (key) => key !== 0x02n && key !== 0x06n && key !== 0x10n && key !== 0x20n, + ); if (unsupported) throw await refuse("not_supported", "REQUEST_UPDATE parameters not supported"); // update() replaces every option, so carry the rest over as Rust does. if (params.subscriberPriority !== undefined) @@ -1102,9 +1138,13 @@ export class Publisher { } async #runSubscribeNamespace(msg: SubscribeNamespace, stream: Stream) { + if (Namespace.reserved(msg.namespace, this.#session.version)) { + await refuseReserved(stream, this.#session.version); + return; + } if (this.#withdrawal.closing.peek()) return; const version = this.#session.version; - const prefix = msg.namespace; + let prefix = msg.namespace; const legacy = version === Version.DRAFT_14 || version === Version.DRAFT_15; // Draft-14/15: the open PUBLISH_NAMESPACE request per advertised suffix. @@ -1117,6 +1157,12 @@ export class Publisher { }; const ending = cancelled(stream, version); + const readUpdate = () => + namespaceUpdate(stream.reader, version).then( + (update) => ({ update }), + (err) => ({ error: error(err) }), + ); + let updating = version >= Version.DRAFT_18 ? readUpdate() : undefined; try { // Send OK response if (version === Version.DRAFT_14) { @@ -1201,10 +1247,48 @@ export class Publisher { // Wait for the next change, or for the peer to unsubscribe. const next = await (retry - ? race([changed, this.#withdrawal.closing, ending, retryAfter(retry).then(() => advertised)]) - : race([changed, this.#withdrawal.closing, ending])); + ? race([ + changed, + this.#withdrawal.closing, + ending, + ...(updating !== undefined ? [updating] : []), + retryAfter(retry).then(() => advertised), + ]) + : race([changed, this.#withdrawal.closing, ending, ...(updating !== undefined ? [updating] : [])])); dispose(); if (!next || next === true) break; + if (typeof next === "object" && "error" in next) throw next.error; + if (typeof next === "object" && "update" in next) { + const update = next.update; + updating = undefined; + if (!update) continue; + this.#session.spendRequest(update.requestId); + if (update.refused || (update.prefix !== undefined && Namespace.reserved(update.prefix, version))) { + await stream.writer.u53(RequestError.id); + await new RequestError({ + requestId: undefined, + errorCode: toRequestCode( + update.refused ?? "does_not_exist", + "subscribe_namespace", + version, + ), + reasonPhrase: "namespace update refused", + }).encode(stream.writer, version); + break; + } + if (update.prefix !== undefined && update.prefix !== prefix) { + for (const suffix of ns.active.keys()) await target.withdraw(suffix); + ns.active.clear(); + ns.offered.clear(); + ns.refused.clear(); + prefix = update.prefix; + // A new cursor starts its backoff fresh, as in Rust. + retry = 0; + } + await stream.writer.u53(RequestOk.id); + await new RequestOk({ requestId: undefined }).encode(stream.writer, version); + updating = readUpdate(); + } } // Withdraw before the ask stream FINs, as Rust does: a peer that reads that @@ -1216,10 +1300,14 @@ export class Publisher { const e = error(err); console.debug(`subscribe_namespace stream error: ${reason(e)}`); stream.abort(e); - if (this.#withdrawal.closing.peek()) throw e; + if (e instanceof ProtocolViolation || this.#withdrawal.closing.peek()) throw e; } finally { // This subscription's advertisements die with it. await withdrawAll(); + if (updating !== undefined) { + stream.reader.stop(new Error("namespace subscription ended")); + await updating; + } } } @@ -1617,6 +1705,10 @@ export class Publisher { * @internal */ async runTrackStatusRequest(msg: TrackStatusRequest, stream: Stream) { + if (Namespace.reserved(msg.trackNamespace, this.#session.version)) { + await refuseReserved(stream, this.#session.version); + return; + } const version = this.#session.version; const name = msg.trackNamespace; const denied: Refusal = { @@ -1710,7 +1802,11 @@ export class Publisher { * * @internal */ - async runSubscribeTracks(stream: Stream) { + async runSubscribeTracks(stream: Stream, namespace?: Path.Valid) { + if (namespace !== undefined && Namespace.reserved(namespace, this.#session.version)) { + await refuseReserved(stream, this.#session.version); + return; + } const version = this.#session.version; await stream.writer.u53(RequestError.id); await new RequestError({ @@ -1728,6 +1824,17 @@ export class Publisher { async runFetch(msg: Fetch, stream: Stream) { this.#fetches.acquire(); try { + if (msg.trackNamespace !== undefined && Namespace.reserved(msg.trackNamespace, this.#session.version)) { + await refuseReserved(stream, this.#session.version); + return; + } + if (msg.rangeFilters) { + await this.#refuse(stream, msg.requestId, FetchError.id, { + errorCode: toRequestCode("invalid_filter", "fetch", this.#session.version), + reasonPhrase: "Range Filters exceed MAX_FILTER_RANGES=0", + }); + return; + } await this.#refuseUnsupported(stream, msg.requestId, "fetch", FetchError.id, "FETCH is not supported"); } finally { this.#fetches.release(); @@ -1767,11 +1874,13 @@ export class Publisher { } /** What a request that failed to resolve is refused with. */ - #failed(err: unknown, kind: RequestKind): Refusal { + #failed(err: unknown, kind: RequestKind, wait = false): Refusal { const e = error(err); const condition = e instanceof StreamError && (e.code === StreamCode.NotFound || e.code === StreamCode.Unroutable) - ? "does_not_exist" + ? wait + ? "timeout" + : "does_not_exist" : "internal"; return { errorCode: toRequestCode(condition, kind, this.#session.version), reasonPhrase: reason(e) }; } diff --git a/js/net/src/ietf/request_stream.test.ts b/js/net/src/ietf/request_stream.test.ts new file mode 100644 index 00000000000..057839026fb --- /dev/null +++ b/js/net/src/ietf/request_stream.test.ts @@ -0,0 +1,35 @@ +import { expect, test } from "bun:test"; +import { ProtocolViolation } from "../error.ts"; +import { Reader } from "../stream.ts"; +import * as Varint from "../varint.ts"; +import { namespaceUpdate } from "./request_stream.ts"; +import { Version } from "./version.ts"; + +test("an oversized or truncated namespace update type is a protocol violation", async () => { + // Both drafts use leading-ones varints. + for (const version of [Version.DRAFT_18, Version.DRAFT_21]) { + const oversized = Varint.encodeLeadingOnes(2n ** 53n); + // A two-byte varint prefix with its second byte missing. + const truncated = Uint8Array.of(0x80); + for (const bytes of [oversized, truncated]) { + const reader = new Reader(undefined, bytes, version); + await expect(namespaceUpdate(reader, version)).rejects.toBeInstanceOf(ProtocolViolation); + } + } +}); + +test("namespace update framing refuses duplicate prefix parameters", async () => { + for (const version of [Version.DRAFT_18, Version.DRAFT_21]) { + const body = [2, 2, 0x34, 1, 1, 97, 0, 1, 1, 98]; + const reader = new Reader(undefined, Uint8Array.from([2, 0, body.length, ...body]), version); + await expect(namespaceUpdate(reader, version)).rejects.toBeInstanceOf(ProtocolViolation); + } +}); + +test("a repeated namespace update token is a request refusal", async () => { + for (const version of [Version.DRAFT_18, Version.DRAFT_21]) { + const body = [2, 2, 3, 3, 3, 0, 170, 0, 3, 3, 0, 170]; + const reader = new Reader(undefined, Uint8Array.from([2, 0, body.length, ...body]), version); + expect(await namespaceUpdate(reader, version)).toEqual({ requestId: 2n, refused: "malformed_auth_token" }); + } +}); diff --git a/js/net/src/ietf/request_stream.ts b/js/net/src/ietf/request_stream.ts index 85fcab4efc5..4bb717571a6 100644 --- a/js/net/src/ietf/request_stream.ts +++ b/js/net/src/ietf/request_stream.ts @@ -1,5 +1,12 @@ import { race } from "@moq/signals"; -import type { Stream } from "../stream.ts"; +import { ProtocolViolation, StreamError } from "../error.ts"; +import type * as Path from "../path.ts"; +import type { Reader, Stream } from "../stream.ts"; +import { type RequestCondition, toRequestCode } from "./error.ts"; +import * as Message from "./message.ts"; +import { Parameters } from "./parameters.ts"; +import { RequestError } from "./request.ts"; +import { MalformedAuthToken } from "./token.ts"; import { type IetfVersion, Version } from "./version.ts"; /** Whether the draft treats the requester finishing its messages as cancellation. */ @@ -21,3 +28,43 @@ export async function cancelled(stream: Stream, version: IetfVersion): Promise undefined); await race([read, stream.writer.closed]).catch(() => undefined); } + +/** Refuse an unrecognized reserved namespace before it reaches the application. */ +export async function refuseReserved(stream: Stream, version: IetfVersion): Promise { + await stream.writer.u53(RequestError.id); + await new RequestError({ + requestId: undefined, + errorCode: toRequestCode("does_not_exist", "subscribe", version), + reasonPhrase: "reserved namespace does not exist", + }).encode(stream.writer, version); + stream.close(); +} + +/** + * Read one whole namespace update without abandoning a partial frame. + * @internal + */ +export async function namespaceUpdate( + reader: Reader, + version: IetfVersion, +): Promise<{ requestId: bigint; prefix?: Path.Valid; refused?: RequestCondition } | undefined> { + if (await reader.done()) return undefined; + try { + // Inside the normalization, so an oversized or truncated type is malformed too. + if ((await reader.u53()) !== 0x02) throw new ProtocolViolation("expected namespace REQUEST_UPDATE"); + return await Message.decode(reader, async (body) => { + const requestId = await body.u62(); + const params = await Parameters.decode(body, version, "namespace-update"); + return { + requestId, + prefix: params.namespacePrefix, + refused: undefined, + }; + }); + } catch (err) { + if (err instanceof MalformedAuthToken && err.requestId !== undefined) + return { requestId: err.requestId, refused: "malformed_auth_token" }; + if (err instanceof ProtocolViolation || err instanceof StreamError) throw err; + throw new ProtocolViolation("malformed namespace REQUEST_UPDATE", { cause: err }); + } +} diff --git a/js/net/src/ietf/subscribe.ts b/js/net/src/ietf/subscribe.ts index 4faf34903ee..baa1f7f531e 100644 --- a/js/net/src/ietf/subscribe.ts +++ b/js/net/src/ietf/subscribe.ts @@ -81,6 +81,9 @@ export class Subscribe { /** Whether the request carried a Range Filter, which we refuse. Never encoded. */ rangeFilters: boolean; + /** Whether RENDEZVOUS_TIMEOUT requested a wait; never encoded. */ + rendezvous: boolean; + constructor({ requestId, trackNamespace, @@ -92,6 +95,7 @@ export class Subscribe { propertiesWanted, forward, rangeFilters, + rendezvous, }: { requestId: bigint; trackNamespace: Path.Valid; @@ -103,6 +107,7 @@ export class Subscribe { propertiesWanted?: boolean; forward?: boolean; rangeFilters?: boolean; + rendezvous?: boolean; }) { this.requestId = requestId; this.trackNamespace = trackNamespace; @@ -114,6 +119,7 @@ export class Subscribe { this.propertiesWanted = propertiesWanted ?? true; this.forward = forward ?? true; this.rangeFilters = rangeFilters ?? false; + this.rendezvous = rendezvous ?? false; } async #encode(w: Writer, version: IetfVersion): Promise { @@ -228,6 +234,7 @@ export class Subscribe { propertiesWanted: params.includeProperties ?? true, forward: params.forward ?? true, rangeFilters: params.rangeFilters, + rendezvous: (params.vars.get(0x04n) ?? 0n) > 0n, }); } } diff --git a/js/net/src/ietf/subscriber.ts b/js/net/src/ietf/subscriber.ts index 0b8564312a0..dce8758941a 100644 --- a/js/net/src/ietf/subscriber.ts +++ b/js/net/src/ietf/subscriber.ts @@ -33,6 +33,7 @@ import { DuplicateTrackAlias, RetiredTrackAlias, TrackAliases } from "./aliases. import * as Cluster from "./cluster.ts"; import { ObjectDatagram } from "./datagram.ts"; import { requestReason, toRequestCode } from "./error.ts"; +import * as Namespace from "./namespace.ts"; import { decodeObjectTime, Frame, type Group as GroupMessage, hasFirstObjectBit, ObjectIdGap } from "./object.ts"; import { fromWire, toWire } from "./priority.ts"; import { type Publish, PublishDone, PublishError, publishDoneClean } from "./publish.ts"; @@ -45,7 +46,7 @@ import { PublishNamespaceUpdate, } from "./publish_namespace.ts"; import { RequestError, RequestOk } from "./request.ts"; -import { finCancels } from "./request_stream.ts"; +import { finCancels, refuseReserved } from "./request_stream.ts"; import { joinFilter, Subscribe, SubscribeError, SubscribeOk, Unsubscribe } from "./subscribe.ts"; import { PublishBlocked, @@ -981,6 +982,10 @@ export class Subscriber { * @internal */ async runPublishNamespace(msg: PublishNamespace, stream: Stream) { + if (Namespace.reserved(msg.trackNamespace, this.#session.version)) { + await refuseReserved(stream, this.#session.version); + return; + } const version = this.#session.version; const path = msg.trackNamespace; @@ -1176,6 +1181,10 @@ export class Subscriber { * @internal */ async runPublish(msg: Publish, stream: Stream) { + if (Namespace.reserved(msg.trackNamespace, this.#session.version)) { + await refuseReserved(stream, this.#session.version); + return; + } const version = this.#session.version; // We decline the method itself rather than this particular track, which would be diff --git a/quest/m1/ietf-malformed-close.md b/quest/m1/ietf-malformed-close.md index 69795632217..7a2e3331de4 100644 --- a/quest/m1/ietf-malformed-close.md +++ b/quest/m1/ietf-malformed-close.md @@ -127,4 +127,3 @@ behaviour moves closer to the drafts. ## Related - [#5107](https://github.com/moq-dev/moq/pull/5107) - landed request-token decode and AUTH_TOKEN_CACHE_OVERFLOW -- [moq-transport request codes](/quest/m2/ietf-request-codes.md) - the request-level half of the same validator report diff --git a/quest/m2/README.md b/quest/m2/README.md index b07f2dbddd6..3e894bb2f6e 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -157,7 +157,6 @@ ranked just below deterministic TS legs, which it requires. - [VAAPI encode and decode](/quest/m2/video-vaapi.md) - H.265 encode and decode, pre-generated bindings, and pooled resize surfaces, including the moq-dev/vaapi release that carries them - [GPU capacity and health](/quest/m2/gpu-health.md) - moq-video reports each device's sessions, memory, utilization, and health on NVIDIA, AMD, and Intel alike - [A release carries multi-vendor GPU input](/quest/m2/gpu-release.md) - `release` carries the GPU surface validated on AMD and Intel; health follows separately -- [moq-transport request codes](/quest/m2/ietf-request-codes.md) - Range Filters (INVALID_FILTER), reserved namespaces, and RENDEZVOUS_TIMEOUT get the draft's answer, or a recorded fallback code, and the deliberate deviations are documented - [Runtime trait](/quest/m2/runtime-trait.md) - one runtime trait for spawn and time replaces web-async, with tokio, browser, io_uring, and sim implementations - [QUIC on the sim](/quest/m2/quic-sim.md) - the sim drives `moq-quic` over in-memory datagrams with latency and loss - [Seeded sim](/quest/m2/sim-seed.md) - sim tests draw every jitter from one seeded generator and replay bit-exact diff --git a/quest/m2/ietf-request-codes.md b/quest/m2/ietf-request-codes.md deleted file mode 100644 index d11977ae16b..00000000000 --- a/quest/m2/ietf-request-codes.md +++ /dev/null @@ -1,76 +0,0 @@ -# [M] moq-transport requests get the draft's answer - -## Goal - -On draft-18 and draft-21, `rs/moq-net` and `js/net` answer these requests -the way the drafts say, without closing the session unless noted. Each answer uses the -draft's code, or an existing code where the exact one costs more than it -is worth and the fallback is recorded in `doc/concept/standard.md`: - -- **Range Filters** get REQUEST_ERROR INVALID_FILTER (0x36), not - NOT_SUPPORTED (draft-19 and later). We advertise no MAX_FILTER_RANGES, so - the default of 0 applies (draft-21 §9.1.6) and every Range Filter is over - the limit. This covers SUBSCRIBE and FETCH alike: both refuse Range - Filters today (`run_subscribe_stream` and `run_fetch_stream` in - `ietf/publisher.rs`). -- **Draft-21 reserved namespaces:** draft-21 §2.4.2 and the `.session` - rules (§6.5) ask for REQUEST_ERROR DOES_NOT_EXIST, without passing the - request to the application, for: - - a request for an unrecognized `.session` track or namespace; - - a `.session` namespace with an empty track name; - - a namespace whose first field is exactly `.`. - - Only these short-circuit. Any other reserved namespace (a first field - starting with `.`) still goes to the application, as §2.4.2 requires. -- **RENDEZVOUS_TIMEOUT:** our wait is capped at 0, which draft-21 §9.20.7 - allows. If a SUBSCRIBE asks to wait and there is no publisher, it gets - TIMEOUT at once. A request that is absent or 0 still gets DOES_NOT_EXIST. - This fixes the two quic-zig `rendezvous-timeout` cells in the interop - matrix. -- **OBJECT_DELIVERY_TIMEOUT (0x02) and SUBGROUP_DELIVERY_TIMEOUT (0x06)** - on REQUEST_UPDATE are accepted and ignored, as SUBSCRIBE already does - (`ietf/subscribe.rs`). Today `ietf/request_stream.rs` decodes both and - marks the update unsupported. -- **REQUEST_UPDATE on a SUBSCRIBE_NAMESPACE stream** is read, so its - TRACK_NAMESPACE_PREFIX applies (a #5028 follow-up). -- **TRACK_PROPERTY_FILTER on a subscription's REQUEST_UPDATE** closes the - session with PROTOCOL_VIOLATION instead of answering REQUEST_ERROR: - draft-19 allows it only on SUBSCRIBE_TRACKS and its updates (a #5028 - follow-up). - -## Plan - -Decided with the maintainer on 2026-10-04 and 2026-10-05: - -- **Deliberate deviations stay.** DUPLICATE_SUBSCRIPTION and PREFIX_OVERLAP - are never sent, because moq-net deduplicates. OBJECT_DELIVERY_TIMEOUT and - SUBGROUP_DELIVERY_TIMEOUT never drop an object or reset a subgroup: they - would need wall-clock delivery deadlines, and moq-net's latency - enforcement is presentation time only (#2890). The rendezvous wait is - capped at 0. Each deviation gets a line in the "Deliberate deviations" - subsection of `doc/concept/standard.md`, so the next validator run has a - reason to point at. Drop the hard-coded count from that subsection's - intro, and update the "Refused, not fatal" bullet above it for the - answers this quest changes. -- **Exact codes when cheap.** INVALID_FILTER becomes a request code. Where - one costs more than it is worth, the fallback in the Goal applies. -- **TIMEOUT, not a timer.** The 0 cap means nothing waits, so no request is - ever parked. The reply depends only on whether the parameter asked for a - wait. `ietf/subscribe.rs` parses RENDEZVOUS_TIMEOUT and discards it; - keep it as far as the publisher's track lookup (`run_subscribe_stream` - in `ietf/publisher.rs`). `Error::Timeout` already maps to - TIMEOUT (`ietf/error.rs`). -- Decided 2026-10-08: build on - [#5028](https://github.com/moq-dev/moq/pull/5028) (merged), which rewrote - the same parameter decode and left the REQUEST_UPDATE delivery timeouts to - this quest. -- One regression test per case, failing without its fix and asserting the - draft's code, or the fallback recorded in `doc/concept/standard.md`. - Mirror in `js/net/src/ietf` in the same PR. - -Public API: none expected. Wire: none new; replies move closer to the -drafts. - -## Related - -- [Malformed moq-transport input](/quest/m1/ietf-malformed-close.md) - the session-level half of the same validator report diff --git a/rs/moq-net/src/fuzz.rs b/rs/moq-net/src/fuzz.rs index 6a39dbc9ed4..4eb964978a7 100644 --- a/rs/moq-net/src/fuzz.rs +++ b/rs/moq-net/src/fuzz.rs @@ -607,6 +607,7 @@ impl Default for Messages { fill: None, properties_wanted: false, forward: true, + rendezvous: false, range_filters: false, authorization_token: None, }, diff --git a/rs/moq-net/src/ietf/error.rs b/rs/moq-net/src/ietf/error.rs index 6a495eaf1d4..532d3c19af1 100644 --- a/rs/moq-net/src/ietf/error.rs +++ b/rs/moq-net/src/ietf/error.rs @@ -200,6 +200,9 @@ pub(crate) mod request { const INVALID_RANGE_14: u64 = 0x5; const INVALID_RANGE: u64 = 0x11; + /// A Range Filter exceeds MAX_FILTER_RANGES (draft-19 and later). + pub(crate) const INVALID_FILTER: u64 = 0x36; + /// A joining FETCH named no active subscription. Removed from the registry in draft-20. const INVALID_JOINING_REQUEST_ID_14: u64 = 0x7; const INVALID_JOINING_REQUEST_ID: u64 = 0x32; diff --git a/rs/moq-net/src/ietf/namespace.rs b/rs/moq-net/src/ietf/namespace.rs index 53d630c8eea..36c15b0be01 100644 --- a/rs/moq-net/src/ietf/namespace.rs +++ b/rs/moq-net/src/ietf/namespace.rs @@ -85,9 +85,61 @@ pub fn decode_namespace(r: &mut Decoder<'_>) -> Result, DecodeErro Ok(from_tuple(&parts)) } +/// Session namespaces belong to the transport, and none of our extensions defines one. +pub(super) fn refusal(namespace: &Path, version: super::Version) -> Option> { + if matches!( + version, + super::Version::Draft14 + | super::Version::Draft15 + | super::Version::Draft16 + | super::Version::Draft17 + | super::Version::Draft18 + | super::Version::Draft19 + | super::Version::Draft20 + ) { + return None; + } + // Reserved literals contain no escapes. Comparing the first escaped field keeps + // a slash within a field and an empty first field from becoming a reserved name. + if !matches!(namespace.as_str().split('/').next(), Some("." | ".session")) { + return None; + } + Some(super::RequestError { + request_id: None, + error_code: super::error::request::to_code( + &crate::Error::NotFound, + super::error::request::Kind::Subscribe, + version, + ), + reason_phrase: "reserved namespace does not exist".into(), + retry_interval: 0, + }) +} + #[cfg(test)] mod tests { use super::*; + + #[test] + fn reserved_namespaces_keep_exact_tuple_fields_and_draft_boundaries() { + for (fields, reserved) in [ + (vec!["."], true), + (vec![".", "child"], true), + (vec![".session"], true), + (vec![".session", "extension"], true), + (vec![".session/extension"], false), + (vec!["", ".session"], false), + (vec![".application"], false), + (vec![".sessionish"], false), + ] { + let parts: Vec<_> = fields.iter().map(|field| (*field).to_owned()).collect(); + let path = from_tuple(&parts); + for version in [super::super::Version::Draft21, super::super::Version::Draft22] { + assert_eq!(refusal(&path, version).is_some(), reserved, "{version}: {fields:?}"); + } + assert!(refusal(&path, super::super::Version::Draft20).is_none()); + } + } use crate::coding::Form; const FORM: Form = Form::LeadingOnes { seven: false }; diff --git a/rs/moq-net/src/ietf/publisher.rs b/rs/moq-net/src/ietf/publisher.rs index b7eb29f52e4..ec5fef0dc40 100644 --- a/rs/moq-net/src/ietf/publisher.rs +++ b/rs/moq-net/src/ietf/publisher.rs @@ -15,7 +15,7 @@ use crate::transport::poll::SendStream as _; use crate::{ AsPath, DecodeError, Error, Timescale, Timestamp, - coding::{Encode as _, Encoder, Stream, Writer}, + coding::{Decode as _, Encode as _, Encoder, Stream, Writer}, ietf::{self, Control, EndLocation, FetchHeader, FetchType, Filter, GroupOrder, Location, RequestId}, priority::{Priority, PriorityHandle, PriorityQueue}, track::{Order, Subscription}, @@ -58,6 +58,17 @@ fn track_properties(info: &track::Info, wanted: bool) -> ietf::Properties { } } +/// The rendezvous cap is zero, but asking to wait still makes a missing publisher a timeout. +/// Once the broadcast resolves, a missing track is the publisher's answer and stays DOES_NOT_EXIST. +fn rendezvous_error(error: Error, requested: bool, resolved: bool) -> Error { + let missing = match &error { + Error::Unroutable | Error::Stream(crate::StreamError::Unroutable) => true, + Error::NotFound | Error::Stream(crate::StreamError::NotFound) => !resolved, + _ => false, + }; + if requested && missing { Error::Timeout } else { error } +} + enum FillStep { Batch, Partial(frame::Consumer), @@ -360,6 +371,36 @@ impl Target { None => Poll::Pending, } } + + fn poll_event( + &mut self, + finished: &mut bool, + version: Version, + cx: &mut std::task::Context<'_>, + ) -> Poll { + if matches!( + version, + Version::Draft14 | Version::Draft15 | Version::Draft16 | Version::Draft17 + ) { + return self.poll_closed(finished, version, cx).map(NamespaceEvent::Closed); + } + let Some(stream) = self.stream() else { + return Poll::Pending; + }; + if !*finished { + match stream + .reader + .poll_decode_maybe::(cx) + { + Poll::Ready(Ok(Some(update))) => return Poll::Ready(NamespaceEvent::Request(update)), + Poll::Ready(Ok(None)) if !super::request_stream::fin_cancels(version) => *finished = true, + Poll::Ready(Ok(None)) => return Poll::Ready(NamespaceEvent::Closed(Ok(()))), + Poll::Ready(Err(err)) => return Poll::Ready(NamespaceEvent::Closed(Err(err))), + Poll::Pending => {} + } + } + stream.writer.poll_closed(cx).map(NamespaceEvent::Closed) + } } /// One announce loop's state: where its advertisements go, and what the peer holds. @@ -376,6 +417,8 @@ struct Namespaces { permit: crate::auth::Permit, /// The auth epoch last applied to `permit`. epoch: u64, + /// Whether this discovery cursor includes hidden namespaces. + hidden: bool, } impl Namespaces { @@ -387,6 +430,7 @@ impl Namespaces { requests: HashMap::new(), permit: Default::default(), epoch: 0, + hidden: false, } } @@ -436,6 +480,8 @@ impl Served { enum NamespaceEvent { /// The session or stream ended, with the result to surface. Closed(Result<(), Error>), + /// A requester changes the namespace prefix. + Request(super::request_stream::NamespaceUpdate), /// An origin-level route (un)announce: whether it is active and whether it /// restarts, `None` once the announce stream ends. Update(Option<(crate::announce::Announce, bool, bool)>), @@ -745,7 +791,7 @@ where .maybe_boxed() } // SUBSCRIBE_TRACKS asks for every track under a prefix via PUBLISH, which we - // never send. The body is already framed off and draft-17+ replies carry no + // never send. Read its prefix to recognize reserved namespaces; replies carry no // Request ID, so there is nothing to decode before refusing. ietf::SUBSCRIBE_TRACKS_ID if !matches!( @@ -753,6 +799,16 @@ where Version::Draft14 | Version::Draft15 | Version::Draft16 | Version::Draft17 ) => { + RequestId::decode(&mut data, this.version)?; + let namespace = super::namespace::decode_namespace(&mut data)?; + if let Some(error) = super::namespace::refusal(&namespace, this.version) { + return Ok(async move { + if let Err(err) = super::request_stream::reject(stream, error).await { + tracing::debug!(%err, "reserved namespace refusal failed"); + } + } + .maybe_boxed()); + } async move { let reason = "SUBSCRIBE_TRACKS is not supported"; if let Err(err) = this.reject_namespace_request(stream, None, reason).await { @@ -821,6 +877,9 @@ where let join = (!Filter::is_draft20(self.version)).then(|| self.register_join(msg.request_id)); async move { let _join = join; + if let Some(error) = super::namespace::refusal(&msg.track_namespace, self.version) { + return super::request_stream::reject(stream, error).await; + } let request_id = msg.request_id; let track_name = msg.track_name.clone(); let absolute = self.origin.absolute(&msg.track_namespace).to_owned(); @@ -858,9 +917,16 @@ where .await; } if msg.range_filters { - return self - .reject_subscribe(stream, request_id, &Error::Unsupported, "range filters not supported") - .await; + return super::request_stream::reject( + stream, + ietf::RequestError { + request_id: None, + error_code: request::INVALID_FILTER, + reason_phrase: "Range Filters exceed MAX_FILTER_RANGES=0".into(), + retry_interval: 0, + }, + ) + .await; } // Held for the life of the subscription, and while the application verifies its // token. A peer past its limits loses the session. @@ -956,12 +1022,22 @@ where // The reason is the origin's, not ours: a dynamic router refusing on // authorization or a drain says so, and only an unroutable path means the // broadcast is not here. - Err(err) => return Ok(Subscribed::Refused(err.to_string(), err)), + Err(err) => { + return Ok(Subscribed::Refused( + err.to_string(), + rendezvous_error(err, msg.rendezvous, false), + )); + } }; let track = match broadcast.track(&msg.track_name) { Ok(track) => track, - Err(err) => return Ok(Subscribed::Refused(err.to_string(), err)), + Err(err) => { + return Ok(Subscribed::Refused( + err.to_string(), + rendezvous_error(err, msg.rendezvous, true), + )); + } }; let order = msg.group_order.to_order(); @@ -973,7 +1049,12 @@ where // right below, before anything is served. let (cache, mut track) = match track.subscribe(subscription.clone()).await { Ok(subscribed) => (track, subscribed), - Err(err) => return Ok(Subscribed::Refused(err.to_string(), err)), + Err(err) => { + return Ok(Subscribed::Refused( + err.to_string(), + rendezvous_error(err, msg.rendezvous, true), + )); + } }; // A relay's copy that went idle cannot say where its live edge is until its @@ -1217,6 +1298,8 @@ where enum Turn { // The track and any fill finished, or the stream failed. Served(Result<(), Error>), + // Reading the requester's next update failed. + Malformed(Error), // The peer cancelled, or the session ended. Cancelled, // A REQUEST_UPDATE, already decoded. @@ -1257,12 +1340,12 @@ where Poll::Ready(Ok(Some(FollowUp::Update(body)))) => { return Poll::Ready(match Update::decode_legacy(&body, self.version) { Ok(update) => Turn::Update(update), - Err(err) => Turn::Served(Err(err)), + Err(err) => Turn::Malformed(err), }); } // UNSUBSCRIBE, or the control stream going away. Poll::Ready(Ok(Some(FollowUp::End) | None)) => return Poll::Ready(Turn::Cancelled), - Poll::Ready(Err(err)) => return Poll::Ready(Turn::Served(Err(err))), + Poll::Ready(Err(err)) => return Poll::Ready(Turn::Malformed(err)), Poll::Pending => {} } } else { @@ -1284,7 +1367,7 @@ where *finished = true } Poll::Ready(Ok(None)) => return Poll::Ready(Turn::Cancelled), - Poll::Ready(Err(err)) => return Poll::Ready(Turn::Served(Err(err))), + Poll::Ready(Err(err)) => return Poll::Ready(Turn::Malformed(err)), Poll::Pending => {} } } @@ -1310,14 +1393,17 @@ where let answer = self.version != Version::Draft14; match turn { - // An update the draft answers by closing the session, such as one whose - // AUTHORIZATION TOKEN names an alias, closes it rather than only ending this - // subscription, as the same token on the request itself would. - Turn::Served(Err(err @ Error::Decode(crate::coding::DecodeError::Session(_)))) => { - self.session.clone().close( - super::error::to_session_code(&crate::SessionError::from(&err)), - &err.to_string(), - ); + // A malformed update, such as one whose AUTHORIZATION TOKEN names an alias, + // closes the session rather than only ending this subscription, as the same + // token on the request itself would. A source track's decode failure is not + // this requester's fault, so it reaches Served and ends only this subscription. + Turn::Malformed(err) => { + if let Error::Decode(_) = err { + self.session.clone().close( + super::error::to_session_code(&crate::SessionError::from(&err)), + &err.to_string(), + ); + } return Some(Served::Track(Err(err))); } Turn::Served(res) => return Some(Served::Track(res)), @@ -1879,18 +1965,27 @@ where return Err(err); } }; + let namespace = match &msg.fetch_type { + FetchType::Standalone { namespace, .. } | FetchType::Filtered { namespace, .. } => Some(namespace), + _ => None, + }; + if let Some(error) = namespace.and_then(|namespace| super::namespace::refusal(namespace, self.version)) { + return super::request_stream::reject(stream, error).await; + } let priority = super::priority::from_wire(msg.subscriber_priority); // Serving a Range Filter unfiltered would deliver objects the subscriber excluded. if msg.range_filters { - return self - .reject_fetch( - stream, - msg.request_id, - &Error::Unsupported, - "range filters not supported", - ) - .await; + return super::request_stream::reject( + stream, + ietf::RequestError { + request_id: None, + error_code: request::INVALID_FILTER, + reason_phrase: "Range Filters exceed MAX_FILTER_RANGES=0".into(), + retry_interval: 0, + }, + ) + .await; } // FILL_TIMEOUT=0 asks for cache only, and any budget ends in Timed-Out gaps we @@ -2385,6 +2480,9 @@ where mut stream: Stream, msg: ietf::TrackStatus<'_>, ) -> Result<(), Error> { + if let Some(error) = super::namespace::refusal(&msg.track_namespace, self.version) { + return super::request_stream::reject(stream, error).await; + } let request_id = msg.request_id; // Answer only for what our grant lets us publish (MoQ Auth): checked before the @@ -3044,6 +3142,9 @@ where mut stream: Stream, msg: ietf::SubscribeNamespace<'_>, ) -> Result<(), Error> { + if let Some(error) = super::namespace::refusal(&msg.namespace, self.version) { + return super::request_stream::reject(stream, error).await; + } let prefix = msg.namespace.to_owned(); tracing::debug!(prefix = %self.origin.absolute(&prefix), "subscribe_namespace stream"); @@ -3155,7 +3256,8 @@ where _ => Target::Inline(stream), }; - let ns = Namespaces::new(peer, target); + let mut ns = Namespaces::new(peer, target); + ns.hidden = !declared.hidden || msg.hidden || self.origin.includes_hidden(); self.run_namespaces(announced, prefix, ns, initial).await } @@ -3200,7 +3302,7 @@ where async fn run_namespaces( &self, mut announced: crate::announce::Consumer, - prefix: crate::PathOwned, + mut prefix: crate::PathOwned, mut ns: Namespaces, initial: Vec, ) -> Result<(), Error> { @@ -3247,15 +3349,15 @@ where if self.withdrawal.poll(waiter).is_ready() { return Poll::Ready(NamespaceEvent::Update(None)); } - let mut cx = waiter.context(); - if let Poll::Ready(res) = target.poll_closed(&mut finished, self.version, &mut cx) { - return Poll::Ready(NamespaceEvent::Closed(res)); - } // A grant change applies before the next update, so a namespace it no // longer covers is withdrawn rather than re-sent. if let Poll::Ready(permit) = self.auth.poll_permit(crate::auth::Direction::Publish, epoch, waiter) { return Poll::Ready(NamespaceEvent::Regrant(permit)); } + let mut cx = waiter.context(); + if let Poll::Ready(event) = target.poll_event(&mut finished, self.version, &mut cx) { + return Poll::Ready(event); + } if let Poll::Ready(next) = announced.poll_next(waiter) { return Poll::Ready(NamespaceEvent::Update(next.map(|event| match event { crate::announce::Event::Start(update) | crate::announce::Event::Update(update) => { @@ -3274,7 +3376,84 @@ where }; match event { - NamespaceEvent::Closed(res) => break res, + NamespaceEvent::Closed(res) => { + if let Err(err @ Error::Decode(_)) = &res { + self.session.clone().close( + super::error::to_session_code(&crate::SessionError::from(err)), + &err.to_string(), + ); + } + break res; + } + NamespaceEvent::Request(update) => { + if let Err(err) = self.control.accept(update.request_id) { + self.session.clone().close( + super::error::to_session_code(&crate::SessionError::from(&err)), + "invalid request ID", + ); + break Err(err); + } + let refusal = update + .refused + .map(|error| ietf::RequestError { + request_id: None, + error_code: request::to_code(&error, request::Kind::SubscribeNamespace, self.version), + reason_phrase: "namespace update refused".into(), + retry_interval: 0, + }) + .or_else(|| { + update + .prefix + .as_ref() + .and_then(|prefix| super::namespace::refusal(prefix, self.version)) + }); + if let Some(error) = refusal { + let stream = ns.target.stream().expect("update has a stream"); + stream.writer.varint(ietf::RequestError::ID).await?; + stream.writer.encode(&error).await?; + // Dropping a finished writer resets it, which could discard the refusal. + stream.writer.finish()?; + break stream.writer.closed().await; + } + if let Some(next) = update.prefix.filter(|next| next != &prefix) { + // DONE still names the old prefix. After OK every suffix is relative + // to the new prefix, so replay the new cursor only after acknowledging. + let held: Vec<_> = ns + .watched + .iter() + .filter(|(_, watch)| watch.sent.wanted()) + .map(|(suffix, _)| suffix.clone()) + .collect(); + for suffix in held { + self.withdraw_namespace(&mut ns.target, &mut ns.requests, suffix) + .await?; + } + ns.watched.clear(); + prefix = next; + let scope = crate::Pattern::subtree(prefix.as_str()) + .map(|p| p.rebase(prefix.as_str())) + .unwrap_or_default(); + let origin = self + .origin + .scope(&prefix, &scope) + .unwrap_or_else(|_| self.origin.empty()); + announced = origin + .excluding(self.exclude(&ns.peer)) + .discovery(ns.hidden) + .announced(); + retry_at = None; + retry_delay = RETRY_BASE; + } + let stream = ns.target.stream().expect("update has a stream"); + stream.writer.varint(ietf::RequestOk::ID).await?; + stream + .writer + .encode(&ietf::RequestOk { + request_id: None, + active: None, + }) + .await?; + } NamespaceEvent::Retry => { retry_at = None; retry_delay = (retry_delay * 2).min(RETRY_MAX); @@ -6087,6 +6266,202 @@ mod serve_tests { } } + #[moq_net_sim::test] + async fn subscription_track_property_filter_closes_the_session() { + for version in [Version::Draft19, Version::Draft21, Version::Draft22] { + let h = serve(version); + let mut session = ScriptedSession::new(vec![0x02, 0, 6, 2, 1, 0x29, 2, 0, 0]); + let mut stream = Stream::open(&mut session, version).await.unwrap(); + let mut serving = TrackServe::new( + h.session.clone(), + h.track.subscribe(None), + RequestId(0), + version, + ServeRange::default(), + None, + ); + let result = h + .publisher + .run_subscription(&mut stream, &mut serving, &mut false, async {}, None) + .await; + assert!( + matches!(result, Some(Served::Track(Err(Error::Decode(_))))), + "{version}: {result:?}" + ); + assert_eq!( + h.log.closes().iter().map(|(code, _)| *code).collect::>(), + [0x03], + "{version}" + ); + assert!(session.log.writes.lock().unwrap().is_empty(), "no REQUEST_ERROR"); + } + } + + /// A source track failing to decode ends only the subscriptions it feeds, not the requester's session. + #[moq_net_sim::test] + async fn source_decode_failure_keeps_the_session() { + for version in [Version::Draft16, Version::Draft19, Version::Draft22] { + let h = serve(version); + let mut session = ScriptedSession::new(Vec::new()); + let mut stream = Stream::open(&mut session, version).await.unwrap(); + let mut serving = TrackServe::new( + h.session.clone(), + h.track.subscribe(None), + RequestId(0), + version, + ServeRange::default(), + None, + ); + h.track.clone().abort(Error::Decode(DecodeError::InvalidValue)).unwrap(); + let result = h + .publisher + .run_subscription(&mut stream, &mut serving, &mut false, async {}, None) + .await; + assert!( + matches!(result, Some(Served::Track(Err(Error::Decode(_))))), + "{version}: {result:?}" + ); + assert!(h.log.closes().is_empty(), "{version}: the session closed"); + } + } + + #[moq_net_sim::test] + async fn namespace_updates_do_not_postpone_an_auth_withdrawal() { + for version in [Version::Draft18, Version::Draft21, Version::Draft22] { + let h = serve(version); + settle().await; + let mut session = ScriptedSession::new(Vec::new()); + let stream = Stream::open(&mut session, version).await.unwrap(); + let mut running = std::pin::pin!(h.publisher.clone().run_subscribe_namespace_stream( + stream, + ietf::SubscribeNamespace { + request_id: RequestId(0), + namespace: crate::Path::empty(), + hidden: false + } + )); + assert!(futures::poll!(running.as_mut()).is_pending()); + let mark = session.log.writes.lock().unwrap().len(); + h.publisher.auth.authorize(&crate::auth::Grant::default()); + // An otherwise valid no-op update is ready at the same time as revocation. + session.push(&[0x02, 0, 2, 2, 0]); + assert!(futures::poll!(running.as_mut()).is_pending()); + let answer = session.log.writes.lock().unwrap().clone(); + let mut wire = Decoder::new(&answer[mark..], version.into()); + assert_eq!( + wire.varint().unwrap(), + ietf::NamespaceDone::ID, + "{version}: withdrawal precedes update OK" + ); + assert_eq!( + ietf::NamespaceDone::decode(&mut wire, version).unwrap().suffix.as_str(), + "room" + ); + assert_eq!(wire.varint().unwrap(), ietf::RequestOk::ID); + ietf::RequestOk::decode(&mut wire, version).unwrap(); + assert!(wire.is_empty()); + } + } + + /// A refused namespace update waits for its REQUEST_ERROR to be acknowledged instead of + /// letting the writer's drop reset discard it. + #[moq_net_sim::test] + async fn refused_namespace_update_is_delivered_before_the_stream_ends() { + for version in [Version::Draft21, Version::Draft22] { + let h = serve(version); + settle().await; + let mut session = ScriptedSession::new(Vec::new()).with_unacked_fin(); + let stream = Stream::open(&mut session, version).await.unwrap(); + let msg = ietf::SubscribeNamespace { + request_id: RequestId(0), + namespace: crate::Path::new("room"), + hidden: false, + }; + let mut running = std::pin::pin!(h.publisher.clone().run_subscribe_namespace_stream(stream, msg)); + assert!(futures::poll!(running.as_mut()).is_pending()); + // Request ID 2; TRACK_NAMESPACE_PREFIX is the reserved one-field tuple ".session". + let mut update = vec![0x02, 0, 13, 2, 1, 0x34, 1, 8]; + update.extend_from_slice(b".session"); + session.push(&update); + assert!( + futures::poll!(running.as_mut()).is_pending(), + "{version}: ended before the ack" + ); + assert!( + session + .log + .trail() + .iter() + .any(|(_, sent)| matches!(sent, crate::lite::test_transport::Sent::Finish)), + "{version}: no FIN" + ); + assert!(session.log.resets().is_empty(), "{version}: the refusal was reset"); + assert!(h.log.closes().is_empty(), "{version}: the session closed"); + } + } + + #[moq_net_sim::test] + async fn namespace_updates_move_the_prefix_after_acknowledgement() { + for version in [Version::Draft18, Version::Draft21, Version::Draft22] { + let h = serve(version); + let _old = h + ._origin + .announce("old/first", crate::origin::Route::default()) + .unwrap(); + let _new = h + ._origin + .announce("new/second", crate::origin::Route::default()) + .unwrap(); + settle().await; + let mut session = ScriptedSession::new(Vec::new()); + let stream = Stream::open(&mut session, version).await.unwrap(); + let msg = ietf::SubscribeNamespace { + request_id: RequestId(0), + namespace: crate::Path::new("old"), + hidden: false, + }; + let mut running = std::pin::pin!(h.publisher.clone().run_subscribe_namespace_stream(stream, msg)); + assert!(futures::poll!(running.as_mut()).is_pending()); + let first = session.log.writes.lock().unwrap().clone(); + let mut wire = Decoder::new(&first, version.into()); + assert_eq!(wire.varint().unwrap(), ietf::RequestOk::ID); + ietf::RequestOk::decode(&mut wire, version).unwrap(); + assert_eq!(wire.varint().unwrap(), ietf::Namespace::ID); + assert_eq!( + ietf::Namespace::decode(&mut wire, version).unwrap().suffix.as_str(), + "first" + ); + assert!(wire.is_empty()); + // Request ID 2; TRACK_NAMESPACE_PREFIX is the one-field tuple "new". + let update = [0x02, 0, 8, 2, 1, 0x34, 1, 3, b'n', b'e', b'w']; + // Partial messages do not consume the update or change the current prefix. + session.push(&update[..6]); + assert!(futures::poll!(running.as_mut()).is_pending()); + assert_eq!(*session.log.writes.lock().unwrap(), first); + session.push(&update[6..]); + assert!(futures::poll!(running.as_mut()).is_pending()); + let answer = session.log.writes.lock().unwrap().clone(); + let mut wire = Decoder::new(&answer[first.len()..], version.into()); + assert_eq!(wire.varint().unwrap(), ietf::NamespaceDone::ID, "{version}"); + assert_eq!( + ietf::NamespaceDone::decode(&mut wire, version).unwrap().suffix.as_str(), + "first" + ); + assert_eq!(wire.varint().unwrap(), ietf::RequestOk::ID, "{version}"); + ietf::RequestOk::decode(&mut wire, version).unwrap(); + assert_eq!(wire.varint().unwrap(), ietf::Namespace::ID, "{version}"); + assert_eq!( + ietf::Namespace::decode(&mut wire, version).unwrap().suffix.as_str(), + "second" + ); + assert!(wire.is_empty()); + // A fresh update ID is required even if the prefix does not change. + session.push(&update); + assert!(futures::poll!(running.as_mut()).is_ready()); + assert_eq!(h.log.closes().iter().map(|(code, _)| *code).collect::>(), [0x04]); + } + } + #[moq_net_sim::test] async fn namespace_requester_fin_is_version_gated() { for version in [Version::Draft17, Version::Draft18, Version::Draft19, Version::Draft22] { @@ -6122,6 +6497,7 @@ mod serve_tests { fill, properties_wanted: true, forward: true, + rendezvous: false, range_filters: false, authorization_token: None, } @@ -6569,6 +6945,116 @@ mod serve_tests { } } + #[moq_net_sim::test] + async fn range_filters_over_the_default_limit_get_invalid_filter() { + for version in [Version::Draft19, Version::Draft20, Version::Draft21, Version::Draft22] { + let h = serve(version); + for fetch in [false, true] { + let stream = Stream::open(&mut h.session.clone(), version).await.unwrap(); + let mark = h.log.writes.lock().unwrap().len(); + if fetch { + h.publisher + .clone() + .run_fetch_stream( + stream, + ietf::Fetch { + request_id: RequestId(REQUEST_ID), + subscriber_priority: 128, + group_order: GroupOrder::Descending, + fetch_type: if Filter::is_draft20(version) { + FetchType::Filtered { + namespace: crate::Path::new("room"), + track: "video".into(), + filter: Filter::Unfiltered, + } + } else { + FetchType::Standalone { + namespace: crate::Path::new("room"), + track: "video".into(), + start: Location { group: 0, object: 0 }, + end: Location { group: 0, object: 0 }, + } + }, + properties_wanted: true, + range_filters: true, + fill_timeout: false, + }, + ) + .await + .unwrap(); + } else { + let mut msg = subscribe(Filter::NextObject, None); + msg.range_filters = true; + h.publisher.clone().run_subscribe_stream(stream, msg).await.unwrap(); + } + assert_eq!( + refusal_code(&h.log.writes.lock().unwrap()[mark..], version), + Some(0x36), + "{version}: fetch={fetch}" + ); + assert!(h.log.closes().is_empty()); + } + } + } + + #[moq_net_sim::test] + async fn rendezvous_wait_is_capped_at_zero_but_answers_timeout() { + for version in [Version::Draft18, Version::Draft21, Version::Draft22] { + // A wait applies only to a missing publisher; a missing track on a live one does not exist. + for (namespace, track, publisher) in [("missing", "video", false), ("room", "audio", true)] { + for wait in [None, Some(0), Some(7)] { + let mut body = Vec::new(); + let mut w = Encoder::new(&mut body, version.into()); + RequestId(REQUEST_ID).encode(&mut w, version).unwrap(); + super::super::namespace::encode_namespace(&mut w, &crate::Path::new(namespace)).unwrap(); + w.string(track).unwrap(); + w.varint(u64::from(wait.is_some())).unwrap(); + if let Some(wait) = wait { + w.varint(0x04).unwrap(); + w.varint(wait).unwrap(); + } + assert_eq!( + refusal(version, ietf::Subscribe::ID, body).await, + if !publisher && wait.is_some_and(|millis| millis > 0) { + 0x02 + } else { + 0x10 + }, + "{version}: {namespace}/{track} {wait:?}" + ); + } + } + } + } + + #[moq_net_sim::test] + async fn reserved_namespace_requests_never_reach_the_application() { + for version in [Version::Draft21, Version::Draft22] { + for path in [".", "./child", ".session", ".session/extension"] { + let h = serve(version); + let claim = h._origin.dynamic("", crate::origin::Route::default()).unwrap(); + settle().await; + let stream = Stream::open(&mut h.session.clone(), version).await.unwrap(); + let mark = h.log.writes.lock().unwrap().len(); + let body = track_status(path, true, version); + let mut serving = std::pin::pin!( + h.publisher + .clone() + .handle_stream(ietf::TrackStatus::ID, ietf::Body(body.into()), stream) + .unwrap() + ); + let done = futures::poll!(serving.as_mut()); + assert!( + claim.requested_broadcast().now_or_never().is_none(), + "{version}: {path} reached the application" + ); + assert!(done.is_ready(), "{version}: {path} was left waiting"); + assert_eq!(refusal_code(&h.log.writes.lock().unwrap()[mark..], version), Some(0x10)); + assert!(h.log.closes().is_empty()); + } + } + } + /// A SUBSCRIBE past the session's cap closes the session with TOO_MANY_REQUESTS. #[moq_net_sim::test] async fn subscriptions_past_the_cap_close_the_session() { @@ -6671,7 +7157,7 @@ mod serve_tests { for (label, id, params) in cases { assert_eq!( refusal(version, id, [head, params].concat()).await, - NOT_SUPPORTED, + if id == ietf::Subscribe::ID { 0x36 } else { NOT_SUPPORTED }, "{version}: {label}" ); } @@ -12463,6 +12949,7 @@ mod tests { fill: None, properties_wanted: true, forward: true, + rendezvous: false, range_filters: false, authorization_token: None, }, @@ -12816,6 +13303,7 @@ mod range_tests { fill: None, properties_wanted: true, forward: true, + rendezvous: false, range_filters: false, authorization_token: None, } diff --git a/rs/moq-net/src/ietf/request_stream.rs b/rs/moq-net/src/ietf/request_stream.rs index c277431314f..491993e8d3e 100644 --- a/rs/moq-net/src/ietf/request_stream.rs +++ b/rs/moq-net/src/ietf/request_stream.rs @@ -119,6 +119,18 @@ impl Decode for Framed { } } +/// Refuse a modern request with its complete REQUEST_ERROR, then finish the response. +pub(super) async fn reject( + mut stream: Stream, + error: super::RequestError<'_>, +) -> Result<(), Error> { + stream.writer.varint(super::RequestError::ID).await?; + stream.writer.encode(&error).await?; + // A peer dropping the response after reading the refusal is a normal end. + let _ = stream.writer.close().await; + Ok(()) +} + /// A framed subscription update, preserving omitted preferences. #[derive(Debug)] pub(super) struct Update { @@ -197,16 +209,17 @@ impl Update { if !data.is_empty() { return Err(DecodeError::InvalidValue); } + // TRACK_PROPERTY_FILTER belongs only to SUBSCRIBE_TRACKS and its updates. + if !track_filter.is_empty() { + return Err(DecodeError::InvalidValue); + } let unsupported = forward == Some(false) || filter.is_some() || fill.is_some() - || object_timeout.is_some() - || subgroup_timeout.is_some() || !subgroup_filter.is_empty() || !object_filter.is_empty() || !priority_filter.is_empty() || !property_filter.is_empty() - || !track_filter.is_empty() || new_group.is_some(); let (refused, authorization_token) = Self::refused(token, unsupported); Ok(Self { @@ -243,10 +256,78 @@ impl Decode for Update { } } +/// The namespace-only parameters of a modern REQUEST_UPDATE. +#[derive(Debug)] +pub(super) struct NamespaceUpdate { + pub(super) request_id: super::RequestId, + pub(super) prefix: Option, + pub(super) refused: Option, +} + +#[derive(Debug)] +struct NamespacePrefix(crate::PathOwned); + +impl super::parameters::Param for NamespacePrefix { + fn param_encode(&self, w: &mut crate::coding::Encoder<'_>, _: Version) -> Result<(), crate::coding::EncodeError> { + super::namespace::encode_namespace(w, &self.0) + } + fn param_decode(r: &mut Decoder<'_>, _: Version) -> Result { + Ok(Self(super::namespace::decode_namespace(r)?)) + } +} + +impl Decode for NamespaceUpdate { + fn decode(r: &mut Decoder<'_>, version: Version) -> Result { + if r.varint()? != super::SubscribeUpdate::ID { + return Err(DecodeError::InvalidValue); + } + let size = r.u16()? as usize; + let mut data = r.sub(size)?; + let mut decode = || { + let request_id = super::RequestId::decode(&mut data, version)?; + decode_params!(&mut data, version, + 0x03 => token: Vec, + 0x34 => prefix: Option, + ); + if !data.is_empty() { + return Err(DecodeError::InvalidValue); + } + Ok(Self { + request_id, + prefix: prefix.map(|p| p.0), + refused: super::token::single(token).err().map(Into::into), + }) + }; + decode().map_err(DecodeError::complete) + } +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn delivery_timeouts_on_subscription_updates_are_accepted() { + for version in [Version::Draft18, Version::Draft21, Version::Draft22] { + // Request ID 2; OBJECT_DELIVERY_TIMEOUT=7, SUBGROUP_DELIVERY_TIMEOUT=9. + let mut buf = bytes::Bytes::from_static(&[2, 2, 0x02, 7, 0x04, 9]); + let update = crate::coding::decode_buf(&mut buf, version, Update::decode_body).unwrap(); + assert!(update.refused.is_none(), "{version}: {:?}", update.refused); + } + } + + #[test] + fn track_property_filter_on_subscription_update_is_a_protocol_violation() { + for version in [Version::Draft19, Version::Draft21, Version::Draft22] { + let mut buf = bytes::Bytes::from_static(&[2, 1, 0x29, 2, 0, 0]); + let error = crate::coding::decode_buf(&mut buf, version, Update::decode_body).unwrap_err(); + assert_eq!( + super::super::error::to_session_code(&crate::SessionError::from(&Error::from(error))), + 0x03 + ); + } + } + /// TRACK_NAMESPACE_PREFIX (0x34) updates a SUBSCRIBE_NAMESPACE or SUBSCRIBE_TRACKS only, /// so on a subscription's REQUEST_UPDATE it closes the session instead of being acked. #[test] diff --git a/rs/moq-net/src/ietf/session.rs b/rs/moq-net/src/ietf/session.rs index 49a118bf45f..af9a871587a 100644 --- a/rs/moq-net/src/ietf/session.rs +++ b/rs/moq-net/src/ietf/session.rs @@ -2533,6 +2533,7 @@ mod tests { fill: None, properties_wanted: true, forward: true, + rendezvous: false, range_filters: false, authorization_token: None, } @@ -2951,6 +2952,7 @@ mod tests { fill: None, properties_wanted: true, forward: true, + rendezvous: false, range_filters: false, authorization_token: None, }; diff --git a/rs/moq-net/src/ietf/subscribe.rs b/rs/moq-net/src/ietf/subscribe.rs index 8ddf6c439ce..3ebc5e6f0fe 100644 --- a/rs/moq-net/src/ietf/subscribe.rs +++ b/rs/moq-net/src/ietf/subscribe.rs @@ -33,6 +33,8 @@ pub struct Subscribe<'a> { /// Whether Objects are forwarded (FORWARD). We only serve forwarding subscriptions, /// so a subscriber that asks for none is refused. pub forward: bool, + /// Whether RENDEZVOUS_TIMEOUT asks to wait for a missing publisher; never sent. + pub rendezvous: bool, /// Whether the request carried a Range Filter (0x25-0x28). We advertise no /// MAX_FILTER_RANGES, so the request is refused rather than served unfiltered. /// Never encoded; we send no range filters. @@ -87,6 +89,7 @@ impl Message for Subscribe<'_> { fill: None, properties_wanted: true, forward, + rendezvous: false, range_filters: false, authorization_token, }) @@ -127,10 +130,8 @@ impl Message for Subscribe<'_> { // Defaults to 1, so an absent parameter means the subscriber wants them. let properties_wanted = include_properties.unwrap_or(true); - // The value is deliberately dropped: we always answer a SUBSCRIBE with what is - // published right now, which is the shorter timeout the draft lets a relay pick. - // We still have to parse it, or the parameter alone would kill the session. - let _ = rendezvous_timeout; + // A zero cap still distinguishes a requested wait from an immediate miss. + let rendezvous = rendezvous_timeout.is_some_and(|millis| millis > 0); let subscriber_priority = subscriber_priority.unwrap_or(128); let group_order = group_order.unwrap_or(GroupOrder::Descending); @@ -148,6 +149,7 @@ impl Message for Subscribe<'_> { properties_wanted, // Absent means 1. forward: forward.unwrap_or(true), + rendezvous, range_filters, authorization_token, }) @@ -562,6 +564,7 @@ mod tests { fill: None, properties_wanted: true, forward: true, + rendezvous: false, range_filters: false, authorization_token: None, }; @@ -587,6 +590,7 @@ mod tests { fill: None, properties_wanted: true, forward: true, + rendezvous: false, range_filters: false, authorization_token: None, }; @@ -625,13 +629,14 @@ mod tests { /// parse: failing to decode it takes the whole session down instead of answering the /// SUBSCRIBE. #[test] - fn rendezvous_timeout_is_accepted_and_ignored() { + fn rendezvous_timeout_retains_whether_a_wait_was_requested() { for version in [Version::Draft17, Version::Draft18, Version::Draft19, Version::Draft20] { for millis in [0, 5000] { let encoded = subscribe_with_rendezvous(millis, version); let msg: Subscribe = decode_message(&encoded, version) .unwrap_or_else(|err| panic!("{version} rendezvous {millis}ms: {err}")); assert_eq!(msg.track_name, "video"); + assert_eq!(msg.rendezvous, millis > 0); } } } @@ -682,6 +687,7 @@ mod tests { fill: None, properties_wanted: true, forward: true, + rendezvous: false, range_filters: false, authorization_token: None, }; @@ -714,6 +720,7 @@ mod tests { fill: None, properties_wanted: true, forward: true, + rendezvous: false, range_filters: false, authorization_token: None, }; @@ -901,6 +908,7 @@ mod tests { fill: None, properties_wanted: wanted, forward: true, + rendezvous: false, range_filters: false, authorization_token: None, }; @@ -1030,6 +1038,7 @@ mod tests { fill: None, properties_wanted: true, forward: true, + rendezvous: false, range_filters: false, authorization_token: None, }; @@ -1093,6 +1102,7 @@ mod tests { fill: None, properties_wanted: true, forward: true, + rendezvous: false, range_filters: false, authorization_token: None, }; @@ -1372,6 +1382,7 @@ mod tests { fill: None, properties_wanted: false, forward: true, + rendezvous: false, range_filters: false, authorization_token: None, }; @@ -1434,6 +1445,7 @@ mod tests { fill: None, properties_wanted: true, forward: false, + rendezvous: false, range_filters: false, authorization_token: None, }; diff --git a/rs/moq-net/src/ietf/subscriber.rs b/rs/moq-net/src/ietf/subscriber.rs index 530e03ce931..10156732928 100644 --- a/rs/moq-net/src/ietf/subscriber.rs +++ b/rs/moq-net/src/ietf/subscriber.rs @@ -1280,6 +1280,9 @@ where peer: cluster::Peer, declared: Option, ) -> Result<(), Error> { + if let Some(error) = super::namespace::refusal(&msg.track_namespace, self.version) { + return super::request_stream::reject(stream, error).await; + } let request_id = msg.request_id; let path = msg.track_namespace.to_owned(); @@ -1794,6 +1797,9 @@ where mut stream: Stream, msg: ietf::Publish<'_>, ) -> Result<(), Error> { + if let Some(error) = super::namespace::refusal(&msg.track_namespace, self.version) { + return super::request_stream::reject(stream, error).await; + } tracing::debug!(broadcast = %msg.track_namespace, track = %msg.track_name, "rejecting publish"); // We decline the method itself rather than this particular track, which would be @@ -2513,6 +2519,7 @@ where // A resumed copy already knows the track, from the answer that accepted it. properties_wanted: matches!(target, Target::Request(_)), forward: true, + rendezvous: false, range_filters: false, authorization_token: None, }) @@ -10879,6 +10886,7 @@ mod stitch_tests { fill: None, properties_wanted: true, forward: true, + rendezvous: false, range_filters: false, authorization_token: None, } @@ -11408,6 +11416,7 @@ mod stitch_tests { fill: None, properties_wanted: true, forward: true, + rendezvous: false, range_filters: false, authorization_token: None, }; diff --git a/rs/moq-net/src/ietf/version.rs b/rs/moq-net/src/ietf/version.rs index 3ac1d465a33..899d571ba4a 100644 --- a/rs/moq-net/src/ietf/version.rs +++ b/rs/moq-net/src/ietf/version.rs @@ -99,6 +99,7 @@ mod tests { }), properties_wanted: false, forward: true, + rendezvous: false, range_filters: false, authorization_token: None, }; @@ -171,6 +172,7 @@ mod tests { fill: None, properties_wanted: true, forward: true, + rendezvous: false, range_filters: false, authorization_token: None, };