//! 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 phoebus_core::effects::{changed_materially, parse_emerge_pretend, ResolvedPlan}; use phoebus_core::selection::Need; use phoebus_core::transaction::TransactionOutcome; use crate::auth::DestructiveAuthorization; use crate::command::{CommandOutput, CommandSpec}; use crate::error::{ExecError, Result}; use crate::exec::Exec; use crate::portage; use crate::snapshot; use crate::{appimage, chooser, ebuild, snap}; #[derive(Debug)] pub struct ActionOutcome { pub action: SystemAction, pub output: String, pub snapshot: Option, } /// 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"); } // A custom ebuild is executable, untrusted content: show the exact artifact // and its digest so approval is bound to what will be built. if let SystemAction::CustomEbuildPrepare { atom, version, rationale, ebuild, } = action { let digest = crate::opencode::sha256_hex(ebuild.as_bytes()); out.push_str(&format!("\nCustom ebuild {atom}-{version}\n")); out.push_str(&format!(" rationale: {rationale}\n")); out.push_str(&format!(" content sha256: {digest}\n")); out.push_str(" --- ebuild begins ---\n"); out.push_str(ebuild); if !ebuild.ends_with('\n') { out.push('\n'); } out.push_str(" --- ebuild ends ---\n"); out.push_str(" It will be treated as untrusted code and built only after approval.\n"); } out } /// Whether the command acts on the running system (`/`) rather than a mounted /// alternate target. pub(crate) fn is_host_root(root: &Path) -> bool { root == Path::new("/") } /// Build a command that acts on the intended system: directly for the running /// root, or inside the target chroot for an alternate root. This is the single /// place package, service and Flatpak commands are rooted, so preview and /// execution always target the same system. fn target_spec( root: &Path, stage: &str, operation: &str, program: &str, args: &[String], ) -> CommandSpec { if is_host_root(root) { CommandSpec::new(stage, operation, program).args(args.iter().cloned()) } else { portage::chroot_spec(stage, operation, root, program, args) } } /// Refuse an operation that genuinely needs the running system (e.g. service /// status, start, stop, restart) when an alternate root was requested. This /// runs before any command is built, so nothing is invoked against the host. fn require_host_root(root: &Path, operation: &str) -> Result<()> { if is_host_root(root) { Ok(()) } else { Err(ExecError::operation( "sys", operation, format!( "cannot target the alternate root {}; this operation needs the \ running system", root.display() ), )) } } /// Run a mutating command against the intended system. fn run_in_target( exec: &Exec, root: &Path, stage: &str, operation: &str, program: &str, args: &[String], ) -> Result { exec.run(target_spec(root, stage, operation, program, args)) } /// Capture a read-only command against the intended system. Output is returned /// regardless of exit status (inspection commands report state, not failure). fn capture_in_target( exec: &Exec, root: &Path, stage: &str, operation: &str, program: &str, args: &[String], ) -> Result { exec.runner .execute(&target_spec(root, stage, operation, program, args)) } /// `systemctl` for boot enable/disable. On the host it acts on PID 1; on an /// alternate root it uses `--root`, which only writes symlinks under the /// target, so the host's service state is never touched. fn systemctl_spec(root: &Path, operation: &str, verb: &str, name: &str) -> CommandSpec { if is_host_root(root) { CommandSpec::new("sys", operation, "systemctl").args([verb, name]) } else { CommandSpec::new("sys", operation, "systemctl") .arg("--root") .arg(root.to_string_lossy().to_string()) .arg(verb) .arg(name) } } /// The Portage arguments that produce a resolved pretend plan for an action, /// or `None` when the action is not a Portage transaction. fn pretend_args(action: &SystemAction) -> Option> { match action { SystemAction::InstallPackage { atom, binary } => { let mut args = vec!["--pretend".into(), "--color=n".into()]; if *binary == Some(true) { args.push("--getbinpkg=y".into()); args.push("--usepkg=y".into()); } args.push("--".into()); args.push(atom.clone()); Some(args) } SystemAction::RemovePackage { atom } => Some(vec![ "--pretend".into(), "--unmerge".into(), "--color=n".into(), "--".into(), atom.clone(), ]), SystemAction::UpdateSystem => Some(vec![ "--pretend".into(), "--update".into(), "--deep".into(), "--newuse".into(), "--color=n".into(), "--".into(), "@world".into(), ]), _ => None, } } /// Resolve exactly what a package action will do. Non-Portage actions yield an /// empty plan. A plan's digest can be bound to an approval. pub fn resolve_effects(exec: &Exec, action: &SystemAction, root: &Path) -> Result { action .validate() .map_err(|e| ExecError::operation("sys", "validate action", e))?; let Some(args) = pretend_args(action) else { return Ok(ResolvedPlan::default()); }; // Same rooting as execution, so the reviewed plan describes the action that // will actually run. let spec = target_spec(root, "sys", "resolve effects", "emerge", &args); let out = exec.run_capture(spec)?; let mut plan = parse_emerge_pretend(&out.stdout_lossy()); if !plan.established { return Err(ExecError::operation( "sys", "resolve effects", "could not establish the package plan from emerge --pretend; \ refusing to proceed unreviewed", )); } if let SystemAction::InstallPackage { atom, binary: Some(true), } = action { if plan .effects .iter() .any(|e| e.source == phoebus_core::effects::EffectSource::Source) { return Err(ExecError::operation( "sys", "binary unavailable", format!( "a prebuilt binary package was requested for `{atom}`, but Portage requires source compilation; a revised review is required" ), )); } } if root.join(snapshot::SNAPSHOT_DIR).is_dir() { plan.recovery_point = Some("a protective snapshot before the change".into()); } Ok(plan) } /// Execute an action after re-resolving it against the approved digest. If the /// plan changed materially since review, execution is refused. pub fn execute_checked( exec: &Exec, action: &SystemAction, auth: Option<&DestructiveAuthorization>, root: &Path, approved: Option<&ResolvedPlan>, ) -> Result { if let Some(approved) = approved { let current = resolve_effects(exec, action, root)?; if changed_materially(approved, ¤t) { return Err(ExecError::operation( "sys", "plan changed", format!( "the reviewed plan changed before execution (approved {}, now {}); \ re-run and review again", &approved.digest[..approved.digest.len().min(12)], ¤t.digest[..current.digest.len().min(12)] ), )); } } execute(exec, action, auth, root) } /// The result of running a reviewed multi-action plan. #[derive(Debug, Default)] pub struct PlanOutcome { /// `(action, output)` for actions that completed, in execution order. pub completed: Vec<(String, String)>, /// `(action, error)` for the action that failed, if any. pub failure: Option<(String, String)>, /// Every action's status in order, including the ones never attempted /// because an earlier action aborted the plan. pub outcomes: Vec, /// The most recent protective snapshot reported by an action. pub snapshot: Option, } /// Execute a reviewed plan action by action, stopping at the first failure and /// recording later actions as unattempted. This is the single execution path /// shared by the assistant and any multi-step caller, so partial failure is /// reported truthfully rather than as success. pub fn execute_plan( exec: &Exec, steps: &[(SystemAction, ResolvedPlan)], auth: Option<&DestructiveAuthorization>, root: &Path, ) -> PlanOutcome { let mut outcome = PlanOutcome::default(); for (action, resolved) in steps { let described = action.describe(); if outcome.failure.is_some() { outcome .outcomes .push(TransactionOutcome::unattempted(described)); continue; } match execute_checked(exec, action, auth, root, Some(resolved)) { Ok(result) => { if result.snapshot.is_some() { outcome.snapshot = result.snapshot; } outcome .outcomes .push(TransactionOutcome::completed(described.clone())); outcome.completed.push((described, result.output)); } Err(e) => { let detail = e.to_string(); outcome.outcomes.push(TransactionOutcome::failed( described.clone(), detail.clone(), )); outcome.failure = Some((described, detail)); } } } outcome } pub fn execute( exec: &Exec, action: &SystemAction, auth: Option<&DestructiveAuthorization>, root: &Path, ) -> Result { // The execution boundary validates every action regardless of its source // (manual phrase, JSON, or AI plan), so an invalid value can never reach a // command. action .validate() .map_err(|e| ExecError::operation("sys", "validate action", e))?; if action.is_mutating() && auth.is_none() { return Err(ExecError::NotAuthorized(action.describe())); } // Rollback moves the root, `/var` and the boot selection together and takes // its own pre-rollback snapshot, so it must not run through the generic // protective-snapshot path below. if let SystemAction::Undo { snapshot } = action { let auth = auth.ok_or_else(|| ExecError::NotAuthorized(action.describe()))?; let outcome = crate::rollback::execute(exec, auth, root, snapshot.as_deref())?; let mut output = format!( "rollback activated: {} -> {}\nnext boot uses {}\nreboot to complete; \ a known-good previous entry is kept", outcome.state.target_snapshot, outcome.state.root_subvol, outcome.state.root_subvol ); for warning in &outcome.warnings { output.push_str(&format!("\nwarning: {warning}")); } return Ok(ActionOutcome { action: action.clone(), output, snapshot: Some(outcome.state.target_snapshot), }); } let mut snapshot_id = None; // 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. // The snapshot source is the target root itself, so an alternate root // snapshots the target, never the host. 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()))?; let source = root.to_string_lossy().to_string(); let record = snapshot::create_and_record(exec, auth, root, &source, &action.describe())?; // Preserve the recovery point so callers can record it. snapshot_id = Some(record.id); } else { exec.logger.warn(format!( "no {}/ subvolume; proceeding without a protective snapshot", snapshot::SNAPSHOT_DIR )); } } let output = match action { SystemAction::InspectService { name } => { require_host_root(root, "inspect service")?; let out = capture_in_target( exec, root, "sys", "inspect service", "systemctl", &["status".into(), name.clone(), "--no-pager".into()], )?; format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy()) } SystemAction::EnableService { name } => { let spec = systemctl_spec(root, "enable service", "enable", name); exec.run(spec)?; format!("enabled {name}") } SystemAction::DisableService { name } => { let spec = systemctl_spec(root, "disable service", "disable", name); exec.run(spec)?; format!("disabled {name}") } SystemAction::StartService { name } => { require_host_root(root, "start service")?; let spec = systemctl_spec(root, "start service", "start", name); exec.run(spec)?; format!("started {name}") } SystemAction::StopService { name } => { require_host_root(root, "stop service")?; let spec = systemctl_spec(root, "stop service", "stop", name); exec.run(spec)?; format!("stopped {name}") } SystemAction::RestartService { name } => { require_host_root(root, "restart service")?; let spec = systemctl_spec(root, "restart service", "restart", name); exec.run(spec)?; format!("restarted {name}") } SystemAction::InspectPackage { atom } => { let out = capture_in_target( exec, root, "sys", "inspect package", "emerge", &[ "--pretend".into(), "--quiet".into(), "--".into(), atom.clone(), ], )?; format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy()) } SystemAction::InstallPackage { atom, binary } => { // Portage resolves a bare name (`vim`) or a full atom. let mut args = vec!["--ask=n".into()]; if *binary == Some(true) { args.push("--getbinpkg=y".into()); args.push("--usepkg=y".into()); } args.push("--".into()); args.push(atom.clone()); run_in_target(exec, root, "sys", "install package", "emerge", &args)?; if *binary == Some(true) { format!("installed binary package {atom} (Portage)") } else { format!("installed {atom} (Portage)") } } SystemAction::RemovePackage { atom } => { run_in_target( exec, root, "sys", "remove package", "emerge", &[ "--unmerge".into(), "--ask=n".into(), "--".into(), atom.clone(), ], )?; format!("removed {atom} (Portage)") } SystemAction::SearchPackages { query } => { let out = capture_in_target( exec, root, "sys", "search packages", "emerge", &[ "--search".into(), "--quiet".into(), "--".into(), query.clone(), ], )?; format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy()) } SystemAction::FlatpakInstall { app_id } => { run_in_target( exec, root, "sys", "install flatpak", "flatpak", &[ "install".into(), "-y".into(), "--".into(), "flathub".into(), app_id.clone(), ], )?; format!("installed Flatpak app {app_id}") } SystemAction::FlatpakRemove { app_id } => { run_in_target( exec, root, "sys", "remove flatpak", "flatpak", &["uninstall".into(), "-y".into(), "--".into(), app_id.clone()], )?; format!("removed Flatpak app {app_id}") } SystemAction::FlatpakList => { let out = capture_in_target( exec, root, "sys", "list flatpaks", "flatpak", &[ "list".into(), "--app".into(), "--columns=application,version,branch".into(), ], )?; let text = format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy()); if text.trim().is_empty() { "no Flatpak applications installed".to_string() } else { text } } SystemAction::ChoosePackage { name, kind, backend, gui, requires_sandbox, } => { let need = Need { name: name.clone(), kind: (*kind).unwrap_or_else(|| chooser::infer_kind(name)), requires_sandbox: *requires_sandbox, requires_proprietary: false, gui: *gui, requires_features: Vec::new(), explicit_backend: *backend, max_install_mib: None, }; chooser::choose(exec, root, &need)?.render() } SystemAction::SetPackagePreference { name, backend } => { let mut prefs = chooser::load_preferences(root); match backend { Some(backend) => { prefs.per_app.insert(name.clone(), *backend); chooser::save_preferences(exec, root, &prefs)?; format!( "preference saved: {name} -> {}\n automatic selection applies again when \ the preferred lane is incompatible", backend.as_str() ) } None => { prefs.per_app.remove(name); chooser::save_preferences(exec, root, &prefs)?; format!("preference cleared for {name}") } } } SystemAction::DiscoverCandidates { query, kind, backend, gui, requires_sandbox, } => { let need = Need { name: query.clone(), kind: (*kind).unwrap_or_else(|| chooser::infer_kind(query)), requires_sandbox: *requires_sandbox, requires_proprietary: false, gui: *gui, requires_features: Vec::new(), explicit_backend: *backend, max_install_mib: None, }; let candidates = chooser::resolve_candidates(exec, root, &need); serde_json::to_string_pretty(&candidates) .unwrap_or_else(|e| format!("could not serialise candidates: {e}")) } SystemAction::InspectCandidate { backend, id } => { let detail = chooser::candidate_detail(exec, root, *backend, id); serde_json::to_string_pretty(&detail) .unwrap_or_else(|e| format!("could not serialise candidate: {e}")) } SystemAction::CheckBackend { backend } => { let status = chooser::backend_status(exec, root, *backend); serde_json::to_string_pretty(&status) .unwrap_or_else(|e| format!("could not serialise backend status: {e}")) } SystemAction::InspectInstallation { application } => { let inspection = chooser::installed_copies(exec, root, application); serde_json::to_string_pretty(&inspection) .unwrap_or_else(|e| format!("could not serialise installations: {e}")) } SystemAction::SnapFind { query } => { require_host_root(root, "find snaps")?; snap::find(exec, query)? } SystemAction::SnapInfo { name } => { require_host_root(root, "inspect snap")?; snap::info(exec, name)? } SystemAction::SnapInstall { name, channel, classic, } => { require_host_root(root, "install snap")?; // snapd is a Portage-managed system dependency; install it first if // the lane is requested but not yet present. if !snap::status(exec)?.usable() { snap::ensure_snapd(exec)?; } let out = snap::install(exec, name, channel.as_deref(), *classic)?; let confinement = snap::status(exec) .map(|s| s.confinement.as_str().to_string()) .unwrap_or_else(|_| "unknown".to_string()); format!("installed snap {name} (confinement: {confinement})\n{out}") } SystemAction::SnapRemove { name } => { require_host_root(root, "remove snap")?; let out = snap::remove(exec, name)?; format!("removed snap {name}\n{out}") } SystemAction::SnapList => { require_host_root(root, "list snaps")?; let entries = snap::list(exec)?; if entries.is_empty() { "no snaps installed".to_string() } else { let mut s = String::new(); for e in entries { s.push_str(&format!( "{:<24} {:<16} {:<12} {}\n", e.name, e.version, e.channel, e.notes )); } s } } SystemAction::SnapRefresh { name } => { require_host_root(root, "refresh snaps")?; let out = snap::refresh(exec, name.as_deref())?; format!( "refreshed {} (snapd also refreshes on its own schedule)\n{out}", name.as_deref().unwrap_or("all snaps") ) } SystemAction::SnapConnections { name } => { require_host_root(root, "snap connections")?; snap::connections(exec, name)? } SystemAction::AppImageImport { path, name } => { let source = Path::new(path); let name = match name { Some(n) => n.clone(), None => appimage::derive_name(source)?, }; let record = appimage::import_local(exec, root, source, &name)?; format!( "imported AppImage {} (sha256 {}, arch {})\n no application sandbox; runs as the user", record.name, &record.sha256[..record.sha256.len().min(12)], record.arch ) } SystemAction::AppImageAcquire { name, url, sha256 } => { let record = appimage::acquire(exec, root, name, url, sha256)?; format!( "acquired AppImage {} from {url} (sha256 verified, arch {})", record.name, record.arch ) } SystemAction::AppImageUpdate { name, url, sha256 } => { let record = appimage::update(exec, root, name, url, sha256)?; format!( "updated AppImage {} to sha256 {}\n the previous image was replaced atomically", record.name, &record.sha256[..record.sha256.len().min(12)] ) } SystemAction::AppImageRemove { name, purge_data } => { appimage::remove(root, name, *purge_data)?; if *purge_data { format!("removed AppImage {name} and its managed data directory") } else { format!( "removed AppImage {name}; user data under $HOME and any unmanaged \ files were preserved" ) } } SystemAction::AppImageInfo { name } => { let record = appimage::info(root, name)?; format!( "name: {}\nsource: {}\nsha256: {}\narch: {}\nsize: {} bytes\ninstalled: {}", record.name, record.provenance, record.sha256, record.arch, record.size_bytes, record.installed_unix ) } SystemAction::AppImageList => { let records = appimage::list(root)?; if records.is_empty() { "no managed AppImages".to_string() } else { let mut s = String::new(); for r in records { s.push_str(&format!( "{:<24} {:<12} {:<16} {}\n", r.name, r.arch, &r.sha256[..r.sha256.len().min(12)], r.provenance )); } s } } SystemAction::CustomEbuildPrepare { atom, version, rationale, ebuild, } => { let staged = ebuild::prepare(exec, root, atom, version, rationale, ebuild)?; format!( "staged custom ebuild {}-{} (sha256 {})\n the artifact is not built until your \ reviewed digest is presented to custom_ebuild_install", staged.atom, staged.version, staged.digest ) } SystemAction::CustomEbuildInstall { atom, version, digest, } => { ebuild::install(exec, root, atom, version, digest)?; format!("installed custom ebuild {atom}-{version} through Portage (Phoebus overlay)") } SystemAction::CustomEbuildRemove { atom } => { ebuild::remove(exec, root, atom)?; format!("removed custom ebuild {atom} from Portage and the Phoebus overlay") } SystemAction::CustomEbuildList => { let staged = ebuild::list(root); if staged.is_empty() { "no Phoebus-managed custom ebuilds".to_string() } else { let mut s = String::new(); for e in staged { s.push_str(&format!( "{:<28} {:<14} {}\n", e.atom, e.version, &e.digest[..e.digest.len().min(12)] )); } s } } SystemAction::NixPrepare { packages } => { let prepared = crate::nix::prepare_dev_packages(exec, root, packages)?; format!("realised Nix development packages: {}", prepared.join(", ")) } SystemAction::UpdateSystem => { run_in_target( exec, root, "sys", "update system", "emerge", &[ "--update".into(), "--deep".into(), "--newuse".into(), "--".into(), "@world".into(), ], )?; // A system with the NVIDIA out-of-tree driver must rebuild its // modules against any newly installed kernel and regenerate the // initramfs, so modules, userspace libraries and the boot image stay // coherent before the next reboot. The record is written by the // installer (or by the installed system's driver setup). if root.join("etc/phoebus/nvidia").is_file() { run_in_target( exec, root, "sys", "rebuild NVIDIA modules", "emerge", &["@module-rebuild".into()], )?; run_in_target( exec, root, "sys", "regenerate the initramfs", "kernel-install", &["add-all".into()], )?; // Do not report success unless the rebuilt modules exist for a // kernel; an update that installed a kernel but no matching // NVIDIA modules must fail loudly, not silently boot degraded. crate::boot::verify_nvidia_modules(root)?; // The previous kernels and their module trees are left in // place, so a failed update still has a bootable, coherent // generation to fall back to. } "system update complete".to_string() } SystemAction::CreateSnapshot { operation } => { let auth = auth.ok_or_else(|| ExecError::NotAuthorized(action.describe()))?; let source = root.to_string_lossy().to_string(); let record = snapshot::create_and_record(exec, auth, root, &source, operation)?; snapshot_id = Some(record.id.clone()); format!("snapshot created: {}", record.id) } // Handled before the match (it has its own snapshot/safety path). SystemAction::Undo { .. } => "rollback handled by the dedicated path".to_string(), 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 overview = crate::update::check_unified_updates(exec, root); overview.render() } SystemAction::History => { let history = snapshot::read_history(root)?; let mut s = String::new(); if history.records.is_empty() { s.push_str("no snapshot history\n"); } else { s.push_str("snapshots:\n"); for r in &history.records { s.push_str(&format!("{:<40} {:<16?} {}\n", r.id, r.status, r.operation)); } } let log = crate::transaction::read(root)?; s.push_str("transactions:\n"); s.push_str(&log.render()); s } SystemAction::RollbackStatus => { // Reading the state may also promote an activated rollback to // verified once the restored root is the running root. let state = crate::rollback::verify(exec, root)?; format!( "status: {:?}\nroot subvolume: {}\n/var subvolume: {}\ntarget: {}\nnote: {}", state.status, state.root_subvol, state.var_subvol.as_deref().unwrap_or("(none)"), state.target_snapshot, state.note ) } }; 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::transaction::ActionStatus; use phoebus_core::Redactor; use std::time::Duration; const PRETEND_VIM: &str = "\ These are the packages that would be merged, in order: Calculating dependencies... done! [ebuild N ] app-editors/vim-9.1.0 Total: 1 package (1 new), Size of downloads: 1,024 KiB "; const PRETEND_WGET: &str = "\ These are the packages that would be merged, in order: Calculating dependencies... done! [ebuild N ] net-misc/wget-1.24.5 Total: 1 package (1 new), Size of downloads: 512 KiB "; 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) } fn auth() -> DestructiveAuthorization { crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap() } fn response(stdout: &str) -> CommandOutput { CommandOutput { status: 0, success: true, stdout: stdout.as_bytes().to_vec(), stderr: Vec::new(), duration: Duration::from_millis(1), } } fn emerge_calls(specs: &[CommandSpec]) -> Vec<&CommandSpec> { specs .iter() .filter(|s| s.program == "emerge" || s.args.iter().any(|a| a == "emerge")) .collect() } #[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 = auth(); execute( &exec, &SystemAction::UpdateSystem, Some(&auth), Path::new(&exec.root), ) .unwrap(); let specs = runner.recorded(); let btrfs = specs .iter() .position(|s| s.program == "btrfs") .expect("snapshot"); let emerge = specs .iter() .position(|s| s.program == "emerge" || s.args.iter().any(|a| a == "emerge")) .expect("emerge"); assert!( btrfs < emerge, "protective snapshot must precede the mutation: {:?}", runner.programs() ); } #[test] fn updating_an_nvidia_system_rebuilds_modules_and_the_initramfs() { let runner = RecordingRunner::new(); let exec = make_exec(runner.clone()); std::fs::create_dir_all(exec.root.join("etc/phoebus")).unwrap(); std::fs::write(exec.root.join("etc/phoebus/nvidia"), "branch=current\n").unwrap(); std::fs::create_dir_all(exec.root.join(snapshot::SNAPSHOT_DIR)).unwrap(); // The rebuilt modules exist for the activated kernel. let modules = exec.root.join("lib/modules/6.18.48"); std::fs::create_dir_all(&modules).unwrap(); std::fs::write(modules.join("modules.dep"), b"").unwrap(); for m in ["nvidia", "nvidia_modeset", "nvidia_uvm", "nvidia_drm"] { std::fs::write(modules.join(format!("{m}.ko")), b"x").unwrap(); } let auth = auth(); execute( &exec, &SystemAction::UpdateSystem, Some(&auth), Path::new(&exec.root), ) .unwrap(); let specs = runner.recorded(); assert!( specs .iter() .any(|s| s.args.iter().any(|a| a == "@module-rebuild")), "the NVIDIA modules must be rebuilt after a kernel update" ); assert!( specs .iter() .any(|s| s.args.iter().any(|a| a == "kernel-install")), "the initramfs must be regenerated with the rebuilt modules" ); } #[test] fn an_nvidia_update_that_produced_no_modules_fails() { let runner = RecordingRunner::new(); let exec = make_exec(runner.clone()); std::fs::create_dir_all(exec.root.join("etc/phoebus")).unwrap(); std::fs::write(exec.root.join("etc/phoebus/nvidia"), "branch=current\n").unwrap(); std::fs::create_dir_all(exec.root.join(snapshot::SNAPSHOT_DIR)).unwrap(); let auth = auth(); let err = execute( &exec, &SystemAction::UpdateSystem, Some(&auth), Path::new(&exec.root), ) .unwrap_err() .to_string(); assert!(err.contains("NVIDIA"), "{err}"); } #[test] fn protective_snapshot_id_is_preserved_in_the_outcome() { let runner = RecordingRunner::new(); let exec = make_exec(runner.clone()); std::fs::create_dir_all(exec.root.join(snapshot::SNAPSHOT_DIR)).unwrap(); let auth = auth(); let outcome = execute( &exec, &SystemAction::UpdateSystem, Some(&auth), Path::new(&exec.root), ) .unwrap(); // The generic protective-snapshot path must report its id, not drop it. assert!(outcome.snapshot.is_some(), "protective snapshot id lost"); } #[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 = auth(); 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 = auth(); let action = SystemAction::RemovePackage { atom: "vim".into() }; execute(&exec, &action, Some(&auth), Path::new(&exec.root)).unwrap(); let recorded = runner.recorded(); let spec = emerge_calls(&recorded)[0]; assert!(spec.args.contains(&"--unmerge".to_string())); assert!(spec.args.contains(&"vim".to_string())); // The operand follows the option terminator. assert!(spec.args.windows(2).any(|w| w[0] == "--" && w[1] == "vim")); } #[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 recorded = runner.recorded(); let spec = emerge_calls(&recorded)[0]; assert!(spec.args.contains(&"--search".to_string())); assert!(spec.args.contains(&"firefox".to_string())); assert!(spec .args .windows(2) .any(|w| w[0] == "--" && w[1] == "firefox")); } #[test] fn enable_builds_separate_arguments() { let runner = RecordingRunner::new(); let exec = make_exec(runner.clone()); 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"]); } #[test] fn service_lifecycle_runs_on_the_host() { for (action, verb) in [ ( SystemAction::StartService { name: "sshd".into(), }, "start", ), ( SystemAction::StopService { name: "sshd".into(), }, "stop", ), ( SystemAction::RestartService { name: "sshd".into(), }, "restart", ), ] { let runner = RecordingRunner::new(); let exec = make_exec(runner.clone()); execute(&exec, &action, Some(&auth()), Path::new("/")).unwrap(); let spec = &runner.recorded()[0]; assert_eq!(spec.program, "systemctl"); assert_eq!(spec.args, vec![verb.to_string(), "sshd".to_string()]); } } #[test] fn service_enable_on_an_alternate_root_uses_root_flag() { let runner = RecordingRunner::new(); let exec = make_exec(runner.clone()); let root = Path::new("/tmp/phoebus-alt"); execute( &exec, &SystemAction::EnableService { name: "sshd".into(), }, Some(&auth()), root, ) .unwrap(); let spec = &runner.recorded()[0]; assert_eq!(spec.program, "systemctl"); assert_eq!( spec.args, vec!["--root", "/tmp/phoebus-alt", "enable", "sshd"] ); } #[test] fn runtime_service_operations_reject_an_alternate_root() { let root = Path::new("/tmp/phoebus-alt"); for action in [ SystemAction::InspectService { name: "sshd".into(), }, SystemAction::StartService { name: "sshd".into(), }, SystemAction::StopService { name: "sshd".into(), }, SystemAction::RestartService { name: "sshd".into(), }, ] { let runner = RecordingRunner::new(); let exec = make_exec(runner.clone()); let err = execute(&exec, &action, Some(&auth()), root).unwrap_err(); assert!( err.to_string().contains("cannot target the alternate root"), "got {err}" ); // Nothing may be invoked against the host. assert!(runner.recorded().is_empty(), "{:?}", runner.programs()); } } #[test] fn preview_and_execution_use_the_same_alternate_root() { let runner = RecordingRunner::new(); runner.set_response("chroot", response(PRETEND_VIM)); let exec = make_exec(runner.clone()); let root = Path::new("/mnt/phoebus-target"); let action = SystemAction::InstallPackage { atom: "app-editors/vim".into(), binary: None, }; let plan = resolve_effects(&exec, &action, root).unwrap(); assert!(!plan.effects.is_empty()); let outcome = execute_checked(&exec, &action, Some(&auth()), root, Some(&plan)).unwrap(); assert!(outcome.output.contains("installed")); let recorded = runner.recorded(); let calls = emerge_calls(&recorded); assert!(calls.len() >= 2, "preview + execution: {:?}", calls); for spec in calls { assert_eq!(spec.program, "chroot", "execution escaped the target"); assert_eq!(spec.args[0], "/mnt/phoebus-target"); } } #[test] fn execution_validates_before_any_command() { let runner = RecordingRunner::new(); let exec = make_exec(runner.clone()); let action = SystemAction::InstallPackage { atom: "--color=n".into(), binary: None, }; // The read path refuses too. assert!(resolve_effects(&exec, &action, Path::new("/")).is_err()); let err = execute(&exec, &action, Some(&auth()), Path::new("/")).unwrap_err(); assert!(err.to_string().contains("invalid"), "got {err}"); assert!(runner.recorded().is_empty()); } #[test] fn resolve_effects_refuses_unparseable_output() { let runner = RecordingRunner::new(); runner.set_response("emerge", response("something went sideways\n")); let exec = make_exec(runner.clone()); let action = SystemAction::InstallPackage { atom: "app-editors/vim".into(), binary: None, }; let err = resolve_effects(&exec, &action, Path::new("/")).unwrap_err(); assert!(err.to_string().contains("could not establish"), "got {err}"); } #[test] fn resolve_effects_accepts_a_genuinely_empty_plan() { let runner = RecordingRunner::new(); runner.set_response( "emerge", response("Calculating dependencies... done!\n\nTotal: 0 packages\n"), ); let exec = make_exec(runner.clone()); let action = SystemAction::InstallPackage { atom: "app-editors/vim".into(), binary: None, }; let plan = resolve_effects(&exec, &action, Path::new("/")).unwrap(); assert!(plan.effects.is_empty()); assert!(plan.established); } #[test] fn a_material_change_invalidates_the_reviewed_plan() { let runner = RecordingRunner::new(); runner.set_response("emerge", response(PRETEND_WGET)); let exec = make_exec(runner.clone()); let approved = phoebus_core::effects::parse_emerge_pretend(PRETEND_VIM); let action = SystemAction::InstallPackage { atom: "net-misc/wget".into(), binary: None, }; let err = execute_checked( &exec, &action, Some(&auth()), Path::new("/"), Some(&approved), ) .unwrap_err(); assert!(err.to_string().contains("plan changed"), "got {err}"); // The unapproved mutation must not run. assert!(!runner .recorded() .iter() .any(|s| s.args.iter().any(|a| a == "--ask=n"))); } #[test] fn plan_stops_at_the_first_failure_and_marks_the_rest_unattempted() { let runner = RecordingRunner::new(); runner.fail("emerge", "boom"); let exec = make_exec(runner.clone()); let steps = vec![ (SystemAction::History, ResolvedPlan::default()), ( SystemAction::InstallPackage { atom: "app-editors/vim".into(), binary: None, }, ResolvedPlan::default(), ), ( SystemAction::EnableService { name: "sshd".into(), }, ResolvedPlan::default(), ), ]; let run = execute_plan(&exec, &steps, Some(&auth()), Path::new("/")); assert_eq!(run.completed.len(), 1); assert!(run.failure.is_some()); assert_eq!(run.outcomes.len(), 3); assert_eq!(run.outcomes[0].status, ActionStatus::Completed); assert_eq!(run.outcomes[1].status, ActionStatus::Failed); assert_eq!(run.outcomes[2].status, ActionStatus::Unattempted); // The third action must never reach the system. assert!(!runner.programs().iter().any(|p| p == "systemctl")); } #[test] fn undo_requires_authorization() { let runner = RecordingRunner::new(); let exec = make_exec(runner); let action = SystemAction::Undo { snapshot: None }; let err = execute(&exec, &action, None, Path::new(&exec.root)).unwrap_err(); assert!(matches!(err, ExecError::NotAuthorized(_))); } #[test] fn rollback_status_reports_default_state() { let runner = RecordingRunner::new(); let exec = make_exec(runner); let action = SystemAction::RollbackStatus; let outcome = execute(&exec, &action, None, Path::new(&exec.root)).unwrap(); assert!(outcome.output.contains("Idle")); assert!(outcome.snapshot.is_none()); } }