Skip to main content

trillium_quinn/
config.rs

1use crate::{
2    connection::QuinnConnection,
3    runtime::{SocketTransport, TrilliumRuntime},
4};
5use rustls::{
6    pki_types::{CertificateDer, PrivateKeyDer, pem::PemObject},
7    server::ResolvesServerCert,
8};
9use std::{
10    borrow::Cow,
11    collections::HashMap,
12    io,
13    net::SocketAddr,
14    sync::{Arc, Mutex},
15};
16use trillium_server_common::{Info, QuicConfig as QuicConfigTrait, QuicEndpoint, Server};
17
18/// User-facing QUIC configuration backed by quinn.
19///
20/// Constructed with TLS credentials and passed to
21/// [`Config::with_quic`](trillium_server_common::Config::with_quic).
22/// The runtime and UDP transport types are inferred from the server.
23///
24/// ```rust,ignore
25/// trillium_tokio::config()
26///     .with_quic(trillium_quinn::QuicConfig::from_single_cert(&cert_pem, &key_pem))
27///     .run(handler);
28/// ```
29pub struct QuicConfig(quinn::ServerConfig);
30
31impl QuicConfig {
32    /// Build a `QuicConfig` from a single PEM-encoded certificate chain and private key.
33    ///
34    /// Automatically configures ALPN for HTTP/3 (`h3`). For a custom TLS setup, use
35    /// [`from_rustls_server_config`](Self::from_rustls_server_config).
36    pub fn from_single_cert(cert_pem: &[u8], key_pem: &[u8]) -> Self {
37        let certs: Vec<_> = CertificateDer::pem_slice_iter(cert_pem)
38            .collect::<Result<_, _>>()
39            .expect("parsing certificate PEM");
40
41        let key = PrivateKeyDer::from_pem_slice(key_pem).expect("parsing private key PEM");
42
43        let mut tls_config =
44            rustls::ServerConfig::builder_with_provider(crate::crypto_provider::crypto_provider())
45                .with_safe_default_protocol_versions()
46                .expect("building TLS config with protocol versions")
47                .with_no_client_auth()
48                .with_single_cert(certs, key)
49                .expect("building TLS config");
50
51        tls_config.alpn_protocols = vec![b"h3".to_vec()];
52
53        let quic_tls = quinn::crypto::rustls::QuicServerConfig::try_from(Arc::new(tls_config))
54            .expect("building QUIC TLS config");
55
56        Self(quinn::ServerConfig::with_crypto(Arc::new(quic_tls)))
57    }
58
59    /// Construct from a pre-built [`rustls::ServerConfig`].
60    ///
61    /// Use this when you need a custom TLS setup (client authentication, custom crypto
62    /// provider, etc.). HTTP/3 ALPN (`h3`) is added automatically if not already present.
63    pub fn from_rustls_server_config(tls_config: rustls::ServerConfig) -> Self {
64        let mut tls_config = tls_config;
65        if !tls_config.alpn_protocols.contains(&b"h3".to_vec()) {
66            tls_config.alpn_protocols.push(b"h3".to_vec());
67        }
68        let quic_tls = quinn::crypto::rustls::QuicServerConfig::try_from(Arc::new(tls_config))
69            .expect("building QUIC TLS config");
70        Self(quinn::ServerConfig::with_crypto(Arc::new(quic_tls)))
71    }
72
73    /// Construct from a pre-built [`quinn::ServerConfig`].
74    ///
75    /// Use this when you also need to customize quinn transport parameters. The caller is
76    /// responsible for configuring ALPN protocols (must include `h3` to support HTTP/3).
77    /// For custom TLS only, prefer [`from_rustls_server_config`](Self::from_rustls_server_config).
78    pub fn from_quinn_server_config(config: quinn::ServerConfig) -> Self {
79        Self(config)
80    }
81
82    /// Override the quinn [`TransportConfig`](quinn::TransportConfig) governing flow-control
83    /// windows, send fairness, congestion control, GSO, and related transport parameters.
84    ///
85    /// Composes with any of the `from_*` constructors — construct with TLS credentials, then call
86    /// this to replace quinn's default transport configuration.
87    #[must_use]
88    pub fn with_transport_config(mut self, transport: Arc<quinn::TransportConfig>) -> Self {
89        self.0.transport_config(transport);
90        self
91    }
92
93    /// Build a `QuicConfig` from a [`rustls::server::ResolvesServerCert`] cert resolver.
94    ///
95    /// Use this to bring your own dynamic certificate source — for example, an ACME integration
96    /// that rotates certificates over time. The resolver is consulted on every new connection,
97    /// so renewals take effect immediately without rebuilding the QUIC server config.
98    ///
99    /// If the resolver returns `None` for a given `ClientHello` (e.g. before the first
100    /// certificate has been obtained), the TLS handshake fails and the connection is rejected.
101    /// This makes it safe to bind the endpoint before any certificate is available.
102    ///
103    /// Automatically configures ALPN for HTTP/3 (`h3`).
104    pub fn from_cert_resolver(resolver: Arc<dyn ResolvesServerCert>) -> Self {
105        let tls_config =
106            rustls::ServerConfig::builder_with_provider(crate::crypto_provider::crypto_provider())
107                .with_safe_default_protocol_versions()
108                .expect("building TLS config with protocol versions")
109                .with_no_client_auth()
110                .with_cert_resolver(resolver);
111        Self::from_rustls_server_config(tls_config)
112    }
113}
114
115impl<S> QuicConfigTrait<S> for QuicConfig
116where
117    S: Server,
118    S::Runtime: Unpin,
119    S::UdpTransport: SocketTransport,
120{
121    type Endpoint = QuinnEndpoint;
122
123    fn bind(
124        self,
125        addr: SocketAddr,
126        runtime: S::Runtime,
127        info: &mut Info,
128    ) -> Option<io::Result<Self::Endpoint>> {
129        let socket = match std::net::UdpSocket::bind(addr) {
130            Ok(s) => s,
131            Err(e) => return Some(Err(e)),
132        };
133        Some(<Self as QuicConfigTrait<S>>::bind_with_socket(
134            self, socket, runtime, info,
135        ))
136    }
137
138    fn bind_with_socket(
139        self,
140        socket: std::net::UdpSocket,
141        runtime: S::Runtime,
142        _info: &mut Info,
143    ) -> io::Result<Self::Endpoint> {
144        let quinn_runtime = TrilliumRuntime::<S::Runtime, S::UdpTransport>::new(runtime);
145        quinn::Endpoint::new(
146            quinn::EndpointConfig::default(),
147            Some(self.0),
148            socket,
149            quinn_runtime,
150        )
151        .map(QuinnEndpoint::new)
152    }
153}
154
155/// A bound quinn QUIC endpoint that accepts and initiates connections.
156pub struct QuinnEndpoint {
157    endpoint: quinn::Endpoint,
158    /// The rustls config the per-connection-ALPN configs are derived from, when this endpoint was
159    /// bound from a [`ClientQuicConfig`](crate::ClientQuicConfig) built from a rustls config.
160    /// `None` for server-bound endpoints and client configs built from a raw
161    /// `quinn::ClientConfig`.
162    base_tls: Option<Arc<rustls::ClientConfig>>,
163    /// Per-ALPN `quinn::ClientConfig`s derived from `base_tls`, keyed by the ALPN protocol list.
164    /// The set is small and closed (`h3`, `doq`), so caching avoids rebuilding the crypto config
165    /// on every connection.
166    alpn_configs: Mutex<HashMap<Vec<Vec<u8>>, quinn::ClientConfig>>,
167}
168
169impl QuinnEndpoint {
170    /// Wrap a quinn endpoint with no rustls config retained (server-bound, or a client built from a
171    /// pre-assembled `quinn::ClientConfig`).
172    pub(crate) fn new(endpoint: quinn::Endpoint) -> Self {
173        Self {
174            endpoint,
175            base_tls: None,
176            alpn_configs: Mutex::new(HashMap::new()),
177        }
178    }
179
180    /// Wrap a client endpoint, retaining `base_tls` so per-connection ALPN configs can be derived.
181    pub(crate) fn new_client(
182        endpoint: quinn::Endpoint,
183        base_tls: Option<Arc<rustls::ClientConfig>>,
184    ) -> Self {
185        Self {
186            endpoint,
187            base_tls,
188            alpn_configs: Mutex::new(HashMap::new()),
189        }
190    }
191
192    /// Build (and cache) a `quinn::ClientConfig` advertising exactly `alpn`, derived from the
193    /// retained rustls config. Returns `None` when no rustls config was retained.
194    fn client_config_for_alpn(
195        &self,
196        alpn: &[Cow<'static, [u8]>],
197    ) -> io::Result<Option<quinn::ClientConfig>> {
198        let Some(base) = &self.base_tls else {
199            return Ok(None);
200        };
201        let key: Vec<Vec<u8>> = alpn.iter().map(|a| a.to_vec()).collect();
202
203        let mut cache = self.alpn_configs.lock().unwrap();
204        if let Some(config) = cache.get(&key) {
205            return Ok(Some(config.clone()));
206        }
207
208        let mut tls = (**base).clone();
209        tls.alpn_protocols = key.clone();
210        let quic_tls = quinn::crypto::rustls::QuicClientConfig::try_from(Arc::new(tls))
211            .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
212        let config = quinn::ClientConfig::new(Arc::new(quic_tls));
213        cache.insert(key, config.clone());
214        Ok(Some(config))
215    }
216}
217
218impl QuicEndpoint for QuinnEndpoint {
219    type Connection = QuinnConnection;
220
221    async fn accept(&self) -> Option<Self::Connection> {
222        loop {
223            let incoming = self.endpoint.accept().await?;
224            match incoming.await {
225                Ok(connection) => return Some(QuinnConnection::new(connection)),
226                Err(e) => log::error!("QUIC accept failed: {e}"),
227            }
228        }
229    }
230
231    async fn connect(&self, addr: SocketAddr, server_name: &str) -> io::Result<Self::Connection> {
232        let connection = self
233            .endpoint
234            .connect(addr, server_name)
235            .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?
236            .await
237            .map_err(|e| io::Error::new(io::ErrorKind::ConnectionRefused, e))?;
238        Ok(QuinnConnection::new(connection))
239    }
240
241    async fn connect_with_alpn(
242        &self,
243        addr: SocketAddr,
244        server_name: &str,
245        alpn: &[Cow<'static, [u8]>],
246    ) -> io::Result<Self::Connection> {
247        // Empty ALPN, or no retained rustls config to rebuild from, falls back to the endpoint's
248        // default client config.
249        let Some(config) = (!alpn.is_empty())
250            .then(|| self.client_config_for_alpn(alpn))
251            .transpose()?
252            .flatten()
253        else {
254            return self.connect(addr, server_name).await;
255        };
256
257        let connection = self
258            .endpoint
259            .connect_with(config, addr, server_name)
260            .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?
261            .await
262            .map_err(|e| io::Error::new(io::ErrorKind::ConnectionRefused, e))?;
263        Ok(QuinnConnection::new(connection))
264    }
265
266    fn local_addr(&self) -> io::Result<SocketAddr> {
267        self.endpoint.local_addr()
268    }
269}