trillium_quinn/client.rs
1use crate::{
2 config::QuinnEndpoint,
3 runtime::{SocketTransport, TrilliumRuntime},
4};
5use std::{
6 fmt::{self, Debug, Formatter},
7 io,
8 net::SocketAddr,
9 sync::Arc,
10};
11use trillium_server_common::{Connector, QuicClientConfig};
12
13/// Client-side QUIC configuration for HTTP/3, backed by quinn.
14///
15/// This is a thin factory that creates [`QuinnEndpoint`]s bound to local addresses.
16/// The resulting endpoints can both accept and initiate QUIC connections.
17///
18/// # Construction
19///
20/// ```rust,ignore
21/// use trillium_tokio::ClientConfig;
22/// use trillium_quinn::ClientQuicConfig;
23///
24/// let client = trillium_client::Client::new_with_quic(
25/// ClientConfig::default(),
26/// ClientQuicConfig::default(),
27/// );
28/// ```
29pub struct ClientQuicConfig {
30 client_config: quinn::ClientConfig,
31 /// Retained so the bound endpoint can rebuild a per-connection `quinn::ClientConfig` with a
32 /// different ALPN (e.g. `doq`) — ALPN is baked into `QuicClientConfig` at construction and
33 /// can't be changed on the assembled `client_config`. `None` when built from a pre-assembled
34 /// `quinn::ClientConfig` (no rustls config to rebuild from), which disables per-connection
35 /// ALPN.
36 base_tls: Option<Arc<rustls::ClientConfig>>,
37}
38
39impl Debug for ClientQuicConfig {
40 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
41 f.debug_struct("ClientQuicConfig").finish_non_exhaustive()
42 }
43}
44
45impl Default for ClientQuicConfig {
46 /// Verifies servers with
47 /// [`rustls-platform-verifier`](https://docs.rs/rustls-platform-verifier) when the
48 /// `platform-verifier` feature is enabled (the default), and against the
49 /// [WebPKI](https://github.com/rustls/webpki-roots) roots compiled into the binary otherwise.
50 ///
51 /// The platform verifier uses the operating system's verifier and trust store on macOS, iOS,
52 /// Windows, and Android. On Linux and other Unix systems it verifies against the system CA
53 /// bundle — or, when `SSL_CERT_FILE` or `SSL_CERT_DIR` is set, against only the certificates
54 /// those name.
55 ///
56 /// # Panics
57 ///
58 /// With the platform verifier on Linux and other Unix systems, panics if no CA certificates
59 /// can be loaded: no system bundle is installed, or `SSL_CERT_FILE` and `SSL_CERT_DIR` name no
60 /// readable certificates.
61 fn default() -> Self {
62 Self::from_rustls_client_config(default_tls_config())
63 }
64}
65
66#[cfg(feature = "platform-verifier")]
67fn default_tls_config() -> rustls::ClientConfig {
68 use rustls_platform_verifier::BuilderVerifierExt;
69 tls_config_builder()
70 .with_platform_verifier()
71 .unwrap_or_else(|e| {
72 panic!(
73 "could not build the platform certificate verifier ({e}). If SSL_CERT_FILE or \
74 SSL_CERT_DIR is set, it must name readable PEM certificates; otherwise install \
75 the system CA certificates (often the `ca-certificates` package), or disable \
76 trillium-quinn's `platform-verifier` feature to use the WebPKI roots compiled \
77 into the binary"
78 )
79 })
80 .with_no_client_auth()
81}
82
83#[cfg(not(feature = "platform-verifier"))]
84fn default_tls_config() -> rustls::ClientConfig {
85 webpki_roots_tls_config()
86}
87
88fn webpki_roots_tls_config() -> rustls::ClientConfig {
89 let root_store =
90 rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
91 tls_config_builder()
92 .with_root_certificates(root_store)
93 .with_no_client_auth()
94}
95
96fn tls_config_builder() -> rustls::ConfigBuilder<rustls::ClientConfig, rustls::WantsVerifier> {
97 rustls::ClientConfig::builder_with_provider(crate::crypto_provider::crypto_provider())
98 .with_safe_default_protocol_versions()
99 .expect("building TLS config with protocol versions")
100}
101
102impl ClientQuicConfig {
103 /// Build a `ClientQuicConfig` trusting only the
104 /// [WebPKI](https://github.com/rustls/webpki-roots) root certificates compiled into the
105 /// binary, regardless of the platform's trust configuration.
106 ///
107 /// [`ClientQuicConfig::default`] is usually what you want. For custom CA trust or client
108 /// authentication, use [`from_rustls_client_config`](Self::from_rustls_client_config).
109 pub fn with_webpki_roots() -> Self {
110 Self::from_rustls_client_config(webpki_roots_tls_config())
111 }
112
113 /// Build from a pre-built [`rustls::ClientConfig`].
114 ///
115 /// `h3` ALPN is added automatically if not already present.
116 pub fn from_rustls_client_config(mut tls: rustls::ClientConfig) -> Self {
117 if !tls.alpn_protocols.contains(&b"h3".to_vec()) {
118 tls.alpn_protocols.push(b"h3".to_vec());
119 }
120 let tls = Arc::new(tls);
121 let quic_tls = quinn::crypto::rustls::QuicClientConfig::try_from(tls.clone())
122 .expect("building QUIC client TLS config");
123 Self {
124 client_config: quinn::ClientConfig::new(Arc::new(quic_tls)),
125 base_tls: Some(tls),
126 }
127 }
128
129 /// Build from a pre-built [`quinn::ClientConfig`].
130 ///
131 /// Use this when you need full control over transport parameters or TLS. The caller is
132 /// responsible for including `h3` in ALPN protocols. Per-connection ALPN override (used by
133 /// DNS-over-QUIC) is unavailable on configs built this way — there is no rustls config to
134 /// derive an alternate-ALPN config from.
135 pub fn from_quinn_client_config(config: quinn::ClientConfig) -> Self {
136 Self {
137 client_config: config,
138 base_tls: None,
139 }
140 }
141
142 /// Override the quinn [`TransportConfig`](quinn::TransportConfig) governing flow-control
143 /// windows, congestion control, GSO, and related transport parameters.
144 ///
145 /// Composes with any of the `from_*` constructors — construct with TLS credentials, then call
146 /// this to replace quinn's default transport configuration. The mirror of
147 /// [`QuicConfig::with_transport_config`](crate::QuicConfig::with_transport_config) on the
148 /// client side.
149 #[must_use]
150 pub fn with_transport_config(mut self, transport: Arc<quinn::TransportConfig>) -> Self {
151 self.client_config.transport_config(transport);
152 self
153 }
154}
155
156impl<C> QuicClientConfig<C> for ClientQuicConfig
157where
158 C: Connector,
159 C::Runtime: Unpin,
160 C::Udp: SocketTransport,
161{
162 type Endpoint = QuinnEndpoint;
163
164 fn bind(&self, addr: SocketAddr, runtime: &C::Runtime) -> io::Result<Self::Endpoint> {
165 let socket = std::net::UdpSocket::bind(addr)?;
166 let quinn_runtime = TrilliumRuntime::<C::Runtime, C::Udp>::new(runtime.clone());
167 let mut endpoint = quinn::Endpoint::new(
168 quinn::EndpointConfig::default(),
169 None, // client-only, no server config
170 socket,
171 quinn_runtime,
172 )?;
173 endpoint.set_default_client_config(self.client_config.clone());
174 Ok(QuinnEndpoint::new_client(endpoint, self.base_tls.clone()))
175 }
176}