Skip to main content

axum_server/tls_rustls/
mod.rs

1//! Tls implementation using [`rustls`].
2//!
3//! # Example
4//!
5//! ```rust,no_run
6//! use axum::{routing::get, Router};
7//! use axum_server::tls_rustls::RustlsConfig;
8//! use std::net::SocketAddr;
9//!
10//! #[tokio::main]
11//! async fn main() {
12//!     let app = Router::new().route("/", get(|| async { "Hello, world!" }));
13//!
14//!     let config = RustlsConfig::from_pem_file(
15//!         "examples/self-signed-certs/cert.pem",
16//!         "examples/self-signed-certs/key.pem",
17//!     )
18//!     .await
19//!     .unwrap();
20//!
21//!     let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
22//!     println!("listening on {}", addr);
23//!     axum_server::bind_rustls(addr, config)
24//!         .serve(app.into_make_service())
25//!         .await
26//!         .unwrap();
27//! }
28//! ```
29
30use self::future::RustlsAcceptorFuture;
31use crate::{
32    accept::{Accept, DefaultAcceptor},
33    server::{io_other, Server},
34    tls::TlsService,
35    Address,
36};
37use arc_swap::ArcSwap;
38use rustls::server::ResolvesServerCertUsingSni;
39use rustls::sign::CertifiedKey;
40use rustls::ServerConfig;
41use rustls_pki_types::pem::PemObject;
42use rustls_pki_types::{CertificateDer, PrivateKeyDer};
43
44#[cfg(feature = "tls-rustls-encrypted-keys")]
45use pkcs8::der::{Decode, Document};
46#[cfg(feature = "tls-rustls-encrypted-keys")]
47use rustls_pki_types::PrivatePkcs8KeyDer;
48use std::time::Duration;
49use std::{fmt, io, net::SocketAddr, path::Path, sync::Arc};
50use tokio::{
51    io::{AsyncRead, AsyncWrite},
52    task::spawn_blocking,
53};
54use tokio_rustls::server::TlsStream;
55
56pub mod future;
57
58/// Create a tls server that will bind to provided address.
59#[cfg_attr(docsrs, doc(cfg(feature = "tls-rustls")))]
60pub fn bind_rustls<A: Address>(addr: A, config: RustlsConfig) -> Server<A, RustlsAcceptor> {
61    let acceptor = RustlsAcceptor::new(config);
62
63    Server::bind(addr).acceptor(acceptor)
64}
65
66/// Create a tls server from existing `std::net::TcpListener`.
67#[cfg_attr(docsrs, doc(cfg(feature = "tls-rustls")))]
68pub fn from_tcp_rustls(
69    listener: std::net::TcpListener,
70    config: RustlsConfig,
71) -> io::Result<Server<SocketAddr, RustlsAcceptor>> {
72    let acceptor = RustlsAcceptor::new(config);
73
74    Ok(crate::from_tcp(listener)?.acceptor(acceptor))
75}
76
77/// Create a tls server from existing `std::os::unix::net::UnixListener`.
78#[cfg_attr(docsrs, doc(cfg(feature = "tls-rustls")))]
79#[cfg(unix)]
80pub fn from_unix_rustls(
81    listener: std::os::unix::net::UnixListener,
82    config: RustlsConfig,
83) -> io::Result<Server<std::os::unix::net::SocketAddr, RustlsAcceptor>> {
84    let acceptor = RustlsAcceptor::new(config);
85
86    Ok(crate::from_unix(listener)?.acceptor(acceptor))
87}
88
89/// Tls acceptor using rustls.
90#[derive(Clone)]
91pub struct RustlsAcceptor<A = DefaultAcceptor> {
92    inner: A,
93    config: RustlsConfig,
94    handshake_timeout: Duration,
95}
96
97impl RustlsAcceptor {
98    /// Create a new rustls acceptor.
99    pub fn new(config: RustlsConfig) -> Self {
100        let inner = DefaultAcceptor::new();
101
102        #[cfg(not(test))]
103        let handshake_timeout = Duration::from_secs(10);
104
105        // Don't force tests to wait too long.
106        #[cfg(test)]
107        let handshake_timeout = Duration::from_secs(1);
108
109        Self {
110            inner,
111            config,
112            handshake_timeout,
113        }
114    }
115
116    /// Override the default TLS handshake timeout of 10 seconds, except during testing.
117    pub fn handshake_timeout(mut self, val: Duration) -> Self {
118        self.handshake_timeout = val;
119        self
120    }
121}
122
123impl<A> RustlsAcceptor<A> {
124    /// Overwrite inner acceptor.
125    pub fn acceptor<Acceptor>(self, acceptor: Acceptor) -> RustlsAcceptor<Acceptor> {
126        RustlsAcceptor {
127            inner: acceptor,
128            config: self.config,
129            handshake_timeout: self.handshake_timeout,
130        }
131    }
132}
133
134impl<A, I, S> Accept<I, S> for RustlsAcceptor<A>
135where
136    A: Accept<I, S>,
137    A::Stream: AsyncRead + AsyncWrite + Unpin,
138{
139    type Stream = TlsStream<A::Stream>;
140    type Service = TlsService<A::Service>;
141    type Future = RustlsAcceptorFuture<A::Future, A::Stream, A::Service>;
142
143    fn accept(&self, stream: I, service: S) -> Self::Future {
144        let inner_future = self.inner.accept(stream, service);
145        let config = self.config.clone();
146
147        RustlsAcceptorFuture::new(inner_future, config, self.handshake_timeout)
148    }
149}
150
151impl<A> fmt::Debug for RustlsAcceptor<A> {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        f.debug_struct("RustlsAcceptor").finish()
154    }
155}
156
157/// Rustls configuration.
158#[derive(Clone)]
159pub struct RustlsConfig {
160    inner: Arc<ArcSwap<ServerConfig>>,
161}
162
163impl RustlsConfig {
164    /// Create config from `Arc<`[`ServerConfig`]`>`.
165    ///
166    /// NOTE: You need to set ALPN protocols (like `http/1.1` or `h2`) manually.
167    pub fn from_config(config: Arc<ServerConfig>) -> Self {
168        let inner = Arc::new(ArcSwap::new(config));
169
170        Self { inner }
171    }
172
173    /// Create config from DER-encoded data.
174    ///
175    /// The certificate must be DER-encoded X.509.
176    ///
177    /// The private key must be DER-encoded ASN.1 in either PKCS#8 or PKCS#1 format.
178    pub async fn from_der(cert: Vec<Vec<u8>>, key: Vec<u8>) -> io::Result<Self> {
179        let server_config = spawn_blocking(|| config_from_der(cert, key))
180            .await
181            .unwrap()?;
182        let inner = Arc::new(ArcSwap::from_pointee(server_config));
183
184        Ok(Self { inner })
185    }
186
187    /// Create config from PEM formatted data.
188    ///
189    /// Certificate and private key must be in PEM format.
190    pub async fn from_pem(cert: Vec<u8>, key: Vec<u8>) -> io::Result<Self> {
191        let server_config = spawn_blocking(|| config_from_pem(cert, key))
192            .await
193            .unwrap()?;
194        let inner = Arc::new(ArcSwap::from_pointee(server_config));
195
196        Ok(Self { inner })
197    }
198
199    /// Create config from PEM formatted files.
200    ///
201    /// Contents of certificate file and private key file must be in PEM format.
202    pub async fn from_pem_file(cert: impl AsRef<Path>, key: impl AsRef<Path>) -> io::Result<Self> {
203        let server_config = config_from_pem_file(cert, key).await?;
204        let inner = Arc::new(ArcSwap::from_pointee(server_config));
205
206        Ok(Self { inner })
207    }
208
209    /// Create config from PEM formatted files, selecting the certificate by
210    /// the server name sent by the client using SNI.
211    ///
212    /// Each item is `(server_name, certificate_path, private_key_path)`. The
213    /// server name is matched against the client's SNI value, and each
214    /// certificate must be valid for the name it is registered under.
215    ///
216    /// The certificate and private key files must be in PEM format.
217    pub async fn from_sni_pem_files<I, S, P, K>(files: I) -> io::Result<Self>
218    where
219        I: IntoIterator<Item = (S, P, K)>,
220        S: AsRef<str>,
221        P: AsRef<Path>,
222        K: AsRef<Path>,
223    {
224        let provider = crypto_provider();
225
226        let mut resolver = ResolvesServerCertUsingSni::new();
227
228        for (name, cert_path, key_path) in files {
229            let cert = fs_err::tokio::read(cert_path.as_ref()).await?;
230            let key = fs_err::tokio::read(key_path.as_ref()).await?;
231
232            let cert = certificates_from_pem(&cert)?;
233            let key = private_key_from_pem(&key)?;
234            let signing_key = provider
235                .key_provider
236                .load_private_key(key)
237                .map_err(io_other)?;
238
239            resolver
240                .add(name.as_ref(), CertifiedKey::new(cert, signing_key))
241                .map_err(io_other)?;
242        }
243
244        let mut config = ServerConfig::builder()
245            .with_no_client_auth()
246            .with_cert_resolver(Arc::new(resolver));
247
248        set_alpn(&mut config);
249
250        let inner = Arc::new(ArcSwap::from_pointee(config));
251
252        Ok(Self { inner })
253    }
254
255    /// Get  inner `Arc<`[`ServerConfig`]`>`.
256    pub fn get_inner(&self) -> Arc<ServerConfig> {
257        self.inner.load_full()
258    }
259
260    /// Reload config from `Arc<`[`ServerConfig`]`>`.
261    pub fn reload_from_config(&self, config: Arc<ServerConfig>) {
262        self.inner.store(config);
263    }
264
265    /// Reload config from DER-encoded data.
266    ///
267    /// The certificate must be DER-encoded X.509.
268    ///
269    /// The private key must be DER-encoded ASN.1 in either PKCS#8 or PKCS#1 format.
270    pub async fn reload_from_der(&self, cert: Vec<Vec<u8>>, key: Vec<u8>) -> io::Result<()> {
271        let server_config = spawn_blocking(|| config_from_der(cert, key))
272            .await
273            .unwrap()?;
274        let inner = Arc::new(server_config);
275
276        self.inner.store(inner);
277
278        Ok(())
279    }
280
281    /// This helper will establish a TLS server based on strong cipher suites
282    /// from a PEM-formatted certificate chain and key.
283    pub async fn from_pem_chain_file(
284        chain: impl AsRef<Path>,
285        key: impl AsRef<Path>,
286    ) -> io::Result<Self> {
287        let server_config = config_from_pem_chain_file(chain, key).await?;
288        let inner = Arc::new(ArcSwap::from_pointee(server_config));
289
290        Ok(Self { inner })
291    }
292
293    /// Reload config from PEM formatted data.
294    ///
295    /// Certificate and private key must be in PEM format.
296    pub async fn reload_from_pem(&self, cert: Vec<u8>, key: Vec<u8>) -> io::Result<()> {
297        let server_config = spawn_blocking(|| config_from_pem(cert, key))
298            .await
299            .unwrap()?;
300        let inner = Arc::new(server_config);
301
302        self.inner.store(inner);
303
304        Ok(())
305    }
306
307    /// Reload config from PEM formatted files.
308    ///
309    /// Contents of certificate file and private key file must be in PEM format.
310    pub async fn reload_from_pem_file(
311        &self,
312        cert: impl AsRef<Path>,
313        key: impl AsRef<Path>,
314    ) -> io::Result<()> {
315        let server_config = config_from_pem_file(cert, key).await?;
316        let inner = Arc::new(server_config);
317
318        self.inner.store(inner);
319
320        Ok(())
321    }
322}
323
324#[cfg(feature = "tls-rustls-encrypted-keys")]
325impl RustlsConfig {
326    /// Create config from a PEM formatted certificate and an encrypted PKCS#8
327    /// private key.
328    ///
329    /// The key must be a PKCS#8 `ENCRYPTED PRIVATE KEY` section, as produced by
330    /// `openssl pkcs8 -topk8`.
331    pub async fn from_pem_with_password(
332        cert: Vec<u8>,
333        key: Vec<u8>,
334        password: impl AsRef<[u8]>,
335    ) -> io::Result<Self> {
336        let password = password.as_ref().to_vec();
337        let server_config =
338            spawn_blocking(move || config_from_pem_with_password(cert, key, password))
339                .await
340                .unwrap()?;
341        let inner = Arc::new(ArcSwap::from_pointee(server_config));
342
343        Ok(Self { inner })
344    }
345
346    /// Create config from PEM formatted files, where the private key is an
347    /// encrypted PKCS#8 key.
348    pub async fn from_pem_file_with_password(
349        cert: impl AsRef<Path>,
350        key: impl AsRef<Path>,
351        password: impl AsRef<[u8]>,
352    ) -> io::Result<Self> {
353        let cert = fs_err::tokio::read(cert.as_ref()).await?;
354        let key = fs_err::tokio::read(key.as_ref()).await?;
355
356        Self::from_pem_with_password(cert, key, password).await
357    }
358
359    /// Reload config from a PEM formatted certificate and an encrypted PKCS#8
360    /// private key.
361    pub async fn reload_from_pem_with_password(
362        &self,
363        cert: Vec<u8>,
364        key: Vec<u8>,
365        password: impl AsRef<[u8]>,
366    ) -> io::Result<()> {
367        let password = password.as_ref().to_vec();
368        let server_config =
369            spawn_blocking(move || config_from_pem_with_password(cert, key, password))
370                .await
371                .unwrap()?;
372
373        self.inner.store(Arc::new(server_config));
374
375        Ok(())
376    }
377
378    /// Reload config from PEM formatted files, where the private key is an
379    /// encrypted PKCS#8 key.
380    pub async fn reload_from_pem_file_with_password(
381        &self,
382        cert: impl AsRef<Path>,
383        key: impl AsRef<Path>,
384        password: impl AsRef<[u8]>,
385    ) -> io::Result<()> {
386        let cert = fs_err::tokio::read(cert.as_ref()).await?;
387        let key = fs_err::tokio::read(key.as_ref()).await?;
388
389        self.reload_from_pem_with_password(cert, key, password)
390            .await
391    }
392}
393
394#[cfg(feature = "tls-rustls-encrypted-keys")]
395fn config_from_pem_with_password(
396    cert: Vec<u8>,
397    key: Vec<u8>,
398    password: Vec<u8>,
399) -> io::Result<ServerConfig> {
400    let cert = certificates_from_pem(&cert)?;
401    let pem = std::str::from_utf8(&key)
402        .map_err(|_| io_other("the private key file is not valid UTF-8"))?;
403    let (label, document) = Document::from_pem(pem).map_err(|_| io_other("failed to parse PEM"))?;
404
405    if label != "ENCRYPTED PRIVATE KEY" {
406        return Err(io_other(
407            "expected an encrypted PKCS#8 private key (ENCRYPTED PRIVATE KEY)",
408        ));
409    }
410
411    let encrypted = pkcs8::EncryptedPrivateKeyInfo::from_der(document.as_bytes())
412        .map_err(|_| io_other("failed to parse encrypted private key"))?;
413    let decrypted = encrypted
414        .decrypt(&password)
415        .map_err(|_| io_other("failed to decrypt private key; is the password correct?"))?;
416    let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(decrypted.as_bytes().to_vec()));
417
418    config_from_cert_and_key(cert, key)
419}
420
421impl fmt::Debug for RustlsConfig {
422    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
423        f.debug_struct("RustlsConfig").finish()
424    }
425}
426
427const ALPN_PROTOCOLS: [&[u8]; 2] = [b"h2", b"http/1.1"];
428
429pub(crate) fn set_alpn(config: &mut ServerConfig) {
430    config.alpn_protocols = ALPN_PROTOCOLS.iter().map(|proto| proto.to_vec()).collect();
431}
432
433fn crypto_provider() -> &'static Arc<rustls::crypto::CryptoProvider> {
434    if let Some(provider) = rustls::crypto::CryptoProvider::get_default() {
435        return provider;
436    }
437
438    // Building a config installs the provider selected by the enabled rustls
439    // crate features if no provider has been installed yet.
440    let _ = ServerConfig::builder();
441
442    rustls::crypto::CryptoProvider::get_default()
443        .expect("a default CryptoProvider is installed by ServerConfig::builder")
444}
445
446fn config_from_der(cert: Vec<Vec<u8>>, key: Vec<u8>) -> io::Result<ServerConfig> {
447    let cert = cert.into_iter().map(CertificateDer::from).collect();
448    let key = PrivateKeyDer::try_from(key).map_err(io_other)?;
449
450    config_from_cert_and_key(cert, key)
451}
452
453fn config_from_cert_and_key(
454    cert: Vec<CertificateDer<'static>>,
455    key: PrivateKeyDer<'static>,
456) -> io::Result<ServerConfig> {
457    let mut config = ServerConfig::builder()
458        .with_no_client_auth()
459        .with_single_cert(cert, key)
460        .map_err(io_other)?;
461
462    set_alpn(&mut config);
463
464    Ok(config)
465}
466
467fn certificates_from_pem(cert: &[u8]) -> io::Result<Vec<CertificateDer<'static>>> {
468    CertificateDer::pem_slice_iter(cert)
469        .collect::<Result<Vec<_>, _>>()
470        .map_err(|_| io_other("failed to parse certificate"))
471}
472
473fn private_key_from_pem(key: &[u8]) -> io::Result<PrivateKeyDer<'static>> {
474    let mut key_result: Result<PrivateKeyDer<'static>, io::Error> =
475        Err(io_other("The private key file contained no keys"));
476
477    // Check the entire PEM file for the key in case it is not first section
478    for item in rustls_pki_types::pem::PemObject::pem_slice_iter(key) {
479        let key: Result<PrivateKeyDer<'static>, io::Error> =
480            item.map_err(|_| io_other("failed to parse PEM"));
481
482        match key_result {
483            // if we already got a key, then...
484            Ok(_) => {
485                // ...if we get a key now, we know that there are multiple keys and that's not allowed
486                if key.is_ok() {
487                    return Err(io_other(
488                        "The private key file contains multiple keys (it must only contain one)",
489                    ));
490                }
491            }
492            // but if already have an error, just overwrite it with whatever we got this time. If
493            // it's a good key, that's cool. If it's an error, then we're just ignoring the old
494            // error in favor of this new one
495            Err(_) => key_result = key,
496        }
497    }
498
499    key_result
500}
501
502fn config_from_pem(cert: Vec<u8>, key: Vec<u8>) -> io::Result<ServerConfig> {
503    let cert = certificates_from_pem(&cert)?;
504    let key = private_key_from_pem(&key)?;
505
506    config_from_cert_and_key(cert, key)
507}
508
509async fn config_from_pem_file(
510    cert: impl AsRef<Path>,
511    key: impl AsRef<Path>,
512) -> io::Result<ServerConfig> {
513    let cert = fs_err::tokio::read(cert.as_ref()).await?;
514    let key = fs_err::tokio::read(key.as_ref()).await?;
515
516    config_from_pem(cert, key)
517}
518
519async fn config_from_pem_chain_file(
520    cert: impl AsRef<Path>,
521    chain: impl AsRef<Path>,
522) -> io::Result<ServerConfig> {
523    let cert = fs_err::tokio::read(cert.as_ref()).await?;
524    let cert = certificates_from_pem(&cert)?;
525    let key = fs_err::tokio::read(chain.as_ref()).await?;
526    let key =
527        PrivateKeyDer::from_pem_slice(&key).map_err(|_| io_other("could not parse pem file"))?;
528
529    config_from_cert_and_key(cert, key)
530}
531
532#[cfg(test)]
533mod tests {
534    use crate::accept::{LocalAddr, LocalAddrAcceptor};
535    use crate::handle::Handle;
536    use crate::server::Server;
537    use crate::tls::TlsInfo;
538    use crate::tls_rustls::{self, RustlsAcceptor, RustlsConfig};
539    use axum::body::Body;
540    use axum::routing::get;
541    use axum::Extension;
542    use axum::Router;
543    use bytes::Bytes;
544    use http::{response, Request};
545    use http_body_util::BodyExt;
546    use hyper::client::conn::http1::{handshake, SendRequest};
547    use hyper_util::rt::TokioIo;
548    use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
549    use rustls::{ClientConfig, DigitallySignedStruct, Error, SignatureScheme};
550    use rustls_pki_types::{CertificateDer, ServerName, UnixTime};
551    use std::fmt::Debug;
552    use std::{convert::TryFrom, io, net::SocketAddr, sync::Arc, time::Duration};
553    use tokio::time::{sleep, timeout};
554    use tokio::{net::TcpStream, task::JoinHandle};
555    use tokio_rustls::TlsConnector;
556
557    #[tokio::test]
558    async fn start_and_request() {
559        let (_handle, _server_task, addr) = start_server().await;
560
561        let (mut client, _conn) = connect(addr).await;
562
563        let (_parts, body) = send_empty_request(&mut client).await;
564
565        assert_eq!(body.as_ref(), b"Hello, world!");
566    }
567
568    #[tokio::test]
569    async fn tls_timeout() {
570        let (handle, _server_task, addr) = start_server().await;
571        assert_eq!(handle.connection_count(), 0);
572
573        // We intentionally avoid driving a TLS handshake to completion.
574        let _stream = TcpStream::connect(addr).await.unwrap();
575
576        sleep(Duration::from_millis(500)).await;
577        assert_eq!(handle.connection_count(), 1);
578
579        tokio::time::sleep(Duration::from_millis(1000)).await;
580        // Timeout defaults to 1s during testing, and we have waited 1.5 seconds.
581        assert_eq!(handle.connection_count(), 0);
582    }
583
584    #[tokio::test]
585    async fn from_pem_chain_file_sets_alpn() {
586        let config = RustlsConfig::from_pem_chain_file(
587            "examples/self-signed-certs/cert.pem",
588            "examples/self-signed-certs/key.pem",
589        )
590        .await
591        .unwrap();
592
593        assert_eq!(
594            config.get_inner().alpn_protocols,
595            vec![b"h2".to_vec(), b"http/1.1".to_vec()]
596        );
597    }
598
599    #[tokio::test]
600    async fn sni_pem_files_select_certificate_by_server_name() {
601        let config = RustlsConfig::from_sni_pem_files([
602            (
603                "localhost",
604                "examples/self-signed-certs/sni/localhost-cert.pem",
605                "examples/self-signed-certs/sni/localhost-key.pem",
606            ),
607            (
608                "other.test",
609                "examples/self-signed-certs/sni/other-test-cert.pem",
610                "examples/self-signed-certs/sni/other-test-key.pem",
611            ),
612        ])
613        .await
614        .unwrap();
615
616        let (handle, server_task, addr) = start_server_with_config(config).await;
617
618        let cert_a = get_first_cert_for(addr, "localhost").await;
619        let cert_b = get_first_cert_for(addr, "other.test").await;
620
621        assert_ne!(cert_a, cert_b);
622
623        handle.shutdown();
624        let _ = timeout(Duration::from_secs(1), server_task).await;
625    }
626
627    #[cfg(feature = "tls-rustls-encrypted-keys")]
628    #[tokio::test]
629    async fn encrypted_key_starts_and_serves() {
630        let config = RustlsConfig::from_pem_file_with_password(
631            "examples/self-signed-certs/cert.pem",
632            "examples/self-signed-certs/encrypted-key.pem",
633            b"axum-server",
634        )
635        .await
636        .unwrap();
637
638        let (handle, server_task, addr) = start_server_with_config(config).await;
639
640        let (mut client, _conn) = connect(addr).await;
641        let (_parts, body) = send_empty_request(&mut client).await;
642
643        assert_eq!(body.as_ref(), b"Hello, world!");
644
645        handle.shutdown();
646        let _ = timeout(Duration::from_secs(1), server_task).await;
647    }
648
649    #[cfg(feature = "tls-rustls-encrypted-keys")]
650    #[tokio::test]
651    async fn wrong_password_is_rejected() {
652        let error = RustlsConfig::from_pem_file_with_password(
653            "examples/self-signed-certs/cert.pem",
654            "examples/self-signed-certs/encrypted-key.pem",
655            b"wrong-password",
656        )
657        .await
658        .unwrap_err();
659
660        assert!(error.to_string().contains("decrypt"), "{error}");
661    }
662
663    #[cfg(feature = "tls-rustls-encrypted-keys")]
664    #[tokio::test]
665    async fn reload_from_pem_file_with_password_works() {
666        let config = RustlsConfig::from_pem_file(
667            "examples/self-signed-certs/cert.pem",
668            "examples/self-signed-certs/key.pem",
669        )
670        .await
671        .unwrap();
672
673        config
674            .reload_from_pem_file_with_password(
675                "examples/self-signed-certs/cert.pem",
676                "examples/self-signed-certs/encrypted-key.pem",
677                b"axum-server",
678            )
679            .await
680            .unwrap();
681    }
682
683    #[tokio::test]
684    async fn handshake_is_cancelled_on_shutdown() {
685        let handle = Handle::new();
686        let server_handle = handle.clone();
687
688        let config = RustlsConfig::from_pem_file(
689            "examples/self-signed-certs/cert.pem",
690            "examples/self-signed-certs/key.pem",
691        )
692        .await
693        .unwrap();
694
695        // Make sure the test fails (via the timeout) rather than hanging if the
696        // handshake is not cancelled.
697        let acceptor = RustlsAcceptor::new(config).handshake_timeout(Duration::from_secs(30));
698        let addr = SocketAddr::from(([127, 0, 0, 1], 0));
699
700        let server_task = tokio::spawn(async move {
701            Server::bind(addr)
702                .acceptor(acceptor)
703                .handle(server_handle)
704                .serve(
705                    Router::new()
706                        .route("/", get(|| async { "Hello, world!" }))
707                        .into_make_service(),
708                )
709                .await
710        });
711
712        let addr = handle.listening().await.unwrap();
713
714        // Open a connection but never start the TLS handshake.
715        let _stream = TcpStream::connect(addr).await.unwrap();
716
717        sleep(Duration::from_millis(200)).await;
718        assert_eq!(handle.connection_count(), 1);
719
720        handle.shutdown();
721
722        let result = tokio::time::timeout(Duration::from_secs(2), server_task)
723            .await
724            .expect("server did not shut down")
725            .unwrap();
726        assert!(result.is_ok());
727
728        // The pending handshake task must be cancelled instead of running
729        // until the (30 second) handshake timeout.
730        sleep(Duration::from_millis(300)).await;
731        assert_eq!(handle.connection_count(), 0);
732    }
733
734    #[tokio::test]
735    async fn tls_info_is_available_to_handlers() {
736        let handle = Handle::new();
737        let server_handle = handle.clone();
738
739        let config = RustlsConfig::from_pem_file(
740            "examples/self-signed-certs/cert.pem",
741            "examples/self-signed-certs/key.pem",
742        )
743        .await
744        .unwrap();
745
746        let addr = SocketAddr::from(([127, 0, 0, 1], 0));
747
748        let server_task = tokio::spawn(async move {
749            let app = Router::new().route(
750                "/",
751                get(
752                    |Extension(info): Extension<Arc<TlsInfo>>,
753                     Extension(local): Extension<LocalAddr>| async move {
754                        format!(
755                            "{}|{}|{}|{}",
756                            info.server_name.as_deref().unwrap_or(""),
757                            info.alpn_protocol.is_some(),
758                            info.peer_certificates.len(),
759                            local.0,
760                        )
761                    },
762                ),
763            );
764
765            let acceptor = RustlsAcceptor::new(config).acceptor(LocalAddrAcceptor::new());
766
767            Server::bind(addr)
768                .acceptor(acceptor)
769                .handle(server_handle)
770                .serve(app.into_make_service())
771                .await
772        });
773
774        let addr = handle.listening().await.unwrap();
775        let (mut client, _conn) = connect(addr).await;
776        let (_parts, body) = send_empty_request(&mut client).await;
777
778        assert_eq!(
779            String::from_utf8(body.to_vec()).unwrap(),
780            format!("localhost|true|0|{addr}")
781        );
782
783        handle.shutdown();
784        let result = timeout(Duration::from_secs(1), server_task)
785            .await
786            .unwrap()
787            .unwrap();
788        assert!(result.is_ok());
789    }
790
791    #[tokio::test]
792    async fn test_reload() {
793        let handle = Handle::new();
794
795        let config = RustlsConfig::from_pem_file(
796            "examples/self-signed-certs/cert.pem",
797            "examples/self-signed-certs/key.pem",
798        )
799        .await
800        .unwrap();
801
802        let server_handle = handle.clone();
803        let rustls_config = config.clone();
804        tokio::spawn(async move {
805            let app = Router::new().route("/", get(|| async { "Hello, world!" }));
806
807            let addr = SocketAddr::from(([127, 0, 0, 1], 0));
808
809            tls_rustls::bind_rustls(addr, rustls_config)
810                .handle(server_handle)
811                .serve(app.into_make_service())
812                .await
813        });
814
815        let addr = handle.listening().await.unwrap();
816
817        let cert_a = get_first_cert(addr).await;
818        let mut cert_b = get_first_cert(addr).await;
819
820        assert_eq!(cert_a, cert_b);
821
822        config
823            .reload_from_pem_file(
824                "examples/self-signed-certs/reload/cert.pem",
825                "examples/self-signed-certs/reload/key.pem",
826            )
827            .await
828            .unwrap();
829
830        cert_b = get_first_cert(addr).await;
831
832        assert_ne!(cert_a, cert_b);
833
834        config
835            .reload_from_pem_file(
836                "examples/self-signed-certs/cert.pem",
837                "examples/self-signed-certs/key.pem",
838            )
839            .await
840            .unwrap();
841
842        cert_b = get_first_cert(addr).await;
843
844        assert_eq!(cert_a, cert_b);
845    }
846
847    async fn start_server() -> (Handle<SocketAddr>, JoinHandle<io::Result<()>>, SocketAddr) {
848        let config = RustlsConfig::from_pem_file(
849            "examples/self-signed-certs/cert.pem",
850            "examples/self-signed-certs/key.pem",
851        )
852        .await
853        .unwrap();
854
855        start_server_with_config(config).await
856    }
857
858    async fn start_server_with_config(
859        config: RustlsConfig,
860    ) -> (Handle<SocketAddr>, JoinHandle<io::Result<()>>, SocketAddr) {
861        let handle = Handle::new();
862
863        let server_handle = handle.clone();
864        let server_task = tokio::spawn(async move {
865            let app = Router::new().route("/", get(|| async { "Hello, world!" }));
866            let addr = SocketAddr::from(([127, 0, 0, 1], 0));
867
868            tls_rustls::bind_rustls(addr, config)
869                .handle(server_handle)
870                .serve(app.into_make_service())
871                .await
872        });
873
874        let addr = handle.listening().await.unwrap();
875
876        (handle, server_task, addr)
877    }
878
879    async fn get_first_cert(addr: SocketAddr) -> CertificateDer<'static> {
880        get_first_cert_for(addr, "localhost").await
881    }
882
883    async fn get_first_cert_for(addr: SocketAddr, name: &'static str) -> CertificateDer<'static> {
884        let stream = TcpStream::connect(addr).await.unwrap();
885        let tls_stream = tls_connector()
886            .connect(ServerName::try_from(name).unwrap(), stream)
887            .await
888            .unwrap();
889
890        let (_io, client_connection) = tls_stream.into_inner();
891
892        client_connection.peer_certificates().unwrap()[0].clone()
893    }
894
895    async fn connect(addr: SocketAddr) -> (SendRequest<Body>, JoinHandle<()>) {
896        let stream = TcpStream::connect(addr).await.unwrap();
897        let tls_stream = TokioIo::new(tls_connector().connect(dns_name(), stream).await.unwrap());
898
899        let (send_request, connection) = handshake(tls_stream).await.unwrap();
900
901        let task = tokio::spawn(async move {
902            let _ = connection.await;
903        });
904
905        (send_request, task)
906    }
907
908    async fn send_empty_request(client: &mut SendRequest<Body>) -> (response::Parts, Bytes) {
909        let (parts, body) = client
910            .send_request(Request::new(Body::empty()))
911            .await
912            .unwrap()
913            .into_parts();
914        let body = body.collect().await.unwrap().to_bytes();
915
916        (parts, body)
917    }
918
919    fn tls_connector() -> TlsConnector {
920        #[derive(Debug)]
921        struct NoVerify;
922
923        impl ServerCertVerifier for NoVerify {
924            fn verify_server_cert(
925                &self,
926                _end_entity: &CertificateDer,
927                _intermediates: &[CertificateDer],
928                _server_name: &ServerName,
929                _ocsp_response: &[u8],
930                _now: UnixTime,
931            ) -> Result<ServerCertVerified, rustls::Error> {
932                Ok(ServerCertVerified::assertion())
933            }
934
935            fn verify_tls12_signature(
936                &self,
937                _message: &[u8],
938                _cert: &CertificateDer<'_>,
939                _dss: &DigitallySignedStruct,
940            ) -> Result<HandshakeSignatureValid, Error> {
941                Ok(HandshakeSignatureValid::assertion())
942            }
943
944            fn verify_tls13_signature(
945                &self,
946                _message: &[u8],
947                _cert: &CertificateDer<'_>,
948                _dss: &DigitallySignedStruct,
949            ) -> Result<HandshakeSignatureValid, Error> {
950                Ok(HandshakeSignatureValid::assertion())
951            }
952
953            fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
954                vec![
955                    SignatureScheme::RSA_PKCS1_SHA1,
956                    SignatureScheme::RSA_PKCS1_SHA256,
957                    SignatureScheme::RSA_PKCS1_SHA384,
958                    SignatureScheme::RSA_PKCS1_SHA512,
959                    SignatureScheme::RSA_PSS_SHA256,
960                    SignatureScheme::RSA_PSS_SHA384,
961                    SignatureScheme::RSA_PSS_SHA512,
962                ]
963            }
964        }
965
966        let mut client_config = ClientConfig::builder()
967            .dangerous()
968            .with_custom_certificate_verifier(Arc::new(NoVerify))
969            .with_no_client_auth();
970
971        client_config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
972
973        TlsConnector::from(Arc::new(client_config))
974    }
975
976    fn dns_name() -> ServerName<'static> {
977        ServerName::try_from("localhost").unwrap()
978    }
979
980    #[tokio::test]
981    async fn from_pem_file_not_found() {
982        let err = RustlsConfig::from_pem_file(
983            "examples/self-signed-certs/missing.pem",
984            "examples/self-signed-certs/key.pem",
985        )
986        .await
987        .unwrap_err();
988        assert_eq!(err.kind(), io::ErrorKind::NotFound);
989        assert_eq!(
990            err.to_string(),
991            "failed to read from file `examples/self-signed-certs/missing.pem`: No such file or directory (os error 2)"
992        );
993
994        let err = RustlsConfig::from_pem_file(
995            "examples/self-signed-certs/cert.pem",
996            "examples/self-signed-certs/missing.pem",
997        )
998        .await
999        .unwrap_err();
1000        assert_eq!(err.kind(), io::ErrorKind::NotFound);
1001        assert_eq!(
1002            err.to_string(),
1003            "failed to read from file `examples/self-signed-certs/missing.pem`: No such file or directory (os error 2)"
1004        );
1005    }
1006
1007    #[tokio::test]
1008    async fn from_pem_file_chain_file_not_found() {
1009        let err = RustlsConfig::from_pem_chain_file(
1010            "examples/self-signed-certs/missing.pem",
1011            "examples/self-signed-certs/key.pem",
1012        )
1013        .await
1014        .unwrap_err();
1015        assert_eq!(err.kind(), io::ErrorKind::NotFound);
1016        assert_eq!(
1017            err.to_string(),
1018            "failed to read from file `examples/self-signed-certs/missing.pem`: No such file or directory (os error 2)"
1019        );
1020
1021        let err = RustlsConfig::from_pem_chain_file(
1022            "examples/self-signed-certs/cert.pem",
1023            "examples/self-signed-certs/missing.pem",
1024        )
1025        .await
1026        .unwrap_err();
1027        assert_eq!(err.kind(), io::ErrorKind::NotFound);
1028        assert_eq!(
1029            err.to_string(),
1030            "failed to read from file `examples/self-signed-certs/missing.pem`: No such file or directory (os error 2)"
1031        );
1032    }
1033}