phoebus_os/installer-rs/crates/phoebus-executor/src/actions.rs

176 lines
6 KiB
Rust

//! Execution of typed system actions after approval.
//!
//! These functions are the privileged broker. The model never calls them
//! directly; a human-approved, validated `SystemAction` does.
use std::path::Path;
use phoebus_core::action::SystemAction;
use crate::auth::DestructiveAuthorization;
use crate::command::CommandSpec;
use crate::error::{ExecError, Result};
use crate::exec::Exec;
use crate::snapshot;
#[derive(Debug)]
pub struct ActionOutcome {
pub action: SystemAction,
pub output: String,
pub snapshot: Option<String>,
}
/// Human-readable preview shown before approval.
pub fn preview(action: &SystemAction) -> String {
let mut out = String::new();
out.push_str("Proposed action:\n");
out.push_str(&format!(" {}\n", action.describe()));
out.push_str(&format!(" risk: {:?}\n", action.risk()));
if action.is_mutating() {
out.push_str(" this will modify the system.\n");
}
out
}
pub fn execute(
exec: &Exec,
action: &SystemAction,
auth: Option<&DestructiveAuthorization>,
root: &Path,
) -> Result<ActionOutcome> {
if action.is_mutating() && auth.is_none() {
return Err(ExecError::NotAuthorized(action.describe()));
}
let mut snapshot_id = None;
let output = match action {
SystemAction::InspectService { name } => {
let out = exec.runner.execute(
&CommandSpec::new("sys", "inspect service", "systemctl").args([
"status",
name,
"--no-pager",
]),
)?;
format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy())
}
SystemAction::EnableService { name } => {
exec.run(
CommandSpec::new("sys", "enable service", "systemctl").args(["enable", name]),
)?;
format!("enabled {name}")
}
SystemAction::DisableService { name } => {
exec.run(
CommandSpec::new("sys", "disable service", "systemctl").args(["disable", name]),
)?;
format!("disabled {name}")
}
SystemAction::InspectPackage { atom } => {
let out = exec.runner.execute(
&CommandSpec::new("sys", "inspect package", "emerge").args([
"--pretend",
"--quiet",
atom,
]),
)?;
format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy())
}
SystemAction::InstallPackage { atom } => {
exec.run(CommandSpec::new("sys", "install package", "emerge").args(["--ask=n", atom]))?;
format!("installed {atom}")
}
SystemAction::UpdateSystem => {
exec.run(
CommandSpec::new("sys", "update system", "emerge")
.args(["--update", "--deep", "--newuse", "@world"]),
)?;
"system update complete".to_string()
}
SystemAction::CreateSnapshot { operation } => {
let auth = auth.expect("mutating action has auth");
let record = snapshot::create_and_record(exec, auth, root, "/", operation)?;
snapshot_id = Some(record.id.clone());
format!("snapshot created: {}", record.id)
}
SystemAction::PrepareUpdates => {
let cores = std::thread::available_parallelism()
.map(|n| n.get() as u32)
.unwrap_or(4);
let outcome = crate::update::prepare(exec, root, cores, true)?;
outcome.note
}
SystemAction::InspectUpdates => {
let state = crate::update::load_state(root);
format!(
"status: {:?}\nnote: {}\nlast prepared: {}",
state.status, state.note, state.last_prepared_unix
)
}
SystemAction::History => {
let history = snapshot::read_history(root);
if history.records.is_empty() {
"no transaction history".to_string()
} else {
let mut s = String::new();
for r in &history.records {
s.push_str(&format!("{:<40} {:<16?} {}\n", r.id, r.status, r.operation));
}
s
}
}
};
Ok(ActionOutcome {
action: action.clone(),
output,
snapshot: snapshot_id,
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::command::RecordingRunner;
use crate::log::Logger;
use phoebus_core::Redactor;
fn make_exec(runner: RecordingRunner) -> Exec {
let path = tempfile::tempdir().unwrap().keep();
let logger = Logger::open(path.join("l.log"), Redactor::new(), false);
Exec::new(Box::new(runner), logger, false, path.join("root"), path)
}
#[test]
fn mutating_action_requires_authorization() {
let runner = RecordingRunner::new();
let exec = make_exec(runner.clone());
let action = SystemAction::EnableService {
name: "sshd".into(),
};
let err = execute(&exec, &action, None, Path::new("/")).unwrap_err();
assert!(matches!(err, ExecError::NotAuthorized(_)));
}
#[test]
fn inspect_does_not_require_authorization() {
let runner = RecordingRunner::new();
let exec = make_exec(runner.clone());
let action = SystemAction::InspectService {
name: "sshd".into(),
};
execute(&exec, &action, None, Path::new("/")).unwrap();
}
#[test]
fn enable_builds_separate_arguments() {
let runner = RecordingRunner::new();
let exec = make_exec(runner.clone());
let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap();
let action = SystemAction::EnableService {
name: "sshd".into(),
};
execute(&exec, &action, Some(&auth), Path::new("/")).unwrap();
let spec = &runner.recorded()[0];
assert_eq!(spec.program, "systemctl");
assert_eq!(spec.args, vec!["enable", "sshd"]);
}
}