use std::path::PathBuf;
#[derive(Debug, Clone, Default)]
pub struct TlsConfig {
pub ca_cert_file: Option<PathBuf>,
pub ca_cert_pem: Option<String>,
pub client_cert_file: Option<PathBuf>,
pub client_key_file: Option<PathBuf>,
pub skip_verification: bool,
}
impl TlsConfig {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_ca_cert_file(mut self, path: impl Into<PathBuf>) -> Self {
self.ca_cert_file = Some(path.into());
self
}
#[must_use]
pub fn with_ca_cert_pem(mut self, pem: impl Into<String>) -> Self {
self.ca_cert_pem = Some(pem.into());
self
}
#[must_use]
pub fn with_client_cert_file(mut self, path: impl Into<PathBuf>) -> Self {
self.client_cert_file = Some(path.into());
self
}
#[must_use]
pub fn with_client_key_file(mut self, path: impl Into<PathBuf>) -> Self {
self.client_key_file = Some(path.into());
self
}
pub fn is_mtls_configured(&self) -> bool {
self.client_cert_file.is_some() && self.client_key_file.is_some()
}
pub fn has_custom_ca(&self) -> bool {
self.ca_cert_file.is_some() || self.ca_cert_pem.is_some()
}
#[must_use]
pub fn insecure(mut self) -> Self {
self.skip_verification = true;
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default() {
let config = TlsConfig::new();
assert!(config.ca_cert_file.is_none());
assert!(!config.is_mtls_configured());
assert!(!config.has_custom_ca());
}
#[test]
fn test_ca_cert_file() {
let config = TlsConfig::new().with_ca_cert_file("/path/to/ca.crt");
assert!(config.has_custom_ca());
assert_eq!(config.ca_cert_file, Some(PathBuf::from("/path/to/ca.crt")));
}
#[test]
fn test_ca_cert_pem() {
let config = TlsConfig::new().with_ca_cert_pem("-----BEGIN CERTIFICATE-----");
assert!(config.has_custom_ca());
}
#[test]
fn test_mtls() {
let config = TlsConfig::new()
.with_client_cert_file("/path/to/client.crt")
.with_client_key_file("/path/to/client.key");
assert!(config.is_mtls_configured());
}
#[test]
fn test_partial_mtls() {
let config = TlsConfig::new().with_client_cert_file("/path/to/client.crt");
assert!(!config.is_mtls_configured());
}
#[test]
fn test_insecure() {
let config = TlsConfig::new().insecure();
assert!(config.skip_verification);
}
}