use anyhow::{bail, Context, Result};
use rustls::pki_types::{pem::PemObject, CertificateDer, PrivateKeyDer};
use std::fs::File;
use std::io::BufReader;
use tokio_rustls::TlsAcceptor;
pub async fn create_tls_acceptor(
cert_file: &std::path::Path,
key_file: &std::path::Path,
) -> Result<TlsAcceptor> {
let cert_file = File::open(cert_file).context("Failed to open SSL certificate file")?;
let mut cert_reader = BufReader::new(cert_file);
let certs: Vec<CertificateDer> = CertificateDer::pem_reader_iter(&mut cert_reader)
.collect::<Result<Vec<_>, _>>()
.context("Failed to read certificate file")?;
if certs.is_empty() {
bail!("No certificates found in certificate file");
}
let key_file = File::open(key_file).context("Failed to open SSL private key file")?;
let mut key_reader = BufReader::new(key_file);
let key = PrivateKeyDer::from_pem_reader(&mut key_reader)
.context("Failed to read private key file")?;
let config = rustls::ServerConfig::builder()
.with_no_client_auth()
.with_single_cert(certs, key)
.context("Failed to create TLS server config")?;
Ok(TlsAcceptor::from(std::sync::Arc::new(config)))
}