phoebus_os/installer-rs/crates/phoebus-executor/src/actions.rs
Phoebus e82aaba5fb fix(executor): fail closed when a protective snapshot cannot be created
High-risk sys actions now create their protective snapshot inside
actions::execute and abort if the .snapshots subvolume exists but the snapshot
fails, instead of warning and mutating anyway. Corrupt snapshot history is
surfaced as an error rather than being silently treated as empty.
2026-09-20 04:39:23 -07:00

251 lines
9.1 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()));
}
// A protective snapshot must exist before a high-risk change. If the
// snapshots subvolume is present but the snapshot cannot be created, fail
// closed rather than proceed without a recovery point. A system without a
// `.snapshots` subvolume (e.g. a non-Btrfs root) is a warning, not a block.
if action.risk() == phoebus_core::action::Risk::High && !exec.dry_run {
if root.join(snapshot::SNAPSHOT_DIR).is_dir() {
let auth = auth.ok_or_else(|| ExecError::NotAuthorized(action.describe()))?;
snapshot::create_and_record(exec, auth, root, "/", &action.describe())?;
} else {
exec.logger.warn(format!(
"no {}/ subvolume; proceeding without a protective snapshot",
snapshot::SNAPSHOT_DIR
));
}
}
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 high_risk_action_snapshots_before_running() {
let runner = RecordingRunner::new();
let exec = make_exec(runner.clone());
std::fs::create_dir_all(exec.root.join(snapshot::SNAPSHOT_DIR)).unwrap();
let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap();
execute(
&exec,
&SystemAction::UpdateSystem,
Some(&auth),
Path::new(&exec.root),
)
.unwrap();
let programs = runner.programs();
let btrfs = programs
.iter()
.position(|p| p == "btrfs")
.expect("snapshot");
let emerge = programs.iter().position(|p| p == "emerge").expect("emerge");
assert!(
btrfs < emerge,
"protective snapshot must precede the mutation: {programs:?}"
);
}
#[test]
fn high_risk_action_aborts_when_protective_snapshot_fails() {
let runner = RecordingRunner::new();
runner.fail("btrfs", "snapshot failed");
let exec = make_exec(runner.clone());
std::fs::create_dir_all(exec.root.join(snapshot::SNAPSHOT_DIR)).unwrap();
let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap();
let err = execute(
&exec,
&SystemAction::UpdateSystem,
Some(&auth),
Path::new(&exec.root),
)
.unwrap_err();
assert!(matches!(err, ExecError::Command { .. }), "got {err}");
// The mutation must not run, and no snapshot may be recorded as
// committed when creation failed.
assert!(!runner.programs().iter().any(|p| p == "emerge"));
let history = snapshot::read_history(Path::new(&exec.root)).unwrap();
assert!(history.records.is_empty());
}
#[test]
fn history_query_reports_corrupt_file() {
let runner = RecordingRunner::new();
let exec = make_exec(runner);
let path = crate::snapshot::history_path(Path::new(&exec.root));
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, "not = = toml [[[").unwrap();
let err = execute(&exec, &SystemAction::History, None, Path::new(&exec.root)).unwrap_err();
assert!(matches!(err, ExecError::Core(_)), "got {err}");
}
#[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"]);
}
}