Skip to main content

moq_net/
setup.rs

1//! The SETUP exchange and the credential a peer may present in it.
2//!
3//! Only [`Token`] and [`Role`] are public; the SETUP messages and the extensions a side
4//! offers in them are wire internals.
5
6use bytes::Bytes;
7
8use crate::{
9	Version,
10	coding::{self, Decode, DecodeError, Decoder, Encode, EncodeError, Encoder},
11	lite,
12};
13
14/// The session direction a client advertises in its SETUP (moq-lite-05+).
15pub use crate::lite::Role;
16
17// SETUP only carries negotiation parameters. Bound it independently of control messages.
18pub(crate) const MAX_SETUP_SIZE: usize = u16::MAX as usize;
19
20const CLIENT_SETUP: u8 = 0x20;
21const SERVER_SETUP: u8 = 0x21;
22
23/// The moq-transport SETUP message type (varint 0x2F00).
24pub(crate) const SETUP: u64 = 0x2F00;
25
26/// Decode a SETUP Implementation value, refusing one that is not UTF-8.
27pub(crate) fn decode_implementation(bytes: Option<&[u8]>) -> Result<Option<String>, crate::DecodeError> {
28	bytes
29		.map(|bytes| {
30			std::str::from_utf8(bytes)
31				.map(str::to_owned)
32				.map_err(|_| crate::DecodeError::InvalidValue)
33		})
34		.transpose()
35}
36
37/// The implementation the peer advertised in SETUP, published once that SETUP is read.
38///
39/// `None` until then. The protocol holds a clone for the life of its driver, so a
40/// dropped driver closes the channel; `Session::peer_implementation` also watches the
41/// session's end, for a finished driver the caller keeps.
42#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
43#[derive(Clone, Default)]
44pub(crate) struct PeerImplementation(kio::Producer<Option<Option<String>>>);
45
46#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
47impl PeerImplementation {
48	/// A slot for a SETUP read before the session started, or a version that carries none.
49	pub fn known(value: Option<String>) -> Self {
50		Self(kio::Producer::new(Some(value)))
51	}
52
53	/// Record what the peer's SETUP advertised. The first SETUP wins.
54	pub fn set(&self, value: Option<String>) {
55		if let Ok(mut slot) = self.0.write()
56			&& slot.is_none()
57		{
58			*slot = Some(value);
59		}
60	}
61
62	pub(crate) fn consume(&self) -> kio::Consumer<Option<Option<String>>> {
63		self.0.consume()
64	}
65}
66
67#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
68/// Our Implementation value to send, or `None` when the caller configured it empty.
69pub(crate) fn implementation(value: &str) -> Option<String> {
70	(!value.is_empty()).then(|| value.to_owned())
71}
72
73/// The SETUP extensions this side offers.
74///
75/// Not public: every session offers Solicit, and only moq-relay offers `ietf`, through
76/// `Client::with_ietf` and `Server::with_ietf` behind the `relay` feature.
77#[derive(Clone, Copy, Debug, PartialEq, Eq)]
78pub(crate) struct Extensions {
79	/// The MoQ Solicit extension: the peer answers our SUBSCRIBE_NAMESPACE rather than
80	/// announcing unasked (moq-transport only). Off only in tests acting as a peer without it.
81	pub solicit: bool,
82	/// The MoQ IETF extension, off by default: a moq-lite 07 hop between relays carries the
83	/// moq-transport object state a relay preserves, such as Object IDs and properties.
84	pub ietf: bool,
85}
86
87impl Default for Extensions {
88	fn default() -> Self {
89		Self {
90			solicit: true,
91			ietf: false,
92		}
93	}
94}
95
96/// A connection credential presented in SETUP: moq-transport's `AUTHORIZATION TOKEN`
97/// option, or moq-lite-07's Token parameter.
98///
99/// The transport never reads the bytes; verifying them is the application's job.
100#[derive(Clone, PartialEq, Eq)]
101pub struct Token {
102	/// The wire Token Type, naming how [`value`](Self::value) is encoded.
103	pub kind: u64,
104	/// The token itself.
105	pub value: Vec<u8>,
106}
107
108impl Token {
109	/// Token Type 0: a format the endpoints agreed on out of band, such as a JWT.
110	pub const OUT_OF_BAND: u64 = 0x0;
111}
112
113// SETUP and handshakes are logged with `Debug`, so the credential shows only its type and length.
114impl std::fmt::Debug for Token {
115	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116		write!(f, "Token(kind={}, <{} bytes>)", self.kind, self.value.len())
117	}
118}
119
120/// The unified SETUP message, with the same encoding for both client and server.
121#[derive(Clone)]
122pub(crate) struct Setup {
123	pub parameters: Bytes,
124}
125
126impl std::fmt::Debug for Setup {
127	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
128		// Opaque parameters can contain credentials, even before we recognize an option.
129		f.debug_struct("Setup")
130			.field("parameters_len", &self.parameters.len())
131			.finish()
132	}
133}
134
135impl Encode<Version> for Setup {
136	fn encode(&self, w: &mut Encoder<'_>, v: Version) -> Result<(), EncodeError> {
137		w.control = Some(crate::stats::Message::Session);
138		if v.is_lite() {
139			return Err(EncodeError::Version);
140		}
141		w.varint(SETUP)?;
142		// Draft-23 (section 9) makes every Message Length a varint, SETUP's included.
143		let prefix = match varint_length(v) {
144			true => w.prefix_varint(),
145			false => w.prefix_u16(),
146		};
147		w.slice(&self.parameters);
148		fill_body(w, prefix)
149	}
150}
151
152impl<'a> Decode<'a, Version> for Setup {
153	fn decode(r: &mut Decoder<'a>, v: Version) -> Result<Self, DecodeError> {
154		r.control = Some(crate::stats::Message::Session);
155		if v.is_lite() {
156			return Err(DecodeError::Version);
157		}
158		let kind = r.varint()?;
159		if kind != SETUP {
160			return Err(DecodeError::InvalidValue);
161		}
162		let size = match varint_length(v) {
163			true => {
164				// Until the peer's SETUP is read the limit is the default 65535
165				// (draft-23 section 9.1.8), SETUP itself included.
166				let size = r.varint()?;
167				match usize::try_from(size) {
168					Ok(size) if size <= MAX_SETUP_SIZE => size,
169					_ => {
170						return Err(DecodeError::MessageTooLarge {
171							size: usize::try_from(size).unwrap_or(usize::MAX),
172							max: MAX_SETUP_SIZE,
173						});
174					}
175				}
176			}
177			false => r.u16()? as usize,
178		};
179		let parameters = Bytes::copy_from_slice(r.slice(size)?);
180		Ok(Self { parameters })
181	}
182}
183
184/// Whether `v` writes the moq-transport SETUP's Message Length as a varint (draft-23).
185fn varint_length(v: Version) -> bool {
186	matches!(v.0, crate::Draft::Ietf(ietf) if ietf.varint_length())
187}
188
189/// Whether `v` encodes the `moql` bidi SETUP exchange: moq-lite 01/02, whose draft-14 framing
190/// and QUIC varints it keeps whichever moq-lite version it negotiates.
191fn framed(v: Version) -> bool {
192	matches!(v.0, crate::Draft::Lite(lite::Version::Lite01 | lite::Version::Lite02))
193}
194
195/// The client half of the `moql` bidi SETUP exchange, offering moq-lite versions.
196///
197/// The framing is moq-transport draft-14's CLIENT_SETUP, which moq-lite borrowed: a
198/// u16 size, the offered versions, then parameters.
199#[derive(Clone)]
200pub(crate) struct Client {
201	/// The list of supported versions in preferred order.
202	pub versions: coding::Versions,
203
204	/// Parameters, unparsed: moq-lite defines none here, so neither side reads them.
205	pub parameters: Bytes,
206}
207
208impl std::fmt::Debug for Client {
209	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
210		f.debug_struct("Client")
211			.field("versions", &self.versions)
212			.field("parameters_len", &self.parameters.len())
213			.finish()
214	}
215}
216
217impl Client {
218	/// The moq-lite version a server answers with: the first one offered that `supported` holds.
219	#[cfg_attr(not(any(test, feature = "async")), allow(dead_code, reason = "async-only"))]
220	pub(crate) fn select(&self, supported: &crate::Versions) -> Result<lite::Version, crate::Error> {
221		let version = self
222			.versions
223			.iter()
224			.flat_map(|v| Version::try_from(*v).ok())
225			.find(|v| supported.contains(v));
226		match version {
227			Some(Version(crate::Draft::Lite(version))) => Ok(version),
228			_ => {
229				// The client only learns that the session closed, so this is the one place
230				// that can name both sides of the mismatch.
231				let offered: Vec<String> = self
232					.versions
233					.iter()
234					.map(|v| Version::try_from(*v).map_or_else(|_| format!("{v:?}"), |v| v.to_string()))
235					.collect();
236				let accepted: Vec<String> = supported.iter().map(ToString::to_string).collect();
237				tracing::warn!(?offered, ?accepted, "client shares no MoQ version with this server");
238				Err(crate::Error::Version)
239			}
240		}
241	}
242}
243
244impl<'a> Decode<'a, Version> for Client {
245	fn decode(r: &mut Decoder<'a>, v: Version) -> Result<Self, DecodeError> {
246		r.control = Some(crate::stats::Message::Session);
247		if !framed(v) {
248			return Err(DecodeError::Version);
249		}
250		let kind = r.u8()?;
251		if kind != CLIENT_SETUP {
252			return Err(DecodeError::InvalidValue);
253		}
254
255		let size = r.u16()? as usize;
256		let mut msg = r.sub(size)?;
257		let versions = coding::Versions::decode(&mut msg, v).map_err(DecodeError::complete)?;
258
259		Ok(Self {
260			versions,
261			parameters: Bytes::copy_from_slice(msg.rest()),
262		})
263	}
264}
265
266impl Encode<Version> for Client {
267	fn encode(&self, w: &mut Encoder<'_>, v: Version) -> Result<(), EncodeError> {
268		w.control = Some(crate::stats::Message::Session);
269		if !framed(v) {
270			return Err(EncodeError::Version);
271		}
272		w.u8(CLIENT_SETUP);
273		let prefix = w.prefix_u16();
274		self.versions.encode(w, v)?;
275		w.slice(&self.parameters);
276		fill_body(w, prefix)
277	}
278}
279
280/// Size a SETUP body, refusing one our own receiver would refuse.
281fn fill_body(w: &mut Encoder<'_>, prefix: coding::Prefix) -> Result<(), EncodeError> {
282	if w.since(&prefix) > MAX_SETUP_SIZE {
283		w.discard(prefix);
284		return Err(EncodeError::TooLarge);
285	}
286	w.fill(prefix)
287}
288
289/// The server half of the `moql` bidi SETUP exchange, selecting a moq-lite version.
290///
291/// The framing is moq-transport draft-14's SERVER_SETUP: a u16 size, the selected version,
292/// then parameters.
293#[derive(Clone)]
294pub(crate) struct Server {
295	/// The selected version.
296	pub version: coding::Version,
297
298	/// Parameters, unparsed: moq-lite defines none here, so neither side reads them.
299	pub parameters: Bytes,
300}
301
302impl std::fmt::Debug for Server {
303	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
304		f.debug_struct("Server")
305			.field("version", &self.version)
306			.field("parameters_len", &self.parameters.len())
307			.finish()
308	}
309}
310
311impl Encode<Version> for Server {
312	fn encode(&self, w: &mut Encoder<'_>, v: Version) -> Result<(), EncodeError> {
313		w.control = Some(crate::stats::Message::Session);
314		if !framed(v) {
315			return Err(EncodeError::Version);
316		}
317		w.u8(SERVER_SETUP);
318		let prefix = w.prefix_u16();
319		self.version.encode(w, v)?;
320		w.slice(&self.parameters);
321		fill_body(w, prefix)
322	}
323}
324
325impl<'a> Decode<'a, Version> for Server {
326	fn decode(r: &mut Decoder<'a>, v: Version) -> Result<Self, DecodeError> {
327		r.control = Some(crate::stats::Message::Session);
328		if !framed(v) {
329			return Err(DecodeError::Version);
330		}
331		let kind = r.u8()?;
332		if kind != SERVER_SETUP {
333			return Err(DecodeError::InvalidValue);
334		}
335
336		let size = r.u16()? as usize;
337		let mut msg = r.sub(size)?;
338		let version = coding::Version::decode(&mut msg, v).map_err(DecodeError::complete)?;
339
340		Ok(Self {
341			version,
342			parameters: Bytes::copy_from_slice(msg.rest()),
343		})
344	}
345}
346
347#[cfg(test)]
348mod tests {
349	use super::*;
350
351	/// The moq-transport SETUP's Length is 16 bits through draft-22 and a varint from
352	/// draft-23 (section 9.1).
353	#[test]
354	fn ietf_setup_length_follows_the_draft() {
355		let setup = Setup {
356			parameters: Bytes::from_static(&[0x00]),
357		};
358		let draft22 = Version::ietf(crate::ietf::Version::Draft22);
359		let draft23 = Version::ietf(crate::ietf::Version::Draft23);
360		let mut kind = Vec::new();
361		Encoder::new(&mut kind, draft22.into()).varint(SETUP).unwrap();
362
363		for (version, length) in [(draft22, &[0x00, 0x01][..]), (draft23, &[0x01][..])] {
364			let wire = setup.encode_bytes(version).unwrap();
365			assert_eq!(wire, [&kind[..], length, &[0x00]].concat(), "{version}");
366			let (decoded, _) = Setup::decode_slice(&wire, version).unwrap();
367			assert_eq!(decoded.parameters, setup.parameters, "{version}");
368		}
369
370		// A length past the default MAX_CONTROL_MESSAGE_SIZE is refused at the prefix.
371		let mut wire = kind.clone();
372		Encoder::new(&mut wire, draft23.into())
373			.varint(MAX_SETUP_SIZE as u64 + 1)
374			.unwrap();
375		assert!(matches!(
376			Setup::decode_slice(&wire, draft23),
377			Err(DecodeError::MessageTooLarge { .. })
378		));
379	}
380
381	#[test]
382	fn credentials_stay_out_of_traces() {
383		let secret = "credential-that-must-not-be-logged";
384		let logs = crate::test_tracing::capture(tracing::Level::TRACE, || {
385			let token = Token {
386				kind: Token::OUT_OF_BAND,
387				value: secret.as_bytes().to_vec(),
388			};
389			let setup = lite::Setup {
390				path: Some(format!("/room?jwt={secret}")),
391				token: Some(token.clone()),
392				..Default::default()
393			};
394			let wire = setup.encode_bytes(lite::Version::Lite07).unwrap();
395			assert_eq!(
396				lite::Setup::decode_slice(&wire, lite::Version::Lite07).unwrap().0,
397				setup
398			);
399			let auth = lite::Auth {
400				token: Bytes::copy_from_slice(secret.as_bytes()),
401			};
402			let wire = auth.encode_bytes(lite::Version::Lite07).unwrap();
403			assert_eq!(lite::Auth::decode_slice(&wire, lite::Version::Lite07).unwrap().0, auth);
404
405			let version = crate::ietf::Version::Draft22;
406			let mut params = crate::ietf::Parameters::default();
407			crate::ietf::token::into_setup(&mut params, &token, version).unwrap();
408			params.set_bytes(
409				crate::ietf::ParameterBytes::Path,
410				format!("/room?jwt={secret}").into_bytes(),
411			);
412			let setup = Setup {
413				parameters: params.encode_bytes(version).unwrap(),
414			};
415			let wire = setup.encode_bytes(crate::Version::ietf(version)).unwrap();
416			let decoded = Setup::decode_slice(&wire, crate::Version::ietf(version)).unwrap().0;
417			let (params, _) = crate::ietf::Parameters::decode_slice(&decoded.parameters, version).unwrap();
418			assert_eq!(crate::ietf::token::from_setup(&params, version).unwrap(), Some(token));
419			tracing::trace!(?setup, ?decoded, ?params, "SETUP diagnostics");
420
421			let uri = format!("https://relay.example/room?jwt={secret}");
422			let goaway = lite::Goaway {
423				uri: uri.as_str().into(),
424			};
425			let wire = goaway.encode_bytes(lite::Version::Lite07).unwrap();
426			lite::Goaway::decode_slice(&wire, lite::Version::Lite07).unwrap();
427			let goaway = crate::ietf::GoAway {
428				new_session_uri: uri.as_str().into(),
429				timeout: 0,
430				request_id: Some(crate::ietf::RequestId(0)),
431			};
432			let wire = goaway.encode_bytes(version).unwrap();
433			crate::ietf::GoAway::decode_slice(&wire, version).unwrap();
434			tracing::trace!(goaway = ?crate::goaway::Goaway::redirect(uri), "GOAWAY diagnostics");
435		})
436		.join("\n");
437		let logs_contain = |needle: &str| logs.contains(needle);
438
439		assert!(logs_contain("encoding"));
440		assert!(logs_contain("decoded"));
441		assert!(logs_contain("SETUP diagnostics"));
442		assert!(logs_contain("GOAWAY diagnostics"));
443		assert!(!logs_contain(secret));
444		let decimal = format!("{:?}", secret.as_bytes());
445		assert!(!logs_contain(&decimal[1..decimal.len() - 1]));
446	}
447
448	/// Deployed lite-01/02 peers frame both halves with draft-14's u16 size, not a varint.
449	#[test]
450	fn the_moql_setup_has_a_u16_size() {
451		for v in [lite::Version::Lite01, lite::Version::Lite02] {
452			let v = Version::lite(v);
453			let client = Client {
454				versions: coding::Versions::from([v.into()]),
455				parameters: Bytes::from_static(&[0]),
456			};
457			let buf = client.encode_bytes(v).unwrap();
458			assert_eq!(buf[..3], [CLIENT_SETUP, 0, (buf.len() - 3) as u8], "{v}");
459			assert_eq!(Client::decode_slice(&buf, v).unwrap().0.versions, client.versions);
460
461			let server = Server {
462				version: v.into(),
463				parameters: Bytes::from_static(&[0]),
464			};
465			let buf = server.encode_bytes(v).unwrap();
466			assert_eq!(buf[..3], [SERVER_SETUP, 0, (buf.len() - 3) as u8], "{v}");
467			assert_eq!(Server::decode_slice(&buf, v).unwrap().0.version, server.version);
468		}
469	}
470
471	/// Never emit a legacy SETUP our own receiver would refuse.
472	#[test]
473	fn encode_enforces_the_setup_limit() {
474		let v = Version::lite(lite::Version::Lite01);
475		let parameters = Bytes::from(vec![0; MAX_SETUP_SIZE]);
476
477		let client = Client {
478			versions: coding::Versions::from([v.into()]),
479			parameters: parameters.clone(),
480		};
481		let mut buf = Vec::new();
482		assert!(matches!(
483			client.encode(&mut Encoder::new(&mut buf, v.into()), v),
484			Err(EncodeError::TooLarge)
485		));
486
487		let server = Server {
488			version: v.into(),
489			parameters,
490		};
491		let mut buf = Vec::new();
492		assert!(matches!(
493			server.encode(&mut Encoder::new(&mut buf, v.into()), v),
494			Err(EncodeError::TooLarge)
495		));
496	}
497}