Skip to main content

haystack_client/
tls.rs

1//! TLS configuration for mutual TLS (mTLS) client authentication.
2//!
3//! Provides [`TlsConfig`] which holds the PEM-encoded client certificate,
4//! private key, and optional CA certificate needed to establish an mTLS
5//! connection to a Haystack server.
6
7/// Configuration for mutual TLS (mTLS) client authentication.
8///
9/// Holds the raw PEM bytes for the client certificate, private key, and an
10/// optional CA certificate used to verify the server.
11#[derive(Debug, Clone)]
12pub struct TlsConfig {
13    /// PEM-encoded client certificate.
14    pub client_cert_pem: Vec<u8>,
15    /// PEM-encoded client private key.
16    pub client_key_pem: Vec<u8>,
17    /// Optional PEM-encoded CA certificate for server verification.
18    pub ca_cert_pem: Option<Vec<u8>>,
19}
20
21impl TlsConfig {
22    /// Load TLS configuration from files on disk.
23    ///
24    /// # Arguments
25    /// * `cert_path` - Path to the PEM-encoded client certificate file
26    /// * `key_path` - Path to the PEM-encoded client private key file
27    /// * `ca_path` - Optional path to a PEM-encoded CA certificate file
28    ///
29    /// # Errors
30    /// Returns an error string if any file cannot be read.
31    pub fn from_files(
32        cert_path: &str,
33        key_path: &str,
34        ca_path: Option<&str>,
35    ) -> Result<Self, String> {
36        let client_cert_pem =
37            std::fs::read(cert_path).map_err(|e| format!("reading cert '{cert_path}': {e}"))?;
38        let client_key_pem =
39            std::fs::read(key_path).map_err(|e| format!("reading key '{key_path}': {e}"))?;
40        let ca_cert_pem = if let Some(ca) = ca_path {
41            Some(std::fs::read(ca).map_err(|e| format!("reading CA '{ca}': {e}"))?)
42        } else {
43            None
44        };
45        Ok(Self {
46            client_cert_pem,
47            client_key_pem,
48            ca_cert_pem,
49        })
50    }
51}