Skip to main content

moq_native/
client.rs

1use crate::QuicBackend;
2use crate::crypto;
3use anyhow::Context;
4use std::path::PathBuf;
5use std::{net, sync::Arc};
6use url::Url;
7
8/// TLS configuration for the client.
9#[derive(Clone, Default, Debug, clap::Args, serde::Serialize, serde::Deserialize)]
10#[serde(default, deny_unknown_fields)]
11#[non_exhaustive]
12pub struct ClientTls {
13	/// Use the TLS root at this path, encoded as PEM.
14	///
15	/// This value can be provided multiple times for multiple roots.
16	/// If this is empty, system roots will be used instead
17	#[serde(skip_serializing_if = "Vec::is_empty")]
18	#[arg(id = "tls-root", long = "tls-root", env = "MOQ_CLIENT_TLS_ROOT")]
19	pub root: Vec<PathBuf>,
20
21	/// Danger: Disable TLS certificate verification.
22	///
23	/// Fine for local development and between relays, but should be used in caution in production.
24	#[serde(skip_serializing_if = "Option::is_none")]
25	#[arg(
26		id = "tls-disable-verify",
27		long = "tls-disable-verify",
28		env = "MOQ_CLIENT_TLS_DISABLE_VERIFY",
29		default_missing_value = "true",
30		num_args = 0..=1,
31		require_equals = true,
32		value_parser = clap::value_parser!(bool),
33	)]
34	pub disable_verify: Option<bool>,
35}
36
37/// Configuration for the MoQ client.
38#[derive(Clone, Debug, clap::Parser, serde::Serialize, serde::Deserialize)]
39#[serde(deny_unknown_fields, default)]
40#[non_exhaustive]
41pub struct ClientConfig {
42	/// Listen for UDP packets on the given address.
43	#[arg(
44		id = "client-bind",
45		long = "client-bind",
46		default_value = "[::]:0",
47		env = "MOQ_CLIENT_BIND"
48	)]
49	pub bind: net::SocketAddr,
50
51	/// The QUIC backend to use.
52	/// Auto-detected from compiled features if not specified.
53	#[arg(id = "client-backend", long = "client-backend", env = "MOQ_CLIENT_BACKEND")]
54	pub backend: Option<QuicBackend>,
55
56	/// Maximum number of concurrent QUIC streams per connection (both bidi and uni).
57	#[serde(skip_serializing_if = "Option::is_none")]
58	#[arg(
59		id = "client-max-streams",
60		long = "client-max-streams",
61		env = "MOQ_CLIENT_MAX_STREAMS"
62	)]
63	pub max_streams: Option<u64>,
64
65	/// Restrict the client to specific MoQ protocol version(s).
66	///
67	/// By default, the client offers all supported versions and lets the server choose.
68	/// Use this to force a specific version, e.g. `--client-version moq-lite-02`.
69	/// Can be specified multiple times to offer a subset of versions.
70	///
71	/// Valid values: moq-lite-01, moq-lite-02, moq-lite-03, moq-transport-14, moq-transport-15, moq-transport-16, moq-transport-17
72	#[serde(default, skip_serializing_if = "Vec::is_empty")]
73	#[arg(id = "client-version", long = "client-version", env = "MOQ_CLIENT_VERSION")]
74	pub version: Vec<moq_lite::Version>,
75
76	#[command(flatten)]
77	#[serde(default)]
78	pub tls: ClientTls,
79
80	#[cfg(feature = "websocket")]
81	#[command(flatten)]
82	#[serde(default)]
83	pub websocket: super::ClientWebSocket,
84}
85
86impl ClientConfig {
87	pub fn init(self) -> anyhow::Result<Client> {
88		Client::new(self)
89	}
90
91	/// Returns the configured versions, defaulting to all if none specified.
92	pub fn versions(&self) -> moq_lite::Versions {
93		if self.version.is_empty() {
94			moq_lite::Versions::all()
95		} else {
96			moq_lite::Versions::from(self.version.clone())
97		}
98	}
99}
100
101impl Default for ClientConfig {
102	fn default() -> Self {
103		Self {
104			bind: "[::]:0".parse().unwrap(),
105			backend: None,
106			max_streams: None,
107			version: Vec::new(),
108			tls: ClientTls::default(),
109			#[cfg(feature = "websocket")]
110			websocket: super::ClientWebSocket::default(),
111		}
112	}
113}
114
115/// Client for establishing MoQ connections over QUIC, WebTransport, or WebSocket.
116///
117/// Create via [`ClientConfig::init`] or [`Client::new`].
118#[derive(Clone)]
119pub struct Client {
120	moq: moq_lite::Client,
121	versions: moq_lite::Versions,
122	#[cfg(feature = "websocket")]
123	websocket: super::ClientWebSocket,
124	tls: rustls::ClientConfig,
125	#[cfg(feature = "noq")]
126	noq: Option<crate::noq::NoqClient>,
127	#[cfg(feature = "quinn")]
128	quinn: Option<crate::quinn::QuinnClient>,
129	#[cfg(feature = "quiche")]
130	quiche: Option<crate::quiche::QuicheClient>,
131	#[cfg(feature = "iroh")]
132	iroh: Option<web_transport_iroh::iroh::Endpoint>,
133	#[cfg(feature = "iroh")]
134	iroh_addrs: Vec<std::net::SocketAddr>,
135}
136
137impl Client {
138	#[cfg(not(any(feature = "noq", feature = "quinn", feature = "quiche")))]
139	pub fn new(_config: ClientConfig) -> anyhow::Result<Self> {
140		anyhow::bail!("no QUIC backend compiled; enable noq, quinn, or quiche feature");
141	}
142
143	/// Create a new client
144	#[cfg(any(feature = "noq", feature = "quinn", feature = "quiche"))]
145	pub fn new(config: ClientConfig) -> anyhow::Result<Self> {
146		let backend = config.backend.clone().unwrap_or({
147			#[cfg(feature = "quinn")]
148			{
149				QuicBackend::Quinn
150			}
151			#[cfg(all(feature = "noq", not(feature = "quinn")))]
152			{
153				QuicBackend::Noq
154			}
155			#[cfg(all(feature = "quiche", not(feature = "quinn"), not(feature = "noq")))]
156			{
157				QuicBackend::Quiche
158			}
159			#[cfg(all(not(feature = "quiche"), not(feature = "quinn"), not(feature = "noq")))]
160			panic!("no QUIC backend compiled; enable noq, quinn, or quiche feature");
161		});
162
163		let provider = crypto::provider();
164
165		// Create a list of acceptable root certificates.
166		let mut roots = rustls::RootCertStore::empty();
167
168		if config.tls.root.is_empty() {
169			let native = rustls_native_certs::load_native_certs();
170
171			// Log any errors that occurred while loading the native root certificates.
172			for err in native.errors {
173				tracing::warn!(%err, "failed to load root cert");
174			}
175
176			// Add the platform's native root certificates.
177			for cert in native.certs {
178				roots.add(cert).context("failed to add root cert")?;
179			}
180		} else {
181			// Add the specified root certificates.
182			for root in &config.tls.root {
183				let root = std::fs::File::open(root).context("failed to open root cert file")?;
184				let mut root = std::io::BufReader::new(root);
185
186				let root = rustls_pemfile::certs(&mut root)
187					.next()
188					.context("no roots found")?
189					.context("failed to read root cert")?;
190
191				roots.add(root).context("failed to add root cert")?;
192			}
193		}
194
195		// Create the TLS configuration we'll use as a client.
196		// Allow TLS 1.2 in addition to 1.3 for WebSocket compatibility.
197		// QUIC always negotiates TLS 1.3 regardless of this setting.
198		let mut tls = rustls::ClientConfig::builder_with_provider(provider.clone())
199			.with_protocol_versions(&[&rustls::version::TLS13, &rustls::version::TLS12])?
200			.with_root_certificates(roots)
201			.with_no_client_auth();
202
203		// Allow disabling TLS verification altogether.
204		if config.tls.disable_verify.unwrap_or_default() {
205			tracing::warn!("TLS server certificate verification is disabled; A man-in-the-middle attack is possible.");
206
207			let noop = NoCertificateVerification(provider.clone());
208			tls.dangerous().set_certificate_verifier(Arc::new(noop));
209		}
210
211		#[cfg(feature = "noq")]
212		#[allow(unreachable_patterns)]
213		let noq = match backend {
214			QuicBackend::Noq => Some(crate::noq::NoqClient::new(&config)?),
215			_ => None,
216		};
217
218		#[cfg(feature = "quinn")]
219		#[allow(unreachable_patterns)]
220		let quinn = match backend {
221			QuicBackend::Quinn => Some(crate::quinn::QuinnClient::new(&config)?),
222			_ => None,
223		};
224
225		#[cfg(feature = "quiche")]
226		let quiche = match backend {
227			QuicBackend::Quiche => Some(crate::quiche::QuicheClient::new(&config)?),
228			_ => None,
229		};
230
231		let versions = config.versions();
232		Ok(Self {
233			moq: moq_lite::Client::new().with_versions(versions.clone()),
234			versions,
235			#[cfg(feature = "websocket")]
236			websocket: config.websocket,
237			tls,
238			#[cfg(feature = "noq")]
239			noq,
240			#[cfg(feature = "quinn")]
241			quinn,
242			#[cfg(feature = "quiche")]
243			quiche,
244			#[cfg(feature = "iroh")]
245			iroh: None,
246			#[cfg(feature = "iroh")]
247			iroh_addrs: Vec::new(),
248		})
249	}
250
251	#[cfg(feature = "iroh")]
252	pub fn with_iroh(mut self, iroh: Option<web_transport_iroh::iroh::Endpoint>) -> Self {
253		self.iroh = iroh;
254		self
255	}
256
257	/// Set direct IP addresses for connecting to iroh peers.
258	///
259	/// This is useful when the peer's IP addresses are known ahead of time,
260	/// bypassing the need for peer discovery (e.g. in tests or local networks).
261	#[cfg(feature = "iroh")]
262	pub fn with_iroh_addrs(mut self, addrs: Vec<std::net::SocketAddr>) -> Self {
263		self.iroh_addrs = addrs;
264		self
265	}
266
267	pub fn with_publish(mut self, publish: impl Into<Option<moq_lite::OriginConsumer>>) -> Self {
268		self.moq = self.moq.with_publish(publish);
269		self
270	}
271
272	pub fn with_consume(mut self, consume: impl Into<Option<moq_lite::OriginProducer>>) -> Self {
273		self.moq = self.moq.with_consume(consume);
274		self
275	}
276
277	#[cfg(not(any(feature = "noq", feature = "quinn", feature = "quiche", feature = "iroh")))]
278	pub async fn connect(&self, _url: Url) -> anyhow::Result<moq_lite::Session> {
279		anyhow::bail!("no QUIC backend compiled; enable noq, quinn, quiche, or iroh feature");
280	}
281
282	#[cfg(any(feature = "noq", feature = "quinn", feature = "quiche", feature = "iroh"))]
283	pub async fn connect(&self, url: Url) -> anyhow::Result<moq_lite::Session> {
284		let session = self.connect_inner(url).await?;
285		tracing::info!(version = %session.version(), "connected");
286		Ok(session)
287	}
288
289	#[cfg(any(feature = "noq", feature = "quinn", feature = "quiche", feature = "iroh"))]
290	async fn connect_inner(&self, url: Url) -> anyhow::Result<moq_lite::Session> {
291		#[cfg(feature = "iroh")]
292		if url.scheme() == "iroh" {
293			let endpoint = self.iroh.as_ref().context("Iroh support is not enabled")?;
294			let session = crate::iroh::connect(endpoint, url, self.iroh_addrs.iter().copied()).await?;
295			let session = self.moq.connect(session).await?;
296			return Ok(session);
297		}
298
299		#[cfg(feature = "noq")]
300		if let Some(noq) = self.noq.as_ref() {
301			let tls = self.tls.clone();
302			let quic_url = url.clone();
303			let quic_handle = async {
304				let res = noq.connect(&tls, quic_url).await;
305				if let Err(err) = &res {
306					tracing::warn!(%err, "QUIC connection failed");
307				}
308				res
309			};
310
311			#[cfg(feature = "websocket")]
312			{
313				let alpns = self.versions.alpns();
314				let ws_handle = crate::websocket::race_handle(&self.websocket, &self.tls, url, &alpns);
315
316				return Ok(tokio::select! {
317					Ok(quic) = quic_handle => self.moq.connect(quic).await?,
318					Some(Ok(ws)) = ws_handle => self.moq.connect(ws).await?,
319					else => anyhow::bail!("failed to connect to server"),
320				});
321			}
322
323			#[cfg(not(feature = "websocket"))]
324			{
325				let session = quic_handle.await?;
326				return Ok(self.moq.connect(session).await?);
327			}
328		}
329
330		#[cfg(feature = "quinn")]
331		if let Some(quinn) = self.quinn.as_ref() {
332			let tls = self.tls.clone();
333			let quic_url = url.clone();
334			let quic_handle = async {
335				let res = quinn.connect(&tls, quic_url).await;
336				if let Err(err) = &res {
337					tracing::warn!(%err, "QUIC connection failed");
338				}
339				res
340			};
341
342			#[cfg(feature = "websocket")]
343			{
344				let alpns = self.versions.alpns();
345				let ws_handle = crate::websocket::race_handle(&self.websocket, &self.tls, url, &alpns);
346
347				return Ok(tokio::select! {
348					Ok(quic) = quic_handle => self.moq.connect(quic).await?,
349					Some(Ok(ws)) = ws_handle => self.moq.connect(ws).await?,
350					else => anyhow::bail!("failed to connect to server"),
351				});
352			}
353
354			#[cfg(not(feature = "websocket"))]
355			{
356				let session = quic_handle.await?;
357				return Ok(self.moq.connect(session).await?);
358			}
359		}
360
361		#[cfg(feature = "quiche")]
362		if let Some(quiche) = self.quiche.as_ref() {
363			let quic_url = url.clone();
364			let quic_handle = async {
365				let res = quiche.connect(quic_url).await;
366				if let Err(err) = &res {
367					tracing::warn!(%err, "QUIC connection failed");
368				}
369				res
370			};
371
372			#[cfg(feature = "websocket")]
373			{
374				let alpns = self.versions.alpns();
375				let ws_handle = crate::websocket::race_handle(&self.websocket, &self.tls, url, &alpns);
376
377				return Ok(tokio::select! {
378					Ok(quic) = quic_handle => self.moq.connect(quic).await?,
379					Some(Ok(ws)) = ws_handle => self.moq.connect(ws).await?,
380					else => anyhow::bail!("failed to connect to server"),
381				});
382			}
383
384			#[cfg(not(feature = "websocket"))]
385			{
386				let session = quic_handle.await?;
387				return Ok(self.moq.connect(session).await?);
388			}
389		}
390
391		anyhow::bail!("no QUIC backend compiled; enable noq, quinn, or quiche feature");
392	}
393}
394
395use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
396
397#[derive(Debug)]
398struct NoCertificateVerification(crypto::Provider);
399
400impl rustls::client::danger::ServerCertVerifier for NoCertificateVerification {
401	fn verify_server_cert(
402		&self,
403		_end_entity: &CertificateDer<'_>,
404		_intermediates: &[CertificateDer<'_>],
405		_server_name: &ServerName<'_>,
406		_ocsp: &[u8],
407		_now: UnixTime,
408	) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
409		Ok(rustls::client::danger::ServerCertVerified::assertion())
410	}
411
412	fn verify_tls12_signature(
413		&self,
414		message: &[u8],
415		cert: &CertificateDer<'_>,
416		dss: &rustls::DigitallySignedStruct,
417	) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
418		rustls::crypto::verify_tls12_signature(message, cert, dss, &self.0.signature_verification_algorithms)
419	}
420
421	fn verify_tls13_signature(
422		&self,
423		message: &[u8],
424		cert: &CertificateDer<'_>,
425		dss: &rustls::DigitallySignedStruct,
426	) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
427		rustls::crypto::verify_tls13_signature(message, cert, dss, &self.0.signature_verification_algorithms)
428	}
429
430	fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
431		self.0.signature_verification_algorithms.supported_schemes()
432	}
433}
434
435#[cfg(test)]
436mod tests {
437	use super::*;
438	use clap::Parser;
439
440	#[test]
441	fn test_toml_disable_verify_survives_update_from() {
442		let toml = r#"
443			tls.disable_verify = true
444		"#;
445
446		let mut config: ClientConfig = toml::from_str(toml).unwrap();
447		assert_eq!(config.tls.disable_verify, Some(true));
448
449		// Simulate: TOML loaded, then CLI args re-applied (no --tls-disable-verify flag).
450		config.update_from(["test"]);
451		assert_eq!(config.tls.disable_verify, Some(true));
452	}
453
454	#[test]
455	fn test_cli_disable_verify_flag() {
456		let config = ClientConfig::parse_from(["test", "--tls-disable-verify"]);
457		assert_eq!(config.tls.disable_verify, Some(true));
458	}
459
460	#[test]
461	fn test_cli_disable_verify_explicit_false() {
462		let config = ClientConfig::parse_from(["test", "--tls-disable-verify=false"]);
463		assert_eq!(config.tls.disable_verify, Some(false));
464	}
465
466	#[test]
467	fn test_cli_disable_verify_explicit_true() {
468		let config = ClientConfig::parse_from(["test", "--tls-disable-verify=true"]);
469		assert_eq!(config.tls.disable_verify, Some(true));
470	}
471
472	#[test]
473	fn test_cli_no_disable_verify() {
474		let config = ClientConfig::parse_from(["test"]);
475		assert_eq!(config.tls.disable_verify, None);
476	}
477
478	#[test]
479	fn test_toml_version_survives_update_from() {
480		let toml = r#"
481			version = ["moq-lite-02"]
482		"#;
483
484		let mut config: ClientConfig = toml::from_str(toml).unwrap();
485		assert_eq!(
486			config.version,
487			vec!["moq-lite-02".parse::<moq_lite::Version>().unwrap()]
488		);
489
490		// Simulate: TOML loaded, then CLI args re-applied (no --client-version flag).
491		config.update_from(["test"]);
492		assert_eq!(
493			config.version,
494			vec!["moq-lite-02".parse::<moq_lite::Version>().unwrap()]
495		);
496	}
497
498	#[test]
499	fn test_cli_version() {
500		let config = ClientConfig::parse_from(["test", "--client-version", "moq-lite-03"]);
501		assert_eq!(
502			config.version,
503			vec!["moq-lite-03".parse::<moq_lite::Version>().unwrap()]
504		);
505	}
506
507	#[test]
508	fn test_cli_no_version_defaults_to_all() {
509		let config = ClientConfig::parse_from(["test"]);
510		assert!(config.version.is_empty());
511		// versions() helper returns all when none specified
512		assert_eq!(config.versions().alpns().len(), moq_lite::ALPNS.len());
513	}
514}