flexible_hyper_server_tls/
rustls_helpers.rs1use std::path::Path;
6use std::sync::Arc;
7
8use rustls_pki_types::pem::PemObject;
9use rustls_pki_types::{CertificateDer, PrivateKeyDer};
10use thiserror::Error;
11use tokio_rustls::rustls;
12
13#[derive(Error, Debug)]
15pub enum TlsAcceptorError {
16 #[error("invalid pem data")]
18 InvalidPem(#[from] rustls_pki_types::pem::Error),
19 #[error("failed to create ServerConfig")]
21 ServerConfig(#[from] rustls::Error),
22 #[error("failed to read file")]
24 FileRead(#[source] std::io::Error),
25}
26
27pub async fn get_tlsacceptor_from_files(
46 cert_path: impl AsRef<Path> + Send,
47 key_path: impl AsRef<Path> + Send,
48) -> Result<tokio_rustls::TlsAcceptor, TlsAcceptorError> {
49 let cert_data = tokio::fs::read(cert_path)
50 .await
51 .map_err(TlsAcceptorError::FileRead)?;
52 let key_data = tokio::fs::read(key_path)
53 .await
54 .map_err(TlsAcceptorError::FileRead)?;
55
56 get_tlsacceptor_from_pem_data(&cert_data, &key_data)
57}
58
59pub fn get_tlsacceptor_from_pem_data(
64 cert_data: &[u8],
65 key_data: &[u8],
66) -> Result<tokio_rustls::TlsAcceptor, TlsAcceptorError> {
67 let certs: Vec<_> = CertificateDer::pem_slice_iter(cert_data).collect::<Result<_, _>>()?;
68
69 let key = PrivateKeyDer::from_pem_slice(key_data)?;
70
71 let mut cfg = rustls::server::ServerConfig::builder()
72 .with_no_client_auth()
73 .with_single_cert(certs, key)?;
74
75 cfg.alpn_protocols = vec![b"http/1.1".to_vec(), b"http/1.0".to_vec()];
76
77 let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(cfg));
78
79 Ok(acceptor)
80}