use std::error::Error; use std::fmt; use std::fs::File as FsFile; use std::io::Write; use std::path::{Path, PathBuf}; use crate::command_runner::CommandRunner; use crate::resources::Resource; use crate::symbols::{Action, OwnedSymbolAction, Symbol, SymbolAction, SymbolRunner}; pub struct AcmeCertChain<'a, D: AsRef, R: AsRef, C: CommandRunner> { domain: D, command_runner: &'a C, root_cert: R, } impl<'a, D: AsRef, R: AsRef, C: CommandRunner> AcmeCertChain<'a, D, R, C> { pub fn new(domain: D, command_runner: &'a C, root_cert: R) -> Self { AcmeCertChain { domain, command_runner, root_cert, } } fn get_single_cert_path(&self) -> PathBuf { format!("/etc/ssl/local_certs/{}.crt", self.domain.as_ref()).into() } fn get_cert_chain_path(&self) -> PathBuf { format!("/etc/ssl/local_certs/{}.chained.crt", self.domain.as_ref()).into() } } impl<'a, D: AsRef, R: AsRef, C: CommandRunner> fmt::Display for AcmeCertChain<'a, D, R, C> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "AcmeCertChain {}", self.domain.as_ref()) } } const DAYS_IN_SECONDS: u32 = 24 * 60 * 60; impl<'a, D: AsRef, R: AsRef, C: CommandRunner> Symbol for AcmeCertChain<'a, D, R, C> { fn target_reached(&self) -> Result> { if !self.get_cert_chain_path().exists() { return Ok(false); } let stdout = self.command_runner.get_output( "openssl", args![ "x509", "-in", self.get_cert_chain_path(), "-noout", "-subject", "-checkend", (30 * DAYS_IN_SECONDS).to_string(), ], )?; if stdout != format!( "subject=CN = {}\nCertificate will not expire\n", self.domain.as_ref() ) .as_bytes() { return Ok(false); } // FIXME: From my understanding, the -untrusted *.pem parameter shouldn't be necessary, but is necessary with openssl 1.1.0f-3 Ok( self .command_runner .run_successfully( "openssl", args![ "verify", "-untrusted", self.root_cert.as_ref(), self.get_cert_chain_path(), ], ) .is_ok(), ) } fn execute(&self) -> Result<(), Box> { let output = self.command_runner.get_output( "cat", args![self.get_single_cert_path(), self.root_cert.as_ref(),], )?; let mut file = FsFile::create(self.get_cert_chain_path())?; file.write_all(&output)?; Ok(()) } fn get_prerequisites(&self) -> Vec { vec![Resource::new( "file", self.get_single_cert_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 {}