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
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	#[cfg(feature = "websocket")]
122	websocket: super::ClientWebSocket,
123	tls: rustls::ClientConfig,
124	#[cfg(feature = "quinn")]
125	quinn: Option<crate::quinn::QuinnClient>,
126	#[cfg(feature = "quiche")]
127	quiche: Option<crate::quiche::QuicheClient>,
128	#[cfg(feature = "iroh")]
129	iroh: Option<web_transport_iroh::iroh::Endpoint>,
130}
131
132impl Client {
133	#[cfg(not(any(feature = "quinn", feature = "quiche")))]
134	pub fn new(_config: ClientConfig) -> anyhow::Result<Self> {
135		anyhow::bail!("no QUIC backend compiled; enable quinn or quiche feature");
136	}
137
138	/// Create a new client
139	#[cfg(any(feature = "quinn", feature = "quiche"))]
140	pub fn new(config: ClientConfig) -> anyhow::Result<Self> {
141		let backend = config.backend.clone().unwrap_or({
142			#[cfg(feature = "quinn")]
143			{
144				QuicBackend::Quinn
145			}
146			#[cfg(all(feature = "quiche", not(feature = "quinn")))]
147			{
148				QuicBackend::Quiche
149			}
150			#[cfg(all(not(feature = "quiche"), not(feature = "quinn")))]
151			panic!("no QUIC backend compiled; enable quinn or quiche feature");
152		});
153
154		let provider = crypto::provider();
155
156		// Create a list of acceptable root certificates.
157		let mut roots = rustls::RootCertStore::empty();
158
159		if config.tls.root.is_empty() {
160			let native = rustls_native_certs::load_native_certs();
161
162			// Log any errors that occurred while loading the native root certificates.
163			for err in native.errors {
164				tracing::warn!(%err, "failed to load root cert");
165			}
166
167			// Add the platform's native root certificates.
168			for cert in native.certs {
169				roots.add(cert).context("failed to add root cert")?;
170			}
171		} else {
172			// Add the specified root certificates.
173			for root in &config.tls.root {
174				let root = std::fs::File::open(root).context("failed to open root cert file")?;
175				let mut root = std::io::BufReader::new(root);
176
177				let root = rustls_pemfile::certs(&mut root)
178					.next()
179					.context("no roots found")?
180					.context("failed to read root cert")?;
181
182				roots.add(root).context("failed to add root cert")?;
183			}
184		}
185
186		// Create the TLS configuration we'll use as a client (relay -> relay)
187		let mut tls = rustls::ClientConfig::builder_with_provider(provider.clone())
188			.with_protocol_versions(&[&rustls::version::TLS13])?
189			.with_root_certificates(roots)
190			.with_no_client_auth();
191
192		// Allow disabling TLS verification altogether.
193		if config.tls.disable_verify.unwrap_or_default() {
194			tracing::warn!("TLS server certificate verification is disabled; A man-in-the-middle attack is possible.");
195
196			let noop = NoCertificateVerification(provider.clone());
197			tls.dangerous().set_certificate_verifier(Arc::new(noop));
198		}
199
200		#[cfg(feature = "quinn")]
201		#[allow(unreachable_patterns)]
202		let quinn = match backend {
203			QuicBackend::Quinn => Some(crate::quinn::QuinnClient::new(&config)?),
204			_ => None,
205		};
206
207		#[cfg(feature = "quiche")]
208		let quiche = match backend {
209			QuicBackend::Quiche => Some(crate::quiche::QuicheClient::new(&config)?),
210			_ => None,
211		};
212
213		Ok(Self {
214			moq: moq_lite::Client::new().with_versions(config.versions()),
215			#[cfg(feature = "websocket")]
216			websocket: config.websocket,
217			tls,
218			#[cfg(feature = "quinn")]
219			quinn,
220			#[cfg(feature = "quiche")]
221			quiche,
222			#[cfg(feature = "iroh")]
223			iroh: None,
224		})
225	}
226
227	#[cfg(feature = "iroh")]
228	pub fn with_iroh(mut self, iroh: Option<web_transport_iroh::iroh::Endpoint>) -> Self {
229		self.iroh = iroh;
230		self
231	}
232
233	pub fn with_publish(mut self, publish: impl Into<Option<moq_lite::OriginConsumer>>) -> Self {
234		self.moq = self.moq.with_publish(publish);
235		self
236	}
237
238	pub fn with_consume(mut self, consume: impl Into<Option<moq_lite::OriginProducer>>) -> Self {
239		self.moq = self.moq.with_consume(consume);
240		self
241	}
242
243	#[cfg(not(any(feature = "quinn", feature = "quiche", feature = "iroh")))]
244	pub async fn connect(&self, _url: Url) -> anyhow::Result<moq_lite::Session> {
245		anyhow::bail!("no QUIC backend compiled; enable quinn, quiche, or iroh feature");
246	}
247
248	#[cfg(any(feature = "quinn", feature = "quiche", feature = "iroh"))]
249	pub async fn connect(&self, url: Url) -> anyhow::Result<moq_lite::Session> {
250		#[cfg(feature = "iroh")]
251		if url.scheme() == "iroh" {
252			let endpoint = self.iroh.as_ref().context("Iroh support is not enabled")?;
253			let session = crate::iroh::connect(endpoint, url).await?;
254			let session = self.moq.connect(session).await?;
255			return Ok(session);
256		}
257
258		#[cfg(feature = "quinn")]
259		if let Some(quinn) = self.quinn.as_ref() {
260			let tls = self.tls.clone();
261			let quic_url = url.clone();
262			let quic_handle = async {
263				let res = quinn.connect(&tls, quic_url).await;
264				if let Err(err) = &res {
265					tracing::warn!(%err, "QUIC connection failed");
266				}
267				res
268			};
269
270			#[cfg(feature = "websocket")]
271			{
272				let ws_handle = crate::websocket::race_handle(&self.websocket, &self.tls, url);
273
274				return Ok(tokio::select! {
275					Ok(quic) = quic_handle => self.moq.connect(quic).await?,
276					Some(Ok(ws)) = ws_handle => self.moq.connect(ws).await?,
277					else => anyhow::bail!("failed to connect to server"),
278				});
279			}
280
281			#[cfg(not(feature = "websocket"))]
282			{
283				let session = quic_handle.await?;
284				return Ok(self.moq.connect(session).await?);
285			}
286		}
287
288		#[cfg(feature = "quiche")]
289		if let Some(quiche) = self.quiche.as_ref() {
290			let quic_url = url.clone();
291			let quic_handle = async {
292				let res = quiche.connect(quic_url).await;
293				if let Err(err) = &res {
294					tracing::warn!(%err, "QUIC connection failed");
295				}
296				res
297			};
298
299			#[cfg(feature = "websocket")]
300			{
301				let ws_handle = crate::websocket::race_handle(&self.websocket, &self.tls, url);
302
303				return Ok(tokio::select! {
304					Ok(quic) = quic_handle => self.moq.connect(quic).await?,
305					Some(Ok(ws)) = ws_handle => self.moq.connect(ws).await?,
306					else => anyhow::bail!("failed to connect to server"),
307				});
308			}
309
310			#[cfg(not(feature = "websocket"))]
311			{
312				let session = quic_handle.await?;
313				return Ok(self.moq.connect(session).await?);
314			}
315		}
316
317		anyhow::bail!("no QUIC backend compiled; enable quinn or quiche feature");
318	}
319}
320
321use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
322
323#[derive(Debug)]
324struct NoCertificateVerification(crypto::Provider);
325
326impl rustls::client::danger::ServerCertVerifier for NoCertificateVerification {
327	fn verify_server_cert(
328		&self,
329		_end_entity: &CertificateDer<'_>,
330		_intermediates: &[CertificateDer<'_>],
331		_server_name: &ServerName<'_>,
332		_ocsp: &[u8],
333		_now: UnixTime,
334	) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
335		Ok(rustls::client::danger::ServerCertVerified::assertion())
336	}
337
338	fn verify_tls12_signature(
339		&self,
340		message: &[u8],
341		cert: &CertificateDer<'_>,
342		dss: &rustls::DigitallySignedStruct,
343	) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
344		rustls::crypto::verify_tls12_signature(message, cert, dss, &self.0.signature_verification_algorithms)
345	}
346
347	fn verify_tls13_signature(
348		&self,
349		message: &[u8],
350		cert: &CertificateDer<'_>,
351		dss: &rustls::DigitallySignedStruct,
352	) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
353		rustls::crypto::verify_tls13_signature(message, cert, dss, &self.0.signature_verification_algorithms)
354	}
355
356	fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
357		self.0.signature_verification_algorithms.supported_schemes()
358	}
359}
360
361#[cfg(test)]
362mod tests {
363	use super::*;
364	use clap::Parser;
365
366	#[test]
367	fn test_toml_disable_verify_survives_update_from() {
368		let toml = r#"
369			tls.disable_verify = true
370		"#;
371
372		let mut config: ClientConfig = toml::from_str(toml).unwrap();
373		assert_eq!(config.tls.disable_verify, Some(true));
374
375		// Simulate: TOML loaded, then CLI args re-applied (no --tls-disable-verify flag).
376		config.update_from(["test"]);
377		assert_eq!(config.tls.disable_verify, Some(true));
378	}
379
380	#[test]
381	fn test_cli_disable_verify_flag() {
382		let config = ClientConfig::parse_from(["test", "--tls-disable-verify"]);
383		assert_eq!(config.tls.disable_verify, Some(true));
384	}
385
386	#[test]
387	fn test_cli_disable_verify_explicit_false() {
388		let config = ClientConfig::parse_from(["test", "--tls-disable-verify=false"]);
389		assert_eq!(config.tls.disable_verify, Some(false));
390	}
391
392	#[test]
393	fn test_cli_disable_verify_explicit_true() {
394		let config = ClientConfig::parse_from(["test", "--tls-disable-verify=true"]);
395		assert_eq!(config.tls.disable_verify, Some(true));
396	}
397
398	#[test]
399	fn test_cli_no_disable_verify() {
400		let config = ClientConfig::parse_from(["test"]);
401		assert_eq!(config.tls.disable_verify, None);
402	}
403
404	#[test]
405	fn test_toml_version_survives_update_from() {
406		let toml = r#"
407			version = ["moq-lite-02"]
408		"#;
409
410		let mut config: ClientConfig = toml::from_str(toml).unwrap();
411		assert_eq!(
412			config.version,
413			vec!["moq-lite-02".parse::<moq_lite::Version>().unwrap()]
414		);
415
416		// Simulate: TOML loaded, then CLI args re-applied (no --client-version flag).
417		config.update_from(["test"]);
418		assert_eq!(
419			config.version,
420			vec!["moq-lite-02".parse::<moq_lite::Version>().unwrap()]
421		);
422	}
423
424	#[test]
425	fn test_cli_version() {
426		let config = ClientConfig::parse_from(["test", "--client-version", "moq-lite-03"]);
427		assert_eq!(
428			config.version,
429			vec!["moq-lite-03".parse::<moq_lite::Version>().unwrap()]
430		);
431	}
432
433	#[test]
434	fn test_cli_no_version_defaults_to_all() {
435		let config = ClientConfig::parse_from(["test"]);
436		assert!(config.version.is_empty());
437		// versions() helper returns all when none specified
438		assert_eq!(config.versions().alpns().len(), moq_lite::ALPNS.len());
439	}
440}