use tonic::transport::{Certificate, Identity};
use super::{ConfigSources, Path, Result, ServerTlsConfig, file::ServerTlsFileConfig, fs};
pub(super) fn tls_config(
file: Option<&ServerTlsFileConfig>,
sources: &ConfigSources,
) -> Result<Option<ServerTlsConfig>> {
let Some(file) = file else {
return Ok(None);
};
let identity = Identity::from_pem(
read_pem(sources, "tls.cert_path", &file.cert_path)?,
read_pem(sources, "tls.key_path", &file.key_path)?,
);
let mut config = ServerTlsConfig::new().identity(identity);
if let Some(path) = &file.client_ca_path {
config = config.client_ca_root(Certificate::from_pem(read_pem(sources, "tls.client_ca_path", path)?));
}
tracing::info!(
client_certificate_verification = file.client_ca_path.is_some(),
"loaded the [tls] listener configuration"
);
Ok(Some(config))
}
fn read_pem(sources: &ConfigSources, field: &'static str, path: &Path) -> Result<Vec<u8>> {
fs::read(path)
.map_err(|error| sources.invalid_with_source(field, format!("`{}` cannot be read", path.display()), error))
}