Skip to main content

moq_native/
quinn.rs

1//! The quinn QUIC backend, used for both WebTransport (`https://`) and raw QUIC (`moqt://`, `moql://`).
2
3use crate::client::ClientConfig;
4use crate::quic::CongestionControl;
5use crate::quic::Resolved;
6use crate::quic::ServerId;
7use crate::server::ServerConfig;
8use crate::tls::{FingerprintVerifier, ServeCerts};
9use std::net;
10use std::sync::Arc;
11use std::time::Duration;
12use url::Url;
13
14pub use web_transport_quinn;
15
16/// Attach a qlog stream writing into `dir`, if one was configured.
17///
18/// quinn's [`quinn::QlogStream`] is a shared handle: every connection on the endpoint
19/// writes into it, tagged with its own qlog `group_id`. So this is one file per
20/// endpoint rather than per connection, unlike the noq and quiche backends.
21fn apply_qlog(transport: &mut quinn::TransportConfig, quic: &Resolved, role: &str) -> Result<()> {
22	// `Client::validate` already rejected a directory this build can't honor, so the
23	// block below is only reached where capture actually works.
24	let Some(dir) = quic.qlog_dir() else {
25		return Ok(());
26	};
27
28	#[cfg(feature = "qlog")]
29	{
30		// The pid keeps concurrent processes sharing a directory from clobbering each other.
31		let path = dir.join(format!("moq-{role}-{}.sqlog", std::process::id()));
32		let file = std::fs::File::create(&path).map_err(Error::CreateQlog)?;
33
34		// Deliberately unbuffered: qlog's streamer only flushes on `finish_log`, which
35		// quinn never calls per event, so a BufWriter would hold every trace in memory
36		// until the endpoint drops and lose the lot if the process is killed. Killing a
37		// stuck process is exactly when these traces are worth having.
38		let mut config = quinn::QlogConfig::default();
39		config.writer(Box::new(file)).title(Some(format!("moq-native {role}")));
40
41		transport.qlog_stream(config.into_stream());
42		tracing::info!(path = %path.display(), "writing qlog");
43	}
44
45	#[cfg(not(feature = "qlog"))]
46	let _ = (transport, dir, role);
47
48	Ok(())
49}
50
51/// Apply the resolved quic knobs to a quinn transport config.
52fn apply_transport(transport: &mut quinn::TransportConfig, quic: &Resolved) {
53	transport.max_idle_timeout(Some(quic.idle_timeout.try_into().expect("idle timeout out of range")));
54	transport.keep_alive_interval(quic.keep_alive);
55
56	// quinn enables MTU discovery by default; disable it unless asked.
57	if !quic.mtu_discovery {
58		transport.mtu_discovery_config(None);
59	}
60
61	let max_streams = quinn::VarInt::from_u64(quic.max_streams).unwrap_or(quinn::VarInt::MAX);
62	transport.max_concurrent_bidi_streams(max_streams);
63	transport.max_concurrent_uni_streams(max_streams);
64
65	// GSO is on by default; only the quinn/noq backends can turn it off.
66	if let Some(gso) = quic.gso {
67		transport.enable_segmentation_offload(gso);
68	}
69
70	transport.congestion_controller_factory(congestion_factory(congestion_control(quic)));
71}
72
73/// The congestion control family to install, defaulting to delay-based.
74///
75/// Live media wants a steady send rate an encoder can track, not CUBIC's sawtooth,
76/// so override quinn's own CUBIC default.
77fn congestion_control(quic: &Resolved) -> CongestionControl {
78	quic.congestion_control.unwrap_or(CongestionControl::Delay)
79}
80
81/// The quinn controller factory for a congestion control family. quinn's BBR is v1.
82fn congestion_factory(family: CongestionControl) -> Arc<dyn quinn::congestion::ControllerFactory + Send + Sync> {
83	match family {
84		CongestionControl::Loss => Arc::new(quinn::congestion::CubicConfig::default()),
85		CongestionControl::Delay => Arc::new(quinn::congestion::BbrConfig::default()),
86	}
87}
88
89/// Errors specific to the quinn QUIC backend.
90#[derive(Debug, thiserror::Error)]
91#[non_exhaustive]
92pub enum Error {
93	/// The UDP socket couldn't be bound, usually because the address is already in use.
94	#[error("failed to bind UDP socket")]
95	BindSocket(#[source] std::io::Error),
96
97	/// The bound socket couldn't be turned into a QUIC endpoint.
98	#[error("failed to create QUIC endpoint")]
99	CreateEndpoint(#[source] std::io::Error),
100
101	/// The qlog trace file couldn't be created, usually a missing directory.
102	#[error("failed to create qlog file")]
103	CreateQlog(#[source] std::io::Error),
104
105	/// Quinn found no async runtime. Construct the client or server from within a tokio context.
106	#[error("no async runtime")]
107	NoRuntime,
108
109	/// The endpoint's local address couldn't be read back from the OS.
110	#[error("failed to get local address")]
111	LocalAddr(#[source] std::io::Error),
112
113	/// The server's configured bind address couldn't be resolved.
114	#[error("failed to resolve bind address")]
115	ResolveBind(#[source] std::io::Error),
116
117	/// The URL has no host to connect to.
118	#[error("invalid DNS name")]
119	InvalidDnsName,
120
121	/// Resolving the URL's host failed.
122	#[error("failed DNS lookup")]
123	DnsLookup(#[source] std::io::Error),
124
125	/// DNS returned no address usable from the local socket, usually an address family mismatch.
126	#[error("no DNS entries")]
127	NoDnsEntries,
128
129	/// The insecure `http://` bootstrap couldn't fetch `/certificate.sha256`.
130	#[error("failed to fetch fingerprint")]
131	FetchFingerprint(#[source] reqwest::Error),
132
133	/// The `/certificate.sha256` fetch returned a non-success status.
134	#[error("fingerprint request failed")]
135	FingerprintStatus(#[source] reqwest::Error),
136
137	/// The fingerprint response body couldn't be read.
138	#[error("failed to read fingerprint")]
139	ReadFingerprint(#[source] reqwest::Error),
140
141	/// The fetched fingerprint wasn't valid hex.
142	#[error("invalid fingerprint")]
143	InvalidFingerprint(#[from] hex::FromHexError),
144
145	/// The URL scheme isn't one this backend can dial.
146	#[error("url scheme must be 'https', 'moqt', or 'moql'")]
147	InvalidScheme,
148
149	/// The URL scheme passed the initial check but has no session type, which means it slipped through a scheme list.
150	#[error("unsupported URL scheme: {0}")]
151	UnsupportedScheme(String),
152
153	/// The connection came up without TLS handshake data, so the negotiated ALPN can't be read.
154	#[error("missing handshake data")]
155	MissingHandshake,
156
157	/// TLS negotiated no ALPN, so there's no protocol to speak.
158	#[error("missing ALPN")]
159	MissingAlpn,
160
161	/// The negotiated ALPN wasn't valid UTF-8.
162	#[error("failed to decode ALPN")]
163	DecodeAlpn(#[from] std::string::FromUtf8Error),
164
165	/// The peer negotiated an ALPN this endpoint doesn't handle.
166	#[error("unsupported ALPN: {0}")]
167	UnsupportedAlpn(String),
168
169	/// A raw QUIC client connected without SNI, so the server can't tell which host it wanted.
170	#[error("missing server name for raw QUIC connection")]
171	MissingServerName,
172
173	/// The client's SNI hostname didn't form a valid URL.
174	#[error("failed to construct URL from server name")]
175	BuildUrl(#[source] url::ParseError),
176
177	/// The configured QUIC-LB nonce is too short to be unguessable.
178	#[error("quic_lb_nonce must be at least 4")]
179	QuicLbNonceTooSmall,
180
181	/// The QUIC-LB server ID plus nonce doesn't fit in a connection ID. Shorten one of them.
182	#[error("connection ID length ({0}) exceeds maximum of 20")]
183	QuicLbCidTooLong(usize),
184
185	/// The mTLS client verifier couldn't be built from the configured roots.
186	#[error("failed to build client certificate verifier")]
187	ClientVerifier(#[source] rustls::server::VerifierBuilderError),
188
189	/// The rustls crypto provider offers no cipher suite usable for QUIC initial packets.
190	#[error(transparent)]
191	NoInitialCipherSuite(#[from] quinn::crypto::rustls::NoInitialCipherSuite),
192
193	/// Quinn refused to start the connection, before any packet was sent.
194	#[error(transparent)]
195	Connect(#[from] quinn::ConnectError),
196
197	/// The QUIC connection failed or was closed by the peer.
198	#[error(transparent)]
199	Connection(#[from] quinn::ConnectionError),
200
201	/// The WebTransport client handshake failed.
202	#[error(transparent)]
203	Client(#[from] web_transport_quinn::ClientError),
204
205	/// The server answered the WebTransport CONNECT with a rejection status.
206	#[error(transparent)]
207	ConnectRejected(#[from] crate::ConnectError),
208
209	/// The WebTransport server handshake failed while responding.
210	#[error(transparent)]
211	Server(#[from] web_transport_quinn::ServerError),
212
213	/// The QUIC handshake didn't complete for an incoming connection.
214	#[error("failed to establish QUIC connection")]
215	Establish(#[source] quinn::ConnectionError),
216
217	/// The client never sent a usable WebTransport CONNECT request.
218	#[error("failed to receive WebTransport request")]
219	RecvRequest(#[source] web_transport_quinn::ServerError),
220
221	/// The TLS configuration or certificates couldn't be loaded.
222	#[error(transparent)]
223	Tls(#[from] crate::tls::Error),
224}
225
226type Result<T> = std::result::Result<T, Error>;
227
228// ── Client ──────────────────────────────────────────────────────────
229
230#[derive(Clone)]
231pub(crate) struct QuinnClient {
232	pub quic: quinn::Endpoint,
233	pub transport: Arc<quinn::TransportConfig>,
234	/// Whether an `http://` URL may bootstrap a pin (see [crate::tls::Client::allows_http_bootstrap]).
235	pub http_bootstrap: bool,
236	/// Optional TLS SNI / verification hostname override (from config).
237	pub host_name: Option<String>,
238}
239
240impl QuinnClient {
241	pub fn new(config: &ClientConfig) -> Result<Self> {
242		let socket = crate::bind::udp(config.bind).map_err(Error::BindSocket)?;
243
244		let quic = config.quic.resolve();
245		let mut transport = quinn::TransportConfig::default();
246		apply_transport(&mut transport, &quic);
247		apply_qlog(&mut transport, &quic, "client")?;
248		let transport = Arc::new(transport);
249
250		// There's a bit more boilerplate to make a generic endpoint.
251		let runtime = quinn::default_runtime().ok_or(Error::NoRuntime)?;
252		let endpoint_config = quinn::EndpointConfig::default();
253
254		// Create the generic QUIC endpoint.
255		let quic = quinn::Endpoint::new(endpoint_config, None, socket, runtime).map_err(Error::CreateEndpoint)?;
256
257		Ok(Self {
258			quic,
259			transport,
260			http_bootstrap: config.tls.allows_http_bootstrap(),
261			host_name: config.tls.host_name.clone(),
262		})
263	}
264
265	pub async fn connect(
266		&self,
267		tls: &rustls::ClientConfig,
268		url: Url,
269		versions: &moq_net::Versions,
270	) -> Result<web_transport_quinn::Session> {
271		let mut url = url;
272		let mut config = tls.clone();
273
274		let host = url.host().ok_or(Error::InvalidDnsName)?.to_string();
275		let port = url.port().unwrap_or(443);
276
277		// Look up the DNS entry.
278		// Quinn doesn't support happy eyeballs, so we pick a single address,
279		// preferring one whose family matches the local socket so the OS
280		// doesn't reject it (notably on Windows, where IPv6 sockets aren't
281		// dual-stack by default).
282		let local = self.quic.local_addr().map_err(Error::LocalAddr)?;
283		let addrs = tokio::net::lookup_host((host.clone(), port))
284			.await
285			.map_err(Error::DnsLookup)?;
286		let ip = crate::util::pick_addr(addrs, local).ok_or(Error::NoDnsEntries)?;
287
288		if url.scheme() == "http" {
289			// Insecure per-connection bootstrap: only honored when no stronger
290			// verification is configured, so an attacker controlling the plaintext
291			// fetch can't weaken an explicit pin or re-enable disabled verification.
292			if self.http_bootstrap {
293				// Perform a HTTP request to fetch the certificate fingerprint.
294				let mut fingerprint = url.clone();
295				fingerprint.set_path("/certificate.sha256");
296				fingerprint.set_query(None);
297				fingerprint.set_fragment(None);
298
299				tracing::warn!(url = %fingerprint, "performing insecure HTTP request for certificate");
300
301				let resp = reqwest::get(fingerprint.as_str())
302					.await
303					.map_err(Error::FetchFingerprint)?
304					.error_for_status()
305					.map_err(Error::FingerprintStatus)?;
306
307				let fingerprint = resp.text().await.map_err(Error::ReadFingerprint)?;
308				let fingerprint = hex::decode(fingerprint.trim())?;
309
310				let verifier = FingerprintVerifier::new(config.crypto_provider().clone(), vec![fingerprint]);
311				config.dangerous().set_certificate_verifier(Arc::new(verifier));
312			} else {
313				tracing::warn!(
314					"ignoring insecure http:// fingerprint bootstrap; using the configured TLS verification"
315				);
316			}
317
318			url.set_scheme("https").expect("failed to set scheme");
319		}
320
321		let alpns: Vec<Vec<u8>> = match url.scheme() {
322			"https" => vec![web_transport_quinn::ALPN.as_bytes().to_vec()],
323			"moqt" | "moql" => versions.alpns().iter().map(|alpn| alpn.as_bytes().to_vec()).collect(),
324			_ => return Err(Error::InvalidScheme),
325		};
326
327		config.alpn_protocols = alpns;
328		config.key_log = Arc::new(rustls::KeyLogFile::new());
329
330		let config: quinn::crypto::rustls::QuicClientConfig = config.try_into()?;
331		let mut config = quinn::ClientConfig::new(Arc::new(config));
332		config.transport_config(self.transport.clone());
333
334		tracing::debug!(%url, %ip, "connecting");
335
336		// Use the configured host_name override for SNI + cert verification, else the URL host.
337		let host_name = self.host_name.clone().unwrap_or(host);
338
339		let connection = self.quic.connect_with(config, ip, &host_name)?.await?;
340		tracing::Span::current().record("id", connection.stable_id());
341
342		let mut request = web_transport_quinn::proto::ConnectRequest::new(url.clone());
343		for alpn in versions.alpns() {
344			request = request.with_protocol(alpn.to_string());
345		}
346
347		let session = match url.scheme() {
348			"https" => web_transport_quinn::Session::connect(connection, request)
349				.await
350				.map_err(map_client_error)?,
351			"moqt" | "moql" => {
352				let handshake = connection
353					.handshake_data()
354					.ok_or(Error::MissingHandshake)?
355					.downcast::<quinn::crypto::rustls::HandshakeData>()
356					.unwrap();
357
358				let alpn = handshake.protocol.ok_or(Error::MissingAlpn)?;
359				let alpn = String::from_utf8(alpn)?;
360
361				let response = web_transport_quinn::proto::ConnectResponse::OK.with_protocol(alpn);
362				web_transport_quinn::Session::raw(connection, request, response)
363			}
364			_ => return Err(Error::UnsupportedScheme(url.scheme().to_string())),
365		};
366
367		Ok(session)
368	}
369}
370
371impl Error {
372	pub(crate) fn connect_error(&self) -> Option<crate::ConnectError> {
373		match self {
374			Self::ConnectRejected(err) => Some(*err),
375			Self::Client(err) => classify_client_error(err),
376			_ => None,
377		}
378	}
379}
380
381fn map_client_error(err: web_transport_quinn::ClientError) -> Error {
382	if let Some(err) = classify_client_error(&err) {
383		return err.into();
384	}
385
386	err.into()
387}
388
389fn classify_client_error(err: &web_transport_quinn::ClientError) -> Option<crate::ConnectError> {
390	match err {
391		web_transport_quinn::ClientError::HttpError(err) => classify_connect_error(err),
392		_ => None,
393	}
394}
395
396fn classify_connect_error(err: &web_transport_quinn::ConnectError) -> Option<crate::ConnectError> {
397	match err {
398		web_transport_quinn::ConnectError::ErrorStatus(status) => crate::ConnectError::from_status_u16(status.as_u16()),
399		web_transport_quinn::ConnectError::ProtoError(err) => classify_proto_error(err),
400		_ => None,
401	}
402}
403
404fn classify_proto_error(err: &web_transport_quinn::proto::ConnectError) -> Option<crate::ConnectError> {
405	match err {
406		web_transport_quinn::proto::ConnectError::ErrorStatus(status)
407		| web_transport_quinn::proto::ConnectError::WrongStatus(Some(status)) => {
408			crate::ConnectError::from_status_u16(status.as_u16())
409		}
410		_ => None,
411	}
412}
413
414// ── Server ──────────────────────────────────────────────────────────
415
416pub(crate) struct QuinnServer {
417	pub quic: quinn::Endpoint,
418	pub certs: Arc<ServeCerts>,
419}
420
421impl QuinnServer {
422	pub fn new(config: ServerConfig) -> Result<Self> {
423		let quic = config.quic.resolve();
424		let mut transport = quinn::TransportConfig::default();
425		apply_transport(&mut transport, &quic);
426		apply_qlog(&mut transport, &quic, "server")?;
427		let transport = Arc::new(transport);
428
429		let provider = crate::crypto::provider();
430
431		let certs = ServeCerts::new(provider.clone());
432		certs.load_certs(&config.tls)?;
433		let certs = Arc::new(certs);
434
435		let tls_builder = rustls::ServerConfig::builder_with_provider(provider.clone())
436			.with_protocol_versions(&[&rustls::version::TLS13])
437			.map_err(crate::tls::Error::from)?;
438
439		let mut tls = if config.tls.root.is_empty() {
440			tls_builder.with_no_client_auth().with_cert_resolver(certs.clone())
441		} else {
442			let roots = config.tls.load_roots()?;
443			let verifier = rustls::server::WebPkiClientVerifier::builder_with_provider(Arc::new(roots), provider)
444				.allow_unauthenticated()
445				.build()
446				.map_err(Error::ClientVerifier)?;
447			tls_builder
448				.with_client_cert_verifier(verifier)
449				.with_cert_resolver(certs.clone())
450		};
451
452		// H3 is last because it requires WebTransport framing which not all H3 endpoints support.
453		let mut alpns: Vec<Vec<u8>> = config
454			.versions()
455			.alpns()
456			.iter()
457			.map(|alpn| alpn.as_bytes().to_vec())
458			.collect();
459		alpns.push(web_transport_quinn::ALPN.as_bytes().to_vec());
460
461		tls.alpn_protocols = alpns;
462		tls.key_log = Arc::new(rustls::KeyLogFile::new());
463
464		let tls: quinn::crypto::rustls::QuicServerConfig = tls.try_into()?;
465		let mut tls = quinn::ServerConfig::with_crypto(Arc::new(tls));
466		tls.transport_config(transport);
467
468		// Advertise the preferred_address transport parameter (RFC 9000 §9.6).
469		// Quinn allocates a fresh CID + reset token for the address during the handshake.
470		if let Some(addr) = config.quic.preferred_v4 {
471			tls.preferred_address_v4(Some(addr));
472		}
473		if let Some(addr) = config.quic.preferred_v6 {
474			tls.preferred_address_v6(Some(addr));
475		}
476
477		// There's a bit more boilerplate to make a generic endpoint.
478		let runtime = quinn::default_runtime().ok_or(Error::NoRuntime)?;
479
480		let listen =
481			crate::util::resolve(config.bind.as_deref(), crate::server::DEFAULT_BIND).map_err(Error::ResolveBind)?;
482
483		// Configure connection ID generator with server ID if provided
484		let mut endpoint_config = quinn::EndpointConfig::default();
485		if let Some(server_id) = config.quic.quic_lb_id {
486			let nonce_len = config.quic.quic_lb_nonce.unwrap_or(8);
487			if nonce_len < 4 {
488				return Err(Error::QuicLbNonceTooSmall);
489			}
490
491			let cid_len = 1 + server_id.len() + nonce_len;
492			if cid_len > 20 {
493				return Err(Error::QuicLbCidTooLong(cid_len));
494			}
495
496			tracing::info!(
497				?server_id,
498				nonce_len,
499				"using QUIC-LB compatible connection ID generation"
500			);
501			endpoint_config.cid_generator(move || Box::new(ServerIdGenerator::new(server_id.clone(), nonce_len)));
502		}
503
504		let socket = crate::bind::udp(listen).map_err(Error::BindSocket)?;
505
506		// Create the generic QUIC endpoint.
507		let quic = quinn::Endpoint::new(endpoint_config, Some(tls), socket, runtime).map_err(Error::CreateEndpoint)?;
508
509		// Spawn the cert reload watcher only after endpoint creation succeeds,
510		// so we don't leave a dangling watcher on failure.
511		tokio::spawn(crate::tls::reload_certs(certs.clone(), config.tls.clone()));
512
513		Ok(Self { quic, certs })
514	}
515
516	pub fn accept(&self) -> impl std::future::Future<Output = Option<quinn::Incoming>> + '_ {
517		self.quic.accept()
518	}
519
520	pub fn certificates(&self) -> crate::tls::Certificates {
521		crate::tls::Certificates::new(self.certs.info.clone())
522	}
523
524	pub fn local_addr(&self) -> Result<net::SocketAddr> {
525		self.quic.local_addr().map_err(Error::LocalAddr)
526	}
527
528	pub fn close(&self) {
529		self.quic.close(quinn::VarInt::from_u32(0), b"server shutdown");
530	}
531}
532
533// ── QuinnRequest ────────────────────────────────────────────────────
534
535/// Accept a QUIC connection, negotiate WebTransport or raw moq, and complete the
536/// handshake (a `200 OK` for WebTransport). Returns the established session plus the
537/// request URL and validated mTLS identity, both captured before the response consumes
538/// the request. Raw QUIC carries no request URL (the path rides the SETUP instead).
539pub(crate) async fn accept(
540	conn: quinn::Incoming,
541	alpns: Vec<&'static str>,
542) -> Result<(
543	web_transport_quinn::Session,
544	Option<Url>,
545	Option<crate::tls::PeerIdentity>,
546)> {
547	let mut conn = conn.accept()?;
548
549	let handshake = conn
550		.handshake_data()
551		.await?
552		.downcast::<quinn::crypto::rustls::HandshakeData>()
553		.unwrap();
554
555	let alpn = handshake.protocol.ok_or(Error::MissingAlpn)?;
556	let alpn = String::from_utf8(alpn)?;
557	let host = handshake.server_name.unwrap_or_default();
558
559	tracing::debug!(%host, ip = %conn.remote_address(), %alpn, "accepting");
560
561	// Wait for the QUIC connection to be established.
562	let conn = conn.await.map_err(Error::Establish)?;
563
564	let span = tracing::Span::current();
565	span.record("id", conn.stable_id()); // TODO can we get this earlier?
566	tracing::debug!(%host, ip = %conn.remote_address(), %alpn, "accepted");
567
568	match alpn.as_str() {
569		web_transport_quinn::ALPN => {
570			// Wait for the CONNECT request, then capture its URL and mTLS identity before
571			// the response consumes it.
572			let request = web_transport_quinn::Request::accept(conn)
573				.await
574				.map_err(Error::RecvRequest)?;
575			let url = Some(request.url.clone());
576			let identity = crate::tls::PeerIdentity::from_any(request.conn().peer_identity());
577
578			let mut response = web_transport_quinn::proto::ConnectResponse::OK;
579			// Pick the first sub-protocol that we actually support.
580			// This is the WebTransport equivalent of ALPN negotiation.
581			// If no match is found, we default to no sub-protocol to support older
582			// clients that don't use ALPN. We assume moq-transport-14/moq-lite-02
583			// and perform the SETUP_x exchange instead.
584			if let Some(protocol) = request.protocols.iter().find(|p| alpns.contains(&p.as_str())) {
585				response = response.with_protocol(protocol);
586			}
587			let session = request.respond(response).await.map_err(Error::Server)?;
588			Ok((session, url, identity))
589		}
590		// Recognize any moq ALPN this server actually offered (its configured versions),
591		// not the global default set. rustls only negotiates an ALPN the server offered, so
592		// this covers opt-in / work-in-progress versions (e.g. moq-lite-06-wip) that are
593		// deliberately absent from `moq_net::ALPNS`.
594		alpn if alpns.contains(&alpn) => {
595			// Raw QUIC carries no in-band request URL like WebTransport's CONNECT, so the TLS
596			// SNI is the only authority the client can offer, and it's optional. A client dialing
597			// a bare IP sends no SNI (RFC 6066 forbids IP literals), leaving `host` empty; the
598			// resulting hostless `moqt://` routes to the root path, exactly like a URL-less stream
599			// transport. `url()` returns `None` for the raw variant either way.
600			let host_str = if host.contains(':') {
601				format!("[{}]", host)
602			} else {
603				host.clone()
604			};
605			let url = format!("moqt://{}", host_str).parse::<Url>().map_err(Error::BuildUrl)?;
606			let request = web_transport_quinn::proto::ConnectRequest::new(url);
607			let response = web_transport_quinn::proto::ConnectResponse::OK.with_protocol(alpn);
608			let identity = crate::tls::PeerIdentity::from_any(conn.peer_identity());
609			// Raw QUIC carries no request URL; the path rides the SETUP.
610			let session = web_transport_quinn::Session::raw(conn, request, response);
611			Ok((session, None, identity))
612		}
613		_ => Err(Error::UnsupportedAlpn(alpn)),
614	}
615}
616
617// ── ServerIdGenerator ───────────────────────────────────────────────
618
619struct ServerIdGenerator {
620	server_id: ServerId,
621	nonce_len: usize,
622}
623
624impl ServerIdGenerator {
625	fn new(server_id: ServerId, nonce_len: usize) -> Self {
626		Self { server_id, nonce_len }
627	}
628}
629
630impl quinn::ConnectionIdGenerator for ServerIdGenerator {
631	fn generate_cid(&mut self) -> quinn::ConnectionId {
632		use rand::RngExt;
633		let cid_len = self.cid_len();
634		let mut cid = Vec::with_capacity(cid_len);
635		// First byte has "self-encoded length" of server ID + nonce
636		cid.push((cid_len - 1) as u8);
637		cid.extend(self.server_id.0.iter());
638		cid.extend(rand::rng().random_iter::<u8>().take(self.nonce_len));
639		quinn::ConnectionId::new(cid.as_slice())
640	}
641
642	fn cid_len(&self) -> usize {
643		1 + self.server_id.len() + self.nonce_len
644	}
645
646	fn cid_lifetime(&self) -> Option<Duration> {
647		None
648	}
649}
650
651#[cfg(test)]
652mod tests {
653	use super::*;
654
655	/// Build a controller from each family's factory and downcast it to the
656	/// concrete quinn implementation it must map to.
657	#[test]
658	fn congestion_factory_maps_each_family() {
659		let now = std::time::Instant::now();
660		let mtu = 1200;
661
662		let loss = congestion_factory(CongestionControl::Loss).build(now, mtu);
663		assert!(loss.into_any().downcast::<quinn::congestion::Cubic>().is_ok());
664
665		let delay = congestion_factory(CongestionControl::Delay).build(now, mtu);
666		assert!(delay.into_any().downcast::<quinn::congestion::Bbr>().is_ok());
667	}
668
669	/// An unset knob must land on BBR rather than quinn's own CUBIC default.
670	#[test]
671	fn congestion_control_defaults_to_delay() {
672		let mut quic = crate::quic::Client::default();
673		assert_eq!(congestion_control(&quic.resolve()), CongestionControl::Delay);
674
675		// An explicit request still gets through.
676		quic.congestion_control = Some(CongestionControl::Loss);
677		assert_eq!(congestion_control(&quic.resolve()), CongestionControl::Loss);
678	}
679
680	/// Loopback regression test: a config selecting BBR must produce live
681	/// connections that actually run quinn's BBR controller, on both ends.
682	#[tokio::test]
683	async fn delay_reaches_the_live_connection() {
684		let server_config = ServerConfig {
685			bind: Some("127.0.0.1:0".to_string()),
686			tls: crate::tls::Server {
687				generate: vec!["localhost".into()],
688				..Default::default()
689			},
690			quic: crate::quic::Server {
691				congestion_control: Some(CongestionControl::Delay),
692				..Default::default()
693			},
694			..Default::default()
695		};
696
697		let server = QuinnServer::new(server_config).expect("server init");
698		let addr = server.local_addr().expect("local addr");
699
700		let accepted = tokio::spawn(async move {
701			let incoming = server.accept().await.expect("no incoming connection");
702			let conn = incoming.accept().expect("accept").await.expect("handshake");
703			conn.congestion_state()
704				.into_any()
705				.downcast::<quinn::congestion::Bbr>()
706				.is_ok()
707		});
708
709		// tls::Client has a private field, so it can't be built with a struct literal.
710		let mut tls_config = crate::tls::Client::default();
711		tls_config.disable_verify = Some(true);
712
713		let client_config = ClientConfig {
714			bind: "127.0.0.1:0".parse().unwrap(),
715			tls: tls_config,
716			quic: crate::quic::Client {
717				congestion_control: Some(CongestionControl::Delay),
718				..Default::default()
719			},
720			..Default::default()
721		};
722
723		let tls = client_config.tls.build().expect("tls config");
724		let client = QuinnClient::new(&client_config).expect("client init");
725		// Dial the loopback IP directly so the system resolver is never involved.
726		let url: Url = format!("moqt://127.0.0.1:{}", addr.port()).parse().unwrap();
727
728		// Bound the whole connect + accept + assert flow so a handshake
729		// regression fails fast instead of stalling CI.
730		tokio::time::timeout(Duration::from_secs(5), async move {
731			let session = client
732				.connect(&tls, url, &moq_net::Versions::default())
733				.await
734				.expect("connect failed");
735
736			// web_transport_quinn::Session derefs to the quinn connection.
737			assert!(
738				session
739					.congestion_state()
740					.into_any()
741					.downcast::<quinn::congestion::Bbr>()
742					.is_ok(),
743				"client connection is not running BBR"
744			);
745			assert!(
746				accepted.await.expect("server task panicked"),
747				"server connection is not running BBR"
748			);
749		})
750		.await
751		.expect("test timed out");
752	}
753}