pueue_lib/
tls.rs

1//! Helper functions for reading and handling TLS certificates.
2use std::{fs::File, io::BufReader, path::Path};
3
4use rustls::pki_types::CertificateDer;
5
6use crate::error::Error;
7
8/// Load a daemon's certificate from a given path.
9///
10/// This certificate needs to be provided when connecting via
11/// [ConnectionSettings::TlsTcpSocket](crate::network::socket::ConnectionSettings::TlsTcpSocket)
12pub fn load_ca<'a>(path: &Path) -> Result<CertificateDer<'a>, Error> {
13    let file = File::open(path)
14        .map_err(|err| Error::IoPathError(path.to_path_buf(), "opening cert", err))?;
15
16    let cert = rustls_pemfile::certs(&mut BufReader::new(file))
17        .collect::<Result<Vec<_>, std::io::Error>>()
18        .map_err(|_| Error::CertificateFailure("Failed to parse daemon certificate.".into()))?
19        .into_iter()
20        .next()
21        .ok_or_else(|| Error::CertificateFailure("Couldn't find CA certificate in file".into()))?;
22
23    Ok(cert)
24}