Some checks are pending
ci / test (push) Waiting to run
sys install <name>, sys remove <name> and sys search <query> are deterministic and model-free: Portage resolves a bare name or a full atom. Adds the remove_package and search_packages typed actions (remove is High risk and gets the protective snapshot; search is read-only). This is the old-fashioned fallback so the system stays fully administrable with no LLM.
294 lines
11 KiB
Rust
294 lines
11 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 } => {
|
|
// Portage resolves a bare name (`vim`) or a full atom.
|
|
exec.run(CommandSpec::new("sys", "install package", "emerge").args(["--ask=n", atom]))?;
|
|
format!("installed {atom} (Portage)")
|
|
}
|
|
SystemAction::RemovePackage { atom } => {
|
|
exec.run(CommandSpec::new("sys", "remove package", "emerge").args([
|
|
"--unmerge",
|
|
"--ask=n",
|
|
atom,
|
|
]))?;
|
|
format!("removed {atom} (Portage)")
|
|
}
|
|
SystemAction::SearchPackages { query } => {
|
|
let out = exec.runner.execute(
|
|
&CommandSpec::new("sys", "search packages", "emerge")
|
|
.args(["--search", "--quiet", query]),
|
|
)?;
|
|
format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy())
|
|
}
|
|
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 remove_package_builds_unmerge() {
|
|
let runner = RecordingRunner::new();
|
|
let exec = make_exec(runner.clone());
|
|
let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap();
|
|
let action = SystemAction::RemovePackage { atom: "vim".into() };
|
|
execute(&exec, &action, Some(&auth), Path::new(&exec.root)).unwrap();
|
|
let spec = &runner.recorded()[0];
|
|
assert_eq!(spec.program, "emerge");
|
|
assert!(spec.args.contains(&"--unmerge".to_string()));
|
|
assert!(spec.args.contains(&"vim".to_string()));
|
|
}
|
|
|
|
#[test]
|
|
fn search_packages_builds_emerge_search() {
|
|
let runner = RecordingRunner::new();
|
|
let exec = make_exec(runner.clone());
|
|
let action = SystemAction::SearchPackages {
|
|
query: "firefox".into(),
|
|
};
|
|
execute(&exec, &action, None, Path::new(&exec.root)).unwrap();
|
|
let spec = &runner.recorded()[0];
|
|
assert_eq!(spec.program, "emerge");
|
|
assert!(spec.args.contains(&"--search".to_string()));
|
|
assert!(spec.args.contains(&"firefox".to_string()));
|
|
}
|
|
|
|
#[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"]);
|
|
}
|
|
}
|