A library for writing host-specific, single-binary configuration management and deployment tools
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.8 KiB

7 years ago
  1. use std::borrow::Cow;
  2. use std::error::Error;
  3. use std::fmt;
  4. use command_runner::CommandRunner;
  5. use symbols::Symbol;
  6. pub struct SelfSignedTlsCert<'a> {
  7. domain: Cow<'a, str>,
  8. command_runner: &'a CommandRunner
  9. }
  10. impl<'a> SelfSignedTlsCert<'a> {
  11. pub fn new(domain: Cow<'a, str>, command_runner: &'a CommandRunner) -> SelfSignedTlsCert<'a> {
  12. SelfSignedTlsCert {
  13. domain: domain,
  14. command_runner: command_runner
  15. }
  16. }
  17. fn get_key_path(&self) -> String {
  18. format!("/etc/ssl/private/{}.key", self.domain)
  19. }
  20. fn get_cert_path(&self) -> String {
  21. format!("/etc/ssl/local_certs/{}.crt", self.domain)
  22. }
  23. }
  24. impl<'a> fmt::Display for SelfSignedTlsCert<'a> {
  25. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  26. write!(f, "SelfSignedTlsCert {}", self.domain)
  27. }
  28. }
  29. const DAYS_IN_SECONDS: u32 = 24*60*60;
  30. impl<'a> Symbol for SelfSignedTlsCert<'a> {
  31. fn target_reached(&self) -> Result<bool, Box<Error>> {
  32. let result = self.command_runner.run_with_args("openssl", &["x509", "-in", &self.get_cert_path(), "-noout", "-subject", "-checkend", &(30*DAYS_IN_SECONDS).to_string()]);
  33. match result {
  34. Err(e) => Err(Box::new(e)),
  35. Ok(output) => match output.status.code() {
  36. Some(0) => Ok(output.stdout == format!("subject=CN = {}\nCertificate will not expire\n", self.domain).as_bytes()),
  37. Some(_) => Ok(false),
  38. _ => Err("Didn't work".to_string().into())
  39. }
  40. }
  41. }
  42. fn execute(&self) -> Result<(), Box<Error>> {
  43. let output = self.command_runner.run_with_args("openssl", &["req", "-x509", "-sha256", "-days", "90", "-key", &self.get_key_path(), "-out", &self.get_cert_path(), "-subj", &format!("/CN={}", self.domain)]);
  44. match output {
  45. Err(e) => Err(Box::new(e)),
  46. Ok(_) => Ok(())
  47. }
  48. }
  49. }
  50. #[cfg(test)]
  51. mod test {
  52. }