use std::borrow::Cow; use std::error::Error; use std::ffi::OsStr; use std::fmt; use std::path::PathBuf; use crate::command_runner::CommandRunner; use crate::resources::Resource; use crate::symbols::{Action, OwnedSymbolAction, Symbol, SymbolAction, SymbolRunner}; pub struct TlsCsr<'a, C: CommandRunner> { domain: Cow<'a, str>, command_runner: &'a C, } impl<'a, C: CommandRunner> TlsCsr<'a, C> { pub fn new(domain: Cow<'a, str>, command_runner: &'a C) -> Self { TlsCsr { domain, command_runner, } } fn get_key_path(&self) -> PathBuf { format!("/etc/ssl/private/{}.key", self.domain).into() } fn get_csr_path(&self) -> PathBuf { format!("/etc/ssl/local_certs/{}.csr", self.domain).into() } } impl fmt::Display for TlsCsr<'_, C> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "TlsCsr {}", self.domain) } } impl Symbol for TlsCsr<'_, C> { fn target_reached(&self) -> Result> { if !self.get_csr_path().exists() { return Ok(false); } let output = self.command_runner.get_stderr( "openssl", &[ OsStr::new("req"), "-in".as_ref(), self.get_csr_path().as_ref(), "-noout".as_ref(), "-verify".as_ref(), ], )?; Ok(output == b"verify OK\n") } fn execute(&self) -> Result<(), Box> { self.command_runner.run_successfully( "openssl", &[ OsStr::new("req"), "-new".as_ref(), "-sha256".as_ref(), "-key".as_ref(), self.get_key_path().as_ref(), "-out".as_ref(), self.get_csr_path().as_ref(), "-subj".as_ref(), format!("/CN={}", self.domain).as_ref(), ], )?; Ok(()) } fn get_prerequisites(&self) -> Vec { vec![Resource::new("file", self.get_key_path().to_str().unwrap())] } fn as_action<'b>(&'b self, runner: &'b dyn SymbolRunner) -> Box { Box::new(SymbolAction::new(runner, self)) } fn into_action<'b>(self: Box, runner: &'b dyn SymbolRunner) -> Box where Self: 'b, { Box::new(OwnedSymbolAction::new(runner, *self)) } } #[cfg(test)] mod test {}