//! 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, CleanupEffect, EffectKind, EffectSource, PackageEffect, ResolvedPlan, UpdateSource, UpdateTransaction, }; use phoebus_core::selection::{Backend, 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"); } // Source conversions and the tuned kernel carry their full review // (exact packages, expected time, temporary disk, power/network, // proposed changes) so the explicit approval step is informed. match action { SystemAction::ConvertToSource { app } => { if let Some(conv) = phoebus_core::fastinstall::source_conversion(app) { out.push('\n'); out.push_str(&phoebus_core::fastinstall::source_conversion_review(conv)); } } SystemAction::BuildTunedKernel { .. } => { out.push('\n'); out.push_str(&phoebus_core::fastinstall::tuned_kernel_review( &phoebus_core::fastinstall::tuned_kernel_plan(), )); } SystemAction::BuildBalancedKernel { .. } => { out.push('\n'); out.push_str(&phoebus_core::fastinstall::balanced_kernel_review( &phoebus_core::fastinstall::balanced_kernel_plan(), )); } _ => {} } 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. pub(crate) fn target_spec( root: &Path, stage: &str, operation: &str, program: &str, args: &[String], ) -> CommandSpec { if is_host_root(root) { let spec = CommandSpec::new(stage, operation, program).args(args.iter().cloned()); // A Flatpak probe/operation can trigger a privileged appstream refresh // that prompts for a password; run it without a controlling terminal so // it can never block. Other programs keep the console. if program == "flatpak" { spec.detached() } else { spec } } 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).show_output()) } /// 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(), ]), // Source conversions and the tuned kernel resolve the same pretend // plan as a Portage install of their source atom, so the reviewed // effects stay comparable at the execution boundary. SystemAction::ConvertToSource { app } => { let conv = phoebus_core::fastinstall::source_conversion(app)?; Some(vec![ "--pretend".into(), "--color=n".into(), "--".into(), conv.source_atom.to_string(), ]) } SystemAction::BuildTunedKernel { .. } => Some(vec![ "--pretend".into(), "--color=n".into(), "--".into(), "sys-kernel/gentoo-kernel".into(), ]), SystemAction::BuildBalancedKernel { .. } => Some(vec![ "--pretend".into(), "--color=n".into(), "--".into(), "sys-kernel/gentoo-kernel".into(), ]), _ => None, } } /// Whether a Portage atom has a VDB record under `root` (installed). fn vdb_has_atom(root: &Path, atom: &str) -> bool { // Normalize first: a versioned/slotted atom (`=app-editors/vim-9.0.2167`, // `dev-libs/openssl:0/1.1`) must resolve to the same `category/name` VDB // directory as the bare atom. let normalized = portage::normalize_dep_atom(atom); let (category, package) = match normalized.split_once('/') { Some((c, p)) => (c, p), None => return false, }; let dir = root.join("var/db/pkg").join(category); let Ok(entries) = std::fs::read_dir(&dir) else { return false; }; entries.flatten().any(|e| { let name = e.file_name().to_string_lossy().to_string(); if name == package { return true; } match name.strip_prefix(&format!("{package}-")) { // A Gentoo version begins with a digit. Requiring it stops a // sibling package (`gentoo-kernel-bin-…`) from matching the // prefix `gentoo-kernel-…`. Some(rest) => rest.chars().next().is_some_and(|c| c.is_ascii_digit()), None => false, } }) } /// Whether a Flatpak app id is installed system-wide under `root`. fn flatpak_has_app(exec: &Exec, root: &Path, app_id: &str) -> bool { let Ok(out) = capture_in_target( exec, root, "sys", "check flatpak app", "flatpak", &[ "list".into(), "--app".into(), "--columns=application".into(), ], ) else { return false; }; out.stdout_lossy().lines().any(|l| l.trim() == app_id) } /// Replace a fast-default prebuilt application with its maintained source /// alternative. /// /// Safety order (the working application is never removed first): /// 1. Check blockers/dependencies with `emerge --pretend` (reviewed plan). /// 2. Build the source as a binary package (`--buildpkgonly`) without /// touching the live system; a failed build leaves the working copy. /// 3. Remove the old copy only after the build succeeds (and only when it /// is actually installed; user data and desktop defaults are preserved — /// neither `--unmerge` nor `flatpak remove` touches home directories or /// the shared `mimeapps.list`). /// 4. Install the new build from the just-built package and verify the VDB /// record; a verification failure is reported, never silent. fn convert_to_source(exec: &Exec, root: &Path, app: &str) -> Result { let conv = phoebus_core::fastinstall::source_conversion(app).ok_or_else(|| { if app.eq_ignore_ascii_case("brave") { ExecError::operation( "sys", "build from source", phoebus_core::fastinstall::brave_source_status(), ) } else { ExecError::operation( "sys", "build from source", format!("no supported source build for `{app}`"), ) } })?; // 1. Blockers and dependencies first: the pretend plan is the reviewed // evidence; an unresolvable plan aborts before anything is built. let pretend = SystemAction::InstallPackage { atom: conv.source_atom.to_string(), binary: None, }; let plan = resolve_effects(exec, &pretend, root)?; if !plan.established { return Err(ExecError::operation( "sys", "build from source", format!( "could not establish the build plan for {}; refusing to proceed unreviewed", conv.source_atom ), )); } // 2. Build without installing. A failure here leaves the working // application exactly as it was. run_in_target( exec, root, "sys", "build from source", "emerge", &[ "--ask=n".into(), "--buildpkgonly".into(), "--".into(), conv.source_atom.to_string(), ], ) .map_err(|e| { ExecError::operation( "sys", "build from source", format!( "the source build of {} failed; the working copy ({}) is still installed: {e}", conv.source_atom, conv.installed_from ), ) })?; // 3. Remove the old copy only now. Data-preserving removals only. let old_is_flatpak = conv.installed_from.contains('.') && !conv.installed_from.contains('/'); if old_is_flatpak { // `installed_from` is prose ("com.x (Flatpak)"); extract the id. let id = conv .installed_from .split_whitespace() .next() .unwrap_or(conv.installed_from); if flatpak_has_app(exec, root, id) { run_in_target( exec, root, "sys", "remove replaced flatpak", "flatpak", &[ "remove".into(), "-y".into(), "--system".into(), "--".into(), id.into(), ], )?; } } else if vdb_has_atom(root, conv.installed_from) { run_in_target( exec, root, "sys", "remove replaced binary package", "emerge", &[ "--unmerge".into(), "--ask=n".into(), "--".into(), conv.installed_from.to_string(), ], )?; } // 4. Install the verified build and confirm the VDB record. run_in_target( exec, root, "sys", "install source build", "emerge", &[ "--ask=n".into(), "--usepkg=y".into(), "--".into(), conv.source_atom.to_string(), ], )?; if !vdb_has_atom(root, conv.source_atom) { return Err(ExecError::operation( "sys", "build from source", format!( "the build of {} did not verify in the package database; \ the previous copy was already removed — restore the protective snapshot", conv.source_atom ), )); } Ok(format!( "built {} from source ({}) and verified the installation; user data preserved", conv.app, conv.source_atom )) } /// /// Portage transactions resolve from `emerge --pretend`; the maintenance /// actions (depclean, per-source updates, cache cleanup) resolve a structured, /// digest-bound plan too. Callers that compare a re-resolution against a /// reviewed plan must use this to avoid treating a "no comparable plan" result /// as material drift. pub fn resolves_effects(action: &SystemAction) -> bool { pretend_args(action).is_some() || matches!( action, SystemAction::Depclean | SystemAction::ApplyUpdates { .. } | SystemAction::CleanCache { .. } ) } /// Resolve exactly what a package or maintenance action will do. A plan's /// digest is bound to the approval and re-checked immediately before execution. pub fn resolve_effects(exec: &Exec, action: &SystemAction, root: &Path) -> Result { action .validate() .map_err(|e| ExecError::operation("sys", "validate action", e))?; match action { SystemAction::Depclean => return resolve_depclean_effects(exec, root), SystemAction::ApplyUpdates { backend } => { return resolve_update_effects(exec, root, *backend); } SystemAction::CleanCache { backend } => { return resolve_cleanup_effects(exec, root, *backend); } _ => {} } let Some(args) = pretend_args(action) else { // An unsupported source conversion fails closed here — before any // approval is requested and before any command runs — with the exact // reason (including Brave's missing source route). if let SystemAction::ConvertToSource { app } = action { if app.eq_ignore_ascii_case("brave") { return Err(ExecError::operation( "sys", "resolve effects", phoebus_core::fastinstall::brave_source_status(), )); } return Err(ExecError::operation( "sys", "resolve effects", format!("no supported source build for `{app}`"), )); } 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 == 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) } /// Depclean removals are parsed into structured effects, not only prose, so a /// changed removal set changes the approved digest and is caught before /// execution. fn resolve_depclean_effects(exec: &Exec, root: &Path) -> Result { let spec = target_spec( root, "sys", "resolve depclean", "emerge", &["--pretend".into(), "--depclean".into(), "--color=n".into()], ); let out = exec.run_capture(spec)?; let mut plan = parse_emerge_pretend(&out.stdout_lossy()); if !plan.established { return Err(ExecError::operation( "sys", "resolve depclean", "could not establish the depclean selection from emerge --pretend; \ refusing to proceed unreviewed", )); } if root.join(snapshot::SNAPSHOT_DIR).is_dir() { plan.recovery_point = Some("a protective snapshot before the change".into()); } plan.recompute_digest(); Ok(plan) } pub(crate) fn update_limitation(backend: Backend) -> &'static str { match backend { Backend::Nix => { "Nix packages are declarative/pinned; update them in their project or profile" } Backend::AppImage => { "managed AppImages have no update repository; re-acquire with a pinned URL + SHA-256" } Backend::CustomEbuild => "rebuild the staged ebuild through Portage explicitly", _ => "this source has no system-level update transaction", } } /// The flatpak client must answer in the intended target. fn flatpak_available(exec: &Exec, root: &Path) -> bool { crate::query::flatpak_available(exec, root) } /// Split a Flatpak `--columns=` row (tab-separated) or whitespace fallback. fn flatpak_cols(line: &str) -> Vec { if line.contains('\t') { line.split('\t').map(|s| s.trim().to_string()).collect() } else { line.split_whitespace().map(|s| s.to_string()).collect() } } /// Parse `flatpak info --system `: the installed `Version`, the installed /// `Active commit` and the remote `Latest commit`. Flatpak's `--columns=commit` /// truncates to 12 characters, so `info` is used for full immutable commits. pub(crate) fn parse_flatpak_info(text: &str) -> (Option, Option, Option) { fn nonempty(value: &str) -> Option { let value = value.trim(); if value.is_empty() { None } else { Some(value.to_string()) } } let (mut version, mut active, mut latest) = (None, None, None); for line in text.lines() { let t = line.trim(); if let Some(v) = t.strip_prefix("Version:") { version = nonempty(v); } else if let Some(v) = t.strip_prefix("Active commit:") { active = nonempty(v); } else if let Some(v) = t.strip_prefix("Latest commit:") { latest = nonempty(v); } } (version, active, latest) } /// Resolve the exact Flatpak update transactions for the target. /// /// `remote-ls` provides the remote refs with updates and their latest version; /// `flatpak info` supplies the installed and remote full commits. A transaction /// is `exact` only when both commits are known; otherwise the source is refused /// rather than approximated. pub(crate) fn flatpak_update_transactions( exec: &Exec, root: &Path, ) -> Result> { if !flatpak_available(exec, root) { return Err(ExecError::operation( "sys", "resolve flatpak updates", "the Flatpak client is not available in the target", )); } let updates = exec .runner .execute(&target_spec( root, "sys", "resolve flatpak updates", "flatpak", &[ "remote-ls".into(), "--system".into(), "--updates".into(), "--columns=ref,version".into(), ], )) .map_err(|e| { ExecError::operation( "sys", "resolve flatpak updates", format!("flatpak remote-ls could not run: {e}"), ) })?; if !updates.success { return Err(ExecError::operation( "sys", "resolve flatpak updates", format!( "flatpak remote-ls failed: {}", updates.stderr_lossy().trim() ), )); } let mut txns = Vec::new(); for line in updates.stdout_lossy().lines() { if line.trim().is_empty() { continue; } let cols = flatpak_cols(line); let Some(identity) = cols.first().filter(|s| !s.is_empty()).cloned() else { continue; }; // `remote-ls` reports refs with the `app/`/`runtime/` type prefix, which // is exactly what `flatpak info` and `flatpak update --commit` accept. let next_version = cols.get(1).cloned().unwrap_or_default(); let info = exec .runner .execute(&target_spec( root, "sys", "resolve flatpak updates", "flatpak", &["info".into(), "--system".into(), identity.to_string()], )) .map_err(|e| { ExecError::operation( "sys", "resolve flatpak updates", format!("flatpak info {identity} could not run: {e}"), ) })?; if !info.success { return Err(ExecError::operation( "sys", "resolve flatpak updates", format!( "flatpak info {identity} failed: {}", info.stderr_lossy().trim() ), )); } let (installed_version, active, latest) = parse_flatpak_info(&info.stdout_lossy()); txns.push(UpdateTransaction { source: UpdateSource::Flatpak, identity, previous_version: installed_version, next_version, previous_revision: active, next_revision: latest, scope: Some("system".to_string()), related: Vec::new(), exact: false, }); } // `remote-ls --system` covers the system installation only. If the user // installation also has applications, we cannot bind their updates here, // so refuse the operation rather than approve an incomplete transaction. let user_apps = exec.runner.execute(&target_spec( root, "sys", "resolve flatpak updates", "flatpak", &["list".into(), "--user".into(), "--columns=ref".into()], )); let user_present = matches!(&user_apps, Ok(o) if o.success && !o.stdout_lossy().trim().is_empty()); for txn in &mut txns { txn.exact = txn.next_revision.is_some() && txn.previous_revision.is_some() && !user_present; } txns.sort_by(|a, b| a.identity.cmp(&b.identity)); Ok(txns) } /// Parse `snap refresh --list` and `snap list` output into exact update /// transactions. Columns: `Name Version Rev Tracking Publisher Notes`; the /// revision is the immutable identity and the tracking channel is the scope. pub(crate) fn parse_snap_transactions(refresh: &str, installed: &str) -> Vec { use std::collections::BTreeMap; /// Installed snap entry: (version, revision, tracking, notes). type InstalledSnapEntry = (Option, Option, Option, String); // name -> (version, revision, tracking, notes) let mut current: BTreeMap = BTreeMap::new(); for line in installed.lines().skip(1) { let cols: Vec<&str> = line.split_whitespace().collect(); if cols.len() < 4 || cols[0].is_empty() { continue; } current.insert( cols[0].to_string(), ( Some(cols[1].to_string()), Some(cols[2].to_string()), Some(cols[3].to_string()), cols.get(5..).map(|n| n.join(" ")).unwrap_or_default(), ), ); } let mut txns = Vec::new(); for line in refresh.lines().skip(1) { let cols: Vec<&str> = line.split_whitespace().collect(); if cols.len() < 3 || cols[0].is_empty() { continue; } let name = cols[0].to_string(); let previous = current.get(&name); let mut related = Vec::new(); if let Some((_, _, _, notes)) = previous { if !notes.trim().is_empty() { related.push(format!("notes: {notes}")); } } txns.push(UpdateTransaction { source: UpdateSource::Snap, identity: name, previous_version: previous.and_then(|(v, _, _, _)| v.clone()), next_version: cols[1].to_string(), previous_revision: previous.and_then(|(_, r, _, _)| r.clone()), next_revision: Some(cols[2].to_string()), scope: Some(cols[3].to_string()), related, exact: !cols[2].is_empty(), }); } txns.sort_by(|a, b| a.identity.cmp(&b.identity)); txns } /// Resolve the exact Snap update transactions. Snaps act on the running /// daemon, so an alternate root is refused before any command is issued. pub(crate) fn snap_update_transactions(exec: &Exec, root: &Path) -> Result> { if !is_host_root(root) { return Err(ExecError::operation( "sys", "resolve snap updates", "Snap acts on the running daemon and cannot be redirected to an alternate root; \ refusing to touch the host", )); } let status = snap::status(exec)?; if !status.usable() { return Err(ExecError::operation( "sys", "resolve snap updates", "snapd is not installed or active", )); } let refresh = exec.runner.execute( &CommandSpec::new("sys", "resolve snap updates", "snap").args(["refresh", "--list"]), )?; if !refresh.success { return Err(ExecError::operation( "sys", "resolve snap updates", format!( "snap refresh --list failed: {}", refresh.stderr_lossy().trim() ), )); } let installed = exec .runner .execute(&CommandSpec::new("sys", "resolve snap updates", "snap").args(["list"]))?; if !installed.success { return Err(ExecError::operation( "sys", "resolve snap updates", format!("snap list failed: {}", installed.stderr_lossy().trim()), )); } Ok(parse_snap_transactions( &refresh.stdout_lossy(), &installed.stdout_lossy(), )) } /// The human-readable `PackageEffect` summary for a set of update transactions. fn update_effect_summary(txns: &[UpdateTransaction]) -> Vec { txns.iter() .map(|txn| PackageEffect { target: format!("{}-{}", txn.identity, txn.next_version), previous: txn.previous_version.clone(), kind: EffectKind::Upgrade, source: EffectSource::Binary, }) .collect() } /// Resolve a reviewable, per-source update plan. Each lane contributes exact /// affected identities (and versions where the backend reports them). A lane /// that cannot be updated deterministically is refused when explicitly /// requested, never silently skipped. fn resolve_update_effects( exec: &Exec, root: &Path, backend: Option, ) -> Result { let lanes: Vec = match backend { Some(backend) => vec![backend], None => vec![Backend::PortageSource, Backend::Flatpak, Backend::Snap], }; let mut plan = ResolvedPlan { established: true, ..Default::default() }; for lane in lanes { if lane.is_portage() { let spec = target_spec( root, "sys", "resolve updates", "emerge", &[ "--pretend".into(), "--update".into(), "--deep".into(), "--newuse".into(), "--color=n".into(), "--".into(), "@world".into(), ], ); let out = exec.run_capture(spec)?; let parsed = parse_emerge_pretend(&out.stdout_lossy()); if !parsed.established { return Err(ExecError::operation( "sys", "resolve updates", "could not establish the update plan from emerge --pretend; \ refusing to proceed unreviewed", )); } plan.effects.extend(parsed.effects); if let Some(bytes) = parsed.download_bytes { *plan.download_bytes.get_or_insert(0) += bytes; } plan.consequences.extend(parsed.consequences); } else if lane == Backend::Flatpak { match flatpak_update_transactions(exec, root) { Ok(txns) => { plan.effects.extend(update_effect_summary(&txns)); plan.updates.extend(txns); } Err(e) if backend.is_none() => plan .consequences .push(format!("[flatpak] updates could not be resolved: {e}")), Err(e) => return Err(e), } } else if lane == Backend::Snap { match snap_update_transactions(exec, root) { Ok(txns) => { plan.effects.extend(update_effect_summary(&txns)); plan.updates.extend(txns); } Err(e) if backend.is_none() => plan .consequences .push(format!("[snap] updates could not be resolved: {e}")), Err(e) => return Err(e), } } else { // Not in the default set; only reachable when explicitly requested. return Err(ExecError::operation( "sys", "resolve updates", format!( "{} updates cannot be applied safely by `sys`: {}", lane.as_str(), update_limitation(lane) ), )); } } if backend.is_none() { plan.consequences.push( "Nix, managed AppImages and custom ebuilds are project- or format-specific and are \ not part of this update transaction" .into(), ); } if plan.effects.is_empty() { plan.consequences.push("no updates are available".into()); } if root.join(snapshot::SNAPSHOT_DIR).is_dir() { plan.recovery_point = Some("a protective snapshot before the change".into()); } plan.recompute_digest(); Ok(plan) } /// The cache cleaners for a lane, as `(cleaner, preview args, destructive args)`. /// /// `eclean-dist`/`eclean-pkg` **delete by default**; only `--pretend` previews /// (verified against the upstream `gentoolkit` CLI). The preview therefore /// passes `--pretend` explicitly, and both the preview and the destructive run /// use the *same* selection policy (`--deep`), so what is reviewed is exactly /// what is removed. pub(crate) fn portage_cleaners(root: &Path) -> Vec<(&'static str, Vec, Vec)> { let mut cleaners = Vec::new(); for cleaner in ["eclean-dist", "eclean-pkg"] { if crate::exec::tool_in_target(root, cleaner) { cleaners.push(( cleaner, vec!["--pretend".to_string(), "--deep".to_string()], vec!["--deep".to_string()], )); } } cleaners } /// Collect the items a cleaner reported, from *both* streams. /// /// The upstream tools do not guarantee which stream the reviewable list lands /// on, so stdout and stderr are combined; only non-empty, trimmed lines become /// bound items. fn cleanup_items(output: &CommandOutput) -> Vec { let mut text = output.stdout_lossy(); if !output.stderr.is_empty() { if !text.is_empty() && !text.ends_with('\n') { text.push('\n'); } text.push_str(&output.stderr_lossy()); } let mut items: Vec = text .lines() .map(str::trim) .filter(|l| !l.is_empty()) .map(str::to_string) .collect(); // The upstream cleaner does not guarantee output order; sort and dedupe so // two previews of the same selection bind to the same digest. items.sort(); items.dedup(); items } /// Resolve a reviewable cache-cleanup plan from non-destructive dry runs. A /// cleaner that cannot run is recorded as unavailable, distinct from one that /// ran and found nothing. fn resolve_cleanup_effects( exec: &Exec, root: &Path, backend: Option, ) -> Result { let lanes: Vec = match backend { Some(backend) => vec![backend], None => vec![Backend::PortageSource, Backend::Nix], }; let mut plan = ResolvedPlan { established: true, ..Default::default() }; for lane in lanes { if lane.is_portage() { for (cleaner, preview_args, _) in portage_cleaners(root) { let out = exec.runner.execute(&target_spec( root, "sys", "resolve cache cleanup", cleaner, &preview_args, )); match out { Ok(output) if output.success => { plan.cleanup.push(CleanupEffect { cleaner: cleaner.to_string(), items: cleanup_items(&output), unavailable: false, }); } Ok(output) => { return Err(ExecError::operation( "sys", "resolve cache cleanup", format!("{cleaner} preview failed: {}", output.stderr_lossy().trim()), )); } Err(e) => { return Err(ExecError::operation( "sys", "resolve cache cleanup", format!("{cleaner} preview could not run: {e}"), )); } } } } else if lane == Backend::Nix { if !crate::nix::installed(root) { plan.cleanup.push(CleanupEffect { cleaner: "nix-store --gc".into(), items: Vec::new(), unavailable: true, }); } else { // `nix-store --gc` deletes by default; the documented, // non-destructive preview is `--print-dead` (the `--dry-run` // global is not documented for the `--gc` operation). let out = exec.runner.execute(&target_spec( root, "sys", "resolve cache cleanup", "/nix/var/nix/profiles/default/bin/nix-store", &["--gc".into(), "--print-dead".into()], )); match out { Ok(output) if output.success => { plan.cleanup.push(CleanupEffect { cleaner: "nix-store --gc".into(), items: cleanup_items(&output), unavailable: false, }); } Ok(output) => { return Err(ExecError::operation( "sys", "resolve cache cleanup", format!( "nix-store --gc preview failed: {}", output.stderr_lossy().trim() ), )); } Err(e) => { return Err(ExecError::operation( "sys", "resolve cache cleanup", format!("nix-store --gc preview could not run: {e}"), )); } } } } else { return Err(ExecError::operation( "sys", "resolve cache cleanup", format!( "the {} lane has no package cache to clean; refusing", lane.as_str() ), )); } } if plan.cleanup.is_empty() { plan.consequences .push("no cache cleaner is available in the target".into()); } plan.recompute_digest(); 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 { let current = 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)] ), )); } Some(current) } else { None }; execute_inner(exec, action, auth, root, current.as_ref()) } /// 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 } /// Update the whole Portage world, then rebuild the NVIDIA out-of-tree modules /// and the initramfs when the driver is installed. Shared by `update_system` /// and `apply_updates` so both paths stay coherent. pub(crate) fn portage_world_update(exec: &Exec, root: &Path) -> Result<()> { 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. } Ok(()) } pub fn execute( exec: &Exec, action: &SystemAction, auth: Option<&DestructiveAuthorization>, root: &Path, ) -> Result { execute_inner(exec, action, auth, root, None) } /// Execute an action, optionally carrying the reviewed plan through to /// execution. Actions whose mutation must equal the reviewed transaction /// (Flatpak/Snap updates, cache cleanup) consume `resolved` instead of /// re-discovering state; without it they refuse the mutation rather than /// presenting approximate approval as exact. pub fn execute_inner( exec: &Exec, action: &SystemAction, auth: Option<&DestructiveAuthorization>, root: &Path, resolved: Option<&ResolvedPlan>, ) -> 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.requires_root() && auth.is_none() { return Err(ExecError::NotAuthorized(action.describe())); } // The global mutation lock is root-owned. Personal preferences are an // atomic user-file write and must remain usable by an unprivileged account. let _lock = if action.requires_root() && exec.is_real() && !exec.dry_run { Some(crate::system_lock::SystemLock::acquire( exec, root, &action.describe(), )?) } else { None }; // 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_set_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, backend } => { crate::query::search(exec, root, query, *backend).render() } SystemAction::FlatpakInstall { app_id } => { run_in_target( exec, root, "sys", "install flatpak", "flatpak", &[ "install".into(), "--system".into(), "--noninteractive".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(), "--system".into(), "--noninteractive".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, system_wide, } => { if *system_wide { // Root-owned system default: changed only through the broker. let mut prefs = chooser::load_system_preferences(root); match backend { Some(backend) => { prefs.per_app.insert(name.clone(), *backend); } None => { prefs.per_app.remove(name); } } chooser::save_system_preferences(exec, root, &prefs)?; match backend { Some(backend) => format!( "system-wide preference saved: {name} -> {}\n automatic selection applies \ again when the preferred lane is incompatible", backend.as_str() ), None => format!("system-wide preference cleared for {name}"), } } else { // Personal, unprivileged preference belonging to the invoking // user. Stored privately under their config directory. let storage = crate::personal::UserStorage::for_initiating_user(); let mut prefs = chooser::load_personal_preferences(&storage).unwrap_or_default(); match backend { Some(backend) => { prefs.per_app.insert(name.clone(), *backend); } None => { prefs.per_app.remove(name); } } chooser::save_personal_preferences(&storage, &prefs)?; match backend { Some(backend) => format!( "preference saved for your account: {name} -> {}\n automatic selection \ applies again when the preferred lane is incompatible", backend.as_str() ), None => 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")?; 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::NixInstall { packages } => { let installed = crate::nix::install_profile_packages(exec, root, packages)?; format!("installed into the Nix profile: {}", installed.join(", ")) } SystemAction::UpdateSystem => { portage_world_update(exec, root)?; "system update complete".to_string() } SystemAction::CheckUpdates { backend } => { crate::query::check_updates(exec, root, *backend).render() } SystemAction::ApplyUpdates { backend } => { crate::query::apply_updates(exec, root, *backend, resolved)? } SystemAction::ListPackages { backend, filter } => { crate::query::inventory(exec, root, *backend, filter.as_deref()).render() } SystemAction::PackageInfo { package, backend } => { crate::query::package_info(exec, root, package, *backend).render() } SystemAction::PackageOwners { path } => crate::query::package_owners(exec, root, path)?, SystemAction::PackageDependencies { package, reverse } => { crate::query::package_dependencies(exec, root, package, *reverse)? } SystemAction::Depclean => crate::query::depclean(exec, root)?, SystemAction::CleanCache { backend } => { crate::query::clean_cache(exec, root, *backend, resolved)? } 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 ) } SystemAction::SystemStatus => crate::query::system_status_report(exec, root)?, SystemAction::ConvertToSource { app } => convert_to_source(exec, root, app)?, SystemAction::BuildTunedKernel { make_default } => { crate::kernel::build_tuned_kernel(exec, root, *make_default)? } SystemAction::BuildBalancedKernel { make_default } => { crate::kernel::build_balanced_kernel(exec, root, *make_default)? } }; 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 snap_install_does_not_add_an_unreviewed_portage_dependency() { let runner = RecordingRunner::new(); let exec = make_exec(runner.clone()); let action = SystemAction::SnapInstall { name: "hello-world".into(), channel: None, classic: false, }; let err = execute(&exec, &action, Some(&auth()), Path::new("/")).unwrap_err(); assert!(err.to_string().contains("snapd is not ready"), "{err}"); assert!(emerge_calls(&runner.recorded()).is_empty()); } #[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!( specs[emerge].show_output, "Portage build output must be visible" ); 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(), backend: Some(phoebus_core::selection::Backend::PortageSource), }; 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 source_conversion_refuses_brave_with_the_reason_before_any_command() { let runner = RecordingRunner::new(); let exec = make_exec(runner.clone()); let action = SystemAction::ConvertToSource { app: "brave".into(), }; let err = resolve_effects(&exec, &action, Path::new("/")).unwrap_err(); assert!(err.to_string().contains("no trustworthy"), "got {err}"); assert!(runner.recorded().is_empty()); } #[test] fn source_conversion_refuses_unknown_apps_without_guessing() { let runner = RecordingRunner::new(); let exec = make_exec(runner.clone()); let action = SystemAction::ConvertToSource { app: "definitely-not-an-app".into(), }; let err = resolve_effects(&exec, &action, Path::new("/")).unwrap_err(); assert!( err.to_string().contains("no supported source build"), "got {err}" ); assert!(runner.recorded().is_empty()); } #[test] fn source_conversion_builds_before_removing_and_verifies() { let runner = RecordingRunner::new(); runner.set_response("chroot", response(PRETEND_VIM)); let exec = make_exec(runner.clone()); let root = exec.root.clone(); // Fixture VDB: the fast-default binary copy and (simulating a // verified install) the source copy. for dir in [ "var/db/pkg/www-client/firefox-bin-128.0", "var/db/pkg/www-client/firefox-128.0", ] { std::fs::create_dir_all(root.join(dir)).unwrap(); } let action = SystemAction::ConvertToSource { app: "firefox".into(), }; let plan = resolve_effects(&exec, &action, &root).unwrap(); assert!(plan.established); let outcome = execute(&exec, &action, Some(&auth()), &root).unwrap(); assert!( outcome.output.contains("verified the installation"), "{}", outcome.output ); // Safety order: the reviewed pretend, then the build-only step, and // only afterwards the removal of the old copy. let args: Vec = runner .recorded() .iter() .flat_map(|s| s.args.clone()) .collect(); let pretend = args .iter() .position(|a| a == "--pretend") .expect("pretend ran"); let build = args .iter() .position(|a| a == "--buildpkgonly") .expect("build ran"); let unmerge = args .iter() .position(|a| a == "--unmerge") .expect("old copy removed"); assert!(pretend < build && build < unmerge, "{args:?}"); } #[test] fn source_conversion_aborts_before_removal_when_the_plan_is_unresolvable() { let runner = RecordingRunner::new(); runner.set_response("chroot", response("something went sideways\n")); let exec = make_exec(runner.clone()); let root = exec.root.clone(); std::fs::create_dir_all(root.join("var/db/pkg/www-client/firefox-bin-128.0")).unwrap(); let action = SystemAction::ConvertToSource { app: "firefox".into(), }; let err = execute(&exec, &action, Some(&auth()), &root).unwrap_err(); assert!(err.to_string().contains("could not establish"), "got {err}"); // No build and no removal were attempted. let args: Vec = runner .recorded() .iter() .flat_map(|s| s.args.clone()) .collect(); assert!(!args.iter().any(|a| a == "--buildpkgonly"), "{args:?}"); assert!(!args.iter().any(|a| a == "--unmerge"), "{args:?}"); } #[test] fn conversion_and_kernel_previews_carry_the_full_review() { let text = preview(&SystemAction::ConvertToSource { app: "firefox".into(), }); assert!(text.contains("www-client/firefox"), "{text}"); assert!(text.contains("Temporary disk"), "{text}"); assert!( text.contains("leaves the working application installed"), "{text}" ); assert!( text.contains("not claimed to produce a noticeable speedup"), "{text}" ); let kernel = preview(&SystemAction::BuildTunedKernel { make_default: false, }); assert!(kernel.contains("sys-kernel/gentoo-kernel"), "{kernel}"); assert!(kernel.contains("gentoo-kernel-bin"), "{kernel}"); assert!(kernel.contains("never replaces the working"), "{kernel}"); } #[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()); } #[test] fn system_status_action_executes_cleanly() { let runner = RecordingRunner::new(); let exec = make_exec(runner); let action = SystemAction::SystemStatus; let outcome = execute(&exec, &action, None, Path::new(&exec.root)).unwrap(); assert!(outcome.output.contains("=== Phoebus System Status ===")); assert!(outcome.snapshot.is_none()); } #[test] fn depclean_is_previewed_as_structured_removals_at_review() { let runner = RecordingRunner::new(); runner.set_response( "emerge", CommandOutput { status: 0, success: true, stdout: b">>> These are the packages that would be unmerged:\n\n \ app-misc/unused\n selected: 1.0\n\n\ All selected packages: app-misc/unused-1.0\n\n\ >>> 'Selected' packages are slated for removal.\n" .to_vec(), stderr: Vec::new(), duration: std::time::Duration::from_millis(1), }, ); let exec = make_exec(runner); let plan = resolve_effects(&exec, &SystemAction::Depclean, Path::new("/")).unwrap(); assert!(plan.established); // Removals are structured effects, so changing them changes the digest // and is caught before execution. assert_eq!(plan.removals(), 1); assert_eq!(plan.effects[0].target, "app-misc/unused-1.0"); assert!(plan .consequences .iter() .any(|c| c.contains("will be removed"))); assert!(plan.render().contains("app-misc/unused-1.0")); } #[test] fn depclean_effect_digest_detects_a_changed_removal_set() { let runner = RecordingRunner::new(); runner.set_response( "emerge", CommandOutput { status: 0, success: true, stdout: b"All selected packages: app-misc/unused-1.0\n".to_vec(), stderr: Vec::new(), duration: std::time::Duration::from_millis(1), }, ); let exec = make_exec(runner.clone()); let approved = resolve_effects(&exec, &SystemAction::Depclean, Path::new("/")).unwrap(); // The next preview selects a different package entirely. runner.set_response( "emerge", CommandOutput { status: 0, success: true, stdout: b"All selected packages: app-misc/other-2.0\n".to_vec(), stderr: Vec::new(), duration: std::time::Duration::from_millis(1), }, ); let current = resolve_effects(&exec, &SystemAction::Depclean, Path::new("/")).unwrap(); assert_ne!(approved.digest, current.digest); assert!(phoebus_core::effects::changed_materially( &approved, ¤t )); assert!(!phoebus_core::effects::approval_holds( &approved, ¤t, &[] )); } #[test] fn maintenance_actions_have_comparable_effects() { assert!(resolves_effects(&SystemAction::Depclean)); assert!(resolves_effects(&SystemAction::ApplyUpdates { backend: None })); assert!(resolves_effects(&SystemAction::ApplyUpdates { backend: Some(phoebus_core::selection::Backend::Flatpak), })); assert!(resolves_effects(&SystemAction::CleanCache { backend: None })); } #[test] fn execute_checked_refuses_depclean_drift_before_any_mutation() { let approved_runner = RecordingRunner::new(); approved_runner.set_response( "emerge", response("All selected packages: app-misc/old-1.0\n"), ); let approved_exec = make_exec(approved_runner); let approved = resolve_effects(&approved_exec, &SystemAction::Depclean, Path::new("/")).unwrap(); let runner = RecordingRunner::new(); runner.set_response( "emerge", response("All selected packages: app-misc/new-2.0\n"), ); let exec = make_exec(runner.clone()); let auth = auth(); let err = execute_checked( &exec, &SystemAction::Depclean, Some(&auth), Path::new("/"), Some(&approved), ) .unwrap_err(); assert!(err.to_string().contains("plan changed"), "{err}"); // Only the re-resolution preview ran; the destructive depclean did not. assert_eq!(runner.recorded().len(), 1, "{:?}", runner.recorded()); } fn install_fake_tool(root: &Path, name: &str) { use std::os::unix::fs::PermissionsExt; let bin = root.join("usr/bin"); std::fs::create_dir_all(&bin).unwrap(); let tool = bin.join(name); std::fs::write(&tool, "#!/bin/sh\n").unwrap(); std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap(); } #[test] fn cleaner_preview_is_non_destructive_and_matches_execution_policy() { let root = tempfile::tempdir().unwrap(); install_fake_tool(root.path(), "eclean-dist"); let cleaners = portage_cleaners(root.path()); assert_eq!(cleaners.len(), 1); let (_, preview, destructive) = &cleaners[0]; // `eclean` deletes by default: the preview must be explicit. assert!(preview.iter().any(|a| a == "--pretend"), "{preview:?}"); assert!( !destructive.iter().any(|a| a == "--pretend"), "the destructive run must not pretend: {destructive:?}" ); // Same selection policy: the only difference is the preview flag. let mut selection = preview.clone(); selection.retain(|a| a != "--pretend"); assert_eq!( &selection, destructive, "preview policy must match execution" ); } #[test] fn cleanup_items_are_order_independent() { let mk = |s: &str| CommandOutput { status: 0, success: true, stdout: s.as_bytes().to_vec(), stderr: Vec::new(), duration: std::time::Duration::from_millis(1), }; let a = cleanup_items(&mk("b.tar.gz\na.tar.gz\n")); let b = cleanup_items(&mk("a.tar.gz\nb.tar.gz\n")); assert_eq!(a, b); assert_eq!(a, vec!["a.tar.gz", "b.tar.gz"]); } #[test] fn resolve_cleanup_effects_never_runs_a_destructive_cleaner() { let runner = RecordingRunner::new(); runner.set_response( "chroot", CommandOutput { status: 0, success: true, stdout: b"/var/cache/distfiles/old.tar.gz\n".to_vec(), stderr: b"Here are the distfiles that would be deleted:\n".to_vec(), duration: std::time::Duration::from_millis(1), }, ); let exec = make_exec(runner.clone()); let root = Path::new(&exec.root); install_fake_tool(root, "eclean-dist"); let plan = resolve_effects( &exec, &SystemAction::CleanCache { backend: Some(Backend::PortageSource), }, root, ) .unwrap(); // Items are taken from both streams and bound to the plan. let items = &plan.cleanup[0].items; assert!(items.iter().any(|i| i.contains("old.tar.gz")), "{items:?}"); assert!( items.iter().any(|i| i.contains("would be deleted")), "{items:?}" ); // Every invocation was a preview; no destructive `eclean` ran. for spec in runner.recorded() { assert!( spec.args.iter().any(|a| a == "--pretend"), "planning must only preview: {spec:?}" ); } } #[test] fn clean_cache_revalidation_only_previews_and_aborts_on_drift() { // Rank 1: reviewed preview (items X). let approved_runner = RecordingRunner::new(); approved_runner.set_response( "chroot", response("Here are the distfiles that would be deleted:\n/var/cache/old-a.tar.gz\n"), ); let approved_exec = make_exec(approved_runner); let approved_root = Path::new(&approved_exec.root); install_fake_tool(approved_root, "eclean-dist"); let approved = resolve_effects( &approved_exec, &SystemAction::CleanCache { backend: Some(Backend::PortageSource), }, approved_root, ) .unwrap(); // Execution-time re-resolution previews a *different* item set. let runner = RecordingRunner::new(); runner.set_response( "chroot", response("Here are the distfiles that would be deleted:\n/var/cache/old-b.tar.gz\n"), ); let exec = make_exec(runner.clone()); let root = Path::new(&exec.root); install_fake_tool(root, "eclean-dist"); let err = execute_checked( &exec, &SystemAction::CleanCache { backend: Some(Backend::PortageSource), }, Some(&auth()), root, Some(&approved), ) .unwrap_err(); assert!(err.to_string().contains("plan changed"), "{err}"); // Only the non-destructive preview ran; the destructive `--deep`-only // invocation never did. for spec in runner.recorded() { assert!( spec.args.iter().any(|a| a == "--pretend"), "a destructive cleaner ran during revalidation: {spec:?}" ); } } #[test] fn clean_cache_without_authorization_runs_no_cleaner() { let runner = RecordingRunner::new(); let exec = make_exec(runner.clone()); let root = Path::new(&exec.root); install_fake_tool(root, "eclean-dist"); let err = execute( &exec, &SystemAction::CleanCache { backend: Some(Backend::PortageSource), }, None, root, ) .unwrap_err(); assert!(matches!(err, ExecError::NotAuthorized(_))); // A cancelled/unauthorized approval must not touch the cache. assert!(runner.recorded().is_empty(), "{:?}", runner.recorded()); } #[test] fn nix_cleanup_preview_uses_the_documented_print_dead_and_not_gc() { let runner = RecordingRunner::new(); runner.set_response( "chroot", CommandOutput { status: 0, success: true, stdout: b"/nix/store/dead-path-1\n".to_vec(), stderr: Vec::new(), duration: std::time::Duration::from_millis(1), }, ); let exec = make_exec(runner.clone()); let root = Path::new(&exec.root); // Pretend Nix is installed by creating the pinned store path. std::fs::create_dir_all(root.join(format!("nix/store/{}", crate::nix::NIX_STORE_NAME))) .unwrap(); let plan = resolve_effects( &exec, &SystemAction::CleanCache { backend: Some(Backend::Nix), }, root, ) .unwrap(); assert_eq!(plan.cleanup[0].cleaner, "nix-store --gc"); assert!(!runner.recorded().is_empty()); for spec in runner.recorded() { let has_gc = spec.args.iter().any(|a| a == "--gc"); let has_print_dead = spec.args.iter().any(|a| a == "--print-dead"); assert!( !has_gc || has_print_dead, "a bare `--gc` deletes; preview must use --print-dead: {spec:?}" ); } } #[test] fn portage_apply_updates_previews_the_world_plan() { let runner = RecordingRunner::new(); runner.set_response( "emerge", CommandOutput { status: 0, success: true, stdout: b"Calculating dependencies... done!\n\ [ebuild N ] app-editors/vim-9.1.0\n\nTotal: 1 package\n" .to_vec(), stderr: Vec::new(), duration: std::time::Duration::from_millis(1), }, ); let exec = make_exec(runner); let action = SystemAction::ApplyUpdates { backend: Some(phoebus_core::selection::Backend::PortageSource), }; let plan = resolve_effects(&exec, &action, Path::new("/")).unwrap(); assert!(plan.established); assert!(plan .effects .iter() .any(|e| e.target == "app-editors/vim-9.1.0")); } }