diff --git a/drafts/draft-lcurley-moq-cluster.md b/drafts/draft-lcurley-moq-cluster.md index 50783cd3c46..9a8609ae289 100644 --- a/drafts/draft-lcurley-moq-cluster.md +++ b/drafts/draft-lcurley-moq-cluster.md @@ -105,35 +105,24 @@ An endpoint MAY generate one randomly, since collisions across a 64-bit space ar Loop detection and origin identification compare Hop IDs for equality, so two endpoints sharing a Hop ID are indistinguishable. -## The Reserved Hop ID 0 {#zero} -**0 means "no identity"** and is reserved. -It is used for an endpoint that did not negotiate this extension, and an endpoint MAY also declare 0 to withhold its identity. - -Because any number of endpoints can be 0, it identifies nothing, which constrains all three uses: - -- **Loop detection**: 0 in a HOP_PATH is never a loop. A receiver whose own Hop ID is 0 cannot detect loops through itself, and MUST NOT discard an advertisement merely because the path contains 0. -- **Origin identity**: an advertisement whose first entry is 0 has an unknown origin. Updating one advertisement is not two ({{updating}}). -- **Filtering**: a peer that declared 0 declared no identity, so there is nothing on the wire to filter that session on. A receiver MAY assign one ({{assigned}}), which covers what it attributes to that session itself but not an advertisement that arrived carrying its own HOP_PATH. - -Duplicate *non-zero* Hop IDs in one HOP_PATH are a loop; duplicate zeros are not. -Declaring 0 therefore trades loop detection and failover for anonymity, except against a receiver that assigns an identity of its own. +0 means "no identity" and is reserved for RELAY_HOPS and for an endpoint that did not negotiate this extension. +A HOP_PATH never contains 0: a chain entry that names nobody is a PROTOCOL_VIOLATION. ## Assigned Identities {#assigned} -A receiver MAY assign a Hop ID of its own to a peer that declared none, whether by declaring 0 or by not negotiating this extension at all. +A receiver MUST assign a Hop ID of its own to a peer that declared none, whether by declaring 0 or by not negotiating this extension at all. It uses that ID wherever it would otherwise have nothing to name the peer with: as the entry it creates for an upstream that sent no HOP_PATH, and as what it filters that session on. The ID is the receiver's own, not the peer's. -An advertisement that arrives carrying its own HOP_PATH names the sender there, as 0 if the sender withheld it, and this document does not define rewriting that entry. -So an assigned ID governs the advertisements a receiver attributed itself, and a peer that both declares 0 and sends its own HOP_PATH keeps the consequences in {{zero}}. +An advertisement that arrives carrying its own HOP_PATH names the sender there; a HOP_PATH never contains 0, so a peer that withheld its identity cannot appear in one it sends. An assigned ID MUST NOT be shared between peers not known to be the same endpoint. Sharing one suppresses each one's advertisements to the other, so two unrelated publishers would starve each other of routes. How an endpoint scopes the ID follows from what it can establish about the peer. One it authenticated, or one it dialed and therefore chose, SHOULD get a single stable ID; assigning per connection there would make one peer look like several. -An endpoint accepting an anonymous session can establish nothing and cannot correlate it with any other, so it SHOULD assign a distinct ID per session: less than an identity, but enough to keep routes it attributed to that session from being advertised back to it, which is the loop 0 cannot prevent. +An endpoint accepting an anonymous session can establish nothing and cannot correlate it with any other, so it SHOULD assign a distinct ID per session: less than an identity, but enough to keep routes it attributed to that session from being advertised back to it. -An assigned ID is indistinguishable on the wire from a declared one, so it identifies the peer to everyone the receiver forwards to; a peer that declared 0 for anonymity did not ask for that. +An assigned ID is indistinguishable on the wire from a declared one, so it identifies the peer to everyone the receiver forwards to. # Namespace Advertisements {#namespace} @@ -172,8 +161,8 @@ HOP_PATH Parameter { } ~~~ -The list always has at least one entry, the original publisher, which is 0 if that publisher is unknown ({{zero}}). -A receiver MUST close the session with a PROTOCOL_VIOLATION if the entries do not exactly fill `Length`, if the list is empty, or if a non-zero Hop ID appears twice. +The list always has at least one entry, the original publisher. +A receiver MUST close the session with a PROTOCOL_VIOLATION if the entries do not exactly fill `Length`, if the list is empty, if any Hop ID is 0, or if a Hop ID appears twice. ## ROUTE_COST Parameter ROUTE_COST is the marginal cost of subscribing via this advertisement: the price of the transfers a new subscription would actually cause. @@ -197,7 +186,7 @@ Unknown, out-of-budget, and saturated routes are outside this guarantee; a recei # Relay Behavior When forwarding an advertisement downstream, a relay MUST append its own Hop ID to the HOP_PATH it received, so its own ID is always the last entry. -An advertisement arriving from an upstream that did not negotiate the extension has no HOP_PATH; the relay creates one containing a single entry for that upstream, 0 ({{zero}}) or an ID it assigned ({{assigned}}), then appends its own. +An advertisement arriving from an upstream that did not negotiate the extension has no HOP_PATH; the relay creates one containing a single entry for that upstream ({{assigned}}), then appends its own. On receipt, a relay MUST discard an advertisement whose HOP_PATH already contains its own non-zero Hop ID: forwarding it would extend a loop, and subscribing through it would route the relay back to itself. This receiver-side check catches loops of any length and is the only loop defense required. @@ -214,7 +203,7 @@ When it stops carrying the namespace it SHOULD restore the accumulated value, op Two relays that independently begin carrying the same namespace would each see the other's 0 as cheaper than its own source, and both switching at once would leave the namespace with no source. Before re-parenting onto a 0-cost advertisement from another actively-carrying relay (one whose HOP_PATH has two or more entries), a relay SHOULD apply a deterministic tie-break, such as comparing a hash of the namespace and each Hop ID, so exactly one side moves. -Equal Hop IDs (including two relays that both declared 0) cannot be ordered, and neither side SHOULD move. +Equal Hop IDs cannot be ordered, and neither side SHOULD move. Cheaper advertisements from anything else carry no such hazard and SHOULD be adopted immediately. ## Updating an Advertisement {#updating} @@ -237,10 +226,9 @@ Pattern support does not follow from negotiating Relay Hops; advertisements to a Within the tier, a receiver SHOULD prefer the lowest ROUTE_COST, breaking ties toward the shorter HOP_PATH and then toward the most recently received. Pattern advertisements tied at the lowest cost are a pool: a deterministic hash of the requested namespace against each advertiser distributes distinct namespaces across them. The hash is FNV-1a from the basis `0x420C0DECB00B`: encode each requested namespace field as its byte length in eight little-endian bytes followed by its bytes, then append the advertiser's first Hop ID in eight little-endian bytes. For each encoded byte, XOR the byte in and multiply by `0x100000001B3`, wrapping at 64 bits; the highest result wins. -A first Hop ID of 0 makes the advertisement a pool member keyed by its incoming session: the receiver assigns each such session a distinct local 64-bit key, stable for that session's lifetime, and appends its eight little-endian bytes after the zero Hop ID when hashing. This key is local selection state, not an origin identity, and MUST NOT be forwarded as a Hop ID. This is advisory: a receiver MAY apply local policy such as measured RTT instead. -NO_CAPACITY and its single re-resolution are defined by {{I-D.lcurley-moq-pattern}}. Excluding the refusing advertiser excludes every route with its non-zero first Hop ID, or its incoming session when that ID is 0. +NO_CAPACITY and its single re-resolution are defined by {{I-D.lcurley-moq-pattern}}. Excluding the refusing advertiser excludes every route with its first Hop ID. An advertisement carries no content identity: nothing promises that two paths to one namespace serve interchangeable bytes. A receiver MUST NOT splice an active subscription across sessions; when the serving session's advertisement goes away, subscriptions through it end, and the receiver re-subscribes through the best remaining path. @@ -256,8 +244,8 @@ Applying one rule to both advertisement and dispatch keeps advertised paths trut # Security Considerations -A Hop ID reveals nothing beyond what its operator encodes in it, and a deployment that considers its identifiers sensitive can use random values or declare 0 ({{zero}}). -Declaring 0 hides an identity from the mesh but not from the peer itself, which MAY assign one and forward it onward ({{assigned}}); an endpoint that needs to stay unlinkable past its first hop cannot get that from this extension. +A Hop ID reveals nothing beyond what its operator encodes in it, and a deployment that considers its identifiers sensitive can use random values or declare 0 in RELAY_HOPS. +Declaring 0 withholds an identity at SETUP, but a HOP_PATH never contains 0, so a peer that wants to advertise must be named, either by a Hop ID it declared or by one the receiver assigned ({{assigned}}). A HOP_PATH does expose how many hops an advertisement crossed, which hints at the size of a deployment; a relay MAY coalesce its internal hops into one entry, or strip HOP_PATH, before forwarding across a trust boundary. Because a relay only appends to HOP_PATH, it cannot make a competing path look shorter than it is; the worst it can do is under-report its own upstream portion to win an advisory tie-break. @@ -294,6 +282,13 @@ All are carried in PUBLISH_NAMESPACE and in the extended NAMESPACE message ({{na The Key-Value-Pair parity is load-bearing: HOP_PATH and RELAY_HOPS are odd, so their values are length-prefixed byte strings, while ROUTE_COST and RELAY_COST are even, so their values are bare varints. +# Appendix A: Changelog + +## 00 +- A HOP_PATH entry of 0 is a PROTOCOL_VIOLATION; duplicate zeros are no longer legal. +- Assigned Identities is mandatory: a receiver MUST assign a Hop ID to a peer that declared none. + + --- back # Acknowledgments diff --git a/drafts/draft-lcurley-moq-lite.md b/drafts/draft-lcurley-moq-lite.md index 2f098b4bfa0..1c08f2522be 100644 --- a/drafts/draft-lcurley-moq-lite.md +++ b/drafts/draft-lcurley-moq-lite.md @@ -395,7 +395,7 @@ Each advertisement carries the path of Hop IDs it traversed and an accumulated W A receiver MUST discard an announcement whose reconstructed path contains its own Hop ID: it has looped back, so forwarding it would extend the loop and subscribing through it would route the receiver back to itself. This is the only loop defense moq-lite requires, and it catches loops of any length. A conforming sender never sends one (see below), so a receiver MAY instead close the session with a protocol violation; discarding is what keeps a mesh working when one member does not conform. -A Hop ID of 0 means unknown and never matches anything; withholding an ID trades loop detection for privacy. +A Hop ID of 0 in ANNOUNCE_OK or the SETUP Hop parameter means the sender declared no identity; the receiver MUST assign one and use it as the trailing path entry, because a Hop ID list never contains 0. A publisher MUST NOT advertise a path whose entries contain the Hop ID the subscriber declared in its SETUP (see [Hop Parameter](#hop-parameter)). The receiver can only discard it, and acting on it would form a loop, so sending one is never useful. @@ -409,8 +409,8 @@ Applying one rule to both advertisement and dispatch keeps advertised paths trut When resolving a path covered by several routes (across any number of streams), the subscriber SHOULD prefer the most specific covering route (see [Resolution](#resolution)), then the lowest Warm Route Cost after adding each arriving link's cost (see [Cost Parameter](#cost-parameter)), breaking ties toward the lowest Cold Route Cost, then toward the shortest path, and then toward the most recently received, so a reconnecting publisher is not outranked by the stale session it replaced. A route's identity is its first hop: the endpoint that originated it (see [ANNOUNCE_START](#announce-start)). -Two routes covering one path with the same non-zero first hop are the same origin reached different ways, and a relay MAY move a live subscription between them, resuming at a group boundary, so a route change the identity survives (a reconnect, a cheaper path, a draining session) is invisible to the subscriber. -Across differing first hops, or where either is 0, the routes promise nothing about each other's content: a relay MUST NOT splice a live subscription across them, and when the serving session ends, in-flight subscriptions end with it (a reset) and the subscriber re-requests through the best remaining route. +Two routes covering one path with the same first hop are the same origin reached different ways, and a relay MAY move a live subscription between them, resuming at a group boundary, so a route change the identity survives (a reconnect, a cheaper path, a draining session) is invisible to the subscriber. +Across differing first hops the routes promise nothing about each other's content: a relay MUST NOT splice a live subscription across them, and when the serving session ends, in-flight subscriptions end with it (a reset) and the subscriber re-requests through the best remaining route. Equal first hops promise the same origin, not interchangeable bytes; what a resuming relay serves next is whatever that origin publishes next at the group boundary. #### Resolution {#resolution} @@ -423,7 +423,7 @@ The winning tier is the whole answer: a refusal from it never falls through to a Within the tier, cost and the tie-breaks of [Routing](#routing) order the routes, except that pattern routes tied at the lowest cost are a pool: a deterministic hash of the requested path against each advertiser distributes distinct paths across them, so one path always resolves the same way and a member arriving or leaving moves only its own share. The hash is FNV-1a: start the accumulator at `0x420C0DECB00B`, then for each byte of the requested path (segments joined by `/`, no leading or trailing `/`) followed by the eight bytes of the advertiser's Hop ID in little-endian order, XOR the byte in and multiply by `0x100000001B3`, wrapping at 64 bits; the highest result wins. -The advertiser is the route's first hop; a first hop of 0 identifies nothing, so such a route is a pool member of its own, keyed by the session it arrived on. The receiver assigns each such session a distinct local 64-bit key, stable for that session's lifetime, and appends its eight little-endian bytes after the zero Hop ID when hashing. This key is local selection state, not an origin identity, and MUST NOT be forwarded as a Hop ID. +The advertiser is the route's first hop. A route resolved this way serves the request like any other, and the pattern is not consumed by it. A relay MUST NOT announce a path merely because it resolved it: the pattern stays the only advertisement until the advertiser announces the concrete path, which it SHOULD do once it is producing, so a later request finds the running broadcast by its exact path instead of resolving a second producer. @@ -837,6 +837,7 @@ This is treated as the implicit trailing entry of every ANNOUNCE_START, ANNOUNCE The value 0 is reserved to mean "unknown": either no Hop ID was assigned (e.g. when bridging from an older protocol version) or the endpoint deliberately withholds it to obscure the underlying routing. A publisher that assigns a Hop ID MUST choose a non-zero value, and SHOULD assign itself one (a fresh random value per session suffices), so downstream receivers can detect loops through it. Receivers reconstruct the full path as `Hop IDs ++ [ANNOUNCE_OK.Hop ID]`. +If that Hop ID is 0, the receiver MUST assign a Hop ID of its own to the peer and use it as the trailing entry, because a Hop ID list never contains 0. **Active Count**: The number of ANNOUNCE_START and ANNOUNCE_PATTERN messages that the publisher will send immediately as the initial set. @@ -880,10 +881,8 @@ A unique identifier for each relay in the path from the origin publisher, ordere The responding publisher's own Hop ID is NOT included in this list; it is carried once in ANNOUNCE_OK, so the total path length is `Hop Count + 1`. When forwarding an announcement received from an upstream peer, a relay MUST append the upstream peer's ANNOUNCE_OK `Hop ID` to this list, since that ID is no longer implicit downstream. The first entry of the reconstructed path identifies the endpoint that originated the route. -A Hop ID value of 0 means the hop is unknown: either it was never assigned or a relay deliberately withholds it (see [Routing](#routing)). -A receiver MUST close the session with a PROTOCOL_VIOLATION if a non-zero Hop ID appears twice in this list. -Duplicate values of 0 are not a violation, since 0 identifies nothing and any number of hops may be unknown. +A receiver MUST close the session with a PROTOCOL_VIOLATION if any Hop ID is 0 or a Hop ID appears twice in this list. **Warm Route Cost** and **Cold Route Cost**: What subscribing to content under this route costs, in units chosen by the deployment. @@ -1387,6 +1386,7 @@ The `Message Length` describes the payload size on the wire. ## moq-lite-06 +- A Hop ID of 0 in an announcement's Hop ID list is a PROTOCOL_VIOLATION; duplicate zeros are no longer legal. A receiver that reads 0 in ANNOUNCE_OK MUST assign a Hop ID of its own and use it as the trailing path entry. - Require error-code translation when bridging protocols and draft versions. - Made a repeated non-zero Hop ID in one announcement's Hop ID list a PROTOCOL_VIOLATION, matching draft-lcurley-moq-cluster. Repeated 0 entries stay legal. - Moved the Qmux-over-WebSocket binding details to draft-lcurley-qmux-websocket; the binding itself is unchanged. @@ -1552,7 +1552,7 @@ The `Increase` Probe level (see [Probe Parameter](#probe-parameter)) lets a subs GOAWAY carries an optional New Session URI that asks the peer to reconnect elsewhere. A malicious or compromised peer could use this to redirect a client to an attacker-controlled server. A recipient MUST validate the URI against local policy (scheme, authority, and port) before reconnecting, and MUST NOT reconnect if validation fails (see [GOAWAY](#goaway)). Migrated subscriptions carry no implicit trust from the prior session; the new session is authenticated independently. ## Routing Metadata and Privacy -Hop IDs (see [ANNOUNCE_OK](#announce-ok) and [ANNOUNCE_START](#announce-start)) expose the relay path of a broadcast, which may reveal internal topology. A relay that does not wish to disclose its position MAY use the reserved value 0 ("unknown") instead of a stable identifier, at the cost of losing loop detection through itself (see [Routing](#routing)). The Hop ID announcement filter (see [Hop Parameter](#hop-parameter)) exists for loop avoidance, not access control: a subscriber cannot verify that a publisher honored it, so it MUST NOT be relied upon to hide a broadcast from a peer that declared its Hop ID. +Hop IDs (see [ANNOUNCE_OK](#announce-ok) and [ANNOUNCE_START](#announce-start)) expose the relay path of a broadcast, which may reveal internal topology. A relay that does not wish to disclose its position MAY declare 0 in ANNOUNCE_OK or omit the SETUP Hop parameter; a Hop ID list never contains 0, so the receiver assigns an identity and the path is still named (see [Routing](#routing)). The Hop ID announcement filter (see [Hop Parameter](#hop-parameter)) exists for loop avoidance, not access control: a subscriber cannot verify that a publisher honored it, so it MUST NOT be relied upon to hide a broadcast from a peer that declared its Hop ID. ## Resource Exhaustion A peer can open many streams (subscriptions, announcements, fetches), request large announce prefixes, or advertise broad patterns. Implementations SHOULD bound the number of concurrent subscriptions, announce matches, and cached groups, and SHOULD rely on QUIC flow control and stream limits to backpressure a misbehaving peer (see [ANNOUNCE_REQUEST](#announce-request)). Expiration (see [Expiration](#expiration)) bounds how long stale groups consume memory and flow control. A pattern route invites a request for any matching path, each of which may start work: an advertiser SHOULD bound the work it starts and refuse beyond that with NO_CAPACITY, and a receiver re-resolves at most once per request, so a flood of requests costs the mesh one round trip each rather than a search (see [Resolution](#resolution)). diff --git a/js/net/src/hop.ts b/js/net/src/hop.ts index fe6b3f72a5b..2a4c1a9ea69 100644 --- a/js/net/src/hop.ts +++ b/js/net/src/hop.ts @@ -30,9 +30,8 @@ export type Hop = z.infer; /** * The reserved id 0, meaning "no identity". * - * It stands in for an endpoint that never declared one, and any number of endpoints can - * be 0, so it identifies nothing: it is never a loop, never a publisher two chains have - * in common, and never excluded from an advertisement. + * Absence marker for AnnounceOk.origin, RELAY_HOPS, and excludeHop. A chain entry of 0 + * is a protocol violation: a chain names real hops only. */ export const UNKNOWN_HOP: Hop = HopSchema.parse(0n); diff --git a/js/net/src/ietf/cluster.test.ts b/js/net/src/ietf/cluster.test.ts index a063cd03421..be150d53f25 100644 --- a/js/net/src/ietf/cluster.test.ts +++ b/js/net/src/ietf/cluster.test.ts @@ -92,11 +92,12 @@ test("Cluster: a zero route cost is absent from the wire", async () => { expect(Cluster.fromParams(decoded).cost).toBe(0n); }); -test("Cluster: a repeated zero is not a loop", async () => { - const advert = { hops: hops(0n, 5n, 0n), cost: 0n }; - const encoded = await encode(Cluster.intoParams(advert)); - const decoded = await Parameters.decode(reader(encoded), VERSION); - expect(Cluster.fromParams(decoded)).toEqual(advert); +test("Cluster: a zero hop is a protocol violation", () => { + expect(() => Cluster.intoParams({ hops: hops(0n, 5n), cost: 0n })).toThrow(); + + const params = new Parameters(); + params.hopPath = new Uint8Array([0x00, 0x05]); + expect(() => Cluster.fromParams(params)).toThrow(ProtocolViolation); }); test("Cluster: a malformed advertisement is a session-fatal violation", () => { @@ -178,7 +179,7 @@ test("Cluster: we advertise our own id, and only once negotiated", () => { }); test("Cluster: a loop is detected by any non-zero id", () => { - const advert = { hops: hops(0n, 5n), cost: 0n }; + const advert = { hops: hops(1n, 5n), cost: 0n }; // A receiver whose own id is 0 cannot detect loops through itself. expect(Cluster.loops(advert, UNKNOWN_HOP)).toBe(false); diff --git a/js/net/src/ietf/cluster.ts b/js/net/src/ietf/cluster.ts index 342383adac1..fd710a4bfaf 100644 --- a/js/net/src/ietf/cluster.ts +++ b/js/net/src/ietf/cluster.ts @@ -200,8 +200,8 @@ export async function decodeParams(r: Reader, version: IetfVersion): Promise encodeAnnounceBroadcast(w, anonymous, Version.DRAFT_05))).rejects.toThrow( + ProtocolViolation, + ); +}); + +test("AnnounceBroadcast lite-03 count is the route cost", async () => { + const msg: AnnounceBroadcast = { + status: "active", + suffix: Path.from("room/cam"), + hops: [], + cost: { warm: 5n, cold: 5n }, + }; + expect(await roundTrip(msg, Version.DRAFT_03)).toEqual(msg); }); diff --git a/js/net/src/lite/announce.ts b/js/net/src/lite/announce.ts index 64197bd06c9..6be53f49391 100644 --- a/js/net/src/lite/announce.ts +++ b/js/net/src/lite/announce.ts @@ -60,8 +60,8 @@ export type AnnounceBroadcast = // Both wire rules on a hop chain, applied to what we send and to what we receive: a // chain that revisits a hop looped, so neither forwarding it nor subscribing through it -// is safe, and a receiver must end the session over one. `UNKNOWN_HOP` identifies -// nothing, so any number of hops may be unknown. +// is safe, and a receiver must end the session over one. A chain entry of 0 names +// nobody, which is the same class of violation. // // `ProtocolViolation` so a receipt takes the session down rather than the one stream, // matching what `ietf/cluster.ts` throws for the identical rule. @@ -73,22 +73,29 @@ function checkHops(hops: Hop[]) { // MAX_HOPS is 32, so the quadratic scan is cheaper than allocating a set. for (let i = 0; i < hops.length; i++) { const hop = hops[i]; - if (hop === UNKNOWN_HOP) continue; + if (hop === UNKNOWN_HOP) { + throw new ProtocolViolation("hop 0 cannot appear in a chain"); + } if (hops.indexOf(hop, i + 1) !== -1) { throw new ProtocolViolation(`hop ${hop} appears twice in the chain`); } } } -async function encodeHops(w: Writer, version: Version, hops: Hop[]) { +async function encodeHops(w: Writer, version: Version, hops: Hop[], cost?: Cost) { checkHops(hops); switch (version) { case Version.DRAFT_01: case Version.DRAFT_02: break; - case Version.DRAFT_03: - await w.u53(hops.length); + case Version.DRAFT_03: { + const count = Number(cost?.warm ?? 0n); + if (count > MAX_HOPS) { + throw new ProtocolViolation(`hop count ${count} exceeds maximum ${MAX_HOPS}`); + } + await w.u53(count); break; + } default: // Lite04+: hop count + individual Hop varints. await w.u53(hops.length); @@ -99,17 +106,18 @@ async function encodeHops(w: Writer, version: Version, hops: Hop[]) { } } -async function decodeHops(r: Reader, version: Version): Promise { +async function decodeHops(r: Reader, version: Version): Promise<{ hops: Hop[]; cost?: Cost }> { switch (version) { case Version.DRAFT_01: case Version.DRAFT_02: - return []; + return { hops: [], cost: { warm: 0n, cold: 0n } }; case Version.DRAFT_03: { const count = await r.u53(); - if (count > MAX_HOPS) throw new Error(`hop count ${count} exceeds maximum ${MAX_HOPS}`); - // Lite03 carries only a hop count, not individual ids, so every entry is - // the reserved "no identity" id. - return new Array(count).fill(UNKNOWN_HOP); + if (count > MAX_HOPS) throw new ProtocolViolation(`hop count ${count} exceeds maximum ${MAX_HOPS}`); + // Lite03 sends only a hop count. That count is the route cost: the chain + // names real hops only, so the distance lives here instead. + const n = BigInt(count); + return { hops: [], cost: { warm: n, cold: n } }; } default: { // Lite04+: hop count + individual Hop varints. @@ -120,7 +128,7 @@ async function decodeHops(r: Reader, version: Version): Promise { hops.push(HopSchema.parse(await r.u62())); } checkHops(hops); - return hops; + return { hops }; } } } @@ -143,7 +151,7 @@ async function encodeAnnounce06Body(w: Writer, msg: AnnounceBroadcast, version: switch (msg.status) { case "active": await w.string(Path.encode(msg.suffix)); - await encodeHops(w, version, msg.hops); + await encodeHops(w, version, msg.hops, msg.cost); await encodeRouteCost(w, version, msg.cost); break; case "endedId": @@ -151,7 +159,7 @@ async function encodeAnnounce06Body(w: Writer, msg: AnnounceBroadcast, version: break; case "restart": await w.u62(msg.id); - await encodeHops(w, version, msg.hops); + await encodeHops(w, version, msg.hops, msg.cost); await encodeRouteCost(w, version, msg.cost); break; case "ended": @@ -178,14 +186,14 @@ async function decodeAnnounce06Body(r: Reader, typ: number, version: Version): P switch (typ) { case ANNOUNCE_START: { const suffix = Path.decode(await r.string()); - const hops = await decodeHops(r, version); + const { hops } = await decodeHops(r, version); return { status: "active", suffix, hops, cost: await decodeRouteCost(r, version) }; } case ANNOUNCE_END: return { status: "endedId", id: await r.u62() }; case ANNOUNCE_RESTART: { const id = await r.u62(); - const hops = await decodeHops(r, version); + const { hops } = await decodeHops(r, version); return { status: "restart", id, hops, cost: await decodeRouteCost(r, version) }; } default: @@ -199,7 +207,7 @@ async function encodeLegacyBody(w: Writer, msg: AnnounceBroadcast, version: Vers case "active": await w.u8(STATUS_ACTIVE); await w.string(Path.encode(msg.suffix)); - await encodeHops(w, version, msg.hops); + await encodeHops(w, version, msg.hops, msg.cost); break; case "ended": await w.u8(STATUS_ENDED); @@ -222,8 +230,9 @@ async function decodeLegacyBody(r: Reader, version: Version): Promise { subscriber.close(); }); -// A responder that withholds its Hop ID sends the reserved 0, and an empty chain means it -// originated the path itself, so the advertisement names nobody. Two such advertisements can -// be unrelated publishers, so a restart must replace the broadcast rather than reroute it: -// cached track info and in-flight subscriptions must not splice across them. Mirrors the Rust -// `unknown_publisher_restart_replaces` regression. -test("a restart from an unidentified publisher replaces rather than reroutes", async () => { +// A responder that withholds its Hop ID sends the reserved 0. Assigned Identities +// names that peer with a session-scoped hop, so an empty chain from this stream is +// the same publisher twice: a restart splices rather than replacing. A later hop +// that names someone else is a real takeover. +test("a withheld AnnounceOk identity is assigned so a restart splices", async () => { const { subscriber, send, settle } = announceHarness(Version.DRAFT_06); const announced = subscriber.announced(Path.empty()); await settle(); @@ -206,8 +205,11 @@ test("a restart from an unidentified publisher replaces rather than reroutes", a ); expect(await announced.next()).toEqual({ prefix: Path.from("room"), active: true }); - // Nobody is named on either side, so this is not provably the same content. + // Same assigned identity, new route: nothing surfaces. await send((w) => encodeAnnounceBroadcast(w, { status: "restart", id: 0n, hops: [] }, Version.DRAFT_06)); + + // A named publisher took the path: that is a replacement. + await send((w) => encodeAnnounceBroadcast(w, { status: "restart", id: 0n, hops: [PUBLISHER_B] }, Version.DRAFT_06)); expect(await announced.next()).toEqual({ prefix: Path.from("room"), active: false }); expect(await announced.next()).toEqual({ prefix: Path.from("room"), active: true }); diff --git a/js/net/src/lite/subscriber.ts b/js/net/src/lite/subscriber.ts index 23945dda025..6952e291bba 100644 --- a/js/net/src/lite/subscriber.ts +++ b/js/net/src/lite/subscriber.ts @@ -5,7 +5,7 @@ import type { Probe as ProbeStats } from "../connection/stats.ts"; import { BroadcastCache } from "../consume.ts"; import { error, ProtocolViolation, reason, StreamCode, StreamError } from "../error.ts"; import * as netGroup from "../group.ts"; -import { type Hop, UNKNOWN_HOP } from "../hop.ts"; +import { type Hop, randomHop, UNKNOWN_HOP } from "../hop.ts"; import * as Path from "../path.ts"; import { type Reader, Stream } from "../stream.ts"; import * as Time from "../time.ts"; @@ -122,6 +122,11 @@ export class Subscriber { // own announcements on a per-call basis (see {@link AnnouncedOptions}). readonly hop: Hop; + // Assigned identity for a peer that declared none (AnnounceOk 0, or a version + // with no hop ids). A chain names real hops only, so an empty received chain + // is attributed to this session. Mirrors Rust `Subscriber::session_origin`. + readonly #sessionOrigin: Hop = randomHop(); + // Our subscribed tracks. `timescale` resolves once known (from TRACK_INFO on // lite-05+, or implicit defaults on older drafts); group streams block on it // before decoding any frame, since a group's QUIC stream can race ahead. @@ -217,11 +222,10 @@ export class Subscriber { let responderOrigin: Hop | undefined; if (hasAnnounceOk(this.version)) { const ok = await AnnounceOk.decode(stream.reader, this.version); - // A responder that withholds its identity sends the reserved 0. It names - // nobody, so folding it into a chain would stamp a placeholder that cannot - // close a loop or tell two publishers apart. Treat it as absent instead, - // which is the loop-blind route the draft describes. - responderOrigin = ok.hop === UNKNOWN_HOP ? undefined : ok.hop; + // A responder that withholds its identity sends the reserved 0. Assigned + // Identities fills that gap with a session-scoped id so a chain never names + // nobody and a restart from this peer still splices. + responderOrigin = ok.hop === UNKNOWN_HOP ? this.#sessionOrigin : ok.hop; } // Every advertisement the peer currently has live, keyed by suffix (at most one @@ -368,23 +372,17 @@ export class Subscriber { if (active) { // The first hop identifies the original publisher; an empty chain means the - // peer itself originated it. See `restart_announce` in the Rust subscriber. - const publisher = hops?.[0] ?? responderOrigin; - - // A publisher with no identity (an empty chain from a peer that withheld its - // own id, or a lite-03 UNKNOWN placeholder) never proves continuity: two such - // advertisements can be unrelated publishers. Mirrors the - // `publisher == Hop::UNKNOWN` arm of the Rust `restart_announce`. - const identified = publisher !== undefined && publisher !== UNKNOWN_HOP; + // peer itself originated it and is named by the assigned session identity. + // See `start_announce` in the Rust subscriber. + const publisher = hops?.[0] ?? responderOrigin ?? this.#sessionOrigin; // A second advertisement for a path we already carry is a restart: either an // explicit ANNOUNCE_UPDATE, or (lite-05) a duplicate ANNOUNCE. const previous = advertised.get(suffix); if (previous?.live) { - if (identified && previous.publisher === publisher) { + if (previous.publisher === publisher) { // Same publisher, new route. In-flight subscriptions resume across it, - // so there is nothing for a consumer to react to. An unidentified - // publisher falls through to the replacement path below instead. + // so there is nothing for a consumer to react to. console.debug(`announced: broadcast=${path} rerouted`); continue; } diff --git a/quest/m1/3060-moq-net-ban-hop-id-0-from-hop-chains.md b/quest/m1/3060-moq-net-ban-hop-id-0-from-hop-chains.md deleted file mode 100644 index 2dea9332b2d..00000000000 --- a/quest/m1/3060-moq-net-ban-hop-id-0-from-hop-chains.md +++ /dev/null @@ -1,120 +0,0 @@ -# [L] moq-net: ban Hop ID 0 from hop chains - -## Goal - -A hop chain names real hops only. `Hop::UNKNOWN` (Hop ID 0) stays the absence -marker in the fields that need one (`AnnounceInterest.exclude_hop`, -`AnnounceOk.origin`, `RELAY_HOPS`), but a chain entry that names nobody is a -decode-time PROTOCOL_VIOLATION on both wire dialects, so nothing has to -filter, loop-detect, or substitute around it. - -## Plan - -`Hop::UNKNOWN` (rs/moq-net/src/model/origin.rs:35, re-exported at -model/mod.rs:49) is documented as "no identity" but is legal inside a hop -chain, and that is where every problem with it comes from. A chain entry that -names nobody cannot be filtered on, cannot be loop-detected, and cannot be -told apart from another entry that also names nobody. 0 keeps its job as the -absence marker because no endpoint may adopt it as an identity, which -`Hop::new` already enforces. What changes is that a chain names real hops -only. - -### What this supersedes - -#3053 (closed): a peer that declares 0 and sends its own HOP_PATH cannot be -filtered on the identity we assigned it. Substituting the assigned id into -the chain was implemented during #3042 and reverted after producing four -defects in four review rounds: - -1. Only the terminal entry may be substituted; earlier zeros belong to - upstreams the receiver never spoke to. -2. Substituting can construct an invalid chain: `[X, 0]` from a peer assigned - `X` becomes `[X, X]`, a PROTOCOL_VIOLATION for whoever we forward it to. -3. The assigned identity must not be tested against a peer that declared - one, or its ordinary traffic is discarded as a loop. -4. The check and the substitution must be gated together, or a peer assigned - `Y` that sent `[Y, 0]` bypasses the check and gets rewritten anyway. - -Each was a new conditional on the same decision. None of them exist if the -chain cannot carry 0. Substitution also raised a privacy question: an -assigned identity is indistinguishable on the wire from a declared one, so -writing it into a forwarded chain publishes our private name for a peer that -asked not to be named. One such substitution still ships: lite/subscriber.rs: -296-307 rewrites the first `Hop::UNKNOWN` placeholder with `session_origin` -through `replace_first`, and the chain that leaves it no longer records that -the entry was assigned rather than declared. - -### Scope - -**Both wire dialects.** A non-zero Hop ID appearing twice is already a -PROTOCOL_VIOLATION on both; #3066 moved the rule into `Hops` so it holds at -construction rather than only at decode. The zero exemption lives there too: -`Hops::push` (model/origin.rs:277) and `TryFrom>` (:340-345) skip -the duplicate check for `Hop::UNKNOWN`. Drop the exemption and refuse a zero -entry outright. `HopPath::validate` (ietf/cluster.rs:88-93) only rejects an -empty list and stays as it is. - -**moq-lite-01/02/03.** These carry no real Hop IDs. Lite-03 sends a bare hop -count that lite/announce.rs:195 expands into that many `Hop::UNKNOWN` -placeholders, the only remaining source of zeros in a chain; lite-01/02 send -nothing at all. They stay supported: the count is read as the route cost -instead, which is what it was for before it was also made to carry loop -prevention, and which the lite draft already equates to it: "the accumulated -Route Costs equal the hop count and routing degenerates to shortest-path" -(drafts/draft-lcurley-moq-lite.md:789). Lite-06 carries a Warm and a Cold -Route Cost (:859-862, :888-889), so the lite-03 count feeds both halves -through `Cost::new` (model/origin.rs:449). - -The loop bound then has to come from the cost, since the count no longer -tracks chain length: - -- charge the configured link cost, with a mandatory floor of 1 on - lite-01/02/03 links. A link priced 0 is a supported config (two relays in - one datacenter) and would otherwise stop the value growing, leaving the - loop unbounded. -- reject a received value above `MAX_HOPS` (model/origin.rs:211), reproducing - today's 32-hop ceiling. -- emit the accumulated cost where `encode_hops` (lite/announce.rs:224) - currently emits `hops.len()`. - -Behavior change worth calling out: a lite-03 route's stored chain drops from -N entries to one (`[assigned_upstream_id]`), so cost carries the distance and -hop length stops standing in for it. That shifts how lite-03 routes rank -against others: `route_order` (model/origin.rs:633-639) ranks cost first, -then chain length, then a hash over the chain. - -**Drafts.** `draft-lcurley-moq-cluster` section "The Reserved Hop ID 0" -(drafts/draft-lcurley-moq-cluster.md:108) is deleted rather than amended. The -rules it anchors change with it: HOP_PATH validity becomes "no Hop ID appears -twice" with no exemption, "an advertisement whose first entry is 0 has an -unknown origin" goes away because every first entry now names a real -publisher, and "Assigned Identities" (:121) shifts from MAY to mandatory, -since a receiver has no way to spell an unnamed upstream in a chain. -`RELAY_HOPS` keeps meaning "no identity" when it carries 0; what a peer may no -longer do is put 0 in a HOP_PATH. `draft-lcurley-moq-lite` gets the matching -chain rule alongside the Hop Count rule and drops "Duplicate values of 0 are -not a violation" (draft-lcurley-moq-lite.md:886). - -The cluster section's summary, "Declaring 0 therefore trades loop detection -and failover for anonymity", becomes false rather than merely narrower: a -peer that declares 0 is assigned an identity and filtered on it, and gets no -anonymity from the chain because it can no longer write into one. - -### Done when - -Every `== Hop::UNKNOWN` / `!= Hop::UNKNOWN` test that exists to ask "does this -chain entry name anybody" is gone, across lite/subscriber.rs, -lite/publisher.rs:612, ietf/subscriber.rs, ietf/publisher.rs, -ietf/cluster.rs, and model/origin.rs. The marker survives only where it means -"this field is absent" (server.rs:404 is one). Any survivor in the first -category means 0 is still special somewhere and the change is incomplete. - -Targets `dev`: it changes published `moq-net` API. - -## Closes - -- [#3060](https://github.com/moq-dev/moq/issues/3060) - close this issue when the quest finishes - -## Related - -- [#3053](https://github.com/moq-dev/moq/issues/3053) - closed; the substitution approach this supersedes diff --git a/quest/m1/README.md b/quest/m1/README.md index de21a29b9c2..6bfc1500e11 100644 --- a/quest/m1/README.md +++ b/quest/m1/README.md @@ -30,7 +30,6 @@ with the dev tree. - [JS announce](/quest/m1/js-announce.md) - js/net drops `publish()` and `RouteProvider` for `createBroadcast`, `announce(route)`, and a `dynamic(pattern, route)` handle - [Wildcard](/quest/m1/wildcard/README.md) - a service advertises a path pattern priced at its start-up cost; Advertise gates the merge, Resolve and Demand are additive - [Route cold cost](/quest/m1/route-cold-cost.md) - MoqRoute carries warm and cold, so an observed route re-announces intact -- [#3060](/quest/m1/3060-moq-net-ban-hop-id-0-from-hop-chains.md) - a hop chain names real hops only; Hop ID 0 stays the absence marker - [Group overflow](/quest/m1/group-overflow-abort.md) - an open group past its budget aborts for every reader with GROUP_TOO_LARGE, and head eviction is deleted - [#2774](/quest/m1/2774-collapse-reload-and-shared-into-one-connection-class.md) - one cloneable refcounted `Connection` mirroring `moq_tokio::Connection`; close releases a handle - [Close classification](/quest/m1/js-close-classification.md) - a browser consumer tells a requested end from a fault, so the media harness fails on real errors during a transition diff --git a/rs/moq-net/CHANGELOG.md b/rs/moq-net/CHANGELOG.md index 6a8c4765c3e..d7e81054766 100644 --- a/rs/moq-net/CHANGELOG.md +++ b/rs/moq-net/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Changed + +- A hop chain names real hops only: `Hops` refuses a zero entry, and `Hops::replace_first` is removed. Hop ID 0 remains the absence marker for AnnounceOk, RELAY_HOPS, and `exclude_hop`. + ## [0.2.19](https://github.com/moq-dev/moq/compare/moq-net-v0.2.18...moq-net-v0.2.19) - 2026-09-09 ### Added diff --git a/rs/moq-net/src/ietf/cluster.rs b/rs/moq-net/src/ietf/cluster.rs index 8e07b336daf..67c85480424 100644 --- a/rs/moq-net/src/ietf/cluster.rs +++ b/rs/moq-net/src/ietf/cluster.rs @@ -68,9 +68,9 @@ pub struct HopPath(Hops); impl HopPath { /// Wrap a hop chain. /// - /// [`Hops`] already refuses a repeated non-zero entry, so the only wire rule - /// left to check is that the list is non-empty; [`Self::validate`] does that on - /// decode, where an empty parameter can arrive. + /// [`Hops`] already refuses a zero entry and a repeated entry, so the only wire + /// rule left to check is that the list is non-empty; [`Self::validate`] does that + /// on decode, where an empty parameter can arrive. pub fn new(hops: Hops) -> Self { Self(hops) } @@ -82,9 +82,9 @@ impl HopPath { /// Reject a path that cannot have come from a conforming sender. /// - /// Only the empty list is left to catch: the other rule, that a non-zero Hop ID may - /// not appear twice, is enforced by [`Hops`] wherever a chain is built, so it - /// holds on the outbound path too rather than only where one was parsed. + /// Only the empty list is left to catch: the other rules, that no Hop ID is 0 + /// and none appears twice, are enforced by [`Hops`] wherever a chain is built, so + /// they hold on the outbound path too rather than only where one was parsed. fn validate(&self) -> Result<(), DecodeError> { match self.0.is_empty() { true => Err(DecodeError::InvalidValue), @@ -158,8 +158,8 @@ impl Advert { /// Whether this advertisement looped back through `self_hop`. /// /// A receiver discards such an advertisement: forwarding it would extend the loop, - /// and subscribing through it would route the receiver back to itself. Hop ID 0 - /// identifies nothing, so a receiver that withheld its own identity detects nothing. + /// and subscribing through it would route the receiver back to itself. A receiver + /// that withheld its own identity (Hop ID 0) detects nothing. pub fn loops(&self, self_hop: Hop) -> bool { self_hop != Hop::UNKNOWN && self.hops.hops().contains(&self_hop) } @@ -283,13 +283,7 @@ mod tests { } fn hop_path(ids: &[u64]) -> HopPath { - let hops = ids - .iter() - .map(|&id| match id { - 0 => Hop::UNKNOWN, - id => hop(id), - }) - .collect::>(); + let hops = ids.iter().map(|&id| hop(id)).collect::>(); HopPath::new(Hops::try_from(hops).unwrap()) } @@ -333,10 +327,23 @@ mod tests { } #[test] - fn hop_path_allows_repeated_zero() { - // 0 identifies nothing, so two unknown hops are not a loop. - let path = hop_path(&[0, 5, 0]); - assert_eq!(round_trip(&path).unwrap(), path); + fn hop_path_rejects_zero() { + // 0 names nobody, so a chain entry of 0 is a protocol violation. The bytes + // are forged rather than encoded from a `HopPath`, because `Hops` no longer + // lets one be built. + let mut value = Vec::new(); + for id in [0u64, 5, 0] { + id.encode(&mut value, VERSION).unwrap(); + } + + let mut buf = BytesMut::new(); + value.encode(&mut buf, VERSION).unwrap(); + + let mut bytes = buf.freeze(); + assert!(matches!( + HopPath::param_decode(&mut bytes, VERSION), + Err(DecodeError::InvalidValue) + )); } #[test] @@ -429,7 +436,7 @@ mod tests { #[test] fn loops_ignores_unknown() { let advert = Advert { - hops: hop_path(&[0, 5]), + hops: hop_path(&[1, 5]), cost: 0, }; // A receiver whose own id is 0 cannot detect loops through itself. diff --git a/rs/moq-net/src/ietf/publisher.rs b/rs/moq-net/src/ietf/publisher.rs index 888a6f54414..42adb386610 100644 --- a/rs/moq-net/src/ietf/publisher.rs +++ b/rs/moq-net/src/ietf/publisher.rs @@ -2804,10 +2804,6 @@ mod tests { /// Declaring the reserved 0 turns the extension on while naming nobody, so the /// identity we assigned stands in, exactly as for a peer that never negotiated. - /// Asserted on the resolution itself rather than through an advertisement: a - /// negotiated peer always sends its own HOP_PATH, so a route attributed to the - /// assigned identity is a state this peer class cannot reach; see - /// [`a_declared_zero_chain_is_still_advertised_back`] for what it gets instead. #[tokio::test(start_paused = true)] async fn withheld_peer_hop_falls_back_to_assigned() { let assigned = crate::Hop::new(777).unwrap(); @@ -2831,13 +2827,10 @@ mod tests { assert_eq!(publisher.exclude(&named), declared, "a declared identity wins"); } - /// A peer that negotiated the extension MUST send a HOP_PATH on every advertisement, - /// and one that declared 0 names itself 0 there. An arriving chain is not rewritten, - /// so the route carries 0, the assigned identity appears nowhere in it, and the - /// split-horizon filter has nothing to match: the peer is advertised its own route - /// back. + /// A peer that declared 0 cannot put 0 in a HOP_PATH, so the route we attributed + /// to it carries the identity we assigned, and the split-horizon filter matches. #[tokio::test(start_paused = true)] - async fn a_declared_zero_chain_is_still_advertised_back() { + async fn a_declared_zero_peer_is_filtered_on_its_assigned_identity() { let assigned = crate::Hop::new(777).unwrap(); let origin = crate::origin::Info::new(crate::Hop::new(1).unwrap()).produce(); let consumer = origin.consume(); @@ -2852,9 +2845,9 @@ mod tests { Version::Draft16, ); - // The chain as ingress stores it: the peer named itself 0. + // The chain as ingress stores it: we named the unnamed upstream ourselves. let mut hops = crate::Hops::new(); - hops.push(crate::Hop::UNKNOWN).unwrap(); + hops.push(assigned).unwrap(); let _echoed = origin .announce("from/peer", crate::origin::Route::default().with_hops(hops)) .unwrap(); @@ -2863,14 +2856,8 @@ mod tests { hop: Some(crate::Hop::UNKNOWN), cost: None, }; - // The excluding cursor cannot match hop 0 (it names nobody), so the route - // still reaches this peer's stream. let mut announced = consumer.excluding(publisher.exclude(&peer)).announced(); - let echoed = announced.assert_next_active("from/peer"); - assert!( - publisher.select(&echoed, &peer).wanted(), - "known gap: the assigned identity is not in the chain, so nothing filters it", - ); + announced.assert_next_wait(); } /// A same-path source can splice into (or detach from) an existing broadcast diff --git a/rs/moq-net/src/ietf/subscriber.rs b/rs/moq-net/src/ietf/subscriber.rs index 0e1670dfd97..d53489c99c0 100644 --- a/rs/moq-net/src/ietf/subscriber.rs +++ b/rs/moq-net/src/ietf/subscriber.rs @@ -355,11 +355,8 @@ pub(super) struct Subscriber for AnnounceBroadcast<'_> { let mut body = Vec::new(); match self { // The cost is a lite-06 addition, so it is simply not on the wire here. - Self::Active { suffix, hops, .. } => { + Self::Active { suffix, hops, cost } => { AnnounceStatus::Active.encode(&mut body, version)?; suffix.encode(&mut body, version)?; - encode_hops(&mut body, version, hops)?; + encode_hops(&mut body, version, hops, cost.warm)?; } Self::Ended { suffix, hops } => { AnnounceStatus::Ended.encode(&mut body, version)?; suffix.encode(&mut body, version)?; - encode_hops(&mut body, version, hops)?; + encode_hops(&mut body, version, hops, 0)?; } // The id-referencing forms only exist on lite-06+. Self::EndedId { .. } | Self::Restart { .. } => return Err(EncodeError::Version), @@ -184,47 +184,38 @@ impl AnnounceBroadcast<'_> { let status = AnnounceStatus::decode(r, version)?; let suffix = Path::decode(r, version)?; - let hops = match version { - Version::Lite01 | Version::Lite02 => Hops::new(), + let (hops, cost) = match version { + Version::Lite01 | Version::Lite02 => (Hops::new(), Cost::new(0)), Version::Lite03 => { - // Lite03 sends only a hop count, not individual ids. Fill with UNKNOWN placeholders. - // push() enforces MAX_HOPS and `?` lifts the overflow to DecodeError::BoundsExceeded. - let count = u64::decode(r, version)? as usize; - let mut list = Hops::new(); - for _ in 0..count { - list.push(Hop::UNKNOWN)?; + // Lite03 sends only a hop count. That count is the route cost: the + // chain names real hops only, so the distance lives here instead. + let count = u64::decode(r, version)?; + if count as usize > MAX_HOPS { + return Err(DecodeError::BoundsExceeded); } - list + (Hops::new(), Cost::new(count)) } - _ => Hops::decode(r, version)?, + _ => (Hops::decode(r, version)?, Cost::UNKNOWN), }; Ok(match status { - AnnounceStatus::Active => Self::Active { - suffix, - hops, - cost: Cost::UNKNOWN, - }, + AnnounceStatus::Active => Self::Active { suffix, hops, cost }, AnnounceStatus::Ended => Self::Ended { suffix, hops }, // On lite-05 a restart travels as a duplicate ANNOUNCE (a second `Active`), so accept // the draft's explicit `restart` status and treat it the same. Either way the // subscriber retires an already-announced path before republishing it; for an unknown // path it's a fresh announce. Older versions never defined this status, so it's an // invalid value there. - AnnounceStatus::Restart if restart_supported(version) => Self::Active { - suffix, - hops, - cost: Cost::UNKNOWN, - }, + AnnounceStatus::Restart if restart_supported(version) => Self::Active { suffix, hops, cost }, AnnounceStatus::Restart => return Err(DecodeError::InvalidValue), }) } } -fn encode_hops(w: &mut W, version: Version, hops: &Hops) -> Result<(), EncodeError> { +fn encode_hops(w: &mut W, version: Version, hops: &Hops, cost: u64) -> Result<(), EncodeError> { match version { Version::Lite01 | Version::Lite02 => Ok(()), - Version::Lite03 => (hops.len() as u64).encode(w, version), + Version::Lite03 => cost.encode(w, version), _ => hops.encode(w, version), } } @@ -473,6 +464,65 @@ mod tests { } } + #[test] + fn announce_broadcast_lite03_count_is_the_route_cost() { + let msg = AnnounceBroadcast::Active { + suffix: Path::new("room/cam"), + hops: Hops::new(), + cost: Cost::new(5), + }; + assert_eq!(broadcast_round_trip(&msg, Version::Lite03), msg); + } + + #[test] + fn announce_broadcast_lite03_rejects_a_count_above_max_hops() { + let mut buf = bytes::BytesMut::new(); + AnnounceBroadcast::Active { + suffix: Path::new("room/cam"), + hops: Hops::new(), + cost: Cost::new(MAX_HOPS as u64), + } + .encode(&mut buf, Version::Lite03) + .unwrap(); + // Layout: . The count is the last byte. + let last = buf.len() - 1; + assert_eq!(buf[last], MAX_HOPS as u8); + buf[last] = (MAX_HOPS as u8) + 1; + let mut slice = &buf[..]; + assert!( + matches!( + AnnounceBroadcast::decode(&mut slice, Version::Lite03), + Err(DecodeError::BoundsExceeded) + ), + "a lite-03 hop count above MAX_HOPS must be rejected" + ); + } + + #[test] + fn announce_broadcast_rejects_a_zero_hop() { + let mut hops = Hops::new(); + hops.push(Hop::new(7).unwrap()).unwrap(); + let mut buf = bytes::BytesMut::new(); + AnnounceBroadcast::Active { + suffix: Path::new("room/cam"), + hops, + cost: Cost::UNKNOWN, + } + .encode(&mut buf, Version::Lite05) + .unwrap(); + // The hop id 7 is a one-byte varint; rewrite it to 0. + let seven = buf.iter().position(|&b| b == 7).expect("hop id 7 on the wire"); + buf[seven] = 0; + let mut slice = &buf[..]; + assert!( + matches!( + AnnounceBroadcast::decode(&mut slice, Version::Lite05), + Err(DecodeError::InvalidValue) + ), + "a chain entry of 0 is a protocol violation" + ); + } + #[test] fn announce_broadcast_round_trip_on_lite05() { let mut hops = Hops::new(); diff --git a/rs/moq-net/src/lite/publisher.rs b/rs/moq-net/src/lite/publisher.rs index 39db1163202..3ee6600eb05 100644 --- a/rs/moq-net/src/lite/publisher.rs +++ b/rs/moq-net/src/lite/publisher.rs @@ -615,18 +615,28 @@ impl AnnounceRun { } // Lite05+ moves the self-stamp to the receiver, which appends our id (reported - // once via AnnounceOk) on receipt. Older versions stamp it here, dropping if the - // chain is full. - if !self.version.has_announce_ok() && hops.push(self.self_origin).is_err() { + // once via AnnounceOk) on receipt. Lite-04 stamps it here. Lite-01/02/03 have + // no hop ids: the cost carries the distance, so stamping would only fail for + // an anonymous publisher (id 0 cannot enter a chain). + if self.version.has_hop_ids() + && !self.version.has_announce_ok() + && self.self_origin != Hop::UNKNOWN + && hops.push(self.self_origin).is_err() + { tracing::warn!(route = %absolute, "dropping announce; hop chain at MAX_HOPS (possible loop)"); return None; } - // Pre-lite-06 wires carry no cost at all, leaving hop count as the - // effective metric exactly as before. + if !self.version.has_hop_ids() && route.cost.warm > crate::origin::MAX_HOPS as u64 { + tracing::warn!(route = %absolute, "dropping announce; lite-03 cost above MAX_HOPS (possible loop)"); + return None; + } + + // Pre-lite-06 wires carry no cost field; lite-03 still emits the accumulated + // cost as its hop count, so keep it. Lite-04/05 rank on hop count alone. let cost = match self.version.has_route_cost() { true => route.cost.clamped(), - false => crate::origin::Cost::UNKNOWN, + false => route.cost, }; Some((hops, cost)) } diff --git a/rs/moq-net/src/lite/subscriber.rs b/rs/moq-net/src/lite/subscriber.rs index 41e33faaff6..8065183c9ec 100644 --- a/rs/moq-net/src/lite/subscriber.rs +++ b/rs/moq-net/src/lite/subscriber.rs @@ -54,22 +54,13 @@ pub(super) struct Subscriber { // they never hit the wire, but this check is what makes it correct. self_origin: crate::Hop, // The origin stamped into the hop chain of broadcasts from versions that - // don't carry real hop ids on the wire (Lite01/02/03), and into the - // placeholder entries Lite03 sends in place of real ids. + // don't carry real hop ids on the wire (Lite01/02/03), and for a peer that + // declared none (AnnounceOk origin 0). // // This is the peer's assigned identity (`peer_hop`) when the caller gave // it one, which also makes the route recognizable across sessions. Otherwise - // it is `Hop::UNKNOWN` (0), the reserved "no identity" value. - // - // Assigning one is the caller's call, not this layer's: a server gives every - // accepted session a fresh id so its routes are at least distinguishable from - // another session's, while a client only assigns one it knows out of band. Either - // way the peer never learns the id, so only we can exclude it for loop detection. + // a fresh id, because a chain cannot name nobody. session_origin: crate::Hop, - // The identity assigned to the peer by the caller (`Client::with_peer_hop`, - // or the per-session default a server hands every request), standing in wherever - // the peer declines to declare one (an AnnounceOk reporting origin id 0). - peer_hop: Option, subscribes: Lock>, next_id: Arc, version: Version, @@ -103,8 +94,7 @@ impl Subscriber { origin: config.origin, recv_bandwidth: config.recv_bandwidth, self_origin, - session_origin: config.peer_hop.unwrap_or(crate::Hop::UNKNOWN), - peer_hop: config.peer_hop, + session_origin: config.peer_hop.unwrap_or_else(crate::Hop::random), subscribes: Default::default(), next_id: Default::default(), version: config.version, @@ -140,6 +130,11 @@ impl Subscriber { // Older versions carry no cost on the wire, so nothing is charged and their // routes rank on hop count alone. Returning early also avoids blocking on a // SETUP that versions without a Setup Stream never send. + if !self.version.has_hop_ids() { + // Lite-01/02/03 have no hop ids, so the loop bound is the cost. A + // link priced 0 would stop that value growing; floor it at 1. + return Poll::Ready(self.cost.unwrap_or(0).max(1)); + } if !self.version.has_route_cost() { return Poll::Ready(0); } @@ -263,12 +258,11 @@ impl Subscriber { // replacing this, or declines it and leaves it exactly as reserved. announced.reserve(path.clone()); - if let Some(responder) = responder_origin { + if let Some(responder) = responder_origin.filter(|hop| *hop != crate::Hop::UNKNOWN) { // A chain already naming the sender came back through it: a reflection, and - // appending the sender again would name it twice. That is legal in a lite - // chain but a PROTOCOL_VIOLATION for an IETF peer we forward it to, so it - // must not enter the model at all. Zero names nobody, so it may repeat. - if responder != crate::Hop::UNKNOWN && hops.contains(&responder) { + // appending the sender again would name it twice, which is a PROTOCOL_VIOLATION + // for any peer we forward it to, so it must not enter the model at all. + if hops.contains(&responder) { tracing::debug!(broadcast = %self.log_path(&path), "dropping announce reflected by its sender"); return Ok(false); } @@ -293,24 +287,9 @@ impl Subscriber { return Ok(false); } - // Lite03 carries its hop count as UNKNOWN placeholders rather than real - // ids. Rewrite the first placeholder with this connection's origin so - // the route is attributable to the upstream session, without changing - // the hop count (shortest-path selection and the MAX_HOPS limit stay - // accurate). Lite01/02 send no placeholders; they're covered below. - // - // The rewrite fails if the chain already names this session, which would put one - // id in it twice: a loop, and one a cluster receiver must close the session over. - if self.version_lacks_hops() && hops.replace_first(crate::Hop::UNKNOWN, self.session_origin).is_err() { - tracing::debug!(broadcast = %self.log_path(&path), "dropping announce reflected by its session"); - return Ok(false); - } - // Guarantee at least one attributable hop for versions that did not provide - // one. Lite05 peers may legally advertise responder id 0; preserve it above - // rather than replacing it, even though that route stays loop-blind (the - // caller can assign an identity via `with_peer_hop`, substituted where - // the AnnounceOk is read). + // one. A peer that advertised responder id 0 is assigned `session_origin` + // where the AnnounceOk is read, so this chain names that identity. if hops.is_empty() { hops.push(self.session_origin) .expect("an empty hop chain always has room for one entry, and repeats nothing"); @@ -353,12 +332,11 @@ impl Subscriber { /// Handle a RESTART (an explicit restart status, or a duplicate ANNOUNCE on lite-05). /// /// The first hop of the chain identifies the original publisher. When it matches - /// the prior advertisement and is a real identity, the broadcast is the same - /// content on a new path: this session's route metadata updates in place, - /// in-flight tracks keep flowing, and the origin only hands over if the winner - /// changed. Consumers observe nothing. When the first hop differs, or is - /// [`Hop::UNKNOWN`](crate::Hop::UNKNOWN), the old route detaches gracefully - /// and a fresh one attaches, so downstream sees a real Ended + Active. + /// the prior advertisement, the broadcast is the same content on a new path: this + /// session's route metadata updates in place, in-flight tracks keep flowing, and + /// the origin only hands over if the winner changed. Consumers observe nothing. + /// When the first hop differs, or the chain is empty, the old route detaches + /// gracefully and a fresh one attaches, so downstream sees a real Ended + Active. /// The advertisement is already live, so this can attach a route even when the /// original advertisement was declined locally. /// @@ -378,12 +356,10 @@ impl Subscriber { announced: &mut Announced, ) -> Result { // Reflected loop (or a full chain): detach its route but keep the advertisement live. - let reflected = match responder_origin { + let reflected = match responder_origin.filter(|hop| *hop != crate::Hop::UNKNOWN) { // A chain already naming the sender came back through it; see `start_announce`. Some(responder) => { - (responder != crate::Hop::UNKNOWN && hops.contains(&responder)) - || hops.push(responder).is_err() - || hops.contains(&self.self_origin) + hops.contains(&responder) || hops.push(responder).is_err() || hops.contains(&self.self_origin) } None => hops.contains(&self.self_origin), }; @@ -448,12 +424,6 @@ impl Subscriber { fn log_path(&self, path: impl AsPath) -> Path<'_> { self.origin.root().join(path) } - - /// True for versions that don't carry a real hop list on the wire, so the - /// received chain is empty (Lite01/02) or anonymous placeholders (Lite03). - fn version_lacks_hops(&self) -> bool { - matches!(self.version, Version::Lite01 | Version::Lite02 | Version::Lite03) - } } /// The subscriber half's driver: the announce prefixes, the uni-stream accept @@ -1163,7 +1133,7 @@ impl AnnouncePrefix { // A peer may legally report id 0 (no identity). When the caller assigned // it one, stand that in so the route isn't loop-blind. let origin = match ok.origin.id() { - 0 => self.subscriber.peer_hop.unwrap_or(ok.origin), + 0 => self.subscriber.session_origin, _ => ok.origin, }; let PrefixState::ReadOk { stream } = std::mem::replace(&mut self.state, PrefixState::Open) else { @@ -1959,8 +1929,8 @@ mod tests { /// /// The decline paths are a list one edit can fall off the end of, and a miss is silent: /// the path reads as free, a later announce takes it, and the declined one's - /// `ANNOUNCE_END` retires that route instead. This walks the one that is hardest to - /// reach, where rewriting a placeholder hop would name this session twice. + /// `ANNOUNCE_END` retires that route instead. This walks a chain that already names + /// this session, which is declined as a reflection. #[tokio::test] async fn every_declined_announce_is_recorded() { let assigned = crate::Hop::new(777).unwrap(); @@ -1969,8 +1939,6 @@ mod tests { session: SinkSession::new(Default::default()), origin, recv_bandwidth: None, - // Lite03 sends placeholders rather than real ids, so this is the version whose - // chain gets rewritten on the way in. version: Version::Lite03, peer_setup: Default::default(), cost: None, @@ -1981,9 +1949,8 @@ mod tests { let path = Path::new("room/host").to_owned(); let mut announced = Announced::default(); - // A chain whose placeholder cannot be rewritten: this session's id is already in it, - // so writing it over the placeholder would name it twice. - let hops = crate::Hops::try_from(vec![crate::Hop::UNKNOWN, assigned]).unwrap(); + // A chain that already names us: a reflection, declined. + let hops = crate::Hops::try_from(vec![crate::Hop::new(1).unwrap()]).unwrap(); assert!( !subscriber .start_announce( @@ -1995,7 +1962,7 @@ mod tests { &mut announced ) .unwrap(), - "a chain that cannot take this session's id must be declined", + "a chain that already names this session must be declined", ); // Declined, but still the peer's advertisement at that path. @@ -2147,12 +2114,11 @@ mod tests { assert_eq!(hops, vec![assigned]); } - /// A peer with no assigned identity is attributed the reserved origin 0 - /// (UNKNOWN). This layer never mints one of its own: whether an anonymous peer - /// gets an identity, and whether two of its sessions share it, is the caller's - /// policy, and a minted id here would be indistinguishable from a declared one. + /// A peer with no assigned identity still gets a real hop: a chain cannot name + /// nobody, so this layer mints one. Two sessions without `with_peer_hop` look + /// like different publishers; the caller pins a stable id when they are the same. #[tokio::test] - async fn absent_peer_hop_stamps_unknown() { + async fn absent_peer_hop_stamps_a_real_hop() { let (mut subscriber, consumer) = restart_subscriber(SinkSession::new(Default::default())); let mut announced = Announced::default(); @@ -2170,7 +2136,8 @@ mod tests { let mut cursor = consumer.announced(); let route = cursor.assert_next_active("room/host"); let hops: Vec<_> = route.hops.iter().copied().collect(); - assert_eq!(hops, vec![crate::Hop::UNKNOWN]); + assert_eq!(hops.len(), 1); + assert_ne!(hops[0], crate::Hop::UNKNOWN); } fn restart_subscriber(session: SinkSession) -> (Subscriber, crate::origin::Consumer) { diff --git a/rs/moq-net/src/lite/version.rs b/rs/moq-net/src/lite/version.rs index 54e8d1a3ac3..8625daa4832 100644 --- a/rs/moq-net/src/lite/version.rs +++ b/rs/moq-net/src/lite/version.rs @@ -73,6 +73,17 @@ impl Version { } } + /// Whether announcements carry a list of Hop IDs. Lite-01/02 send none; lite-03 + /// sends only a hop count, which is the route cost. Added in lite-04. + #[allow(clippy::match_like_matches_macro)] + pub fn has_hop_ids(self) -> bool { + // Match form so future versions default forward (CLAUDE.md convention). + match self { + Self::Lite01 | Self::Lite02 | Self::Lite03 => false, + _ => true, + } + } + /// Whether announce streams begin with ANNOUNCE_OK and omit the sender's origin /// from each announcement's hop chain. Added in lite-05. #[allow(clippy::match_like_matches_macro)] diff --git a/rs/moq-net/src/model/mod.rs b/rs/moq-net/src/model/mod.rs index 168c982ad02..d6db9839a6a 100644 --- a/rs/moq-net/src/model/mod.rs +++ b/rs/moq-net/src/model/mod.rs @@ -34,6 +34,7 @@ pub use time::*; /// Publishing broadcasts, announcing routes, and consuming both through an origin. pub mod origin { + pub(crate) use super::origin_impl::MAX_HOPS; pub use super::origin_impl::{ Consumer, Cost, DRAIN_COST, Driver, Dynamic, Info, MAX_COST, Prefix, Producer, Request, Requesting, Route, Run, }; diff --git a/rs/moq-net/src/model/origin.rs b/rs/moq-net/src/model/origin.rs index 4d265c24f39..234ccf532cd 100644 --- a/rs/moq-net/src/model/origin.rs +++ b/rs/moq-net/src/model/origin.rs @@ -29,8 +29,9 @@ use crate::{ /// passes through, so a receiver can spot its own id and reject a loop. /// /// Local hops are built with [`Hop::new`] or [`Hop::random`], both of which guarantee a -/// non-zero id so loop detection can work. Remote peers may still send `0`; it is legal -/// on the wire but cannot be used for loop detection. +/// non-zero id so loop detection can work. Remote peers may still send `0` in the fields +/// that mean "no identity" (AnnounceOk.origin, RELAY_HOPS, `exclude_hop`); a chain +/// entry of 0 is a protocol violation. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct Hop { /// 62-bit identifier. Encoded as a QUIC varint on the wire. @@ -38,15 +39,15 @@ pub struct Hop { } impl Hop { - /// Placeholder for hop entries whose actual id is not on the wire (Lite03). - /// Also used for remote peers that choose the legal but loop-blind id 0. + /// Absence marker: no identity in AnnounceOk.origin, RELAY_HOPS, or `exclude_hop`. + /// Never a chain entry. pub(crate) const UNKNOWN: Self = Self { id: 0 }; /// Build a hop from a stable id. /// /// The id must be non-zero and fit in the 62-bit QUIC varint range. Wire - /// decode accepts remote id 0, but a local hop should not use it because - /// downstream peers cannot exclude it for loop detection. + /// decode accepts 0 in the fields that mean "no identity", but a local hop + /// must not use it, and a chain must not contain it. pub fn new(id: u64) -> Result { if id == 0 || id >= 1u64 << 62 { return Err(InvalidHop::Range); @@ -212,11 +213,11 @@ pub(crate) const MAX_HOPS: usize = 32; /// Bounded, loop-free list of [`Hop`] entries: the hop chain of a broadcast. /// -/// Guarantees `len() <= MAX_HOPS` and that no non-zero [`Hop`] appears twice. Both -/// are wire rules, and both hold wherever a list exists rather than only where one was -/// parsed, so a chain that a conforming receiver would reject cannot be built and sent. -/// Construct via [`Hops::new`] + [`Hops::push`], or fall back to the -/// fallible [`TryFrom>`]. +/// Guarantees `len() <= MAX_HOPS`, that no entry is 0, and that no +/// [`Hop`] appears twice. Those are wire rules, and they hold wherever a list exists +/// rather than only where one was parsed, so a chain that a conforming receiver would +/// reject cannot be built and sent. Construct via [`Hops::new`] + [`Hops::push`], or +/// fall back to the fallible [`TryFrom>`]. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Hops(Vec); @@ -224,8 +225,8 @@ pub struct Hops(Vec); #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[non_exhaustive] pub enum InvalidHop { - /// The id is zero or outside the 62-bit wire range, so it cannot identify a local - /// hop. Only [`Hop::new`] returns this; a chain never holds one. + /// The id is zero or outside the 62-bit wire range, so it cannot identify a hop. + /// [`Hop::new`] returns this for a local hop; a chain returns it for a zero entry. Range, /// The list is already at its hop-count cap, which a real path never reaches and a @@ -233,15 +234,14 @@ pub enum InvalidHop { TooMany, /// The id is already in the list. A chain that revisits a hop looped, which every - /// receiver of it must reject, so it must not be built in the first place. The - /// reserved id 0 identifies nothing and may repeat. + /// receiver of it must reject, so it must not be built in the first place. Duplicate, } impl fmt::Display for InvalidHop { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::Range => write!(f, "local hop id must be non-zero and below 2^62"), + Self::Range => write!(f, "hop id must be non-zero and below 2^62"), Self::TooMany => write!(f, "too many hops (max {MAX_HOPS})"), Self::Duplicate => write!(f, "hop already in the chain"), } @@ -267,46 +267,23 @@ impl Hops { /// Append an [`Hop`], rejecting anything a conforming receiver would. /// - /// Fails with [`InvalidHop::TooMany`] once the list is full, and with - /// [`InvalidHop::Duplicate`] for an id already in the chain, which is a loop. The - /// reserved id 0 identifies nothing, so it may repeat. + /// Fails with [`InvalidHop::Range`] for the reserved id 0, which names nobody; + /// with [`InvalidHop::TooMany`] once the list is full; and with + /// [`InvalidHop::Duplicate`] for an id already in the chain, which is a loop. pub fn push(&mut self, hop: Hop) -> Result<(), InvalidHop> { + if hop == Hop::UNKNOWN { + return Err(InvalidHop::Range); + } if self.0.len() >= MAX_HOPS { return Err(InvalidHop::TooMany); } - if hop != Hop::UNKNOWN && self.0.contains(&hop) { + if self.0.contains(&hop) { return Err(InvalidHop::Duplicate); } self.0.push(hop); Ok(()) } - /// Replace the first entry equal to `target` with `replacement`, returning - /// true if a match was found. The length is unchanged. - /// - /// Fails with [`InvalidHop::Duplicate`] only when the rewrite would actually name - /// `replacement` twice, which is the loop [`Self::push`] refuses to build. A `target` - /// that is not present changes nothing and so cannot duplicate anything, and the slot - /// being overwritten is not a duplicate of itself. - pub fn replace_first(&mut self, target: Hop, replacement: Hop) -> Result { - let Some(index) = self.0.iter().position(|entry| *entry == target) else { - return Ok(false); - }; - - if replacement != Hop::UNKNOWN - && self - .0 - .iter() - .enumerate() - .any(|(i, entry)| i != index && *entry == replacement) - { - return Err(InvalidHop::Duplicate); - } - - self.0[index] = replacement; - Ok(true) - } - /// Returns true if any entry matches `hop`. pub fn contains(&self, hop: &Hop) -> bool { self.0.contains(hop) @@ -342,7 +319,10 @@ impl TryFrom> for Hops { } // MAX_HOPS is 32, so the quadratic scan is cheaper than allocating a set. for (i, hop) in v.iter().enumerate() { - if *hop != Hop::UNKNOWN && v[i + 1..].contains(hop) { + if *hop == Hop::UNKNOWN { + return Err(InvalidHop::Range); + } + if v[i + 1..].contains(hop) { return Err(InvalidHop::Duplicate); } } @@ -554,8 +534,8 @@ pub struct Route { impl Route { /// Append a hop to the chain, oldest first. /// - /// Fails with [`crate::InvalidHop`] for a hop the wire would reject: one past the - /// chain's length cap, or one already in it, which is a loop. + /// Fails with [`crate::InvalidHop`] for a hop the wire would reject: the reserved + /// id 0, one past the chain's length cap, or one already in it, which is a loop. pub fn with_hop(mut self, hop: Hop) -> Result { self.hops.push(hop)?; Ok(self) @@ -829,8 +809,8 @@ impl TableCursor { /// Whether this cursor may observe `entry` at all (split horizon). fn visible(&self, entry: &RouteEntry) -> bool { match self.exclude { - Some(peer) if peer != Hop::UNKNOWN => !entry.hops.contains(&peer), - _ => true, + Some(peer) => !entry.hops.contains(&peer), + None => true, } } } @@ -2498,10 +2478,9 @@ enum Identity { /// No source has attached yet: the first request may resolve through any /// covering route, and whoever serves it fixes the identity. Undetermined, - /// The serving route's first hop was absent or [`Hop::UNKNOWN`], which - /// identifies nobody and never matches itself: the front cannot resume, so - /// its source ending ends it. Two anonymous publishers must never pass for - /// one reconnecting. + /// The serving route had no first hop, so it identifies nobody and never + /// matches itself: the front cannot resume, and its source ending ends it. + /// Two anonymous publishers must never pass for one reconnecting. Anonymous, /// The first hop of the serving route: the endpoint that originated it. /// Routes sharing it are the same origin reached another way and safe to @@ -2827,8 +2806,8 @@ impl FrontDriver { self.serving = Some((id, route, source)); if self.identity == Identity::Undetermined { self.identity = match first { - Some(hop) if hop != Hop::UNKNOWN => Identity::Publisher(hop), - _ => Identity::Anonymous, + Some(hop) => Identity::Publisher(hop), + None => Identity::Anonymous, }; } if let Some(request) = self.initial.take() @@ -2999,8 +2978,7 @@ impl OriginState { /// With `publisher` set, only routes originated by that first hop are /// candidates: this is the identity a front resumes through, and a route from /// anyone else is different content rather than an alternate path (see - /// [`run_remote_front`]). `Hop::UNKNOWN` identifies nobody, so callers never - /// pin it. + /// [`run_remote_front`]). fn best_route( &self, path: &Path, @@ -3013,8 +2991,8 @@ impl OriginState { .iter() .filter(|entry| path.has_prefix(&entry.prefix)) .filter(|entry| match exclude { - Some(peer) if peer != Hop::UNKNOWN => !entry.hops.contains(&peer), - _ => true, + Some(peer) => !entry.hops.contains(&peer), + None => true, }) .filter(|entry| match publisher { Some(first) => entry.hops.iter().next() == Some(&first), @@ -4033,6 +4011,26 @@ mod tests { list } + #[test] + fn hops_refuse_a_zero_entry() { + let mut list = Hops::new(); + assert_eq!(list.push(Hop::UNKNOWN), Err(InvalidHop::Range)); + assert!(list.is_empty()); + + assert_eq!(Hops::try_from(vec![Hop::UNKNOWN]), Err(InvalidHop::Range)); + assert_eq!(Hops::try_from(vec![origin(1), Hop::UNKNOWN]), Err(InvalidHop::Range)); + } + + #[test] + fn hops_refuse_a_duplicate() { + let mut list = hops(&[1, 2]); + assert_eq!(list.push(origin(1)), Err(InvalidHop::Duplicate)); + assert_eq!( + Hops::try_from(vec![origin(4), origin(8), origin(4)]), + Err(InvalidHop::Duplicate) + ); + } + /// Yield to the driver until `check` passes, bounded so a bug fails instead /// of hanging. async fn settle(mut check: impl FnMut() -> bool) { diff --git a/rs/moq-relay/tests/cluster_unknown.rs b/rs/moq-relay/tests/cluster_unknown.rs index 70257aaf8e2..020352f78db 100644 --- a/rs/moq-relay/tests/cluster_unknown.rs +++ b/rs/moq-relay/tests/cluster_unknown.rs @@ -1,6 +1,6 @@ //! Regression for an external publisher whose protocol does not declare a Hop ID. -//! The relay records that publisher as `Hop::UNKNOWN`; reflected cluster paths -//! must not replace it while gossiping around a redundant mesh. +//! The relay assigns that publisher an identity; reflected cluster paths must not +//! replace it while gossiping around a redundant mesh. use std::{net::TcpListener, time::Duration}; @@ -122,8 +122,8 @@ async fn publish_version(port: u16, version: &str) -> Publisher { } async fn publish_unknown(port: u16) -> Publisher { - // Draft-14 has no Cluster extension, so the accepting relay must represent - // this external publisher with the wire-defined UNKNOWN Hop ID. + // Draft-14 has no Cluster extension, so the accepting relay assigns this + // external publisher an identity of its own. publish_version(port, "moq-transport-14").await }