//! Central command execution layer. //! //! Arguments stay separate: there is no `sh -c`, no string interpolation into //! a shell, and secrets travel only via stdin. The `ProcessRunner` trait lets //! privileged logic be tested with a fake runner without touching the system. use std::collections::HashMap; use std::io::Write; use std::path::PathBuf; use std::process::{Command, Stdio}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use crate::error::{ExecError, Result}; #[derive(Debug, Clone)] pub struct CommandSpec { pub program: String, pub args: Vec, /// Raw stdin bytes. Never logged. Used for LUKS passphrases and password /// hashes. pub stdin: Option>, pub env: Vec<(String, String)>, pub cwd: Option, pub stage: String, pub operation: String, } impl CommandSpec { pub fn new( stage: impl Into, operation: impl Into, program: impl Into, ) -> Self { Self { program: program.into(), args: Vec::new(), stdin: None, env: Vec::new(), cwd: None, stage: stage.into(), operation: operation.into(), } } pub fn arg(mut self, arg: impl Into) -> Self { self.args.push(arg.into()); self } pub fn args(mut self, args: I) -> Self where I: IntoIterator, S: Into, { self.args.extend(args.into_iter().map(Into::into)); self } pub fn stdin(mut self, bytes: impl Into>) -> Self { self.stdin = Some(bytes.into()); self } pub fn env(mut self, key: impl Into, value: impl Into) -> Self { self.env.push((key.into(), value.into())); self } pub fn cwd(mut self, dir: impl Into) -> Self { self.cwd = Some(dir.into()); self } } #[derive(Debug, Clone)] pub struct CommandOutput { pub status: i32, pub success: bool, pub stdout: Vec, pub stderr: Vec, pub duration: Duration, } impl CommandOutput { pub fn dry_run() -> Self { Self { status: 0, success: true, stdout: Vec::new(), stderr: Vec::new(), duration: Duration::ZERO, } } pub fn stdout_lossy(&self) -> String { String::from_utf8_lossy(&self.stdout).into_owned() } pub fn stderr_lossy(&self) -> String { String::from_utf8_lossy(&self.stderr).into_owned() } } pub trait ProcessRunner: Send + Sync { fn execute(&self, spec: &CommandSpec) -> Result; } /// The real process runner. pub struct RealRunner; impl ProcessRunner for RealRunner { fn execute(&self, spec: &CommandSpec) -> Result { let start = Instant::now(); let mut command = Command::new(&spec.program); command.args(&spec.args); for (k, v) in &spec.env { command.env(k, v); } if let Some(cwd) = &spec.cwd { command.current_dir(cwd); } command.stdout(Stdio::piped()); command.stderr(Stdio::piped()); command.stdin(if spec.stdin.is_some() { Stdio::piped() } else { Stdio::null() }); let mut child = command.spawn().map_err(|source| ExecError::Spawn { program: spec.program.clone(), source, })?; if let Some(bytes) = &spec.stdin { if let Some(mut stdin) = child.stdin.take() { // Ignore broken-pipe style errors; the process exit status is // the source of truth. let _ = stdin.write_all(bytes); let _ = stdin.flush(); } } let output = child .wait_with_output() .map_err(|source| ExecError::Spawn { program: spec.program.clone(), source, })?; let duration = start.elapsed(); let status = output.status.code().unwrap_or(-1); Ok(CommandOutput { status, success: output.status.success(), stdout: output.stdout, stderr: output.stderr, duration, }) } } /// A recording runner for tests. It records every spec and returns canned /// output per program (or a default success). Cloneable so a test can keep a /// handle while the `Exec` owns another. #[derive(Clone, Default)] pub struct RecordingRunner { recorded: Arc>>, responses: Arc>>, default: Arc>>, } impl RecordingRunner { pub fn new() -> Self { Self::default() } pub fn set_response(&self, program: &str, output: CommandOutput) { self.responses .lock() .unwrap() .insert(program.to_string(), output); } pub fn set_default(&self, output: CommandOutput) { *self.default.lock().unwrap() = Some(output); } pub fn fail(&self, program: &str, stderr: &str) { self.set_response( program, CommandOutput { status: 1, success: false, stdout: Vec::new(), stderr: stderr.as_bytes().to_vec(), duration: Duration::from_millis(1), }, ); } pub fn recorded(&self) -> Vec { self.recorded.lock().unwrap().clone() } pub fn programs(&self) -> Vec { self.recorded().iter().map(|s| s.program.clone()).collect() } pub fn len(&self) -> usize { self.recorded.lock().unwrap().len() } pub fn is_empty(&self) -> bool { self.len() == 0 } } impl ProcessRunner for RecordingRunner { fn execute(&self, spec: &CommandSpec) -> Result { self.recorded.lock().unwrap().push(spec.clone()); if let Some(out) = self.responses.lock().unwrap().get(&spec.program) { return Ok(out.clone()); } if let Some(out) = self.default.lock().unwrap().clone() { return Ok(out); } Ok(CommandOutput { status: 0, success: true, stdout: Vec::new(), stderr: Vec::new(), duration: Duration::from_millis(1), }) } } /// A runner that refuses to execute and returns a failure for every command. /// Useful for proving that dry-run never reaches the system. pub struct NeverRunner; impl ProcessRunner for NeverRunner { fn execute(&self, spec: &CommandSpec) -> Result { Err(ExecError::operation( &spec.stage, &spec.operation, "command attempted while execution is disabled", )) } } #[cfg(test)] mod tests { use super::*; #[test] fn arguments_stay_separate() { let spec = CommandSpec::new("s", "op", "mkfs.btrfs") .arg("-f") .arg("/dev/vda2") .arg("-L") .arg("phoebus"); assert_eq!(spec.args, vec!["-f", "/dev/vda2", "-L", "phoebus"]); assert_eq!(spec.program, "mkfs.btrfs"); } #[test] fn recording_runner_records_and_responds() { let runner = RecordingRunner::new(); runner.fail("sgdisk", "boom"); let spec = CommandSpec::new("storage", "partition", "sgdisk").arg("--zap-all"); let out = runner.execute(&spec).unwrap(); assert!(!out.success); assert_eq!(runner.programs(), vec!["sgdisk"]); } #[test] fn real_runner_runs_a_trivial_command() { let runner = RealRunner; let spec = CommandSpec::new("test", "true", "true"); assert!(runner.execute(&spec).unwrap().success); } }