diff --git a/doc/bin/relay/cluster.md b/doc/bin/relay/cluster.md index 154e3ee2fb5..d1c482f6f83 100644 --- a/doc/bin/relay/cluster.md +++ b/doc/bin/relay/cluster.md @@ -278,16 +278,18 @@ decides which relays receive the cluster token. ## Identity -Each relay has a Hop ID: the value it adds to a route's hop list for loop -detection and shortest-path routing. It is random on every start, so a +Each relay has an identity that it uses for loop detection and routing, and +declares in SETUP on moq-lite-05 and later: a Hop ID added to each route's hop +list, or on the opt-in `moq-lite-07-wip` a Node ID naming the route's origin. It is random on every start, so a restarted relay is a new node to the rest of the mesh, and there is no setting to pin it. A relay never dials its own `cluster.node`, so every relay can share one `cluster.connect` list or API response. Peer URLs that differ only in query, userinfo, fragment, or slashes name one peer and get one link. A relay -refuses a session that declares its own Hop ID, which means a peer URL -reaches the relay itself under another name, such as an IP for its hostname. +refuses a session that declares its own identity (its Hop ID, or on +`moq-lite-07-wip` its Node ID), which means a peer URL reaches the relay itself +under another name, such as an IP for its hostname. ## Failure detection diff --git a/drafts/draft-lcurley-moq-lite.md b/drafts/draft-lcurley-moq-lite.md index 7234ec57f4f..068d33b6d16 100644 --- a/drafts/draft-lcurley-moq-lite.md +++ b/drafts/draft-lcurley-moq-lite.md @@ -966,6 +966,8 @@ The following Setup Parameters are defined: |------|----------------|-------------| | 0x4 | Cost | Cost (i) | |------|----------------|-------------| +| 0x5 | Node ID | Node ID (i) | +|------|----------------|-------------| | 0x6 | Implementation | Tokens (s) | |------|----------------|-------------| | 0x7 | Token | Token (b) | @@ -1022,6 +1024,14 @@ Both endpoints send it and the two values need not match: the parameter prices t A declared cost is an assertion, not an instruction: a receiver MAY charge a locally configured value of at least 1 instead, so a peer cannot reprice its neighbours by declaring itself cheap. +### Node ID Parameter {#node-id-parameter} +The Node ID Parameter declares the Node ID the sender originates its own routes under (see [Routing](#routing)). +Its value MUST NOT be 0 or have the most significant bit set; a receiver MUST close the session with a PROTOCOL_VIOLATION if it does. + +A receiver that receives its own Node ID has reached itself, such as a relay dialing an address of its own, and SHOULD close the session. +A Node ID in SETUP is declared, not proven, and a receiver MUST NOT authorize on it. +Either endpoint MAY send it, and an endpoint that originates no routes omits it, having no Node ID to declare. A relay MUST NOT forward it. + ### Implementation Parameter {#implementation-parameter} The Implementation Parameter names the sender's software, so a peer can attribute a session to its build. The Parameter Value is a UTF-8 string of space-separated `name/version` product tokens, outermost first, such as `moq-ffi/0.4.12 moq-net-rs/0.3.10`; it is otherwise opaque to moq-lite. @@ -2189,7 +2199,7 @@ The `Message Length` describes the payload size on the wire. - An advertiser MAY announce a path it answers through a claim under the claim's Instance, so subscriptions resolved through the claim continue, and a claim still serving that Instance when the announcement ends restarts under a new one. - A receiver mints an Instance, starting with `~`, for each announcement a session of an earlier version delivers. - Added announce compression: ANNOUNCE_START gains `Path Base` and `Path Keep` to copy the head of a live claim's suffix. -- Split routing into two layers on the Announce Stream. ROUTE_START (0x6), ROUTE_UPDATE (0x7), and ROUTE_END (0x8) advertise how the publisher reaches an origin node, named by a Node ID, with a seqno, an additive metric, and a down-only bit, and loops are prevented by Babel's feasibility condition. Every ANNOUNCE_START names its route's Route ID in place of the Hop ID list, so a link change sends one ROUTE_UPDATE per origin rather than an update per claim. Removed the Hop ID list, ANNOUNCE_OK's Hop ID, and the SETUP Hop parameter (0x5). +- Split routing into two layers on the Announce Stream. ROUTE_START (0x6), ROUTE_UPDATE (0x7), and ROUTE_END (0x8) advertise how the publisher reaches an origin node, named by a Node ID, with a seqno, an additive metric, and a down-only bit, and loops are prevented by Babel's feasibility condition. Every ANNOUNCE_START names its route's Route ID in place of the Hop ID list, so a link change sends one ROUTE_UPDATE per origin rather than an update per claim. Removed the Hop ID list and ANNOUNCE_OK's Hop ID, and replaced the SETUP Hop parameter (0x5) with a [Node ID parameter](#node-id-parameter), so an endpoint that reaches itself detects it at setup. - Added ROUTE_HOLD (0xB), which holds a route while it recovers; ROUTE_END lets it go. Neither withdraws the origin's claims, and the subscriber echoes every ROUTE_END back. - Added ROUTE_REQUEST (0xA), sent by the subscriber on the Announce Stream to ask for a route with a newer seqno when every route it has is infeasible. - Added ANNOUNCE_FLOOR (0x9), closing each batch of a route's claims with the origin Revision at which the stream's claims across the requested prefix are certified plus one, or 0 to certify nothing, so a stale copy never revives a claim whose withdrawal a newer one delivered. A floor certifies only the claims its own request shows. diff --git a/js/net/src/lite/connection.ts b/js/net/src/lite/connection.ts index 04e89b5c819..894d9f0fc1b 100644 --- a/js/net/src/lite/connection.ts +++ b/js/net/src/lite/connection.ts @@ -40,6 +40,7 @@ import { hasDatagramTracks, hasGoaway, hasHidden, + hasNodeId, hasPadding, hasProbeRtt, hasRouteKey, @@ -422,9 +423,10 @@ export class Connection implements Session { // path and leave routing to the URL. The probe level reflects what this transport // can actually measure; we never pad, so we never advertise Increase. // Role stays Both: the publish origin starts empty and fills later, and consume is - // called after this point, so there is nothing to narrow yet. The origin declares - // our session identity so the peer can filter - // reflected announcements (lite-06 removed ANNOUNCE_REQUEST's exclude_hop for it). + // called after this point, so there is nothing to narrow yet. Before lite-07 the hop + // declares our session identity so the peer can filter reflected announcements + // (lite-06 removed ANNOUNCE_REQUEST's exclude_hop for it). From lite-07 the parameter + // is a Node ID, which this per-connection hop is not: we originate no routes, so we omit it. async #sendSetup(): Promise { const writer = await Writer.open(this.#quic, { version: this.#version }); try { @@ -433,7 +435,7 @@ export class Connection implements Session { const routeKey = hasRouteKey(this.#version) ? await proveRouteKey(this.#quic, this.#client) : undefined; await new Setup({ probe, - hop: this.hop, + hop: hasNodeId(this.#version) ? undefined : this.hop, token: this.#token, implementation: this.#implementation, routeKey, diff --git a/js/net/src/lite/setup.test.ts b/js/net/src/lite/setup.test.ts index 361925a0021..0ac430ce02d 100644 --- a/js/net/src/lite/setup.test.ts +++ b/js/net/src/lite/setup.test.ts @@ -1,6 +1,6 @@ import { expect, test } from "bun:test"; import { HopSchema } from "../hop.ts"; -import { Reader, Writer } from "../stream.ts"; +import { encodeVarint, Reader, Writer } from "../stream.ts"; import * as Varint from "../varint.ts"; import { ProbeLevel, Role, Setup } from "./setup.ts"; import { Version } from "./version.ts"; @@ -149,6 +149,14 @@ test("hop 0 decodes as absent", async () => { expect(got.hop).toBeUndefined(); }); +test("lite-07 Node ID is never 0 or qualified", async () => { + for (const id of [0n, (1n << 63n) | 7n]) { + await expect(decodeParam(PARAM_HOP, encodeVarint(id, Version.DRAFT_07), Version.DRAFT_07)).rejects.toThrow(); + } + const qualified = new Setup({ hop: HopSchema.parse((1n << 63n) | 7n) }); + await expect(bytes((w) => qualified.encode(w, Version.DRAFT_07), Version.DRAFT_07)).rejects.toThrow(); +}); + test("SETUP with implementation round-trips", async () => { const got = await roundTrip( new Setup({ hop: HopSchema.parse(7n), implementation: "moq-ffi/0.4.12 moq-net-rs/0.3.10" }), diff --git a/js/net/src/lite/setup.ts b/js/net/src/lite/setup.ts index f5c30b80c2c..25f671cdeaa 100644 --- a/js/net/src/lite/setup.ts +++ b/js/net/src/lite/setup.ts @@ -9,7 +9,7 @@ import { type Hop, HopSchema, wireHop } from "../hop.ts"; import { encodeVarint, Reader, type Writer } from "../stream.ts"; import { decodeUtf8 } from "../util/utf8.ts"; import * as Message from "./message.ts"; -import { hasAuth, hasImplementation, hasRouteKey, hasSetupStream, type Version } from "./version.ts"; +import { hasAuth, hasImplementation, hasNodeId, hasRouteKey, hasSetupStream, type Version } from "./version.ts"; const clientParameters = new WeakSet(); @@ -24,8 +24,10 @@ const PARAM_PROBE = 0x1n; const PARAM_PATH = 0x2n; /** Setup Parameter id for the client's intended {@link Role} (client-only). */ const PARAM_ROLE = 0x3n; -/** Setup Parameter id for the endpoint's Hop ID. */ +/** Setup Parameter id for the endpoint's Hop ID, or from lite-07 its Node ID. */ const PARAM_HOP = 0x5n; +/** The top bit, which marks a Node ID a relay qualified; an endpoint never declares one. */ +const QUALIFIED = 1n << 63n; /** Setup Parameter id for the endpoint's implementation name and version. */ const PARAM_IMPLEMENTATION = 0x6n; /** Setup Parameter id for the client's connection credential (client-only, lite-07+). */ @@ -218,7 +220,9 @@ export class Setup { * This endpoint's Hop ID. The peer uses it to filter announcements and * subscriptions whose route flows through this endpoint (lite-06 removed the * per-stream `exclude_hop` in its favor). `undefined` when the endpoint declares - * no identity; a wire value of 0 decodes the same way. + * no identity; a wire value of 0 decodes the same way. From lite-07 it is the + * endpoint's Node ID instead, never 0 or with the top bit set, so a peer that + * receives its own has reached itself. */ hop?: Hop; @@ -270,6 +274,7 @@ export class Setup { params.setVarint(PARAM_ROLE, this.role, version); } if (this.hop !== undefined && this.hop !== 0n) { + if (hasNodeId(version) && this.hop >= QUALIFIED) throw new Error("setup Node ID cannot be qualified"); params.setVarint(PARAM_HOP, wireHop(this.hop, version), version); } if (this.implementation) { @@ -302,8 +307,12 @@ export class Setup { const roleCode = await params.getVarint(PARAM_ROLE, version); const role = roleCode === undefined ? Role.Both : roleFromCode(roleCode); - // 0 carries no identity (it cannot be excluded), so it decodes as absent. + // Before lite-07, 0 carries no identity (it cannot be excluded), so it decodes as + // absent. A lite-07 Node ID is never 0 or qualified. const hopRaw = await params.getVarint(PARAM_HOP, version); + if (hopRaw !== undefined && hasNodeId(version) && (hopRaw === 0n || hopRaw >= QUALIFIED)) { + throw new Error("setup Node ID must be non-zero and unqualified"); + } const hop = hopRaw === undefined || hopRaw === 0n ? undefined : HopSchema.parse(hopRaw); // An older version does not know the token parameter, so it ignores it like any other. diff --git a/js/net/src/lite/version.ts b/js/net/src/lite/version.ts index f8f03106635..b1501d072b1 100644 --- a/js/net/src/lite/version.ts +++ b/js/net/src/lite/version.ts @@ -672,6 +672,22 @@ export function hasSynced(version: Version): boolean { } } +/** Whether SETUP's 0x5 parameter carries a Node ID rather than a Hop ID, from lite-07. */ +export function hasNodeId(version: Version): boolean { + // Explicitly list older versions so future versions default to carrying it. + switch (version) { + case Version.DRAFT_01: + case Version.DRAFT_02: + case Version.DRAFT_03: + case Version.DRAFT_04: + case Version.DRAFT_05: + case Version.DRAFT_06: + return false; + default: + return true; + } +} + /** Whether SETUP may carry a route key proof, added in lite-07. */ export function hasRouteKey(version: Version): boolean { // Explicitly list older versions so future versions default to carrying it. diff --git a/quest/m2/cluster-routing/README.md b/quest/m2/cluster-routing/README.md index c4df6a306bc..b1df1c94fd2 100644 --- a/quest/m2/cluster-routing/README.md +++ b/quest/m2/cluster-routing/README.md @@ -134,7 +134,6 @@ setup after the capabilities land. - [Outbound federation](/quest/m2/cluster-routing/federation.md) - an outbound-only local relay exchanges authorized broadcasts with the CDN and survives partition/healing - [Routes and announces](/quest/m2/cluster-routing/routes/README.md) - implement the proven route layer with Rust/JS parity and tiered-cluster acceptance -- [A relay refuses a lite-07 session with itself](/quest/m2/cluster-routing/lite07-self-dial.md) - the self-dial refusal lite-06 has, on lite-07, whose SETUP carries no Hop ID ## Related diff --git a/quest/m2/cluster-routing/lite07-self-dial.md b/quest/m2/cluster-routing/lite07-self-dial.md deleted file mode 100644 index 45dfd114741..00000000000 --- a/quest/m2/cluster-routing/lite07-self-dial.md +++ /dev/null @@ -1,27 +0,0 @@ -# [S] A relay refuses a lite-07 session with itself - -## Goal - -A relay whose cluster peer URL reaches itself under a spelling `PeerKey` -misses, such as an IP for its hostname, refuses that session on lite-07 as it -already does on lite-05, lite-06, and moq-transport. - -## Plan - -Planned 2026-11-08 (maintainer, approved follow-up of -[moq-dev/moq#8225](https://github.com/moq-dev/moq/pull/8225)). Milestone: -m2, since the likely fix changes lite-07-wip's SETUP, which the cut -publishes. - -`rs/moq-relay/src/connection.rs` refuses a session whose `peer_hop()` is -this relay's own Hop ID, but lite-07 SETUP carries no Hop ID -(`lite::Version::has_routes`), so the check never fires there. The route key -cannot stand in: relays may share one on purpose. - -- Decide, with the maintainer: a per-process node identity in lite-07 SETUP - (a wire change, lands while lite-07 is wip), or a local check that this - relay's own route came back over the session (no wire change; would move - this to m1). -- Test a relay dialing itself by IP on lite-07. - -Public API: none expected. Wire: possibly a lite-07-wip SETUP field. diff --git a/rs/moq-net/src/client.rs b/rs/moq-net/src/client.rs index 6f60cc4f4df..863961c6ddd 100644 --- a/rs/moq-net/src/client.rs +++ b/rs/moq-net/src/client.rs @@ -325,6 +325,7 @@ impl Client { cost: self.cost, // Filled by `lite::start` from the attached origin handles. hop: None, + node: None, // Older versions carry the credential in the URL query instead. token: self.setup_token.clone().filter(|_| version.has_auth()), ietf: self.extensions.ietf && version.has_ietf(), diff --git a/rs/moq-net/src/lite/session.rs b/rs/moq-net/src/lite/session.rs index 485e4be4e84..f4897890363 100644 --- a/rs/moq-net/src/lite/session.rs +++ b/rs/moq-net/src/lite/session.rs @@ -265,6 +265,15 @@ pub fn start(config: Config) -> Result { .or_else(|| subscribe.as_ref().map(|origin| origin.hop())) .map(Hop::from); } + // Lite-07 declares the Node ID our routes originate under instead, so a peer that is + // this same process recognizes itself. Read without creating the route node, which + // the session's route layer creates when it starts. + if version.has_routes() && our_setup.node.is_none() { + our_setup.node = publish + .as_ref() + .and_then(|origin| origin.node_id()) + .or_else(|| subscribe.as_ref().and_then(|origin| origin.consume().node_id())); + } // Prove our origin's route key, bound to this session, so a peer that scopes us files // our routes under it. A transport without an exporter cannot bind a proof, so neither diff --git a/rs/moq-net/src/lite/setup.rs b/rs/moq-net/src/lite/setup.rs index 1fa835e333e..9e729b0d804 100644 --- a/rs/moq-net/src/lite/setup.rs +++ b/rs/moq-net/src/lite/setup.rs @@ -13,7 +13,7 @@ const PARAM_PATH: u64 = 0x2; const PARAM_ROLE: u64 = 0x3; /// Setup Parameter id for the link cost the dialer assigns to this connection. const PARAM_COST: u64 = 0x4; -/// Setup Parameter id for the endpoint's Hop ID (before lite-07, which names routes instead). +/// Setup Parameter id for the endpoint's Hop ID before lite-07, and its Node ID from lite-07. const PARAM_HOP: u64 = 0x5; /// Setup Parameter id for the sender's implementation, as `name/version` product tokens. const PARAM_IMPLEMENTATION: u64 = 0x6; @@ -198,9 +198,12 @@ pub struct Setup { /// The peer uses it to serve this endpoint's subscriptions from a route that /// does not flow through it (the same split horizon the announce filter /// applies). `None` when the endpoint has no meaningful identity (a - /// leaf that never forwards); a wire value of 0 decodes as `None`. Lite-07 names - /// routes instead, so it never sends one and ignores one received. + /// leaf that never forwards); a wire value of 0 decodes as `None`. Lite-07 declares + /// [`node`](Self::node) instead, so it never sends one. pub hop: Option, + /// This endpoint's own Node ID (lite-07+), the identity it originates routes under. + /// A peer that receives its own Node ID has reached itself. Never 0 or qualified. + pub node: Option, /// The connection credential (lite-07+), which the empty-token Auth Stream names. /// Sent only by the client. The parameter carries no Token Type, so it is always /// [`Token::OUT_OF_BAND`](crate::setup::Token::OUT_OF_BAND). @@ -227,6 +230,7 @@ impl std::fmt::Debug for Setup { .field("role", &self.role) .field("cost", &self.cost) .field("hop", &self.hop) + .field("node", &self.node) .field("token", &self.token) .field("ietf", &self.ietf) .field("implementation", &self.implementation) @@ -270,6 +274,15 @@ impl<'a> Message<'a> for Setup { if let Some(hop) = self.hop.filter(|_| !version.has_routes()) { params.set_varint(PARAM_HOP, hop.wire_id(version.into()), version)?; } + if let Some(node) = self.node { + if !version.has_routes() { + return Err(EncodeError::Version); + } + if node.get() & crate::route::QUALIFIED != 0 { + return Err(EncodeError::InvalidState); + } + params.set_varint(PARAM_HOP, node.get(), version)?; + } if let Some(implementation) = &self.implementation { params.set_bytes(PARAM_IMPLEMENTATION, implementation.as_bytes().to_vec()); } @@ -336,15 +349,20 @@ impl<'a> Message<'a> for ReceivedSetup { if cost == Some(0) && version.has_routes() { return Err(DecodeError::InvalidValue); } - // 0 is legal on the wire but carries no identity (it can't be excluded), - // so it decodes as "not declared" rather than an error. Lite-07 dropped the - // parameter, so it ignores one like any unknown parameter. - let hop = match version.has_routes() { - true => None, - false => params - .get_varint(PARAM_HOP, version)? - .and_then(std::num::NonZeroU64::new) - .map(crate::Hop::from), + // Before lite-07, 0 is legal on the wire but carries no identity (it can't be + // excluded), so it decodes as "not declared" rather than an error. A lite-07 + // Node ID is never 0 or qualified. + let declared = params.get_varint(PARAM_HOP, version)?; + let (hop, node) = match version.has_routes() { + true => match declared { + None => (None, None), + Some(id) if id & crate::route::QUALIFIED != 0 => return Err(DecodeError::InvalidValue), + Some(id) => ( + None, + Some(std::num::NonZeroU64::new(id).ok_or(DecodeError::InvalidValue)?), + ), + }, + false => (declared.and_then(std::num::NonZeroU64::new).map(crate::Hop::from), None), }; let implementation = if version.has_implementation() { crate::setup::decode_implementation(params.get_bytes(PARAM_IMPLEMENTATION))? @@ -382,6 +400,7 @@ impl<'a> Message<'a> for ReceivedSetup { role, cost, hop, + node, token, ietf, implementation, @@ -992,28 +1011,35 @@ mod tests { assert_eq!(Setup::decode_slice(&buf, Version::Lite06).unwrap().0.hop, None); } - /// Lite-07 names routes instead of hops: it never sends the Hop parameter, and ignores - /// one a peer sends like any unknown parameter. + /// Lite-07 carries the endpoint's Node ID in the parameter that names its Hop ID before. #[test] - fn lite07_drops_the_hop() { + fn lite07_declares_the_node_instead_of_the_hop() { let version = Version::Lite07; let msg = Setup { hop: Some(crate::Hop::new(42).unwrap()), + node: std::num::NonZeroU64::new(7), ..Default::default() }; - assert_eq!( - msg.encode_bytes(version).unwrap(), - Setup::default().encode_bytes(version).unwrap() + let got = Setup::decode_slice(&msg.encode_bytes(version).unwrap(), version) + .unwrap() + .0; + assert_eq!(got.hop, None); + assert_eq!(got.node, msg.node); + assert!( + msg.encode_bytes(Version::Lite06).is_err(), + "only lite-07 carries a Node ID" ); - let mut params = Parameters::default(); - params.set_varint(super::PARAM_HOP, 42, version).unwrap(); - let mut data = Vec::new(); - let mut writer = Encoder::new(&mut data, version.into()); - let prefix = writer.prefix_varint(); - params.encode(&mut writer, version).unwrap(); - writer.fill(prefix).unwrap(); - assert_eq!(Setup::decode_slice(&data, version).unwrap().0.hop, None); + for id in [0, crate::route::QUALIFIED | 7] { + let mut params = Parameters::default(); + params.set_varint(super::PARAM_HOP, id, version).unwrap(); + let mut data = Vec::new(); + let mut writer = Encoder::new(&mut data, version.into()); + let prefix = writer.prefix_varint(); + params.encode(&mut writer, version).unwrap(); + writer.fill(prefix).unwrap(); + assert!(Setup::decode_slice(&data, version).is_err(), "Node ID {id:#x}"); + } } // A declared id of 0 carries no identity (it cannot be excluded), so it diff --git a/rs/moq-net/src/model/origin.rs b/rs/moq-net/src/model/origin.rs index 9d6f064c724..f0415a9afe5 100644 --- a/rs/moq-net/src/model/origin.rs +++ b/rs/moq-net/src/model/origin.rs @@ -2293,6 +2293,12 @@ impl Producer { self.hop } + /// Whether `id`, as a peer declared it, names this origin: its hop id, or the Node ID + /// its moq-lite-07 sessions declare. + pub fn is_own(&self, id: NonZeroU64) -> bool { + id == self.hop || self.consume().node_id() == Some(id) + } + /// The key sessions prove for this origin. #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))] pub(crate) fn route_key(&self) -> Option { @@ -7161,6 +7167,18 @@ impl Consumer { self } + /// The Node ID this origin's moq-lite-07 sessions declare, without creating the route + /// node: its identity once created, or the one it will declare. `None` only before a + /// node whose hop leaves nothing to derive draws a random one. + pub(crate) fn node_id(&self) -> Option { + let node = self.shared.lock().route_node.clone(); + let id = match node { + Some((node, _)) => Some(node.declared()), + None => crate::route::node::declared_for(self.hop), + }; + id.and_then(NonZeroU64::new) + } + /// The route layer node every lite-07 session on this origin shares, created on /// first use along with the task that feeds it the routes this node serves /// itself: everything in the table the route layer did not select. It is caught up diff --git a/rs/moq-net/src/route/node.rs b/rs/moq-net/src/route/node.rs index 46a0ac02475..6ca50e44773 100644 --- a/rs/moq-net/src/route/node.rs +++ b/rs/moq-net/src/route/node.rs @@ -408,10 +408,7 @@ impl Node { /// loses it, or is replaced by a random one if nothing is left. pub fn origin(hop: std::num::NonZeroU64) -> Self { let mut rng = kio::clock::rng(); - let id = match hop.get() & !QUALIFIED { - 0 => rng.random_range(1..=GENERATED), - id => id, - }; + let id = declared_for(hop).unwrap_or_else(|| rng.random_range(1..=GENERATED)); Self::new(id, rng.random()) } @@ -748,6 +745,15 @@ impl State { } } +/// The identity a node created for the origin hop `hop` declares, or `None` when nothing +/// is left once the qualified marker is cleared, and it draws a random one instead. +pub(crate) fn declared_for(hop: std::num::NonZeroU64) -> Option { + match hop.get() & !QUALIFIED { + 0 => None, + id => Some(id), + } +} + /// The lite-06 hop a router identity travels as, so a relay translating its routes /// for a lite-06 peer recognizes them coming back. A declared identity is the /// origin's own hop id; a qualified key is folded into the 53 bits a generated hop diff --git a/rs/moq-net/src/server.rs b/rs/moq-net/src/server.rs index ecbbe1c7c9c..6a1b5d480aa 100644 --- a/rs/moq-net/src/server.rs +++ b/rs/moq-net/src/server.rs @@ -247,6 +247,7 @@ impl Server { cost: None, // Filled by `lite::start` from the attached origin handles. hop: None, + node: None, token: None, ietf: self.extensions.ietf && version.has_ietf(), implementation: self.implementation(), @@ -312,7 +313,8 @@ impl Server { Some(client_setup) => ( client_setup.setup.path.clone(), client_setup.setup.role, - client_setup.setup.hop, + // Lite-07 declares a Node ID where older versions declare a Hop ID. + client_setup.setup.hop.or(client_setup.setup.node.map(crate::Hop::from)), client_setup.setup.token.clone(), client_setup.setup.implementation.clone(), PausedHandshake::LiteSetup { @@ -1096,11 +1098,12 @@ impl Handshake { self.role } - /// The Hop ID declared by the peer, when the negotiated protocol carries one. + /// The identity the peer declared for itself, when the negotiated protocol carries one. /// /// A moq-lite-05+ endpoint declares this when it attaches a publish or subscribe - /// origin; a moq-transport endpoint declares it via the MoQ Cluster extension. Older - /// versions and endpoints without one return `None`. + /// origin: its Hop ID, or from moq-lite-07 its Node ID. A moq-transport endpoint + /// declares its Hop ID via the MoQ Cluster extension. Older versions and endpoints + /// without one return `None`. [`origin::Producer::is_own`] tells whether it is ours. /// /// Self-declared, so treat it as a correlation hint rather than an /// authenticated identity: authorize on the token or client certificate. @@ -1715,6 +1718,7 @@ mod tests { role, cost: None, hop, + node: None, token: None, ietf: false, implementation: None, diff --git a/rs/moq-relay/src/connection.rs b/rs/moq-relay/src/connection.rs index 28027874fb9..7adf63cb1c6 100644 --- a/rs/moq-relay/src/connection.rs +++ b/rs/moq-relay/src/connection.rs @@ -95,13 +95,13 @@ impl Connection { /// Admit the request and answer its SETUP, returning the session's supervision. async fn start(mut request: R, lifecycle: &Lifecycle) -> anyhow::Result { - // Only this relay's origin holds its Hop ID, so a session declaring it is this + // Only this relay's origin holds its identity, so a session declaring it is this // relay dialing itself under a spelling its self filter missed. Every route // from it would be dropped as reflected, so refuse it rather than serve it. - if let Some(hop) = request.peer_hop().filter(|hop| hop.get() == lifecycle.cluster.id()) { + if let Some(id) = request.peer_hop().filter(|id| lifecycle.cluster.origin.is_own(*id)) { request.reject(moq_net::SessionError::Internal).await; anyhow::bail!( - "refused a session declaring this relay's own Hop ID {hop}: a cluster peer URL reaches this relay itself" + "refused a session declaring this relay's own identity {id}: a cluster peer URL reaches this relay itself" ); } let shared = request.shared().cloned(); diff --git a/rs/moq-relay/src/incoming.rs b/rs/moq-relay/src/incoming.rs index 92e053b195e..567bf0f942c 100644 --- a/rs/moq-relay/src/incoming.rs +++ b/rs/moq-relay/src/incoming.rs @@ -83,7 +83,7 @@ pub trait Sealed: Sized { fn auth(&self) -> moq_net::auth::Handle; fn requests(&mut self) -> moq_net::auth::Requests; fn role(&self) -> Option; - /// The Hop ID the peer declared in its SETUP, if any. + /// The identity the peer declared in its SETUP, if any: its Hop ID, or from moq-lite-07 its Node ID. fn peer_hop(&self) -> Option; fn with_stats(self, stats: moq_net::stats::Session) -> Self; fn with_limits(self, limits: moq_net::session::Limits) -> Self; diff --git a/rs/moq-relay/tests/integration/connection.rs b/rs/moq-relay/tests/integration/connection.rs index 6b7ba1ee241..fcfff7480ef 100644 --- a/rs/moq-relay/tests/integration/connection.rs +++ b/rs/moq-relay/tests/integration/connection.rs @@ -122,12 +122,12 @@ async fn assert_refused(result: Result) { assert_eq!(moq_net::SessionError::from(&err), moq_net::SessionError::Unauthorized); } -/// A session declaring the relay's own Hop ID is the relay reaching itself, so it is -/// refused instead of served with every route it sends dropped as reflected. A -/// session declaring any other Hop ID is served. +/// A session declaring the relay's own identity (its Hop ID, or its Node ID from +/// lite-07) is the relay reaching itself, so it is refused instead of served with +/// every route it sends dropped as reflected. A session declaring any other is served. #[kio::test] async fn a_session_declaring_the_relays_own_hop_is_refused() { - for alpn in ["moq-lite-05", "moq-lite-06"] { + for alpn in ["moq-lite-05", "moq-lite-06", "moq-lite-07-wip"] { let version = alpn.parse().unwrap(); let auth = memory::public(&["**"], &[], &[]); let cluster = memory::cluster(); @@ -135,7 +135,7 @@ async fn a_session_declaring_the_relays_own_hop_is_refused() { let err = match connect(client, version, &cluster, &auth).await { Ok(session) => kio::clock::timeout(TIMEOUT, session.closed()) .await - .expect("the relay must close a session declaring its own Hop ID"), + .expect("the relay must close a session declaring its own identity"), Err(err) => err, }; assert_eq!( @@ -150,11 +150,39 @@ async fn a_session_declaring_the_relays_own_hop_is_refused() { .expect("another hop connects"); assert!( kio::clock::timeout(TIMEOUT, session.closed()).await.is_err(), - "{alpn}: a session declaring another Hop ID stays open" + "{alpn}: a session declaring another identity stays open" ); } } +#[test] +fn a_relay_dialing_itself_on_lite07_is_refused() { + memory::run(a_relay_dialing_itself_on_lite07_is_refused_inner); +} + +/// A relay whose cluster peer URL reaches itself under a spelling its self filter +/// misses, as an IP does for its hostname, refuses that lite-07 session from its own +/// SETUP, so its dialer redials instead of holding a session with itself. +async fn a_relay_dialing_itself_on_lite07_is_refused_inner() { + use futures::StreamExt; + + let net = memory::Net::new(); + let auth = memory::public(&["**"], &[], &[]); + let cluster = memory::spawn_cluster(net.options(&["self"])); + let (_trigger, shutdown) = moq_relay::shutdown::Observer::new(TIMEOUT); + let mut accepts = net.relay("self", &cluster, &auth, &shutdown); + let mut connect = moq_tokio::connect::Config::default(); + connect.version = vec!["moq-lite-07-wip".parse().unwrap()]; + memory::start(cluster, connect).await; + + for attempt in ["dial", "redial after the refusal"] { + kio::clock::timeout(TIMEOUT, accepts.next()) + .await + .unwrap_or_else(|_| panic!("no {attempt}: the relay held a session with itself")) + .expect("the relay stopped accepting"); + } +} + /// A publisher whose grant covers only subscribing is refused during the handshake, /// instead of accepted to stream into a dropped session forever. Its SETUP's role /// says it publishes. diff --git a/rs/moq-tokio/src/server.rs b/rs/moq-tokio/src/server.rs index 1834a1b800d..dcdf7afc4ce 100644 --- a/rs/moq-tokio/src/server.rs +++ b/rs/moq-tokio/src/server.rs @@ -1822,9 +1822,10 @@ impl Request { self.handshake.requests() } - /// The Hop ID the peer declared in its SETUP (moq-lite-05+). + /// The identity the peer declared in its SETUP (moq-lite-05+). /// - /// A peer declares this when it attaches a publish or subscribe origin. + /// A peer declares this when it attaches a publish or subscribe origin: + /// its Hop ID, or from moq-lite-07 its Node ID. /// Older versions and peers without one return `None`. /// /// Self-declared, so treat it as a correlation hint rather than an