use axum_server::tls_rustls::RustlsConfig;
#[cfg(feature = "dev-certs")]
use std::net::SocketAddr;
use std::path::Path;
fn ensure_crypto_provider() {
let _ = rustls::crypto::ring::default_provider().install_default();
}
pub async fn load_rustls_config(
cert_pem: impl AsRef<Path>,
key_pem: impl AsRef<Path>,
) -> anyhow::Result<RustlsConfig> {
ensure_crypto_provider();
RustlsConfig::from_pem_file(cert_pem, key_pem)
.await
.map_err(|e| anyhow::anyhow!("loading TLS cert/key: {e}"))
}
#[cfg(feature = "dev-certs")]
pub struct TlsMaterial {
pub config: RustlsConfig,
pub cert_pem: String,
}
#[cfg(feature = "dev-certs")]
pub async fn generate_dev_cert(addr: SocketAddr) -> anyhow::Result<TlsMaterial> {
ensure_crypto_provider();
let names = vec!["localhost".to_string(), addr.ip().to_string()];
let rcgen::CertifiedKey { cert, key_pair } = rcgen::generate_simple_self_signed(names)?;
let cert_pem = cert.pem();
let key_pem = key_pair.serialize_pem();
let config = RustlsConfig::from_pem(cert_pem.clone().into_bytes(), key_pem.into_bytes())
.await
.map_err(|e| anyhow::anyhow!("building dev TLS config: {e}"))?;
Ok(TlsMaterial { config, cert_pem })
}