From 1bf31c5a7290eda5557bf7363fdf7da12b97345b Mon Sep 17 00:00:00 2001 From: Phoebus Date: Fri, 25 Sep 2026 18:34:36 -0700 Subject: [PATCH] refactor(installer): split service.rs into mod/plan/validation/execution/tests Move the 4218-line shared service layer into focused modules with no behavior change: mod.rs keeps the plan types, render, and shared helpers with explicit re-exports so every phoebus_installer::service::* path, the serialized plan format, approval digests, replay protection, and privileged validation behavior are unchanged; plan.rs holds PlanStore and the planning APIs; validation.rs holds seals, digests, and the privileged validation boundary; execution.rs holds validated elevated execution; tests.rs holds the regression suite verbatim. Sibling-private helpers (constrain_action, plan_integrity, reviewed_steps, validate_effect_bindings, ServiceConfirm) are pub(super) with explicit imports; no glob re-exports. cargo fmt clean; cargo clippy --workspace --all-targets -- -D warnings clean; cargo test --workspace passes (692 passed, 0 failed, identical to the pre-split baseline; plan_golden and adversarial digest tests unchanged). --- .../crates/phoebus-installer/src/service.rs | 4218 ----------------- .../src/service/execution.rs | 529 +++ .../phoebus-installer/src/service/mod.rs | 329 ++ .../phoebus-installer/src/service/plan.rs | 872 ++++ .../phoebus-installer/src/service/tests.rs | 2111 +++++++++ .../src/service/validation.rs | 451 ++ 6 files changed, 4292 insertions(+), 4218 deletions(-) delete mode 100644 installer-rs/crates/phoebus-installer/src/service.rs create mode 100644 installer-rs/crates/phoebus-installer/src/service/execution.rs create mode 100644 installer-rs/crates/phoebus-installer/src/service/mod.rs create mode 100644 installer-rs/crates/phoebus-installer/src/service/plan.rs create mode 100644 installer-rs/crates/phoebus-installer/src/service/tests.rs create mode 100644 installer-rs/crates/phoebus-installer/src/service/validation.rs diff --git a/installer-rs/crates/phoebus-installer/src/service.rs b/installer-rs/crates/phoebus-installer/src/service.rs deleted file mode 100644 index 7137e9b..0000000 --- a/installer-rs/crates/phoebus-installer/src/service.rs +++ /dev/null @@ -1,4218 +0,0 @@ -//! Shared administration service layer for Phoebus OS. -//! -//! Provides a single, unified implementation for both the CLI (`sys`) and desktop -//! GUI (`phoebus-assistant`) covering: -//! - Bounded investigation and connected model planning -//! - Candidate discovery, provenance verification, and policy enforcement -//! - Plan staging (`PreparedPlan`) and cryptographically bound approval digests -//! - TTL enforcement and replay/tamper protection (`PlanStore`) -//! - Cross-source application removal preserving user data by default -//! - Two-phase transaction logging (`begin` before mutation, `finish` with verification) -//! - Unprivileged-to-privileged desktop Polkit elevation (`pkexec`) - -use std::io::Write; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::time::{SystemTime, UNIX_EPOCH}; - -use phoebus_ai::assistant::{complete_plan, run_assistant, AssistantPlan}; -use phoebus_ai::install::Evidence; -use phoebus_ai::provider::SystemFacts; -use phoebus_core::action::SystemAction; -use phoebus_core::effects::{approval_holds, PackageEffect, ResolvedPlan}; -use phoebus_core::selection::{Backend, Candidate, Rejected, SandboxLevel}; -use phoebus_core::transaction::{TransactionOutcome, TransactionRecord}; -use phoebus_executor::actions; -use phoebus_executor::auth::{authorize, Confirmation}; -use phoebus_executor::chooser; -use phoebus_executor::error::{ExecError, Result}; -use phoebus_executor::exec::Exec; -use phoebus_executor::install::{self, AiInstall, InstallRequest, InstallSource}; -use phoebus_executor::transaction; - -use crate::approval::{ApprovalIdentity, ApprovalLedger, ApprovalStatus, Finished}; - -use serde::{Deserialize, Serialize}; -use sha2::{Digest, Sha256}; - -pub const DEFAULT_PLAN_TTL_SECONDS: u64 = 900; // 15 minutes - -/// How many plan identifiers may be generated before the process-wide counter -/// wraps. Identifiers also include 128 bits of randomness from `/dev/urandom`. -static PLAN_COUNTER: AtomicU64 = AtomicU64::new(1); -/// A plan id is exactly this token: no separators, no traversal. -const PLAN_ID_HEX_LEN: usize = 32; - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum PlanKind { - Install, - LegacyInstall, - Removal, - General, - Undo, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct PreparedPlan { - pub id: String, - pub created_unix: u64, - pub expires_unix: u64, - pub kind: PlanKind, - pub summary: String, - pub recommendation: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub application: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub candidate: Option, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub alternatives: Vec, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub rationale: Vec, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub warnings: Vec, - pub actions: Vec, - pub effects: ResolvedPlan, - /// Per-step resolved effects, so a multi-action plan can be revalidated - /// action by action instead of comparing one action against the aggregate. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub step_effects: Vec, - pub digest: String, - pub verification: String, - pub requires_root: bool, - pub source: String, - pub executed: bool, - /// Canonical root the plan was reviewed against. Elevated execution refuses - /// to run against any other root (never silently falls back to `/`). - #[serde(default)] - pub target_root: String, - /// The unprivileged user that reviewed and approved the plan. A privileged - /// broker refuses to run a plan prepared for another user. - #[serde(default)] - pub initiator_uid: u32, - /// Self-consistency seal over the reviewed fields (including target root, - /// initiator and digest). Rejected if it does not match on reload. - #[serde(default)] - pub integrity: String, -} - -/// A handle to a prepared plan that the broker has atomically claimed for -/// execution. Holding it proves the plan was consumed exactly once. -#[derive(Debug)] -pub struct PlanClaim { - marker: PathBuf, -} - -impl PlanClaim { - pub fn marker_path(&self) -> &Path { - &self.marker - } -} - -impl Drop for PlanClaim { - fn drop(&mut self) { - // The claim marker is intentionally left in place: it is the durable - // record that the plan was consumed, so a retry cannot repeat it. - } -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct PlanExecutionOutcome { - pub completed: bool, - pub snapshot: Option, - pub result: String, - pub verification: String, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub output: Vec, - /// A concrete command that launches the installed application, when a - /// desktop entry could be identified. Never guessed. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub launch: Option>, -} - -impl PreparedPlan { - pub fn render(&self) -> String { - let mut out = String::new(); - match self.kind { - PlanKind::Install | PlanKind::LegacyInstall => { - out.push_str(&format!( - "Install plan ({}):\n", - if self.kind == PlanKind::LegacyInstall { - "explicit selection" - } else { - "AI recommendation" - } - )); - if let Some(app) = &self.application { - out.push_str(&format!(" application: {app}\n")); - } - if let Some(c) = &self.candidate { - out.push_str(&format!(" backend: {}\n", c.backend.as_str())); - out.push_str(&format!(" candidate: {}\n", c.id)); - out.push_str(&format!( - " version: {}\n", - c.version.as_deref().unwrap_or("(resolved at install time)") - )); - out.push_str(&format!(" source: {}\n", self.source)); - out.push_str(&format!( - " integrity: {}\n", - if c.verified { - "verified (signature/hash)" - } else { - "UNVERIFIED — provenance not cryptographic" - } - )); - out.push_str(&format!( - " sandbox: {} wayland: {} desktop: {}\n", - match c.sandbox { - SandboxLevel::None => "none", - SandboxLevel::Partial => "partial", - SandboxLevel::Strong => "strong", - }, - match c.wayland { - phoebus_core::selection::Capability::No => "no", - phoebus_core::selection::Capability::Partial => "partial", - phoebus_core::selection::Capability::Yes => "yes", - }, - match c.desktop_integration { - phoebus_core::selection::Capability::No => "no", - phoebus_core::selection::Capability::Partial => "partial", - phoebus_core::selection::Capability::Yes => "yes", - } - )); - if let Some(mib) = c.download_mib { - out.push_str(&format!(" download: ~{mib} MiB\n")); - } - if let Some(mib) = c.install_mib { - out.push_str(&format!(" on disk: ~{mib} MiB\n")); - } - } - out.push_str("Why:\n"); - out.push_str(&format!(" - {}\n", self.recommendation)); - for r in &self.rationale { - out.push_str(&format!(" - {r}\n")); - } - if !self.alternatives.is_empty() { - out.push_str("Alternatives considered:\n"); - for alt in &self.alternatives { - out.push_str(&format!( - " - {} ({}): {}\n", - alt.id, - alt.backend.as_str(), - alt.reason.explain() - )); - } - } - for w in &self.warnings { - out.push_str(&format!(" ! {w}\n")); - } - if self.effects.established && !self.effects.effects.is_empty() { - out.push_str(&self.effects.render()); - } - out.push_str(&format!("Verification: {}\n", self.verification)); - out.push_str(&format!("Approval digest: {}\n", self.digest)); - } - PlanKind::Removal => { - out.push_str("Removal plan:\n"); - if let Some(app) = &self.application { - out.push_str(&format!(" application: {app}\n")); - } - out.push_str(&format!(" source: {}\n", self.source)); - out.push_str("Why:\n"); - out.push_str(&format!(" - {}\n", self.recommendation)); - for r in &self.rationale { - out.push_str(&format!(" - {r}\n")); - } - if self.effects.established && !self.effects.effects.is_empty() { - out.push_str(&self.effects.render()); - } - out.push_str(&format!("Verification: {}\n", self.verification)); - out.push_str(&format!("Approval digest: {}\n", self.digest)); - } - _ => { - out.push_str(&format!("Assistant Plan:\n {}\n", self.summary)); - for a in &self.actions { - out.push_str(&format!(" - {}\n", a.describe())); - } - if self.effects.established && !self.effects.effects.is_empty() { - out.push_str(&self.effects.render()); - } - out.push_str(&format!("Verification: {}\n", self.verification)); - out.push_str(&format!("Approval digest: {}\n", self.digest)); - } - } - out - } -} - -fn now_unix() -> u64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|d| d.as_secs()) - .unwrap_or(0) -} - -pub fn effective_uid() -> u32 { - if std::env::var("PHOEBUS_ALLOW_UNPRIVILEGED_EXEC").as_deref() == Ok("1") { - return 0; - } - std::process::Command::new("id") - .arg("-u") - .output() - .ok() - .and_then(|o| String::from_utf8_lossy(&o.stdout).trim().parse().ok()) - .unwrap_or(1) -} - -/// Canonicalise a target root so two spellings of the same path compare equal. -/// When the path cannot be canonicalised (e.g. a not-yet-created target), fall -/// back to the lexical path rather than silently selecting `/`. -pub fn canonical_root(root: &Path) -> String { - match std::fs::canonicalize(root) { - Ok(p) => p.to_string_lossy().to_string(), - Err(_) => { - let p = if root.as_os_str().is_empty() { - Path::new("/") - } else { - root - }; - p.to_string_lossy().to_string() - } - } -} - -/// 128 bits of unpredictable data for a plan identifier/marker name. -fn random_token() -> String { - let mut bytes = [0u8; 16]; - let filled = std::fs::File::open("/dev/urandom") - .and_then(|mut f| { - use std::io::Read; - f.read_exact(&mut bytes) - }) - .is_ok(); - if !filled { - // Fallback that is still unique within a boot: time + pid + counter. - let nanos = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0); - let mut hasher = Sha256::new(); - hasher.update(nanos.to_le_bytes()); - hasher.update(std::process::id().to_le_bytes()); - hasher.update(PLAN_COUNTER.fetch_add(1, Ordering::SeqCst).to_le_bytes()); - let digest = format!("{:x}", hasher.finalize()); - return digest[..PLAN_ID_HEX_LEN].to_string(); - } - bytes.iter().map(|b| format!("{b:02x}")).collect() -} - -/// A fresh, unpredictable plan identifier: `plan--<32 hex>`. -pub(crate) fn fresh_plan_id(prefix: &str) -> String { - let counter = PLAN_COUNTER.fetch_add(1, Ordering::SeqCst); - let mut hasher = Sha256::new(); - hasher.update(random_token().as_bytes()); - hasher.update(counter.to_le_bytes()); - let digest = format!("{:x}", hasher.finalize()); - format!("plan-{prefix}-{}", &digest[..PLAN_ID_HEX_LEN]) -} - -fn is_safe_plan_id(plan_id: &str) -> bool { - !plan_id.is_empty() - && plan_id.len() <= 128 - && plan_id - .bytes() - .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') -} - -/// Recompute the self-consistency seal over every reviewed field. The stored -/// `integrity` value is deliberately excluded. A reload whose recomputation -/// differs was modified after it was approved. -fn plan_integrity(plan: &PreparedPlan) -> String { - let mut hasher = Sha256::new(); - hasher.update(plan.id.as_bytes()); - hasher.update(b"\0"); - hasher.update(format!("{:?}", plan.kind).as_bytes()); - hasher.update(b"\0"); - hasher.update(plan.created_unix.to_le_bytes()); - hasher.update(plan.expires_unix.to_le_bytes()); - hasher.update(plan.digest.as_bytes()); - hasher.update(b"\0"); - hasher.update(plan.effects.digest.as_bytes()); - hasher.update(b"\0"); - if let Some(c) = &plan.candidate { - hasher.update(c.backend.as_str().as_bytes()); - hasher.update(b"\0"); - hasher.update(c.id.as_bytes()); - hasher.update(b"\0"); - hasher.update(c.version.as_deref().unwrap_or("").as_bytes()); - hasher.update(b"\0"); - } - for act in &plan.actions { - hasher.update(serde_json::to_string(act).unwrap_or_default().as_bytes()); - hasher.update(b"\0"); - } - for step in &plan.step_effects { - hasher.update(step.digest.as_bytes()); - hasher.update(b"\0"); - } - hasher.update(plan.target_root.as_bytes()); - hasher.update(b"\0"); - hasher.update(plan.source.as_bytes()); - hasher.update(b"\0"); - hasher.update(plan.initiator_uid.to_le_bytes()); - hasher.update(b"\0"); - hasher.update([plan.requires_root as u8]); - hasher.update([plan.executed as u8]); - // Everything the human reviewed is sealed, so a modified summary or - // verification statement cannot pass as the approved plan. - for field in [ - &plan.summary, - &plan.recommendation, - plan.application.as_deref().unwrap_or(""), - &plan.verification, - ] { - hasher.update(field.as_bytes()); - hasher.update(b"\0"); - } - for line in plan.rationale.iter().chain(plan.warnings.iter()) { - hasher.update(line.as_bytes()); - hasher.update(b"\0"); - } - for alt in &plan.alternatives { - hasher.update(serde_json::to_string(alt).unwrap_or_default().as_bytes()); - hasher.update(b"\0"); - } - format!("{:x}", hasher.finalize()) -} - -/// Compute and store the plan seal. Must be called before persistence. -pub fn seal_plan(plan: &mut PreparedPlan) { - plan.integrity = plan_integrity(plan); -} - -/// The canonical digest of a single step's material effects. -/// -/// The digest is *recomputed* from the effect list rather than read from the -/// stored `digest` field, so a plan owner cannot change a step's contents while -/// leaving its stored digest (and therefore the approval) intact. -fn step_effects_digest(step: &ResolvedPlan) -> String { - let mut normalized = step.clone(); - normalized.recompute_digest(); - normalized.digest -} - -/// The per-step reviewed effects that execution will actually trust. -/// -/// New plans always store one step per action. A single-action plan may fall -/// back to its aggregate effects for backward compatibility; a multi-action -/// plan without per-step effects cannot be bound and is refused. -fn reviewed_steps(plan: &PreparedPlan) -> Result> { - if plan.step_effects.len() == plan.actions.len() && !plan.step_effects.is_empty() { - Ok(plan.step_effects.clone()) - } else if plan.actions.len() == 1 { - Ok(vec![plan.effects.clone()]) - } else { - Err(ExecError::operation( - "service", - "validate plan", - "plan is missing per-step effects; refusing to execute a multi-action plan whose \ - reviewed effects are not individually bound", - )) - } -} - -/// Verify that every stored per-step effect digest matches its actual contents -/// and that the aggregate effects are exactly the concatenation of the steps. -fn validate_effect_bindings(plan: &PreparedPlan, steps: &[ResolvedPlan]) -> Result<()> { - for (idx, step) in steps.iter().enumerate() { - if step.digest != step_effects_digest(step) { - return Err(ExecError::operation( - "service", - "validate plan", - format!( - "the stored effect digest for step {idx} does not match its contents; the \ - plan was modified after it was reviewed" - ), - )); - } - } - let mut combined = ResolvedPlan { - established: true, - ..Default::default() - }; - for step in steps { - combined.effects.extend(step.effects.clone()); - combined.cleanup.extend(step.cleanup.clone()); - combined.updates.extend(step.updates.clone()); - combined.consequences.extend(step.consequences.clone()); - } - combined.recompute_digest(); - let mut aggregate = plan.effects.clone(); - aggregate.recompute_digest(); - if combined.digest != aggregate.digest { - return Err(ExecError::operation( - "service", - "validate plan", - "the aggregate effects are not consistent with the reviewed per-step effects; the \ - plan was modified after it was reviewed", - )); - } - Ok(()) -} - -/// Compute a cryptographic digest binding the exact actions, candidate, the -/// reviewed aggregate effects and every per-step effect that execution trusts. -pub fn compute_plan_digest( - actions: &[SystemAction], - candidate: Option<&Candidate>, - effects: &ResolvedPlan, - step_effects: &[ResolvedPlan], -) -> String { - // A single installed candidate binds through the install-specific digest. - // `validate_effect_bindings` separately requires that its one step equals - // the aggregate, so the step effects are bound transitively. - if let (Some(cand), Some(act)) = (candidate, actions.first()) { - if actions.len() == 1 { - return install::approval_digest_for(cand, act, effects); - } - } - - let mut hasher = Sha256::new(); - if let Some(c) = candidate { - hasher.update(c.backend.as_str().as_bytes()); - hasher.update(b"\0"); - hasher.update(c.id.as_bytes()); - hasher.update(b"\0"); - hasher.update(c.version.as_deref().unwrap_or("").as_bytes()); - hasher.update(b"\0"); - } - for act in actions { - hasher.update(serde_json::to_string(act).unwrap_or_default().as_bytes()); - hasher.update(b"\0"); - } - // Bind every material per-step effect execution will trust, recomputed from - // its contents so a retained approval cannot hide a changed schedule. - for step in step_effects { - hasher.update(step_effects_digest(step).as_bytes()); - hasher.update(b"\0"); - } - hasher.update(b"aggregate\0"); - if effects.established { - hasher.update(effects.digest.as_bytes()); - } else { - hasher.update(b"no-established-effects"); - } - format!("{:x}", hasher.finalize()) -} - -/// Produce an honest, evidence-based human recommendation for an application candidate. -pub fn format_recommendation(candidate: &Candidate, application: &str) -> String { - let source_name = match candidate.backend { - Backend::PortageBinary => "Gentoo binhost", - Backend::PortageSource => "Gentoo Portage", - Backend::PortageVendor => "Portage vendor binary", - Backend::Flatpak => "Flathub", - Backend::Snap => "Snap Store", - Backend::Nix => "Nixpkgs", - Backend::AppImage => "managed AppImage", - Backend::CustomEbuild => "Phoebus custom ebuild", - }; - - let sandbox_desc = match candidate.sandbox { - SandboxLevel::Strong => "strong application isolation", - SandboxLevel::Partial => "partial confinement", - SandboxLevel::None => "direct host integration (unconfined)", - }; - - let build_desc = if let Some(secs) = candidate.build_seconds { - if secs < 60 { - format!("fast install (~{secs}s)") - } else { - let mins = secs.div_ceil(60); - format!("compiles native binaries (~{mins} min build)") - } - } else { - match candidate.backend { - Backend::PortageBinary | Backend::Flatpak | Backend::Snap | Backend::AppImage => { - "pre-built binary package".to_string() - } - Backend::PortageSource => "source compilation (build time unmeasured)".to_string(), - _ => "pre-built binary".to_string(), - } - }; - - format!( - "Install {application} from {source_name}. Recommended for {sandbox_desc} and {build_desc}." - ) -} - -// ----------------------------------------------------------------------------- -// PlanStore -// ----------------------------------------------------------------------------- - -/// Protected, per-user plan storage. -/// -/// A plan is written with a 0600 mode inside a 0700 directory owned by the -/// reviewing user (or the broker for root). Reloading rejects a symlink, a -/// file owned by someone other than the initiator/root, or a group/world -/// writable file. Consumption uses an `O_EXCL` marker so two concurrent -/// executions cannot both run the same plan. -#[derive(Debug, Clone)] -pub struct PlanStore { - dir: PathBuf, - /// The uid a plan is expected to belong to. The privileged broker sets this - /// to the initiating user so it can read that user's plan while still - /// rejecting a file owned by anyone else. - expected_uid: Option, -} - -impl PlanStore { - /// Storage for a specific uid. Used by the privileged broker, which - /// recomputes the directory from the uid the caller passed rather than - /// trusting an arbitrary path. - pub fn for_uid(uid: u32) -> Self { - if let Ok(dir) = std::env::var("PHOEBUS_PLANS_DIR") { - return Self { - dir: PathBuf::from(dir), - expected_uid: Some(uid), - }; - } - let candidates: Vec = if uid == 0 { - vec![PathBuf::from("/run/phoebus/plans")] - } else { - // Prefer the canonical per-user runtime path so the privileged - // broker (which derives the same path from the uid) finds it. - let mut v = vec![PathBuf::from(format!("/run/user/{uid}/phoebus/plans"))]; - if let Ok(xdg) = std::env::var("XDG_RUNTIME_DIR") { - v.push(PathBuf::from(xdg).join("phoebus/plans")); - } - v - }; - for dir in candidates { - if std::fs::create_dir_all(&dir).is_ok() { - return Self { - dir, - expected_uid: Some(uid), - }; - } - } - let temp = std::env::temp_dir().join(format!("phoebus-plans-{uid}")); - let _ = std::fs::create_dir_all(&temp); - Self { - dir: temp, - expected_uid: Some(uid), - } - } - - pub fn for_current_user() -> Self { - Self::for_uid(effective_uid()) - } - - /// Explicit directory, for tests and callers that manage their own store. - pub fn with_dir(dir: impl Into) -> Self { - Self { - dir: dir.into(), - expected_uid: None, - } - } - - pub fn dir(&self) -> &Path { - &self.dir - } - - fn ensure_dir(&self) -> Result<()> { - std::fs::create_dir_all(&self.dir).map_err(|e| ExecError::io(self.dir.clone(), e))?; - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - let _ = std::fs::set_permissions(&self.dir, std::fs::Permissions::from_mode(0o700)); - } - Ok(()) - } - - fn path(&self, plan_id: &str, suffix: &str) -> Result { - if !is_safe_plan_id(plan_id) { - return Err(ExecError::operation( - "service", - "plan path", - format!("unsafe plan identifier `{plan_id}`"), - )); - } - Ok(self.dir.join(format!("{plan_id}{suffix}"))) - } - - /// Write a plan atomically (temp file -> fsync -> rename) with mode 0600. - pub fn save(&self, plan: &mut PreparedPlan) -> Result { - seal_plan(plan); - let path = self.path(&plan.id, ".json")?; - self.ensure_dir()?; - let text = serde_json::to_string_pretty(plan) - .map_err(|e| ExecError::operation("service", "serialize plan", e.to_string()))?; - - let tmp = self.dir.join(format!(".{}.tmp", random_token())); - { - let mut opts = std::fs::OpenOptions::new(); - opts.write(true).create_new(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt; - opts.mode(0o600); - } - let mut file = opts.open(&tmp).map_err(|e| ExecError::io(tmp.clone(), e))?; - file.write_all(text.as_bytes()) - .and_then(|_| file.flush()) - .and_then(|_| file.sync_all()) - .map_err(|e| ExecError::io(tmp.clone(), e))?; - } - std::fs::rename(&tmp, &path).map_err(|e| { - let _ = std::fs::remove_file(&tmp); - ExecError::io(path.clone(), e) - })?; - if let Ok(dir) = std::fs::File::open(&self.dir) { - let _ = dir.sync_all(); - } - Ok(path) - } - - /// Load a plan, rejecting malformed identifiers, symlinks and unsafe - /// ownership/permissions. The caller still has to validate the contents. - pub fn load(&self, plan_id: &str) -> Result { - let path = self.path(plan_id, ".json")?; - let meta = std::fs::symlink_metadata(&path).map_err(|_| { - ExecError::operation( - "service", - "load plan", - format!("plan `{plan_id}` not found, consumed or expired"), - ) - })?; - if meta.file_type().is_symlink() { - return Err(ExecError::operation( - "service", - "load plan", - "plan path is a symlink; refusing to follow it", - )); - } - if !meta.is_file() { - return Err(ExecError::operation( - "service", - "load plan", - "plan path is not a regular file", - )); - } - #[cfg(unix)] - { - use std::os::unix::fs::{MetadataExt, PermissionsExt}; - if meta.permissions().mode() & 0o022 != 0 { - return Err(ExecError::operation( - "service", - "load plan", - "plan file is group/world writable; refusing to trust it", - )); - } - let owner = meta.uid(); - let expected = self.expected_uid.unwrap_or_else(effective_uid); - // The broker runs as root but is reading the initiating user's plan, - // so the expected owner is the initiator, not root. A plan owned by - // a third party is rejected. - if owner != expected && owner != 0 { - return Err(ExecError::operation( - "service", - "load plan", - format!("plan file is owned by uid {owner}, not the expected uid {expected}"), - )); - } - } - let text = std::fs::read_to_string(&path).map_err(|e| ExecError::io(path.clone(), e))?; - let plan: PreparedPlan = serde_json::from_str(&text) - .map_err(|e| ExecError::operation("service", "deserialize plan", e.to_string()))?; - if plan.id != plan_id { - return Err(ExecError::operation( - "service", - "load plan", - "plan identifier does not match its storage name", - )); - } - Ok(plan) - } - - /// Atomically claim a plan for execution. Returns a guard that keeps the - /// marker on disk; a second claim (or a retry after a crash) fails. - pub fn claim(&self, plan_id: &str) -> Result { - let marker = self.path(plan_id, ".claim")?; - self.ensure_dir()?; - let mut opts = std::fs::OpenOptions::new(); - opts.write(true).create_new(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt; - opts.mode(0o600); - } - opts.open(&marker).map_err(|e| { - ExecError::operation( - "service", - "claim plan", - format!("plan `{plan_id}` is already consumed or being executed ({e})"), - ) - })?; - Ok(PlanClaim { marker }) - } - - /// True when a plan has already been claimed (consumed) for execution. - pub fn is_claimed(&self, plan_id: &str) -> bool { - match self.path(plan_id, ".claim") { - Ok(p) => p.exists(), - Err(_) => true, - } - } -} - -// ----------------------------------------------------------------------------- -// Planning APIs -// ----------------------------------------------------------------------------- - -/// Plan an installation using AI investigation and policy checks. -pub fn plan_install( - plans: &PlanStore, - exec: &Exec, - root: &Path, - request: &InstallRequest, - session: &dyn phoebus_ai::install::InstallSession, - ai: Option<&AiInstall>, - facts: &SystemFacts, -) -> Result { - let ai = match ai { - Some(a) => a, - None => { - return Err(ExecError::operation( - "service", - "plan_install", - "No AI provider is configured. Specify a model or select deterministic legacy administration (--legacy --).", - )); - } - }; - - let resolved = install::resolve_with_ai(exec, root, request, session, ai, facts)?; - build_install_plan(plans, root, resolved, PlanKind::Install) -} - -/// Plan an installation deterministically without contacting a model. -pub fn plan_legacy_install( - plans: &PlanStore, - exec: &Exec, - root: &Path, - request: &InstallRequest, -) -> Result { - if request.backend.is_none() { - return Err(ExecError::operation( - "service", - "plan_legacy_install", - "Legacy install requires an explicit package source flag (--flatpak, --portage, --nix, --snap, --appimage, --ebuild)", - )); - } - let resolved = install::resolve_explicit(exec, root, request)?; - build_install_plan(plans, root, resolved, PlanKind::LegacyInstall) -} - -fn build_install_plan( - plans: &PlanStore, - root: &Path, - resolved: install::ResolvedInstall, - kind: PlanKind, -) -> Result { - let now = now_unix(); - let plan_id = fresh_plan_id("inst"); - - let rec = format_recommendation(&resolved.candidate, &resolved.request.application); - let source_display = match resolved.candidate.backend { - Backend::PortageBinary => "Gentoo binhost", - Backend::PortageSource => "Gentoo Portage", - Backend::PortageVendor => "Portage vendor", - Backend::Flatpak => "Flathub", - Backend::Snap => "Snap Store", - Backend::Nix => "Nixpkgs", - Backend::AppImage => "managed AppImage", - Backend::CustomEbuild => "Phoebus custom ebuild", - } - .to_string(); - - let digest = resolved.approval_digest(); - let actions = vec![resolved.action.clone()]; - let requires_root = resolved.action.is_mutating(); - // Normalize the stored effect digest so the per-step binding check sees a - // digest that matches the contents. - let mut effects = resolved.effects.clone(); - effects.recompute_digest(); - let step_effects = vec![effects.clone()]; - - let mut plan = PreparedPlan { - id: plan_id, - created_unix: now, - expires_unix: now + DEFAULT_PLAN_TTL_SECONDS, - kind, - summary: format!( - "install {} via {}", - resolved.request.application, - resolved.candidate.backend.as_str() - ), - recommendation: rec, - application: Some(resolved.request.application.clone()), - candidate: Some(resolved.candidate.clone()), - alternatives: resolved.alternatives.clone(), - rationale: resolved.rationale.clone(), - warnings: resolved.warnings.clone(), - actions, - effects, - step_effects, - digest, - verification: resolved.verification.clone(), - requires_root, - source: source_display, - executed: false, - target_root: canonical_root(root), - initiator_uid: effective_uid(), - integrity: String::new(), - }; - - plans.save(&mut plan)?; - Ok(plan) -} - -/// Deterministically choose which installed copy a removal targets. Shared by -/// the legacy and AI-first paths so ownership discovery and the ambiguity -/// policy cannot diverge. Ambiguity always requires an explicit lane flag. -pub fn select_removal_copy( - exec: &Exec, - root: &Path, - application: &str, - backend_filter: Option, -) -> Result { - let inspection = chooser::installed_copies(exec, root, application); - if inspection.copies.is_empty() { - return Err(ExecError::operation( - "service", - "plan_removal", - format!("`{application}` is not installed on this system"), - )); - } - - if let Some(b) = backend_filter { - return inspection - .copies - .into_iter() - .find(|c| c.backend == b.as_str()) - .ok_or_else(|| { - ExecError::operation( - "service", - "plan_removal", - format!( - "`{application}` is not installed via {} (found in other lanes)", - b.as_str() - ), - ) - }); - } - if inspection.copies.len() > 1 { - let details = inspection - .copies - .iter() - .map(|c| format!("{} ({})", c.id, c.backend)) - .collect::>() - .join(", "); - return Err(ExecError::operation( - "service", - "plan_removal", - format!( - "`{application}` is installed in multiple lanes: {details}. Specify which one to remove explicitly (e.g. sys remove {application} --flatpak or --portage)." - ), - )); - } - Ok(inspection.copies.into_iter().next().unwrap()) -} - -/// Plan an application removal across supported sources preserving user data by -/// default, without contacting a model (legacy mode only). -pub fn plan_removal( - plans: &PlanStore, - exec: &Exec, - root: &Path, - application: &str, - backend_filter: Option, -) -> Result { - let target_copy = select_removal_copy(exec, root, application, backend_filter)?; - build_removal_plan( - plans, - exec, - root, - application, - &target_copy, - Vec::new(), - Vec::new(), - ) -} - -/// Plan an application removal through the connected model (the default). The -/// deterministic discovery and ambiguity policy run first; the model must then -/// confirm exactly the discovered target. A model failure, or a proposal that -/// does not match the deterministic target, stops the workflow. -pub fn plan_removal_with_ai( - plans: &PlanStore, - exec: &Exec, - root: &Path, - application: &str, - backend_filter: Option, - ai: &AiInstall, - facts: &SystemFacts, -) -> Result { - let target_copy = select_removal_copy(exec, root, application, backend_filter)?; - let discovered = chooser::installed_copies(exec, root, application); - let list = discovered - .copies - .iter() - .map(|c| format!("{} ({})", c.id, c.backend)) - .collect::>() - .join(", "); - - let instruction = format!( - "The user asked to remove `{application}`. Read-only discovery found these installed \ - copies: [{list}]. The policy-selected target is `{}` in the {} lane. Confirm a removal \ - plan for exactly that copy by proposing the matching remove action; if the request is \ - ambiguous, propose no action and explain what clarification is needed.", - target_copy.id, target_copy.backend - ); - let assistant_plan: AssistantPlan = complete_plan( - ai.provider, - &ai.endpoint, - &ai.model, - facts, - &instruction, - ai.transport, - ) - .map_err(|e| ExecError::operation("service", "plan_removal_with_ai", e.to_string()))?; - - if assistant_plan.actions.len() != 1 - || !removal_action_matches(&assistant_plan.actions[0], &target_copy) - { - return Err(ExecError::operation( - "service", - "plan_removal_with_ai", - format!( - "the model did not confirm the discovered removal target `{}` ({}); no removal \ - plan was produced", - target_copy.id, target_copy.backend - ), - )); - } - - let mut rationale: Vec = assistant_plan - .rationale - .into_iter() - .map(|r| format!("AI: {}", r.reason)) - .collect(); - if rationale.is_empty() { - rationale.push(format!( - "AI confirmed removal of the discovered {} copy", - target_copy.backend - )); - } - - build_removal_plan( - plans, - exec, - root, - application, - &target_copy, - rationale, - Vec::new(), - ) -} - -/// Whether a proposed action is the correct removal of the discovered copy. -fn removal_action_matches(action: &SystemAction, copy: &chooser::InstalledCopy) -> bool { - match (action, copy.backend.as_str()) { - (SystemAction::FlatpakRemove { app_id }, "flatpak") => app_id == ©.id, - (SystemAction::SnapRemove { name }, "snap") => name == ©.id, - (SystemAction::AppImageRemove { name, .. }, "appimage") => name == ©.id, - (SystemAction::RemovePackage { atom }, _) - if copy.backend != "flatpak" - && copy.backend != "snap" - && copy.backend != "appimage" => - { - atom == ©.id - } - _ => false, - } -} - -/// Build a removal plan for a specific, already-discovered installed copy. -/// Used by both the deterministic (legacy) path and the AI-first path, so the -/// ownership discovery and policy validation are identical. -pub fn build_removal_plan( - plans: &PlanStore, - exec: &Exec, - root: &Path, - application: &str, - target_copy: &chooser::InstalledCopy, - rationale: Vec, - warnings: Vec, -) -> Result { - let action = match target_copy.backend.as_str() { - "flatpak" => SystemAction::FlatpakRemove { - app_id: target_copy.id.clone(), - }, - "snap" => SystemAction::SnapRemove { - name: target_copy.id.clone(), - }, - "appimage" => SystemAction::AppImageRemove { - name: target_copy.id.clone(), - // User data preserved by default - purge_data: false, - }, - _ => SystemAction::RemovePackage { - atom: target_copy.id.clone(), - }, - }; - - let mut effects = actions::resolve_effects(exec, &action, root)?; - effects.recompute_digest(); - let now = now_unix(); - let plan_id = fresh_plan_id("rem"); - let actions_vec = vec![action.clone()]; - let step_effects = vec![effects.clone()]; - let digest = compute_plan_digest(&actions_vec, None, &effects, &step_effects); - - let mut rationale = rationale; - rationale.insert( - 0, - format!( - "installed package {} detected in {} lane", - target_copy.id, target_copy.backend - ), - ); - rationale.push("preserves user configuration and data in home directory by default".into()); - - let mut plan = PreparedPlan { - id: plan_id, - created_unix: now, - expires_unix: now + DEFAULT_PLAN_TTL_SECONDS, - kind: PlanKind::Removal, - summary: format!("remove {} ({})", target_copy.id, target_copy.backend), - recommendation: format!( - "Remove application {} from {}. Application binaries will be uninstalled while user data in the home directory is preserved.", - target_copy.id, target_copy.backend - ), - application: Some(application.to_string()), - candidate: None, - alternatives: Vec::new(), - rationale, - warnings, - actions: actions_vec, - effects, - step_effects, - digest, - verification: format!( - "verify that `{}` ({}) is completely removed from the system", - target_copy.id, target_copy.backend - ), - requires_root: action.is_mutating(), - source: target_copy.backend.clone(), - executed: false, - target_root: canonical_root(root), - initiator_uid: effective_uid(), - integrity: String::new(), - }; - - plans.save(&mut plan)?; - Ok(plan) -} - -/// Rewrite a lane-selectable catalogue action to an explicit source, and refuse -/// an action that targets a different lane. A spanning action (history, -/// snapshots, services) is returned unchanged. -fn constrain_action( - action: SystemAction, - constraint: Backend, -) -> std::result::Result { - Ok(match action { - SystemAction::SearchPackages { query, .. } => SystemAction::SearchPackages { - query, - backend: Some(constraint), - }, - SystemAction::ListPackages { filter, .. } => SystemAction::ListPackages { - backend: Some(constraint), - filter, - }, - SystemAction::PackageInfo { package, .. } => SystemAction::PackageInfo { - package, - backend: Some(constraint), - }, - SystemAction::CheckUpdates { .. } => SystemAction::CheckUpdates { - backend: Some(constraint), - }, - SystemAction::ApplyUpdates { .. } => SystemAction::ApplyUpdates { - backend: Some(constraint), - }, - SystemAction::CleanCache { .. } => SystemAction::CleanCache { - backend: Some(constraint), - }, - // Optional-backend discovery and selection requests must be *rewritten* - // to the constraint, not merely filtered afterwards: otherwise the - // resolver would still query every lane before the results are - // discarded. - SystemAction::DiscoverCandidates { - query, - kind, - gui, - requires_sandbox, - .. - } => SystemAction::DiscoverCandidates { - query, - kind, - backend: Some(constraint), - gui, - requires_sandbox, - }, - SystemAction::ChoosePackage { - name, - kind, - gui, - requires_sandbox, - .. - } => SystemAction::ChoosePackage { - name, - kind, - backend: Some(constraint), - gui, - requires_sandbox, - }, - // `InspectInstallation` has no lane field but probes every lane; under - // an explicit constraint it is refused rather than leaking other lanes. - SystemAction::InspectInstallation { .. } => { - return Err(format!( - "inspect_installation spans every package lane, but this request was constrained \ - to {}; use a lane-specific inventory instead", - constraint.as_str() - )); - } - other => { - if let Some(own) = other.backend() { - let matches = own == constraint || (own.is_portage() && constraint.is_portage()); - if !matches { - return Err(format!( - "`{}` targets the {} lane, but this request was constrained to {}", - other.describe(), - own.as_str(), - constraint.as_str() - )); - } - } - other - } - }) -} - -/// Plan general system administration tasks via the connected model. -/// -/// The model may run a bounded, read-only investigation (search, inventory, -/// information, update checks) before answering. An explicit `constraint` -/// forbids any action that targets a different package lane, so a source flag -/// constrains the AI workflow rather than bypassing it. -pub fn plan_general( - plans: &PlanStore, - exec: &Exec, - root: &Path, - query: &str, - facts: &SystemFacts, - ai: &AiInstall, - constraint: Option, -) -> Result { - let instruction = match constraint { - Some(backend) => format!( - "{query}\n\n[source constraint: only the `{}` lane may be used; do not use \ - another lane]", - backend.as_str() - ), - None => query.to_string(), - }; - let investigate = |requests: &[SystemAction]| -> Vec { - requests - .iter() - .map(|request| { - let output = match constraint { - Some(backend) => match constrain_action(request.clone(), backend) { - Ok(action) => match actions::execute(exec, &action, None, root) { - Ok(outcome) => outcome.output, - Err(e) => format!("investigation failed: {e}"), - }, - Err(msg) => format!("refused by the source constraint: {msg}"), - }, - None => match actions::execute(exec, request, None, root) { - Ok(outcome) => outcome.output, - Err(e) => format!("investigation failed: {e}"), - }, - }; - Evidence { - request: request.describe(), - output, - } - }) - .collect() - }; - let assistant_plan: AssistantPlan = run_assistant( - ai.provider, - &ai.endpoint, - &ai.model, - facts, - &instruction, - ai.transport, - &investigate, - &ai.limits, - ) - .map_err(|e| ExecError::operation("service", "run_assistant", e.to_string()))?; - - // Apply the source constraint to the final actions too: a lane-specific - // query is rewritten to the constraint, and an action that targets a - // different lane is refused before anything is planned. - let actions_list: Vec = match constraint { - Some(backend) => assistant_plan - .actions - .iter() - .cloned() - .map(|action| { - constrain_action(action, backend) - .map_err(|msg| ExecError::operation("service", "source constraint", msg)) - }) - .collect::>>()?, - None => assistant_plan.actions.clone(), - }; - - let mut combined_effects = ResolvedPlan { - established: true, - ..Default::default() - }; - let mut any_mutating = false; - let mut step_effects = Vec::new(); - - for act in &actions_list { - let mut eff = actions::resolve_effects(exec, act, root).map_err(|e| { - ExecError::operation( - "service", - "resolve_effects", - format!("could not resolve effects for `{}`: {e}", act.describe()), - ) - })?; - // Normalize the stored digest so the per-step binding check sees a - // digest that matches the contents. - eff.recompute_digest(); - if eff.established { - combined_effects.effects.extend(eff.effects.clone()); - combined_effects.cleanup.extend(eff.cleanup.clone()); - combined_effects.updates.extend(eff.updates.clone()); - combined_effects - .consequences - .extend(eff.consequences.clone()); - } - step_effects.push(eff); - any_mutating |= act.is_mutating(); - } - combined_effects.recompute_digest(); - - let now = now_unix(); - let plan_id = fresh_plan_id("gen"); - let digest = compute_plan_digest(&actions_list, None, &combined_effects, &step_effects); - let rationale_strings: Vec = assistant_plan - .rationale - .into_iter() - .map(|r| format!("{}: {}", r.action, r.reason)) - .collect(); - - let mut plan = PreparedPlan { - id: plan_id, - created_unix: now, - expires_unix: now + DEFAULT_PLAN_TTL_SECONDS, - kind: PlanKind::General, - summary: assistant_plan.summary.clone(), - recommendation: assistant_plan.summary, - application: None, - candidate: None, - alternatives: Vec::new(), - rationale: rationale_strings, - warnings: Vec::new(), - actions: actions_list, - effects: combined_effects, - step_effects, - digest, - verification: "verify execution of planned actions".into(), - requires_root: any_mutating, - source: "AI Assistant".into(), - executed: false, - target_root: canonical_root(root), - initiator_uid: effective_uid(), - integrity: String::new(), - }; - - plans.save(&mut plan)?; - Ok(plan) -} - -// ----------------------------------------------------------------------------- -// Execution API -// ----------------------------------------------------------------------------- - -struct ServiceConfirm { - assume_yes: bool, -} - -impl Confirmation for ServiceConfirm { - fn confirm_erase(&self, _preview: &str) -> Result { - Ok(self.assume_yes) - } - fn confirm_final(&self, _message: &str) -> Result { - Ok(self.assume_yes) - } -} - -/// The single authoritative validation boundary. Runs immediately before any -/// privileged mutation, in both the unprivileged pre-check and the broker after -/// authentication. It binds the approval to the exact actions, effects, -/// candidate, target root and initiating user, re-derives the plan seal, and -/// revalidates live state. Plan files are untrusted input. -pub fn validate_prepared_plan( - exec: &Exec, - root: &Path, - plan: &PreparedPlan, - expected_digest: Option<&str>, - initiator_uid: u32, -) -> Result<()> { - if plan.integrity.is_empty() || plan.integrity != plan_integrity(plan) { - return Err(ExecError::operation( - "service", - "validate plan", - "plan integrity check failed; the plan was modified after it was reviewed", - )); - } - if !is_safe_plan_id(&plan.id) { - return Err(ExecError::operation( - "service", - "validate plan", - "plan has an invalid identifier", - )); - } - if plan.executed { - return Err(ExecError::operation( - "service", - "validate plan", - "plan has already been executed; replayed plans are rejected", - )); - } - if now_unix() > plan.expires_unix { - return Err(ExecError::operation( - "service", - "validate plan", - "plan has expired; review and approve a fresh plan", - )); - } - if plan.actions.is_empty() { - return Err(ExecError::operation( - "service", - "validate plan", - "plan proposes no actions", - )); - } - // Independently recompute the canonical approval digest from the exact - // executable actions, candidate and reviewed material effects. The - // `integrity` seal stored beside the plan is a self-consistency check the - // owning user can recompute, so it is not authentication: the canonical - // digest is. It must match the digest stored in the plan *and* the - // independently supplied approval digest. This binds every plan kind - // (Install, LegacyInstall, Removal, General, Undo) to the reviewed actions, - // so retaining an old digest while swapping an action and resealing is - // rejected before any mutation. - // - // Execution trusts the per-step effects (`step_effects`), so those must be - // bound too: each stored effect digest must match its actual contents, the - // aggregate must be the concatenation of the steps, and the canonical - // digest must cover every step. This closes the "retain the approved digest, - // change only `step_effects`, reseal" gap for General and Undo plans. - let steps = reviewed_steps(plan)?; - validate_effect_bindings(plan, &steps)?; - let canonical = compute_plan_digest( - &plan.actions, - plan.candidate.as_ref(), - &plan.effects, - &steps, - ); - if plan.digest != canonical { - return Err(ExecError::operation( - "service", - "validate plan", - "plan digest does not match its reviewed actions and effects; the plan was \ - substituted or resealed and is refused", - )); - } - if let Some(digest) = expected_digest { - if !digest.is_empty() && canonical != digest { - return Err(ExecError::operation( - "service", - "validate plan", - "approval digest mismatch; the plan was altered or is not the one reviewed", - )); - } - } - if plan.target_root.is_empty() { - return Err(ExecError::operation( - "service", - "validate plan", - "plan does not record a target root; refusing to guess `/`", - )); - } - let want_root = canonical_root(root); - if plan.target_root != want_root { - return Err(ExecError::operation( - "service", - "validate plan", - format!( - "target root mismatch: the plan was reviewed for {} but execution targets {}", - plan.target_root, want_root - ), - )); - } - if plan.initiator_uid != initiator_uid { - return Err(ExecError::operation( - "service", - "validate plan", - format!( - "plan belongs to uid {} and cannot be executed by uid {initiator_uid}", - plan.initiator_uid - ), - )); - } - revalidate_plan_state(exec, root, plan) -} - -/// Revalidate a plan's material state against live metadata. A material change -/// invalidates the earlier approval. -fn revalidate_plan_state(exec: &Exec, root: &Path, plan: &PreparedPlan) -> Result<()> { - match plan.kind { - PlanKind::Install | PlanKind::LegacyInstall => { - let (Some(cand), Some(act)) = (&plan.candidate, plan.actions.first()) else { - return Err(ExecError::operation( - "service", - "revalidate", - "installation plan is missing its candidate or action", - )); - }; - let resolved = install::ResolvedInstall { - request: InstallRequest::new(plan.application.as_deref().unwrap_or("")), - candidate: cand.clone(), - action: act.clone(), - effects: plan.effects.clone(), - rationale: plan.rationale.clone(), - alternatives: plan.alternatives.clone(), - source: match plan.kind { - PlanKind::LegacyInstall => InstallSource::ExplicitBackend, - _ => InstallSource::AiRecommendation, - }, - warnings: plan.warnings.clone(), - verification: plan.verification.clone(), - }; - let current_digest = install::revalidate(exec, root, &resolved).map_err(|e| { - ExecError::operation( - "service", - "revalidate", - format!("the reviewed plan changed before execution ({e}); review again"), - ) - })?; - if current_digest != plan.digest { - return Err(ExecError::operation( - "service", - "revalidate", - "system state or package metadata changed materially since review; review again", - )); - } - } - PlanKind::Removal => { - let Some(app) = &plan.application else { - return Err(ExecError::operation( - "service", - "revalidate", - "removal plan has no application", - )); - }; - let check = chooser::installed_copies(exec, root, app); - if !check.copies.iter().any(|c| c.backend == plan.source) { - return Err(ExecError::operation( - "service", - "revalidate", - format!( - "`{app}` is no longer installed via {}; the removal plan is stale", - plan.source - ), - )); - } - if let Some(act) = plan.actions.first() { - let eff = actions::resolve_effects(exec, act, root)?; - if eff.established && plan.effects.established && eff.digest != plan.effects.digest - { - return Err(ExecError::operation( - "service", - "revalidate", - "the removal effects changed since review; review again", - )); - } - } - } - PlanKind::General | PlanKind::Undo => { - if plan.step_effects.len() == plan.actions.len() && !plan.step_effects.is_empty() { - // Compare each step against its own reviewed effects, never one - // action against the whole plan. - for (act, reviewed) in plan.actions.iter().zip(plan.step_effects.iter()) { - let eff = actions::resolve_effects(exec, act, root)?; - if reviewed.established && eff.established && reviewed.digest != eff.digest { - return Err(ExecError::operation( - "service", - "revalidate", - format!( - "effects for `{}` changed materially since review; review again", - act.describe() - ), - )); - } - } - } else { - // Older plans carried only the aggregate; recompute the same - // aggregate and compare, rather than mixing per-action digests. - let mut combined = ResolvedPlan { - established: true, - ..Default::default() - }; - for act in &plan.actions { - let eff = actions::resolve_effects(exec, act, root)?; - if eff.established { - combined.effects.extend(eff.effects); - combined.cleanup.extend(eff.cleanup); - combined.updates.extend(eff.updates); - combined.consequences.extend(eff.consequences); - } - } - combined.recompute_digest(); - if plan.effects.established && combined.digest != plan.effects.digest { - return Err(ExecError::operation( - "service", - "revalidate", - "system state or package effects changed materially since review; review again", - )); - } - } - } - } - Ok(()) -} - -/// Execute a prepared plan with full validation, elevation, verification, and -/// transaction recording. -pub fn execute_plan( - exec: &Exec, - root: &Path, - plans: &PlanStore, - plan_id: &str, - expected_digest: &str, - assume_yes: bool, -) -> Result { - let initiator = effective_uid(); - let plan = plans.load(plan_id)?; - validate_prepared_plan(exec, root, &plan, Some(expected_digest), initiator)?; - if plans.is_claimed(plan_id) { - return Err(ExecError::operation( - "service", - "execute_plan", - "plan has already been consumed; retrying will not repeat the mutation", - )); - } - - if plan.requires_root && initiator != 0 { - return elevate_and_execute(root, plan, initiator, expected_digest); - } - execute_prepared(exec, root, plans, plan, assume_yes, None) -} - -/// The privileged broker entry point. -/// -/// It repeats the full validation after authentication (never trusting the -/// unprivileged caller), binds execution to the independently preserved -/// `expected_digest` the approval UI showed the user, and anchors consumption in -/// the broker-controlled [`ApprovalLedger`]. A plan file replaced during -/// authentication no longer matches `expected_digest`; a replay is refused even -/// when the user deletes every file in their own plan directory. -#[allow(clippy::too_many_arguments)] -pub fn execute_plan_privileged( - exec: &Exec, - root: &Path, - plans: &PlanStore, - approvals: &ApprovalLedger, - plan_id: &str, - expected_digest: &str, - initiator_uid: u32, - assume_yes: bool, -) -> Result { - let plan = plans.load(plan_id)?; - // The expected digest is the independently preserved approval the user - // reviewed. A self-consistent reseal of a replacement plan cannot match it. - validate_prepared_plan(exec, root, &plan, Some(expected_digest), initiator_uid)?; - // `execute_prepared` authenticates *before* claiming the approval, so a - // cancelled or refused operation consumes nothing; it then anchors the - // claim in the broker-controlled ledger and records a terminal status. - execute_prepared( - exec, - root, - plans, - plan, - assume_yes, - Some((approvals, initiator_uid)), - ) -} - -fn elevate_and_execute( - root: &Path, - plan: PreparedPlan, - initiator: u32, - expected_digest: &str, -) -> Result { - let sys_exe = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("/usr/local/bin/sys")); - // The privileged broker is given the plan identifier, the independently - // preserved approval digest, the initiating uid and the exact target root. - // A dropped `--root` would (correctly) fail validation rather than execute - // against `/`. - let output = std::process::Command::new("pkexec") - .arg(sys_exe) - .arg("--broker") - .arg("--execute-plan") - .arg(&plan.id) - .arg("--plan-uid") - .arg(initiator.to_string()) - .arg("--approval-digest") - .arg(expected_digest) - .arg("--root") - .arg(canonical_root(root)) - .output() - .map_err(|e| { - ExecError::operation( - "service", - "pkexec", - format!("could not spawn pkexec for root authorization: {e}"), - ) - })?; - - if output.status.success() { - let out_str = String::from_utf8_lossy(&output.stdout); - return serde_json::from_str::(out_str.trim()).map_err(|e| { - ExecError::operation( - "service", - "broker protocol", - format!("privileged execution reported success but returned malformed output: {e}"), - ) - }); - } - let code = output.status.code().unwrap_or(1); - if code == 126 || code == 127 { - return Err(ExecError::operation( - "service", - "authenticate", - "authentication was cancelled; no changes were made", - )); - } - let err_msg = String::from_utf8_lossy(&output.stderr); - Err(ExecError::operation( - "service", - "pkexec", - format!( - "privileged execution failed (code {code}): {}", - err_msg.trim() - ), - )) -} - -/// Authenticate, claim and run a plan, recording a truthful transaction outcome -/// on every exit path (success, action failure, verification failure, -/// cancellation, and effect drift). When `approvals` is present the claim is -/// anchored in the broker-controlled ledger and always reaches a terminal -/// status; a refused or cancelled operation claims nothing. -fn execute_prepared( - exec: &Exec, - root: &Path, - plans: &PlanStore, - plan: PreparedPlan, - assume_yes: bool, - approvals: Option<(&ApprovalLedger, u32)>, -) -> Result { - // Authentication/refusal happens before any claim, so a refused plan is not - // consumed and stays reviewable (until it expires). - let confirm = ServiceConfirm { assume_yes }; - let auth = if plan.requires_root { - Some(authorize(&confirm, &plan.summary, "execute")?) - } else { - None - }; - - // Anchor the approval in the broker-controlled ledger before mutation. The - // key is the *stable* approval identity (plan id, canonical digest, - // authenticated initiating uid, target root); presentation fields are - // excluded, so editing the summary and resealing cannot mint a fresh entry - // for an already-consumed approval. - let approved_key = match approvals { - Some((ledger, uid)) => { - let identity = ApprovalIdentity::new( - plan.id.clone(), - plan.digest.clone(), - uid, - plan.target_root.clone(), - plan.expires_unix, - plan.actions.len(), - ); - ledger.claim(&identity)?; - Some(identity.key) - } - None => None, - }; - - let result = execute_claimed(exec, root, plans, &plan, auth.as_ref()); - - if let (Some((ledger, _)), Some(key)) = (approvals, approved_key.as_ref()) { - let (status, note) = match &result { - Ok(_) => (ApprovalStatus::Consumed, "ok".to_string()), - Err(e) => (ApprovalStatus::Failed, e.to_string()), - }; - // The transition is monotonic. A conflicting terminal (only possible if - // recovery had already declared the owner gone) must not be silently - // overwritten or reported as success. - match ledger.finish(key, status, ¬e) { - Ok(Finished::Recorded) => {} - Ok(Finished::AlreadyTerminal(existing)) if existing.status == status.as_str() => {} - Ok(Finished::AlreadyTerminal(existing)) => { - return Err(ExecError::operation( - "service", - "record approval", - format!( - "the approval already reached terminal status `{}` and was not \ - overwritten with `{}`", - existing.status, - status.as_str() - ), - )); - } - Err(ledger_err) => { - return match result { - Ok(_) => Err(ExecError::operation( - "service", - "record approval", - format!( - "the operation completed but its approval outcome could not be \ - recorded: {ledger_err}" - ), - )), - Err(e) => Err(ExecError::operation( - "service", - "record approval", - format!("{e}; the approval outcome could not be recorded: {ledger_err}"), - )), - }; - } - } - } - result -} - -/// The authenticated execution body. Freshly resolved effects are compared -/// against the reviewed per-step effects; only changes explained by earlier -/// approved steps are allowed. -fn execute_claimed( - exec: &Exec, - root: &Path, - plans: &PlanStore, - plan: &PreparedPlan, - auth: Option<&phoebus_executor::auth::DestructiveAuthorization>, -) -> Result { - // Atomic claim: at most one caller can proceed with this plan. - let _claim = plans.claim(&plan.id)?; - - let record = TransactionRecord { - id: 0, - created_unix: now_unix(), - origin: match plan.kind { - PlanKind::LegacyInstall => "sys-legacy".into(), - PlanKind::Removal => "sys-removal".into(), - _ => "assistant".into(), - }, - summary: plan.summary.clone(), - actions: plan.actions.iter().map(|a| a.describe()).collect(), - result: "in progress".into(), - snapshot: None, - digest: Some(plan.digest.clone()), - outcomes: Vec::new(), - }; - let tx_id = transaction::begin(exec, root, record)?; - - // Carry the *reviewed* per-step effects forward. Freshly resolved effects - // below are evidence to compare against these, never a replacement - // approval. `reviewed_steps` uses the same binding validation already - // performed at the privileged boundary. - let reviewed_steps: Vec = reviewed_steps(plan)?; - - let mut completed: Vec<(String, String)> = Vec::new(); - let mut outcomes: Vec = Vec::new(); - let mut snapshot: Option = None; - let mut introduced: Vec = Vec::new(); - let mut failure: Option<(String, String)> = None; - // A distinct, terminal "the approved plan no longer matches live state" - // reason: effect resolution failed, or the effects changed materially. - let mut drift: Option = None; - - for (idx, action) in plan.actions.iter().enumerate() { - let described = action.describe(); - if failure.is_some() || drift.is_some() { - outcomes.push(TransactionOutcome::unattempted(described)); - continue; - } - // Only Portage transactions have a comparable `emerge --pretend` plan - // at this boundary. Other lanes' effects were validated by - // `validate_prepared_plan` (install revalidation / installed-copy - // checks); re-resolving them here would see an empty plan and falsely - // report drift. - let mut current: Option = None; - if actions::resolves_effects(action) { - let reviewed = &reviewed_steps[idx]; - let resolved = match actions::resolve_effects(exec, action, root) { - Ok(current) => current, - Err(e) => { - let detail = format!("effect resolution failed for `{described}`: {e}"); - outcomes.push(TransactionOutcome::failed( - described.clone(), - detail.clone(), - )); - drift = Some(format!("stale plan: {detail}")); - continue; - } - }; - if !approval_holds(reviewed, &resolved, &introduced) { - let detail = format!( - "the reviewed effects for `{described}` changed materially before execution" - ); - outcomes.push(TransactionOutcome::failed( - described.clone(), - detail.clone(), - )); - drift = Some(format!("stale plan: {detail}")); - continue; - } - current = Some(resolved); - } - - // Execution carries the *reviewed* transaction for actions that must - // not re-discover state (Flatpak/Snap updates, cache cleanup). - let carried = if actions::resolves_effects(action) { - Some(&reviewed_steps[idx]) - } else { - None - }; - match actions::execute_inner(exec, action, auth, root, carried) { - Ok(result) => { - if result.snapshot.is_some() { - snapshot = result.snapshot; - } - outcomes.push(TransactionOutcome::completed(described.clone())); - completed.push((described, result.output)); - // Packages this approved action installed may legitimately - // appear in a later step's re-resolution. - if let Some(current) = current { - introduced.extend(current.effects); - } - } - Err(e) => { - let detail = e.to_string(); - outcomes.push(TransactionOutcome::failed( - described.clone(), - detail.clone(), - )); - failure = Some((described, detail)); - } - } - } - - if let Some(reason) = drift { - finish_or_report( - exec, - root, - tx_id, - reason.clone(), - snapshot.clone(), - outcomes.clone(), - "the stale plan was recorded", - )?; - return Err(ExecError::operation("service", "execute", reason)); - } - - if let Some((action_str, detail)) = &failure { - finish_or_report( - exec, - root, - tx_id, - format!("failed: {detail}"), - snapshot.clone(), - outcomes.clone(), - "the action failed", - )?; - return Err(ExecError::operation( - "service", - "execute", - format!("action failed: {action_str}: {detail}"), - )); - } - - // Post-execution verification. A verification error finishes the - // transaction as a failed verification; it never leaves it "in progress". - let verification_result = match plan.kind { - PlanKind::Install | PlanKind::LegacyInstall => { - if let (Some(cand), Some(act)) = (&plan.candidate, plan.actions.first()) { - let resolved = install::ResolvedInstall { - request: InstallRequest::new(plan.application.as_deref().unwrap_or("")), - candidate: cand.clone(), - action: act.clone(), - effects: plan.effects.clone(), - rationale: plan.rationale.clone(), - alternatives: plan.alternatives.clone(), - source: match plan.kind { - PlanKind::LegacyInstall => InstallSource::ExplicitBackend, - _ => InstallSource::AiRecommendation, - }, - warnings: plan.warnings.clone(), - verification: plan.verification.clone(), - }; - match install::verify_installed(exec, root, &resolved) { - Ok(text) => text, - Err(e) => { - finish_or_report( - exec, - root, - tx_id, - format!("verify failed: {e}"), - snapshot.clone(), - outcomes.clone(), - "verification failed", - )?; - return Err(e); - } - } - } else { - "verified ok".into() - } - } - PlanKind::Removal => { - if let Some(app) = &plan.application { - let check = chooser::installed_copies(exec, root, app); - if let Some(ref_copy) = check.copies.iter().find(|c| c.backend == plan.source) { - let err = format!( - "removal reported success but `{app}` is still present in {} ({})", - ref_copy.backend, ref_copy.id - ); - finish_or_report( - exec, - root, - tx_id, - format!("verify failed: {err}"), - snapshot.clone(), - outcomes.clone(), - "verification failed", - )?; - return Err(ExecError::operation("service", "verify removal", err)); - } - format!("verified: `{app}` removed from {}", plan.source) - } else { - "removal verified ok".into() - } - } - _ => "ok".into(), - }; - - let launch = detect_launch(root, plan); - - finish_or_report( - exec, - root, - tx_id, - "ok", - snapshot.clone(), - outcomes.clone(), - "the transaction could not be recorded", - )?; - - let outputs: Vec = completed.into_iter().map(|(_, out)| out).collect(); - - Ok(PlanExecutionOutcome { - completed: true, - snapshot, - result: "ok".into(), - verification: verification_result, - output: outputs, - launch, - }) -} - -/// Finish a transaction, surfacing a persistence failure instead of hiding it. -/// The execution result is preserved either way. -fn finish_or_report( - exec: &Exec, - root: &Path, - tx_id: u64, - result: impl Into, - snapshot: Option, - outcomes: Vec, - persistence_note: &str, -) -> Result<()> { - let result = result.into(); - match transaction::finish(exec, root, tx_id, result.clone(), snapshot, outcomes) { - Ok(()) => Ok(()), - Err(e) => Err(ExecError::operation( - "service", - "record transaction", - format!("{persistence_note}: {result} (history error: {e})"), - )), - } -} - -/// Identify a concrete launch command for a freshly installed application. -/// Only offered when a desktop entry (or an unambiguous Flatpak/Snap command) -/// is actually found; never guessed. -fn detect_launch(root: &Path, plan: &PreparedPlan) -> Option> { - let candidate = plan.candidate.as_ref()?; - match candidate.backend { - Backend::Flatpak => { - return Some(vec!["flatpak".into(), "run".into(), candidate.id.clone()]) - } - Backend::Snap => return Some(vec![candidate.id.clone()]), - _ => {} - } - let app = plan.application.as_deref().unwrap_or(""); - let stem = app.rsplit('/').next().unwrap_or(app).to_ascii_lowercase(); - if stem.is_empty() { - return None; - } - let dir = root.join("usr/share/applications"); - let entries = std::fs::read_dir(&dir).ok()?; - for entry in entries.flatten() { - let path = entry.path(); - if path.extension().and_then(|e| e.to_str()) != Some("desktop") { - continue; - } - let file_stem = path - .file_stem() - .and_then(|s| s.to_str()) - .unwrap_or("") - .to_ascii_lowercase(); - if file_stem == stem || file_stem.starts_with(&format!("{stem}.")) { - return Some(vec!["gtk-launch".into(), file_stem]); - } - } - None -} - -#[cfg(test)] -mod tests { - use super::*; - use phoebus_core::effects::parse_emerge_pretend; - use phoebus_core::selection::Capability; - use phoebus_core::Redactor; - use phoebus_executor::command::RecordingRunner; - use phoebus_executor::Logger; - use tempfile::tempdir; - - fn make_test_exec(root: &Path) -> Exec { - let temp = tempdir().unwrap().keep(); - let logger = Logger::open(temp.join("test.log"), Redactor::new(), false); - Exec::new( - Box::new(RecordingRunner::new()), - logger, - false, - root.to_path_buf(), - temp, - ) - } - - fn sample_candidate() -> Candidate { - let mut cand = Candidate::new(Backend::Flatpak, "org.mozilla.firefox", "flathub"); - cand.version = Some("120.0".into()); - cand.verified = true; - cand.download_mib = Some(85); - cand.install_mib = Some(230); - cand.sandbox = SandboxLevel::Strong; - cand.wayland = Capability::Yes; - cand.desktop_integration = Capability::Yes; - cand.permissions = vec!["network".into()]; - cand - } - - #[test] - fn test_format_recommendation_honest() { - let cand = sample_candidate(); - let rec = format_recommendation(&cand, "firefox"); - assert!(rec.contains("Flathub")); - assert!(rec.contains("strong application isolation")); - assert!(rec.contains("pre-built binary")); - assert!(!rec.contains("avoids a lengthy build")); - } - - /// Build a sealed plan for validation tests. The canonical approval digest - /// is derived from the actions and reviewed effects, exactly as the - /// privileged boundary does; the trailing marker argument is retained only - /// so existing call sites read naturally and is ignored. - fn sealed( - id: &str, - kind: PlanKind, - actions: Vec, - _marker: &str, - target_root: &Path, - initiator_uid: u32, - ) -> PreparedPlan { - let mut effects = ResolvedPlan::default(); - effects.recompute_digest(); - let step_effects = vec![effects.clone(); actions.len()]; - let digest = compute_plan_digest(&actions, None, &effects, &step_effects); - let mut plan = PreparedPlan { - id: id.into(), - created_unix: now_unix(), - expires_unix: now_unix() + 900, - kind, - summary: "test plan".into(), - recommendation: "rec".into(), - application: Some("firefox".into()), - candidate: None, - alternatives: Vec::new(), - rationale: Vec::new(), - warnings: Vec::new(), - actions, - effects, - step_effects, - digest, - verification: "verify".into(), - requires_root: false, - source: "test".into(), - executed: false, - target_root: canonical_root(target_root), - initiator_uid, - integrity: String::new(), - }; - seal_plan(&mut plan); - plan - } - - #[test] - fn plan_store_roundtrips_and_claims_once() { - let dir = tempdir().unwrap(); - let store = PlanStore::with_dir(dir.path()); - let mut plan = sealed( - "plan-abc", - PlanKind::General, - vec![SystemAction::History], - "d", - Path::new("/tmp"), - 0, - ); - store.save(&mut plan).unwrap(); - let loaded = store.load("plan-abc").unwrap(); - assert_eq!(loaded.id, "plan-abc"); - - let _claim = store.claim("plan-abc").unwrap(); - assert!(store.is_claimed("plan-abc")); - // A second claim (or a retry after a crash) must not run the mutation. - assert!(store.claim("plan-abc").is_err()); - } - - #[test] - fn concurrent_claims_allow_at_most_one_execution() { - let dir = tempdir().unwrap(); - let store = PlanStore::with_dir(dir.path()); - let mut plan = sealed( - "plan-race", - PlanKind::General, - vec![SystemAction::History], - "d", - Path::new("/tmp"), - 0, - ); - store.save(&mut plan).unwrap(); - - let handles: Vec<_> = (0..8) - .map(|_| { - let store = store.clone(); - std::thread::spawn(move || store.claim("plan-race").is_ok()) - }) - .collect(); - let successes = handles - .into_iter() - .map(|h| h.join().expect("claim thread panicked")) - .filter(|won| *won) - .count(); - assert_eq!(successes, 1, "exactly one claim may win"); - } - - #[test] - fn replacing_the_plan_after_review_is_rejected() { - let dir = tempdir().unwrap(); - let store = PlanStore::with_dir(dir.path()); - let root = tempdir().unwrap(); - let exec = make_test_exec(root.path()); - let uid = effective_uid(); - - let mut original = sealed( - "plan-replace", - PlanKind::General, - vec![SystemAction::History], - "reviewed-digest", - root.path(), - uid, - ); - store.save(&mut original).unwrap(); - - // An attacker (or a re-plan) replaces the stored plan under the same id. - let mut replacement = sealed( - "plan-replace", - PlanKind::General, - vec![SystemAction::EnableService { - name: "sshd".into(), - }], - "different-digest", - root.path(), - uid, - ); - replacement.requires_root = true; - seal_plan(&mut replacement); - store.save(&mut replacement).unwrap(); - - // The unprivileged caller's reviewed digest no longer matches. - let err = execute_plan( - &exec, - root.path(), - &store, - "plan-replace", - "reviewed-digest", - true, - ) - .unwrap_err(); - assert!(err.to_string().contains("digest mismatch"), "{err}"); - // And nothing was consumed. - assert!(!store.is_claimed("plan-replace")); - } - - #[test] - fn plan_store_rejects_traversal_and_bad_ids() { - let dir = tempdir().unwrap(); - let store = PlanStore::with_dir(dir.path()); - assert!(store.load("../escape").is_err()); - assert!(store.load("a/b").is_err()); - assert!(store.load("").is_err()); - } - - #[test] - fn plan_store_rejects_group_writable_files() { - use std::os::unix::fs::PermissionsExt; - let dir = tempdir().unwrap(); - let store = PlanStore::with_dir(dir.path()); - let mut plan = sealed( - "plan-mode", - PlanKind::General, - vec![SystemAction::History], - "d", - Path::new("/tmp"), - 0, - ); - let path = store.save(&mut plan).unwrap(); - std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o666)).unwrap(); - assert!(store.load("plan-mode").is_err()); - } - - #[test] - fn validation_rejects_tampering_expiry_replay_root_and_uid() { - let store_dir = tempdir().unwrap(); - let store = PlanStore::with_dir(store_dir.path()); - let root = tempdir().unwrap(); - let exec = make_test_exec(root.path()); - let uid = effective_uid(); - - // Baseline validates. - let mut plan = sealed( - "plan-ok", - PlanKind::General, - vec![SystemAction::History], - "same-digest", - root.path(), - uid, - ); - store.save(&mut plan).unwrap(); - let loaded = store.load("plan-ok").unwrap(); - validate_prepared_plan(&exec, root.path(), &loaded, Some(&loaded.digest), uid).unwrap(); - - // Tampering with any reviewed field breaks the seal. - let path = store_dir.path().join("plan-ok.json"); - let mut raw: serde_json::Value = - serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); - raw["summary"] = serde_json::json!("tampered"); - std::fs::write(&path, serde_json::to_string(&raw).unwrap()).unwrap(); - let tampered = store.load("plan-ok").unwrap(); - let err = validate_prepared_plan(&exec, root.path(), &tampered, None, uid).unwrap_err(); - assert!(err.to_string().contains("integrity"), "{err}"); - - // Expired. - let mut expired = sealed( - "plan-exp", - PlanKind::General, - vec![SystemAction::History], - "d", - root.path(), - uid, - ); - expired.expires_unix = 10; - seal_plan(&mut expired); - store.save(&mut expired).unwrap(); - let err = validate_prepared_plan( - &exec, - root.path(), - &store.load("plan-exp").unwrap(), - None, - uid, - ) - .unwrap_err(); - assert!(err.to_string().contains("expired"), "{err}"); - - // Replayed. - let mut replayed = sealed( - "plan-rep", - PlanKind::General, - vec![SystemAction::History], - "d", - root.path(), - uid, - ); - replayed.executed = true; - seal_plan(&mut replayed); - store.save(&mut replayed).unwrap(); - let err = validate_prepared_plan( - &exec, - root.path(), - &store.load("plan-rep").unwrap(), - None, - uid, - ) - .unwrap_err(); - assert!(err.to_string().contains("already been executed"), "{err}"); - - // Wrong target root: reviewed for /, executed against the temp root. - let mut wrong_root = sealed( - "plan-root", - PlanKind::General, - vec![SystemAction::History], - "d", - Path::new("/"), - uid, - ); - seal_plan(&mut wrong_root); - store.save(&mut wrong_root).unwrap(); - let err = validate_prepared_plan( - &exec, - root.path(), - &store.load("plan-root").unwrap(), - None, - uid, - ) - .unwrap_err(); - assert!(err.to_string().contains("target root mismatch"), "{err}"); - - // Wrong initiator uid. - let mut wrong_uid = sealed( - "plan-uid", - PlanKind::General, - vec![SystemAction::History], - "d", - root.path(), - uid, - ); - seal_plan(&mut wrong_uid); - store.save(&mut wrong_uid).unwrap(); - let err = validate_prepared_plan( - &exec, - root.path(), - &store.load("plan-uid").unwrap(), - None, - uid.wrapping_add(4242), - ) - .unwrap_err(); - assert!( - err.to_string().contains("cannot be executed by uid"), - "{err}" - ); - } - - #[test] - fn validation_rejects_digest_mismatch_and_malformed_action_set() { - let store_dir = tempdir().unwrap(); - let store = PlanStore::with_dir(store_dir.path()); - let root = tempdir().unwrap(); - let exec = make_test_exec(root.path()); - let uid = effective_uid(); - - let mut plan = sealed( - "plan-dig", - PlanKind::General, - vec![SystemAction::History], - "correct", - root.path(), - uid, - ); - store.save(&mut plan).unwrap(); - let err = validate_prepared_plan( - &exec, - root.path(), - &store.load("plan-dig").unwrap(), - Some("wrong"), - uid, - ) - .unwrap_err(); - assert!(err.to_string().contains("digest mismatch"), "{err}"); - - let mut empty = sealed( - "plan-empty", - PlanKind::General, - Vec::new(), - "d", - root.path(), - uid, - ); - seal_plan(&mut empty); - store.save(&mut empty).unwrap(); - let err = validate_prepared_plan( - &exec, - root.path(), - &store.load("plan-empty").unwrap(), - None, - uid, - ) - .unwrap_err(); - assert!(err.to_string().contains("no actions"), "{err}"); - } - - struct FlatpakRunner { - installed: std::sync::Arc, - /// When true, a successful `flatpak install` marks the app installed, - /// so verification can succeed. When false, verification always fails. - mark_on_install: bool, - } - - impl phoebus_executor::command::ProcessRunner for FlatpakRunner { - fn execute( - &self, - spec: &phoebus_executor::command::CommandSpec, - ) -> Result { - use std::time::Duration; - let ok = |s: String| phoebus_executor::command::CommandOutput { - status: 0, - success: true, - stdout: s.into_bytes(), - stderr: Vec::new(), - duration: Duration::from_millis(1), - }; - let invokes_flatpak_install = spec.args.iter().any(|a| a == "install") - && (spec.program == "flatpak" || spec.args.iter().any(|a| a == "flatpak")); - if invokes_flatpak_install { - if self.mark_on_install { - self.installed - .store(true, std::sync::atomic::Ordering::SeqCst); - } - return Ok(ok("installed\n".into())); - } - let installed = self.installed.load(std::sync::atomic::Ordering::SeqCst); - let is_flatpak = spec.program == "flatpak" || spec.args.iter().any(|a| a == "flatpak"); - if is_flatpak && spec.args.iter().any(|a| a == "search") { - Ok(ok("org.mozilla.firefox 128\n".into())) - } else if is_flatpak && spec.args.iter().any(|a| a == "list") { - if !installed { - return Ok(ok(String::new())); - } - // `--columns=application` (verification) vs the richer - // `application,name,version` (discovery). - if spec.args.iter().any(|a| a == "--columns=application") { - Ok(ok("org.mozilla.firefox\n".into())) - } else { - Ok(ok("org.mozilla.firefox Firefox 128\n".into())) - } - } else { - Ok(ok(String::new())) - } - } - } - - fn make_exec_with_runner( - root: &Path, - runner: Box, - ) -> Exec { - let temp = tempdir().unwrap().keep(); - let logger = Logger::open(temp.join("test.log"), Redactor::new(), false); - Exec::new(runner, logger, false, root.to_path_buf(), temp) - } - - /// A target that actually has a Flatpak client, so lane availability - /// resolves from the target rather than the host. - fn install_fake_flatpak(root: &Path) { - use std::os::unix::fs::PermissionsExt; - let bin = root.join("usr/bin"); - std::fs::create_dir_all(&bin).unwrap(); - let flatpak = bin.join("flatpak"); - std::fs::write(&flatpak, "#!/bin/sh\n").unwrap(); - std::fs::set_permissions(&flatpak, std::fs::Permissions::from_mode(0o755)).unwrap(); - } - - #[test] - fn install_verification_failure_finishes_the_transaction_as_failed() { - let root = tempdir().unwrap(); - let installed = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - let exec = make_exec_with_runner( - root.path(), - Box::new(FlatpakRunner { - installed: installed.clone(), - mark_on_install: false, - }), - ); - let store = PlanStore::with_dir(tempdir().unwrap().keep()); - let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); - install_fake_flatpak(root.path()); - - let mut request = InstallRequest::new("firefox"); - request.backend = Some(Backend::Flatpak); - let plan = plan_legacy_install(&store, &exec, root.path(), &request).unwrap(); - - // The install command "succeeds" but `flatpak list` never reports the - // app: verification must fail and the transaction must not say "ok". - let err = execute_plan_privileged( - &exec, - root.path(), - &store, - &approvals, - &plan.id, - &plan.digest, - plan.initiator_uid, - true, - ) - .unwrap_err(); - assert!(err.to_string().contains("Flatpak"), "{err}"); - - let log = transaction::read(root.path()).unwrap(); - assert_eq!( - log.records.len(), - 1, - "one transaction, not stuck in progress" - ); - assert!( - log.records[0].result.starts_with("verify failed"), - "{}", - log.records[0].result - ); - // The plan was consumed exactly once and cannot be retried. - assert!(execute_plan_privileged( - &exec, - root.path(), - &store, - &approvals, - &plan.id, - &plan.digest, - plan.initiator_uid, - true, - ) - .is_err()); - } - - #[test] - fn successful_install_finishes_ok_and_records_a_launch_command() { - let root = tempdir().unwrap(); - let installed = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - let exec = make_exec_with_runner( - root.path(), - Box::new(FlatpakRunner { - installed: installed.clone(), - mark_on_install: true, - }), - ); - let store = PlanStore::with_dir(tempdir().unwrap().keep()); - let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); - install_fake_flatpak(root.path()); - let mut request = InstallRequest::new("firefox"); - request.backend = Some(Backend::Flatpak); - let plan = plan_legacy_install(&store, &exec, root.path(), &request).unwrap(); - - let outcome = execute_plan_privileged( - &exec, - root.path(), - &store, - &approvals, - &plan.id, - &plan.digest, - plan.initiator_uid, - true, - ) - .unwrap(); - assert!(outcome.completed); - assert_eq!( - outcome.launch, - Some(vec![ - "flatpak".into(), - "run".into(), - "org.mozilla.firefox".into() - ]) - ); - let log = transaction::read(root.path()).unwrap(); - assert_eq!(log.records[0].result, "ok"); - } - - #[test] - fn explicit_refusal_does_not_mutate_or_consume_the_plan() { - let root = tempdir().unwrap(); - let exec = make_test_exec(root.path()); - let store = PlanStore::with_dir(tempdir().unwrap().keep()); - let mut plan = sealed( - "plan-refuse", - PlanKind::General, - vec![SystemAction::EnableService { - name: "sshd".into(), - }], - "d", - root.path(), - effective_uid(), - ); - plan.requires_root = true; - seal_plan(&mut plan); - store.save(&mut plan).unwrap(); - - let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); - let err = execute_plan_privileged( - &exec, - root.path(), - &store, - &approvals, - &plan.id, - &plan.digest, - plan.initiator_uid, - false, - ) - .unwrap_err(); - assert!(matches!(err, ExecError::NotAuthorized(_)), "{err}"); - assert!( - !store.is_claimed(&plan.id), - "a refused plan is not consumed" - ); - // Refusal happens before the approval is claimed, so nothing is - // consumed in the broker ledger either. - let key = approval_identity(&plan, plan.initiator_uid).key; - assert!( - approvals.get(&key).unwrap().is_none(), - "a refused plan must not consume its approval" - ); - } - - /// The stable approval identity the broker derives for a plan. - fn approval_identity(plan: &PreparedPlan, uid: u32) -> ApprovalIdentity { - ApprovalIdentity::new( - plan.id.clone(), - plan.digest.clone(), - uid, - plan.target_root.clone(), - plan.expires_unix, - plan.actions.len(), - ) - } - - // ----------------------------------------------------------------------- - // Regression tests for the approval boundary and transaction truthfulness. - // ----------------------------------------------------------------------- - - const VIM_PRETEND: &str = "Calculating dependencies... done!\n\ - [ebuild N ] app-editors/vim-9.1.0\n\nTotal: 1 package\n"; - const WGET_PRETEND: &str = "Calculating dependencies... done!\n\ - [ebuild N ] net-misc/wget-1.24.5\n\nTotal: 1 package\n"; - - fn command_out(text: &str, success: bool) -> phoebus_executor::command::CommandOutput { - phoebus_executor::command::CommandOutput { - status: if success { 0 } else { 1 }, - success, - stdout: text.as_bytes().to_vec(), - stderr: Vec::new(), - duration: std::time::Duration::from_millis(1), - } - } - - struct SequenceRunner { - responses: std::sync::Mutex>, - fallback: phoebus_executor::command::CommandOutput, - } - - impl phoebus_executor::command::ProcessRunner for SequenceRunner { - fn execute( - &self, - _spec: &phoebus_executor::command::CommandSpec, - ) -> Result { - let mut responses = self.responses.lock().unwrap(); - if !responses.is_empty() { - return Ok(responses.remove(0)); - } - Ok(self.fallback.clone()) - } - } - - fn portage_install_plan( - id: &str, - action: SystemAction, - reviewed: ResolvedPlan, - root: &Path, - uid: u32, - ) -> PreparedPlan { - let actions = vec![action]; - let mut reviewed = reviewed; - reviewed.recompute_digest(); - let step_effects = vec![reviewed.clone()]; - let digest = compute_plan_digest(&actions, None, &reviewed, &step_effects); - let mut plan = PreparedPlan { - id: id.into(), - created_unix: now_unix(), - expires_unix: now_unix() + 900, - kind: PlanKind::General, - summary: "install reviewed package".into(), - recommendation: "rec".into(), - application: Some("app-editors/vim".into()), - candidate: None, - alternatives: Vec::new(), - rationale: Vec::new(), - warnings: Vec::new(), - actions, - effects: reviewed, - step_effects, - digest, - verification: "verify".into(), - requires_root: true, - source: "test".into(), - executed: false, - target_root: canonical_root(root), - initiator_uid: uid, - integrity: String::new(), - }; - seal_plan(&mut plan); - plan - } - - fn ledger_entries(ledger: &ApprovalLedger) -> usize { - std::fs::read_dir(ledger.dir()) - .map(|d| d.flatten().count()) - .unwrap_or(0) - } - - #[test] - fn replacing_the_plan_during_authentication_is_rejected() { - let root = tempdir().unwrap(); - let exec = make_test_exec(root.path()); - let store = PlanStore::with_dir(tempdir().unwrap().keep()); - let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); - let uid = effective_uid(); - - let mut original = sealed( - "plan-replace", - PlanKind::General, - vec![SystemAction::History], - "reviewed-digest", - root.path(), - uid, - ); - store.save(&mut original).unwrap(); - let approved_digest = original.digest.clone(); - - // Replace the plan under the same identifier with a different action and - // a valid recomputed checksum. - let mut replacement = sealed( - "plan-replace", - PlanKind::General, - vec![SystemAction::EnableService { - name: "sshd".into(), - }], - "different-digest", - root.path(), - uid, - ); - replacement.requires_root = true; - seal_plan(&mut replacement); - assert_eq!( - replacement.integrity, - plan_integrity(&replacement), - "the replacement is self-consistent, yet must still be refused" - ); - store.save(&mut replacement).unwrap(); - - let err = execute_plan_privileged( - &exec, - root.path(), - &store, - &approvals, - "plan-replace", - &approved_digest, - uid, - true, - ) - .unwrap_err(); - assert!(err.to_string().contains("digest mismatch"), "{err}"); - // No system mutation and no approval consumed. - assert_eq!(ledger_entries(&approvals), 0, "nothing may be claimed"); - } - - #[test] - fn replay_is_rejected_after_the_user_deletes_their_plan_state() { - let root = tempdir().unwrap(); - let exec = make_test_exec(root.path()); - let store = PlanStore::with_dir(tempdir().unwrap().keep()); - let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); - let uid = effective_uid(); - - let mut plan = sealed( - "plan-replay", - PlanKind::General, - vec![SystemAction::History], - "d", - root.path(), - uid, - ); - let path = store.save(&mut plan).unwrap(); - let digest = plan.digest.clone(); - let bytes = std::fs::read(&path).unwrap(); - - execute_plan_privileged( - &exec, - root.path(), - &store, - &approvals, - "plan-replay", - &digest, - uid, - true, - ) - .unwrap(); - - // The user wipes their own plan and claim files and rewrites the plan - // with identical bytes (0600, as the store would): the approval is still - // consumed. - std::fs::remove_file(&path).unwrap(); - let _ = std::fs::remove_file(store.dir().join("plan-replay.claim")); - std::fs::write(&path, &bytes).unwrap(); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); - } - - let err = execute_plan_privileged( - &exec, - root.path(), - &store, - &approvals, - "plan-replay", - &digest, - uid, - true, - ) - .unwrap_err(); - assert!(err.to_string().contains("already used"), "{err}"); - } - - #[test] - fn concurrent_privileged_executions_allow_at_most_one() { - let root = tempdir().unwrap().keep(); - let store = PlanStore::with_dir(tempdir().unwrap().keep()); - let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); - let uid = effective_uid(); - - let mut plan = sealed( - "plan-concurrent", - PlanKind::General, - vec![SystemAction::History], - "d", - &root, - uid, - ); - store.save(&mut plan).unwrap(); - let digest = plan.digest.clone(); - let id = plan.id.clone(); - - let handles: Vec<_> = (0..8) - .map(|_| { - let root = root.clone(); - let store = store.clone(); - let approvals = approvals.clone(); - let id = id.clone(); - let digest = digest.clone(); - std::thread::spawn(move || { - let exec = make_test_exec(&root); - execute_plan_privileged( - &exec, &root, &store, &approvals, &id, &digest, uid, true, - ) - .is_ok() - }) - }) - .collect(); - let successes = handles - .into_iter() - .map(|h| h.join().expect("execution thread panicked")) - .filter(|won| *won) - .count(); - assert_eq!(successes, 1, "exactly one execution may proceed"); - } - - #[test] - fn wrong_caller_root_and_expired_plans_are_rejected() { - let root = tempdir().unwrap(); - let other_root = tempdir().unwrap(); - let exec = make_test_exec(root.path()); - let store = PlanStore::with_dir(tempdir().unwrap().keep()); - let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); - let uid = effective_uid(); - - let mut plan = sealed( - "plan-guard", - PlanKind::General, - vec![SystemAction::History], - "d", - root.path(), - uid, - ); - store.save(&mut plan).unwrap(); - - let err = execute_plan_privileged( - &exec, - root.path(), - &store, - &approvals, - "plan-guard", - &plan.digest, - uid.wrapping_add(4242), - true, - ) - .unwrap_err(); - assert!( - err.to_string().contains("cannot be executed by uid"), - "{err}" - ); - - let err = execute_plan_privileged( - &exec, - other_root.path(), - &store, - &approvals, - "plan-guard", - &plan.digest, - uid, - true, - ) - .unwrap_err(); - assert!(err.to_string().contains("target root mismatch"), "{err}"); - - let mut expired = sealed( - "plan-expired", - PlanKind::General, - vec![SystemAction::History], - "d", - root.path(), - uid, - ); - expired.expires_unix = 1; - seal_plan(&mut expired); - store.save(&mut expired).unwrap(); - let err = execute_plan_privileged( - &exec, - root.path(), - &store, - &approvals, - "plan-expired", - &expired.digest, - uid, - true, - ) - .unwrap_err(); - assert!(err.to_string().contains("expired"), "{err}"); - assert_eq!(ledger_entries(&approvals), 0); - } - - #[test] - fn an_interrupted_operation_is_reconciled_and_cannot_be_retried() { - let root = tempdir().unwrap(); - let exec = make_test_exec(root.path()); - let store = PlanStore::with_dir(tempdir().unwrap().keep()); - let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); - let uid = effective_uid(); - - let mut plan = sealed( - "plan-interrupted", - PlanKind::General, - vec![SystemAction::History], - "d", - root.path(), - uid, - ); - store.save(&mut plan).unwrap(); - - // Simulate a crash after claiming but before finishing: the owning - // process is provably gone, so reconciliation recovers it. - let dead = crate::approval::ProcessIdentity { - pid: u32::MAX, - start_ticks: 1, - boot_id: String::new(), - }; - let identity = approval_identity(&plan, uid); - approvals.claim_with_owner(&identity, dead).unwrap(); - assert_eq!(approvals.reconcile_interrupted().unwrap(), 1); - assert_eq!( - approvals.get(&identity.key).unwrap().unwrap().status, - "interrupted" - ); - - let err = execute_plan_privileged( - &exec, - root.path(), - &store, - &approvals, - &plan.id, - &plan.digest, - uid, - true, - ) - .unwrap_err(); - assert!(err.to_string().contains("already used"), "{err}"); - } - - #[test] - fn stale_effects_between_validation_and_execution_abort_the_transaction() { - let root = tempdir().unwrap(); - let uid = effective_uid(); - let reviewed = parse_emerge_pretend(VIM_PRETEND); - let changed = parse_emerge_pretend(WGET_PRETEND); - let runner = SequenceRunner { - responses: std::sync::Mutex::new(vec![ - command_out(VIM_PRETEND, true), - command_out(WGET_PRETEND, true), - ]), - fallback: command_out(WGET_PRETEND, true), - }; - let exec = make_exec_with_runner(root.path(), Box::new(runner)); - let store = PlanStore::with_dir(tempdir().unwrap().keep()); - let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); - - let mut plan = portage_install_plan( - "plan-drift", - SystemAction::InstallPackage { - atom: "app-editors/vim".into(), - binary: None, - }, - reviewed, - root.path(), - uid, - ); - store.save(&mut plan).unwrap(); - let digest = plan.digest.clone(); - - let err = execute_plan_privileged( - &exec, - root.path(), - &store, - &approvals, - "plan-drift", - &digest, - uid, - true, - ) - .unwrap_err(); - assert!(err.to_string().contains("stale plan"), "{err}"); - - let log = transaction::read(root.path()).unwrap(); - assert_eq!(log.records.len(), 1); - assert!( - log.records[0].result.starts_with("stale plan"), - "{}", - log.records[0].result - ); - assert!(!changed.effects.is_empty()); - } - - #[test] - fn effect_resolution_failure_after_transaction_begin_is_terminal() { - let root = tempdir().unwrap(); - let uid = effective_uid(); - let reviewed = parse_emerge_pretend(VIM_PRETEND); - let runner = SequenceRunner { - responses: std::sync::Mutex::new(vec![ - command_out(VIM_PRETEND, true), - command_out("not valid emerge output\n", true), - ]), - fallback: command_out("not valid emerge output\n", true), - }; - let exec = make_exec_with_runner(root.path(), Box::new(runner)); - let store = PlanStore::with_dir(tempdir().unwrap().keep()); - let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); - - let mut plan = portage_install_plan( - "plan-resolve-fail", - SystemAction::InstallPackage { - atom: "app-editors/vim".into(), - binary: None, - }, - reviewed, - root.path(), - uid, - ); - store.save(&mut plan).unwrap(); - let digest = plan.digest.clone(); - - let err = execute_plan_privileged( - &exec, - root.path(), - &store, - &approvals, - "plan-resolve-fail", - &digest, - uid, - true, - ) - .unwrap_err(); - assert!( - err.to_string().contains("effect resolution failed"), - "{err}" - ); - - let log = transaction::read(root.path()).unwrap(); - assert_eq!(log.records.len(), 1); - assert!( - log.records[0].result.contains("effect resolution failed"), - "{}", - log.records[0].result - ); - let key = approval_identity(&plan, uid).key; - assert!( - approvals - .get(&key) - .unwrap() - .is_some_and(|r| r.status == "failed"), - "the approval must reach a terminal failed status" - ); - } - - struct FailFlatpakRunner; - - impl phoebus_executor::command::ProcessRunner for FailFlatpakRunner { - fn execute( - &self, - spec: &phoebus_executor::command::CommandSpec, - ) -> Result { - // The target is chrooted, so the real program is `chroot` and the - // wrapped tool appears in the arguments. - if spec.program == "flatpak" || spec.args.iter().any(|a| a == "flatpak") { - return Err(ExecError::operation("test", "flatpak", "flatpak exploded")); - } - Ok(command_out("ok\n", true)) - } - } - - #[test] - fn a_later_step_failure_after_an_earlier_success_is_recorded_truthfully() { - let root = tempdir().unwrap(); - let uid = effective_uid(); - let exec = make_exec_with_runner(root.path(), Box::new(FailFlatpakRunner)); - let store = PlanStore::with_dir(tempdir().unwrap().keep()); - let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); - - let mut plan = sealed( - "plan-two-step", - PlanKind::General, - vec![ - SystemAction::EnableService { - name: "sshd".into(), - }, - SystemAction::FlatpakInstall { - app_id: "org.example.App".into(), - }, - ], - "d", - root.path(), - uid, - ); - plan.requires_root = true; - // `sealed` already stores one normalized per-step effect per action. - seal_plan(&mut plan); - store.save(&mut plan).unwrap(); - let digest = plan.digest.clone(); - - let err = execute_plan_privileged( - &exec, - root.path(), - &store, - &approvals, - "plan-two-step", - &digest, - uid, - true, - ) - .unwrap_err(); - assert!(err.to_string().contains("action failed"), "{err}"); - - let log = transaction::read(root.path()).unwrap(); - assert_eq!(log.records.len(), 1); - assert!( - log.records[0].result.starts_with("failed"), - "{}", - log.records[0].result - ); - let (done, failed, _) = log.records[0].outcome_counts(); - assert_eq!(done, 1, "the earlier step completed"); - assert_eq!(failed, 1, "the later step failed"); - } - - // ----------------------------------------------------------------------- - // Adversarial approval-boundary tests. - // ----------------------------------------------------------------------- - - /// Build a plan whose digest is the canonical digest for its (actions, - /// candidate, effects), sealed for storage. - fn canonical_plan( - id: &str, - kind: PlanKind, - actions: Vec, - candidate: Option, - effects: ResolvedPlan, - root: &Path, - uid: u32, - ) -> PreparedPlan { - let mut effects = effects; - effects.recompute_digest(); - let step_effects = vec![effects.clone(); actions.len()]; - let digest = compute_plan_digest(&actions, candidate.as_ref(), &effects, &step_effects); - let mut plan = PreparedPlan { - id: id.into(), - created_unix: now_unix(), - expires_unix: now_unix() + 900, - kind, - summary: "test plan".into(), - recommendation: "rec".into(), - application: Some("firefox".into()), - candidate, - alternatives: Vec::new(), - rationale: Vec::new(), - warnings: Vec::new(), - actions, - effects, - step_effects, - digest, - verification: "verify".into(), - requires_root: false, - source: "test".into(), - executed: false, - target_root: canonical_root(root), - initiator_uid: uid, - integrity: String::new(), - }; - seal_plan(&mut plan); - plan - } - - #[test] - fn a_general_plan_with_swapped_action_and_retained_approved_digest_is_rejected() { - let root = tempdir().unwrap(); - let uid = effective_uid(); - let reviewed = parse_emerge_pretend(VIM_PRETEND); - let substituted = parse_emerge_pretend(WGET_PRETEND); - let runner = RecordingRunner::new(); - let exec = make_exec_with_runner(root.path(), Box::new(runner.clone())); - let store = PlanStore::with_dir(tempdir().unwrap().keep()); - let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); - - let mut original = portage_install_plan( - "plan-swap", - SystemAction::InstallPackage { - atom: "app-editors/vim".into(), - binary: None, - }, - reviewed, - root.path(), - uid, - ); - store.save(&mut original).unwrap(); - let approved = original.digest.clone(); - - // The attacker swaps the action and its effects, recomputes the - // self-consistency seal, but deliberately retains the previously - // approved digest. - let mut forged = portage_install_plan( - "plan-swap", - SystemAction::InstallPackage { - atom: "net-misc/wget".into(), - binary: None, - }, - substituted, - root.path(), - uid, - ); - forged.digest = approved.clone(); - seal_plan(&mut forged); - store.save(&mut forged).unwrap(); - - let err = execute_plan_privileged( - &exec, - root.path(), - &store, - &approvals, - "plan-swap", - &approved, - uid, - true, - ) - .unwrap_err(); - assert!( - err.to_string().contains("digest does not match") - || err.to_string().contains("approval digest mismatch"), - "{err}" - ); - // Rejected before any command ran or any approval was consumed. - assert!(runner.recorded().is_empty(), "no command may run"); - assert_eq!(ledger_entries(&approvals), 0, "nothing may be claimed"); - assert!(transaction::read(root.path()).unwrap().records.is_empty()); - - // A more sophisticated forgery also recomputes the stored digest, but - // the independently preserved approved digest still differs. - let mut forged2 = portage_install_plan( - "plan-swap", - SystemAction::InstallPackage { - atom: "net-misc/wget".into(), - binary: None, - }, - parse_emerge_pretend(WGET_PRETEND), - root.path(), - uid, - ); - seal_plan(&mut forged2); - store.save(&mut forged2).unwrap(); - let err = execute_plan_privileged( - &exec, - root.path(), - &store, - &approvals, - "plan-swap", - &approved, - uid, - true, - ) - .unwrap_err(); - assert!(err.to_string().contains("digest"), "{err}"); - assert_eq!(ledger_entries(&approvals), 0); - } - - #[test] - fn canonical_digest_is_recomputed_for_every_plan_kind() { - let root = tempdir().unwrap(); - let uid = effective_uid(); - let exec = make_test_exec(root.path()); - let cand = sample_candidate(); - - // (kind, reviewed action, substituted action, candidate) - let cases: Vec<(PlanKind, SystemAction, SystemAction, Option)> = vec![ - ( - PlanKind::Install, - SystemAction::FlatpakInstall { - app_id: "org.mozilla.firefox".into(), - }, - SystemAction::FlatpakInstall { - app_id: "org.chromium.Chromium".into(), - }, - Some(cand.clone()), - ), - ( - PlanKind::LegacyInstall, - SystemAction::FlatpakInstall { - app_id: "org.mozilla.firefox".into(), - }, - SystemAction::FlatpakInstall { - app_id: "org.chromium.Chromium".into(), - }, - Some(cand.clone()), - ), - ( - PlanKind::Removal, - SystemAction::RemovePackage { - atom: "app-editors/vim".into(), - }, - SystemAction::RemovePackage { - atom: "net-misc/wget".into(), - }, - None, - ), - ( - PlanKind::General, - SystemAction::EnableService { - name: "sshd".into(), - }, - SystemAction::DisableService { - name: "sshd".into(), - }, - None, - ), - ( - PlanKind::Undo, - SystemAction::Undo { snapshot: None }, - SystemAction::Undo { - snapshot: Some("other-snapshot".into()), - }, - None, - ), - ]; - - for (idx, (kind, reviewed_action, substituted_action, candidate)) in - cases.into_iter().enumerate() - { - let id = format!("plan-kind-{idx}"); - let reviewed = canonical_plan( - &id, - kind, - vec![reviewed_action], - candidate, - ResolvedPlan::default(), - root.path(), - uid, - ); - let approved = reviewed.digest.clone(); - // Substitute the action, retain the approved digest, reseal. - let mut forged = canonical_plan( - &id, - kind, - vec![substituted_action], - reviewed.candidate.clone(), - ResolvedPlan::default(), - root.path(), - uid, - ); - forged.digest = approved.clone(); - seal_plan(&mut forged); - - let err = validate_prepared_plan(&exec, root.path(), &forged, Some(&approved), uid) - .unwrap_err(); - assert!( - err.to_string().contains("digest"), - "kind {kind:?} must be rejected: {err}" - ); - } - } - - /// Execute a plan, then edit a presentation field, reseal, delete the user - /// claim and replay. The stable ledger identity must still refuse it. - fn replay_after_presentation_edit(field: &str) { - let root = tempdir().unwrap(); - let exec = make_test_exec(root.path()); - let store = PlanStore::with_dir(tempdir().unwrap().keep()); - let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); - let uid = effective_uid(); - - let mut plan = sealed( - "plan-replay-edit", - PlanKind::General, - vec![SystemAction::History], - "d", - root.path(), - uid, - ); - store.save(&mut plan).unwrap(); - let digest = plan.digest.clone(); - execute_plan_privileged( - &exec, - root.path(), - &store, - &approvals, - "plan-replay-edit", - &digest, - uid, - true, - ) - .unwrap(); - - // The user deletes their own claim and edits only a presentation field, - // then reseals. - let _ = std::fs::remove_file(store.dir().join("plan-replay-edit.claim")); - let mut tampered = store.load("plan-replay-edit").unwrap(); - match field { - "summary" => tampered.summary = "a completely different summary".into(), - "recommendation" => tampered.recommendation = "edited".into(), - "rationale" => tampered.rationale = vec!["edited rationale".into()], - "verification" => tampered.verification = "edited verification".into(), - other => panic!("unknown field {other}"), - } - seal_plan(&mut tampered); - store.save(&mut tampered).unwrap(); - - let err = execute_plan_privileged( - &exec, - root.path(), - &store, - &approvals, - "plan-replay-edit", - &digest, - uid, - true, - ) - .unwrap_err(); - assert!(err.to_string().contains("already used"), "{err}"); - } - - #[test] - fn replay_after_editing_only_the_summary_is_rejected() { - replay_after_presentation_edit("summary"); - } - - #[test] - fn replay_after_editing_other_presentation_fields_is_rejected() { - replay_after_presentation_edit("recommendation"); - replay_after_presentation_edit("rationale"); - replay_after_presentation_edit("verification"); - } - - #[test] - fn recreating_an_identical_plan_under_the_same_id_is_rejected() { - let root = tempdir().unwrap(); - let exec = make_test_exec(root.path()); - let store = PlanStore::with_dir(tempdir().unwrap().keep()); - let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); - let uid = effective_uid(); - - let mut plan = sealed( - "plan-identical", - PlanKind::General, - vec![SystemAction::History], - "d", - root.path(), - uid, - ); - let path = store.save(&mut plan).unwrap(); - let digest = plan.digest.clone(); - let bytes = std::fs::read(&path).unwrap(); - execute_plan_privileged( - &exec, - root.path(), - &store, - &approvals, - "plan-identical", - &digest, - uid, - true, - ) - .unwrap(); - - // Recreate byte-identical plan state under the original id. - std::fs::remove_file(&path).unwrap(); - let _ = std::fs::remove_file(store.dir().join("plan-identical.claim")); - std::fs::write(&path, &bytes).unwrap(); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); - } - - let err = execute_plan_privileged( - &exec, - root.path(), - &store, - &approvals, - "plan-identical", - &digest, - uid, - true, - ) - .unwrap_err(); - assert!(err.to_string().contains("already used"), "{err}"); - } - - #[test] - fn a_newly_reviewed_identical_operation_with_a_new_id_is_allowed() { - let root = tempdir().unwrap(); - let exec = make_test_exec(root.path()); - let store = PlanStore::with_dir(tempdir().unwrap().keep()); - let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); - let uid = effective_uid(); - - // Two independently reviewed plans with identical content but distinct - // random identifiers: the first may not block the second. - for id in ["plan-fresh-a", "plan-fresh-b"] { - let mut plan = sealed( - id, - PlanKind::General, - vec![SystemAction::History], - "d", - root.path(), - uid, - ); - let digest = plan.digest.clone(); - store.save(&mut plan).unwrap(); - execute_plan_privileged( - &exec, - root.path(), - &store, - &approvals, - id, - &digest, - uid, - true, - ) - .unwrap_or_else(|e| panic!("{id} should be allowed: {e}")); - } - } - - #[test] - fn a_live_claim_is_not_reconciled_but_an_abandoned_one_is() { - let root = tempdir().unwrap(); - let uid = effective_uid(); - let store = PlanStore::with_dir(tempdir().unwrap().keep()); - let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); - - let mut live = sealed( - "plan-live", - PlanKind::General, - vec![SystemAction::History], - "d", - root.path(), - uid, - ); - store.save(&mut live).unwrap(); - let live_identity = approval_identity(&live, uid); - // Claimed with the real, currently running process. - approvals.claim(&live_identity).unwrap(); - - // A second broker starting must not mark the live operation interrupted. - assert_eq!(approvals.reconcile_interrupted().unwrap(), 0); - assert_eq!( - approvals.get(&live_identity.key).unwrap().unwrap().status, - "in_progress" - ); - - // An abandoned claim (owner gone) is recovered. - let mut dead = sealed( - "plan-dead", - PlanKind::General, - vec![SystemAction::History], - "d", - root.path(), - uid, - ); - store.save(&mut dead).unwrap(); - let dead_identity = approval_identity(&dead, uid); - approvals - .claim_with_owner( - &dead_identity, - crate::approval::ProcessIdentity { - pid: u32::MAX, - start_ticks: 1, - boot_id: String::new(), - }, - ) - .unwrap(); - assert_eq!(approvals.reconcile_interrupted().unwrap(), 1); - assert_eq!( - approvals.get(&dead_identity.key).unwrap().unwrap().status, - "interrupted" - ); - } - - // ----------------------------------------------------------------------- - // Per-step effect binding (step_effects must be bound by the approval). - // ----------------------------------------------------------------------- - - /// A General plan with one reviewed Portage effect per action, bound by the - /// canonical digest exactly as `plan_general` builds it. - fn general_portage_plan( - id: &str, - actions: Vec, - steps: Vec, - root: &Path, - uid: u32, - ) -> PreparedPlan { - assert_eq!(actions.len(), steps.len()); - let steps: Vec = steps - .into_iter() - .map(|mut step| { - step.recompute_digest(); - step - }) - .collect(); - let mut combined = ResolvedPlan { - established: true, - ..Default::default() - }; - for step in &steps { - combined.effects.extend(step.effects.clone()); - combined.cleanup.extend(step.cleanup.clone()); - combined.updates.extend(step.updates.clone()); - combined.consequences.extend(step.consequences.clone()); - } - combined.recompute_digest(); - let digest = compute_plan_digest(&actions, None, &combined, &steps); - let mut plan = PreparedPlan { - id: id.into(), - created_unix: now_unix(), - expires_unix: now_unix() + 900, - kind: PlanKind::General, - summary: "reviewed portage plan".into(), - recommendation: "rec".into(), - application: None, - candidate: None, - alternatives: Vec::new(), - rationale: Vec::new(), - warnings: Vec::new(), - actions, - effects: combined, - step_effects: steps, - digest, - verification: "verify".into(), - requires_root: true, - source: "test".into(), - executed: false, - target_root: canonical_root(root), - initiator_uid: uid, - integrity: String::new(), - }; - seal_plan(&mut plan); - plan - } - - fn vim_action() -> SystemAction { - SystemAction::InstallPackage { - atom: "app-editors/vim".into(), - binary: None, - } - } - - fn wget_action() -> SystemAction { - SystemAction::InstallPackage { - atom: "net-misc/wget".into(), - binary: None, - } - } - - /// Assert no command ran, no approval was consumed and no transaction was - /// recorded — i.e. the plan was refused before any mutation. - fn assert_no_mutation(runner: &RecordingRunner, approvals: &ApprovalLedger, root: &Path) { - assert!(runner.recorded().is_empty(), "no command may run"); - assert_eq!(ledger_entries(approvals), 0, "no approval may be consumed"); - assert!( - transaction::read(root).unwrap().records.is_empty(), - "no transaction may be recorded" - ); - } - - #[test] - fn single_action_step_effect_tampering_is_rejected_before_mutation() { - let root = tempdir().unwrap(); - let uid = effective_uid(); - let runner = RecordingRunner::new(); - let exec = make_exec_with_runner(root.path(), Box::new(runner.clone())); - let store = PlanStore::with_dir(tempdir().unwrap().keep()); - let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); - - let mut reviewed = portage_install_plan( - "plan-step-single", - vim_action(), - parse_emerge_pretend(VIM_PRETEND), - root.path(), - uid, - ); - store.save(&mut reviewed).unwrap(); - let approved = reviewed.digest.clone(); - - // Variant A: change only `step_effects`; retain the original aggregate - // effects and the independently approved digest. - let mut forged = reviewed.clone(); - forged.step_effects = vec![parse_emerge_pretend(WGET_PRETEND)]; - seal_plan(&mut forged); - store.save(&mut forged).unwrap(); - - let err = execute_plan_privileged( - &exec, - root.path(), - &store, - &approvals, - "plan-step-single", - &approved, - uid, - true, - ) - .unwrap_err(); - assert!( - err.to_string().contains("aggregate") || err.to_string().contains("digest"), - "{err}" - ); - assert_no_mutation(&runner, &approvals, root.path()); - - // Variant B: also make the aggregate match the new step, but retain the - // approved digest. The canonical digest must still reject it. - let changed = parse_emerge_pretend(WGET_PRETEND); - let mut forged_b = reviewed.clone(); - forged_b.effects = changed.clone(); - forged_b.step_effects = vec![changed]; - seal_plan(&mut forged_b); - store.save(&mut forged_b).unwrap(); - - let err = execute_plan_privileged( - &exec, - root.path(), - &store, - &approvals, - "plan-step-single", - &approved, - uid, - true, - ) - .unwrap_err(); - assert!(err.to_string().contains("digest"), "{err}"); - assert_no_mutation(&runner, &approvals, root.path()); - } - - #[test] - fn multi_action_step_effect_tampering_is_rejected_before_mutation() { - let root = tempdir().unwrap(); - let uid = effective_uid(); - let runner = RecordingRunner::new(); - let exec = make_exec_with_runner(root.path(), Box::new(runner.clone())); - let store = PlanStore::with_dir(tempdir().unwrap().keep()); - let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); - - let mut reviewed = general_portage_plan( - "plan-step-multi", - vec![vim_action(), wget_action()], - vec![ - parse_emerge_pretend(VIM_PRETEND), - parse_emerge_pretend(WGET_PRETEND), - ], - root.path(), - uid, - ); - store.save(&mut reviewed).unwrap(); - let approved = reviewed.digest.clone(); - - // Variant A: swap one step's effects, retain the aggregate and digest. - let mut forged = reviewed.clone(); - forged.step_effects[0] = parse_emerge_pretend(WGET_PRETEND); - seal_plan(&mut forged); - store.save(&mut forged).unwrap(); - - let err = execute_plan_privileged( - &exec, - root.path(), - &store, - &approvals, - "plan-step-multi", - &approved, - uid, - true, - ) - .unwrap_err(); - assert!( - err.to_string().contains("aggregate") || err.to_string().contains("digest"), - "{err}" - ); - assert_no_mutation(&runner, &approvals, root.path()); - - // Variant B: make the aggregate consistent with the new steps, but keep - // the approved digest; the canonical digest must still reject it. - let new_steps = vec![ - parse_emerge_pretend(WGET_PRETEND), - parse_emerge_pretend(WGET_PRETEND), - ]; - let mut combined = ResolvedPlan { - established: true, - ..Default::default() - }; - for step in &new_steps { - combined.effects.extend(step.effects.clone()); - } - combined.recompute_digest(); - let mut forged_b = reviewed.clone(); - forged_b.effects = combined; - forged_b.step_effects = new_steps; - seal_plan(&mut forged_b); - store.save(&mut forged_b).unwrap(); - - let err = execute_plan_privileged( - &exec, - root.path(), - &store, - &approvals, - "plan-step-multi", - &approved, - uid, - true, - ) - .unwrap_err(); - assert!(err.to_string().contains("digest"), "{err}"); - assert_no_mutation(&runner, &approvals, root.path()); - } - - #[test] - fn a_legitimate_bound_multi_step_plan_still_validates() { - let root = tempdir().unwrap(); - let uid = effective_uid(); - // Live re-resolution returns the same reviewed effects for each step. - let runner = SequenceRunner { - responses: std::sync::Mutex::new(vec![ - command_out(VIM_PRETEND, true), - command_out(WGET_PRETEND, true), - ]), - fallback: command_out(WGET_PRETEND, true), - }; - let exec = make_exec_with_runner(root.path(), Box::new(runner)); - let store = PlanStore::with_dir(tempdir().unwrap().keep()); - - let mut plan = general_portage_plan( - "plan-legit-multi", - vec![vim_action(), wget_action()], - vec![ - parse_emerge_pretend(VIM_PRETEND), - parse_emerge_pretend(WGET_PRETEND), - ], - root.path(), - uid, - ); - store.save(&mut plan).unwrap(); - - validate_prepared_plan(&exec, root.path(), &plan, Some(&plan.digest), uid) - .expect("a legitimate bound multi-step plan must validate"); - } - - // ------------------------------------------------------------------ - // General assistant routing: read-only investigation + source constraint - // ------------------------------------------------------------------ - - fn general_ai<'a>(transport: &'a dyn phoebus_ai::provider::ModelTransport) -> AiInstall<'a> { - AiInstall { - provider: phoebus_ai::provider::ProviderKind::Local, - endpoint: "http://127.0.0.1:11434/v1/chat/completions".into(), - model: "m".into(), - transport, - limits: phoebus_ai::install::Limits::default(), - } - } - - #[test] - fn plan_general_investigates_with_read_only_tools_then_answers() { - use phoebus_ai::provider::{chat_response, ScriptedTransport}; - let transport = ScriptedTransport::new(vec![ - chat_response( - r#"{"version":1,"kind":"investigate","requests":[{"action":"search_packages","query":"chrome"}]}"#, - ), - chat_response(r#"{"version":1,"summary":"Two real candidates found.","actions":[]}"#), - ]); - let exec = make_test_exec(Path::new("/")); - let store = PlanStore::with_dir(tempdir().unwrap().keep()); - let plan = plan_general( - &store, - &exec, - Path::new("/"), - "search chrome", - &SystemFacts::default(), - &general_ai(&transport), - None, - ) - .unwrap(); - assert!(plan.actions.is_empty(), "an answer has no actions"); - assert_eq!(plan.summary, "Two real candidates found."); - assert!(!plan.requires_root, "a read-only answer needs no elevation"); - // Two model turns: investigate, then answer. - assert_eq!(transport.requests().len(), 2); - assert!(transport.requests()[1].contains("Package catalogue")); - } - - #[test] - fn plan_general_refuses_a_foreign_lane_under_a_constraint() { - use phoebus_ai::provider::{chat_response, ScriptedTransport}; - let transport = ScriptedTransport::new(vec![chat_response( - r#"{"version":1,"summary":"list flatpaks","actions":[{"action":"flatpak_list"}],"rationale":[{"action":"flatpak_list","reason":"asked"}]}"#, - )]); - let exec = make_test_exec(Path::new("/")); - let store = PlanStore::with_dir(tempdir().unwrap().keep()); - let err = plan_general( - &store, - &exec, - Path::new("/"), - "list flatpaks", - &SystemFacts::default(), - &general_ai(&transport), - Some(Backend::PortageSource), - ) - .unwrap_err(); - assert!(err.to_string().contains("constrained"), "{err}"); - } - - #[test] - fn plan_general_rewrites_a_laneless_query_to_the_constraint() { - use phoebus_ai::provider::{chat_response, ScriptedTransport}; - let transport = ScriptedTransport::new(vec![chat_response( - r#"{"version":1,"summary":"search","actions":[{"action":"search_packages","query":"chrome"}],"rationale":[{"action":"search_packages","reason":"asked"}]}"#, - )]); - let exec = make_test_exec(Path::new("/")); - let store = PlanStore::with_dir(tempdir().unwrap().keep()); - let plan = plan_general( - &store, - &exec, - Path::new("/"), - "search chrome", - &SystemFacts::default(), - &general_ai(&transport), - Some(Backend::Flatpak), - ) - .unwrap(); - assert_eq!( - plan.actions, - vec![SystemAction::SearchPackages { - query: "chrome".into(), - backend: Some(Backend::Flatpak), - }] - ); - } - - #[test] - fn effect_binding_aggregates_cleanup_intents_for_a_clean_cache_step() { - let root = tempdir().unwrap(); - let mut step = ResolvedPlan { - established: true, - ..Default::default() - }; - step.cleanup.push(phoebus_core::effects::CleanupEffect { - cleaner: "eclean-dist".into(), - items: vec!["app-misc/one".into()], - unavailable: false, - }); - let plan = general_portage_plan( - "plan-cleanup", - vec![SystemAction::CleanCache { backend: None }], - vec![step], - root.path(), - effective_uid(), - ); - let steps = reviewed_steps(&plan).unwrap(); - validate_effect_bindings(&plan, &steps) - .expect("cleanup intents must aggregate into the bound plan"); - } - - #[test] - fn effect_binding_aggregates_update_transactions() { - let root = tempdir().unwrap(); - let mut step = ResolvedPlan { - established: true, - ..Default::default() - }; - step.updates.push(phoebus_core::effects::UpdateTransaction { - source: phoebus_core::effects::UpdateSource::Flatpak, - identity: "app/org.mozilla.firefox/x86_64/stable".into(), - previous_version: Some("128".into()), - next_version: "129".into(), - previous_revision: Some("OLD".into()), - next_revision: Some("NEW".into()), - scope: Some("system".into()), - related: Vec::new(), - exact: true, - }); - let plan = general_portage_plan( - "plan-updates", - vec![SystemAction::ApplyUpdates { - backend: Some(Backend::Flatpak), - }], - vec![step], - root.path(), - effective_uid(), - ); - let steps = reviewed_steps(&plan).unwrap(); - validate_effect_bindings(&plan, &steps) - .expect("update transactions must aggregate into the bound plan"); - } - - #[test] - fn constrain_action_rewrites_optional_backend_discovery_before_querying() { - let discover = constrain_action( - SystemAction::DiscoverCandidates { - query: "chrome".into(), - kind: None, - backend: None, - gui: false, - requires_sandbox: false, - }, - Backend::Flatpak, - ) - .unwrap(); - assert_eq!(discover.backend(), Some(Backend::Flatpak)); - - let choose = constrain_action( - SystemAction::ChoosePackage { - name: "chrome".into(), - kind: None, - backend: None, - gui: false, - requires_sandbox: false, - }, - Backend::Flatpak, - ) - .unwrap(); - assert_eq!(choose.backend(), Some(Backend::Flatpak)); - } - - #[test] - fn constrain_action_refuses_portage_only_actions_under_another_lane() { - for action in [ - SystemAction::RemovePackage { - atom: "www-client/firefox".into(), - }, - SystemAction::UpdateSystem, - SystemAction::Depclean, - SystemAction::PackageOwners { - path: "/usr/bin/vim".into(), - }, - SystemAction::PackageDependencies { - package: "vim".into(), - reverse: false, - }, - SystemAction::InstallPackage { - atom: "vim".into(), - binary: None, - }, - SystemAction::InspectPackage { atom: "vim".into() }, - ] { - let err = constrain_action(action.clone(), Backend::Flatpak).unwrap_err(); - assert!( - err.contains("constrained") || err.contains("targets the"), - "{action:?} -> {err}" - ); - } - } - - #[test] - fn constrain_action_refuses_cross_lane_installation_inspection() { - let err = constrain_action( - SystemAction::InspectInstallation { - application: "firefox".into(), - }, - Backend::Flatpak, - ) - .unwrap_err(); - assert!(err.contains("spans every package lane"), "{err}"); - } - - #[test] - fn constrain_action_allows_spanning_non_package_actions() { - for action in [ - SystemAction::History, - SystemAction::RollbackStatus, - SystemAction::EnableService { - name: "sshd".into(), - }, - ] { - assert!(constrain_action(action, Backend::Flatpak).is_ok()); - } - // A Portage-only action is allowed when the constraint is Portage. - assert!(constrain_action(SystemAction::UpdateSystem, Backend::PortageSource).is_ok()); - } -} diff --git a/installer-rs/crates/phoebus-installer/src/service/execution.rs b/installer-rs/crates/phoebus-installer/src/service/execution.rs new file mode 100644 index 0000000..5970c07 --- /dev/null +++ b/installer-rs/crates/phoebus-installer/src/service/execution.rs @@ -0,0 +1,529 @@ +//! Validated, elevated execution with transaction recording: the only path +//! from an approved [`PreparedPlan`] to a system mutation. + +use std::path::{Path, PathBuf}; + +use phoebus_core::effects::{approval_holds, PackageEffect, ResolvedPlan}; +use phoebus_core::selection::Backend; +use phoebus_core::transaction::{TransactionOutcome, TransactionRecord}; +use phoebus_executor::actions; +use phoebus_executor::auth::authorize; +use phoebus_executor::chooser; +use phoebus_executor::error::{ExecError, Result}; +use phoebus_executor::exec::Exec; +use phoebus_executor::install::{InstallRequest, InstallSource}; +use phoebus_executor::{install, transaction}; + +use crate::approval::{ApprovalIdentity, ApprovalLedger, ApprovalStatus, Finished}; + +use super::validation::{reviewed_steps, validate_prepared_plan, ServiceConfirm}; +use super::{ + canonical_root, effective_uid, now_unix, PlanExecutionOutcome, PlanKind, PlanStore, + PreparedPlan, +}; + +/// Execute a prepared plan with full validation, elevation, verification, and +/// transaction recording. +pub fn execute_plan( + exec: &Exec, + root: &Path, + plans: &PlanStore, + plan_id: &str, + expected_digest: &str, + assume_yes: bool, +) -> Result { + let initiator = effective_uid(); + let plan = plans.load(plan_id)?; + validate_prepared_plan(exec, root, &plan, Some(expected_digest), initiator)?; + if plans.is_claimed(plan_id) { + return Err(ExecError::operation( + "service", + "execute_plan", + "plan has already been consumed; retrying will not repeat the mutation", + )); + } + + if plan.requires_root && initiator != 0 { + return elevate_and_execute(root, plan, initiator, expected_digest); + } + execute_prepared(exec, root, plans, plan, assume_yes, None) +} + +/// The privileged broker entry point. +/// +/// It repeats the full validation after authentication (never trusting the +/// unprivileged caller), binds execution to the independently preserved +/// `expected_digest` the approval UI showed the user, and anchors consumption in +/// the broker-controlled [`ApprovalLedger`]. A plan file replaced during +/// authentication no longer matches `expected_digest`; a replay is refused even +/// when the user deletes every file in their own plan directory. +#[allow(clippy::too_many_arguments)] +pub fn execute_plan_privileged( + exec: &Exec, + root: &Path, + plans: &PlanStore, + approvals: &ApprovalLedger, + plan_id: &str, + expected_digest: &str, + initiator_uid: u32, + assume_yes: bool, +) -> Result { + let plan = plans.load(plan_id)?; + // The expected digest is the independently preserved approval the user + // reviewed. A self-consistent reseal of a replacement plan cannot match it. + validate_prepared_plan(exec, root, &plan, Some(expected_digest), initiator_uid)?; + // `execute_prepared` authenticates *before* claiming the approval, so a + // cancelled or refused operation consumes nothing; it then anchors the + // claim in the broker-controlled ledger and records a terminal status. + execute_prepared( + exec, + root, + plans, + plan, + assume_yes, + Some((approvals, initiator_uid)), + ) +} + +fn elevate_and_execute( + root: &Path, + plan: PreparedPlan, + initiator: u32, + expected_digest: &str, +) -> Result { + let sys_exe = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("/usr/local/bin/sys")); + // The privileged broker is given the plan identifier, the independently + // preserved approval digest, the initiating uid and the exact target root. + // A dropped `--root` would (correctly) fail validation rather than execute + // against `/`. + let output = std::process::Command::new("pkexec") + .arg(sys_exe) + .arg("--broker") + .arg("--execute-plan") + .arg(&plan.id) + .arg("--plan-uid") + .arg(initiator.to_string()) + .arg("--approval-digest") + .arg(expected_digest) + .arg("--root") + .arg(canonical_root(root)) + .output() + .map_err(|e| { + ExecError::operation( + "service", + "pkexec", + format!("could not spawn pkexec for root authorization: {e}"), + ) + })?; + + if output.status.success() { + let out_str = String::from_utf8_lossy(&output.stdout); + return serde_json::from_str::(out_str.trim()).map_err(|e| { + ExecError::operation( + "service", + "broker protocol", + format!("privileged execution reported success but returned malformed output: {e}"), + ) + }); + } + let code = output.status.code().unwrap_or(1); + if code == 126 || code == 127 { + return Err(ExecError::operation( + "service", + "authenticate", + "authentication was cancelled; no changes were made", + )); + } + let err_msg = String::from_utf8_lossy(&output.stderr); + Err(ExecError::operation( + "service", + "pkexec", + format!( + "privileged execution failed (code {code}): {}", + err_msg.trim() + ), + )) +} + +/// Authenticate, claim and run a plan, recording a truthful transaction outcome +/// on every exit path (success, action failure, verification failure, +/// cancellation, and effect drift). When `approvals` is present the claim is +/// anchored in the broker-controlled ledger and always reaches a terminal +/// status; a refused or cancelled operation claims nothing. +fn execute_prepared( + exec: &Exec, + root: &Path, + plans: &PlanStore, + plan: PreparedPlan, + assume_yes: bool, + approvals: Option<(&ApprovalLedger, u32)>, +) -> Result { + // Authentication/refusal happens before any claim, so a refused plan is not + // consumed and stays reviewable (until it expires). + let confirm = ServiceConfirm { assume_yes }; + let auth = if plan.requires_root { + Some(authorize(&confirm, &plan.summary, "execute")?) + } else { + None + }; + + // Anchor the approval in the broker-controlled ledger before mutation. The + // key is the *stable* approval identity (plan id, canonical digest, + // authenticated initiating uid, target root); presentation fields are + // excluded, so editing the summary and resealing cannot mint a fresh entry + // for an already-consumed approval. + let approved_key = match approvals { + Some((ledger, uid)) => { + let identity = ApprovalIdentity::new( + plan.id.clone(), + plan.digest.clone(), + uid, + plan.target_root.clone(), + plan.expires_unix, + plan.actions.len(), + ); + ledger.claim(&identity)?; + Some(identity.key) + } + None => None, + }; + + let result = execute_claimed(exec, root, plans, &plan, auth.as_ref()); + + if let (Some((ledger, _)), Some(key)) = (approvals, approved_key.as_ref()) { + let (status, note) = match &result { + Ok(_) => (ApprovalStatus::Consumed, "ok".to_string()), + Err(e) => (ApprovalStatus::Failed, e.to_string()), + }; + // The transition is monotonic. A conflicting terminal (only possible if + // recovery had already declared the owner gone) must not be silently + // overwritten or reported as success. + match ledger.finish(key, status, ¬e) { + Ok(Finished::Recorded) => {} + Ok(Finished::AlreadyTerminal(existing)) if existing.status == status.as_str() => {} + Ok(Finished::AlreadyTerminal(existing)) => { + return Err(ExecError::operation( + "service", + "record approval", + format!( + "the approval already reached terminal status `{}` and was not \ + overwritten with `{}`", + existing.status, + status.as_str() + ), + )); + } + Err(ledger_err) => { + return match result { + Ok(_) => Err(ExecError::operation( + "service", + "record approval", + format!( + "the operation completed but its approval outcome could not be \ + recorded: {ledger_err}" + ), + )), + Err(e) => Err(ExecError::operation( + "service", + "record approval", + format!("{e}; the approval outcome could not be recorded: {ledger_err}"), + )), + }; + } + } + } + result +} + +/// The authenticated execution body. Freshly resolved effects are compared +/// against the reviewed per-step effects; only changes explained by earlier +/// approved steps are allowed. +fn execute_claimed( + exec: &Exec, + root: &Path, + plans: &PlanStore, + plan: &PreparedPlan, + auth: Option<&phoebus_executor::auth::DestructiveAuthorization>, +) -> Result { + // Atomic claim: at most one caller can proceed with this plan. + let _claim = plans.claim(&plan.id)?; + + let record = TransactionRecord { + id: 0, + created_unix: now_unix(), + origin: match plan.kind { + PlanKind::LegacyInstall => "sys-legacy".into(), + PlanKind::Removal => "sys-removal".into(), + _ => "assistant".into(), + }, + summary: plan.summary.clone(), + actions: plan.actions.iter().map(|a| a.describe()).collect(), + result: "in progress".into(), + snapshot: None, + digest: Some(plan.digest.clone()), + outcomes: Vec::new(), + }; + let tx_id = transaction::begin(exec, root, record)?; + + // Carry the *reviewed* per-step effects forward. Freshly resolved effects + // below are evidence to compare against these, never a replacement + // approval. `reviewed_steps` uses the same binding validation already + // performed at the privileged boundary. + let reviewed_steps: Vec = reviewed_steps(plan)?; + + let mut completed: Vec<(String, String)> = Vec::new(); + let mut outcomes: Vec = Vec::new(); + let mut snapshot: Option = None; + let mut introduced: Vec = Vec::new(); + let mut failure: Option<(String, String)> = None; + // A distinct, terminal "the approved plan no longer matches live state" + // reason: effect resolution failed, or the effects changed materially. + let mut drift: Option = None; + + for (idx, action) in plan.actions.iter().enumerate() { + let described = action.describe(); + if failure.is_some() || drift.is_some() { + outcomes.push(TransactionOutcome::unattempted(described)); + continue; + } + // Only Portage transactions have a comparable `emerge --pretend` plan + // at this boundary. Other lanes' effects were validated by + // `validate_prepared_plan` (install revalidation / installed-copy + // checks); re-resolving them here would see an empty plan and falsely + // report drift. + let mut current: Option = None; + if actions::resolves_effects(action) { + let reviewed = &reviewed_steps[idx]; + let resolved = match actions::resolve_effects(exec, action, root) { + Ok(current) => current, + Err(e) => { + let detail = format!("effect resolution failed for `{described}`: {e}"); + outcomes.push(TransactionOutcome::failed( + described.clone(), + detail.clone(), + )); + drift = Some(format!("stale plan: {detail}")); + continue; + } + }; + if !approval_holds(reviewed, &resolved, &introduced) { + let detail = format!( + "the reviewed effects for `{described}` changed materially before execution" + ); + outcomes.push(TransactionOutcome::failed( + described.clone(), + detail.clone(), + )); + drift = Some(format!("stale plan: {detail}")); + continue; + } + current = Some(resolved); + } + + // Execution carries the *reviewed* transaction for actions that must + // not re-discover state (Flatpak/Snap updates, cache cleanup). + let carried = if actions::resolves_effects(action) { + Some(&reviewed_steps[idx]) + } else { + None + }; + match actions::execute_inner(exec, action, auth, root, carried) { + Ok(result) => { + if result.snapshot.is_some() { + snapshot = result.snapshot; + } + outcomes.push(TransactionOutcome::completed(described.clone())); + completed.push((described, result.output)); + // Packages this approved action installed may legitimately + // appear in a later step's re-resolution. + if let Some(current) = current { + introduced.extend(current.effects); + } + } + Err(e) => { + let detail = e.to_string(); + outcomes.push(TransactionOutcome::failed( + described.clone(), + detail.clone(), + )); + failure = Some((described, detail)); + } + } + } + + if let Some(reason) = drift { + finish_or_report( + exec, + root, + tx_id, + reason.clone(), + snapshot.clone(), + outcomes.clone(), + "the stale plan was recorded", + )?; + return Err(ExecError::operation("service", "execute", reason)); + } + + if let Some((action_str, detail)) = &failure { + finish_or_report( + exec, + root, + tx_id, + format!("failed: {detail}"), + snapshot.clone(), + outcomes.clone(), + "the action failed", + )?; + return Err(ExecError::operation( + "service", + "execute", + format!("action failed: {action_str}: {detail}"), + )); + } + + // Post-execution verification. A verification error finishes the + // transaction as a failed verification; it never leaves it "in progress". + let verification_result = match plan.kind { + PlanKind::Install | PlanKind::LegacyInstall => { + if let (Some(cand), Some(act)) = (&plan.candidate, plan.actions.first()) { + let resolved = install::ResolvedInstall { + request: InstallRequest::new(plan.application.as_deref().unwrap_or("")), + candidate: cand.clone(), + action: act.clone(), + effects: plan.effects.clone(), + rationale: plan.rationale.clone(), + alternatives: plan.alternatives.clone(), + source: match plan.kind { + PlanKind::LegacyInstall => InstallSource::ExplicitBackend, + _ => InstallSource::AiRecommendation, + }, + warnings: plan.warnings.clone(), + verification: plan.verification.clone(), + }; + match install::verify_installed(exec, root, &resolved) { + Ok(text) => text, + Err(e) => { + finish_or_report( + exec, + root, + tx_id, + format!("verify failed: {e}"), + snapshot.clone(), + outcomes.clone(), + "verification failed", + )?; + return Err(e); + } + } + } else { + "verified ok".into() + } + } + PlanKind::Removal => { + if let Some(app) = &plan.application { + let check = chooser::installed_copies(exec, root, app); + if let Some(ref_copy) = check.copies.iter().find(|c| c.backend == plan.source) { + let err = format!( + "removal reported success but `{app}` is still present in {} ({})", + ref_copy.backend, ref_copy.id + ); + finish_or_report( + exec, + root, + tx_id, + format!("verify failed: {err}"), + snapshot.clone(), + outcomes.clone(), + "verification failed", + )?; + return Err(ExecError::operation("service", "verify removal", err)); + } + format!("verified: `{app}` removed from {}", plan.source) + } else { + "removal verified ok".into() + } + } + _ => "ok".into(), + }; + + let launch = detect_launch(root, plan); + + finish_or_report( + exec, + root, + tx_id, + "ok", + snapshot.clone(), + outcomes.clone(), + "the transaction could not be recorded", + )?; + + let outputs: Vec = completed.into_iter().map(|(_, out)| out).collect(); + + Ok(PlanExecutionOutcome { + completed: true, + snapshot, + result: "ok".into(), + verification: verification_result, + output: outputs, + launch, + }) +} + +/// Finish a transaction, surfacing a persistence failure instead of hiding it. +/// The execution result is preserved either way. +fn finish_or_report( + exec: &Exec, + root: &Path, + tx_id: u64, + result: impl Into, + snapshot: Option, + outcomes: Vec, + persistence_note: &str, +) -> Result<()> { + let result = result.into(); + match transaction::finish(exec, root, tx_id, result.clone(), snapshot, outcomes) { + Ok(()) => Ok(()), + Err(e) => Err(ExecError::operation( + "service", + "record transaction", + format!("{persistence_note}: {result} (history error: {e})"), + )), + } +} + +/// Identify a concrete launch command for a freshly installed application. +/// Only offered when a desktop entry (or an unambiguous Flatpak/Snap command) +/// is actually found; never guessed. +fn detect_launch(root: &Path, plan: &PreparedPlan) -> Option> { + let candidate = plan.candidate.as_ref()?; + match candidate.backend { + Backend::Flatpak => { + return Some(vec!["flatpak".into(), "run".into(), candidate.id.clone()]) + } + Backend::Snap => return Some(vec![candidate.id.clone()]), + _ => {} + } + let app = plan.application.as_deref().unwrap_or(""); + let stem = app.rsplit('/').next().unwrap_or(app).to_ascii_lowercase(); + if stem.is_empty() { + return None; + } + let dir = root.join("usr/share/applications"); + let entries = std::fs::read_dir(&dir).ok()?; + for entry in entries.flatten() { + let path = entry.path(); + if path.extension().and_then(|e| e.to_str()) != Some("desktop") { + continue; + } + let file_stem = path + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("") + .to_ascii_lowercase(); + if file_stem == stem || file_stem.starts_with(&format!("{stem}.")) { + return Some(vec!["gtk-launch".into(), file_stem]); + } + } + None +} diff --git a/installer-rs/crates/phoebus-installer/src/service/mod.rs b/installer-rs/crates/phoebus-installer/src/service/mod.rs new file mode 100644 index 0000000..48b50b8 --- /dev/null +++ b/installer-rs/crates/phoebus-installer/src/service/mod.rs @@ -0,0 +1,329 @@ +//! Shared administration service layer for Phoebus OS. +//! +//! Provides a single, unified implementation for both the CLI (`sys`) and desktop +//! GUI (`phoebus-assistant`) covering: +//! - Bounded investigation and connected model planning +//! - Candidate discovery, provenance verification, and policy enforcement +//! - Plan staging (`PreparedPlan`) and cryptographically bound approval digests +//! - TTL enforcement and replay/tamper protection (`PlanStore`) +//! - Cross-source application removal preserving user data by default +//! - Two-phase transaction logging (`begin` before mutation, `finish` with verification) +//! - Unprivileged-to-privileged desktop Polkit elevation (`pkexec`) +//! +//! Module layout (structural split, no behavior change): +//! - [`plan`]: recommendation text, [`PlanStore`], and the planning APIs. +//! - [`validation`]: integrity seals, approval digests, and plan validation. +//! - [`execution`]: validated, elevated execution with transaction recording. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use phoebus_core::action::SystemAction; +use phoebus_core::effects::ResolvedPlan; +use phoebus_core::selection::{Candidate, Rejected, SandboxLevel}; + +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +pub const DEFAULT_PLAN_TTL_SECONDS: u64 = 900; // 15 minutes + +/// How many plan identifiers may be generated before the process-wide counter +/// wraps. Identifiers also include 128 bits of randomness from `/dev/urandom`. +static PLAN_COUNTER: AtomicU64 = AtomicU64::new(1); +/// A plan id is exactly this token: no separators, no traversal. +const PLAN_ID_HEX_LEN: usize = 32; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum PlanKind { + Install, + LegacyInstall, + Removal, + General, + Undo, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PreparedPlan { + pub id: String, + pub created_unix: u64, + pub expires_unix: u64, + pub kind: PlanKind, + pub summary: String, + pub recommendation: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub application: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub candidate: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub alternatives: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub rationale: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub warnings: Vec, + pub actions: Vec, + pub effects: ResolvedPlan, + /// Per-step resolved effects, so a multi-action plan can be revalidated + /// action by action instead of comparing one action against the aggregate. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub step_effects: Vec, + pub digest: String, + pub verification: String, + pub requires_root: bool, + pub source: String, + pub executed: bool, + /// Canonical root the plan was reviewed against. Elevated execution refuses + /// to run against any other root (never silently falls back to `/`). + #[serde(default)] + pub target_root: String, + /// The unprivileged user that reviewed and approved the plan. A privileged + /// broker refuses to run a plan prepared for another user. + #[serde(default)] + pub initiator_uid: u32, + /// Self-consistency seal over the reviewed fields (including target root, + /// initiator and digest). Rejected if it does not match on reload. + #[serde(default)] + pub integrity: String, +} + +/// A handle to a prepared plan that the broker has atomically claimed for +/// execution. Holding it proves the plan was consumed exactly once. +#[derive(Debug)] +pub struct PlanClaim { + marker: PathBuf, +} + +impl PlanClaim { + pub fn marker_path(&self) -> &Path { + &self.marker + } +} + +impl Drop for PlanClaim { + fn drop(&mut self) { + // The claim marker is intentionally left in place: it is the durable + // record that the plan was consumed, so a retry cannot repeat it. + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PlanExecutionOutcome { + pub completed: bool, + pub snapshot: Option, + pub result: String, + pub verification: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub output: Vec, + /// A concrete command that launches the installed application, when a + /// desktop entry could be identified. Never guessed. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub launch: Option>, +} + +impl PreparedPlan { + pub fn render(&self) -> String { + let mut out = String::new(); + match self.kind { + PlanKind::Install | PlanKind::LegacyInstall => { + out.push_str(&format!( + "Install plan ({}):\n", + if self.kind == PlanKind::LegacyInstall { + "explicit selection" + } else { + "AI recommendation" + } + )); + if let Some(app) = &self.application { + out.push_str(&format!(" application: {app}\n")); + } + if let Some(c) = &self.candidate { + out.push_str(&format!(" backend: {}\n", c.backend.as_str())); + out.push_str(&format!(" candidate: {}\n", c.id)); + out.push_str(&format!( + " version: {}\n", + c.version.as_deref().unwrap_or("(resolved at install time)") + )); + out.push_str(&format!(" source: {}\n", self.source)); + out.push_str(&format!( + " integrity: {}\n", + if c.verified { + "verified (signature/hash)" + } else { + "UNVERIFIED — provenance not cryptographic" + } + )); + out.push_str(&format!( + " sandbox: {} wayland: {} desktop: {}\n", + match c.sandbox { + SandboxLevel::None => "none", + SandboxLevel::Partial => "partial", + SandboxLevel::Strong => "strong", + }, + match c.wayland { + phoebus_core::selection::Capability::No => "no", + phoebus_core::selection::Capability::Partial => "partial", + phoebus_core::selection::Capability::Yes => "yes", + }, + match c.desktop_integration { + phoebus_core::selection::Capability::No => "no", + phoebus_core::selection::Capability::Partial => "partial", + phoebus_core::selection::Capability::Yes => "yes", + } + )); + if let Some(mib) = c.download_mib { + out.push_str(&format!(" download: ~{mib} MiB\n")); + } + if let Some(mib) = c.install_mib { + out.push_str(&format!(" on disk: ~{mib} MiB\n")); + } + } + out.push_str("Why:\n"); + out.push_str(&format!(" - {}\n", self.recommendation)); + for r in &self.rationale { + out.push_str(&format!(" - {r}\n")); + } + if !self.alternatives.is_empty() { + out.push_str("Alternatives considered:\n"); + for alt in &self.alternatives { + out.push_str(&format!( + " - {} ({}): {}\n", + alt.id, + alt.backend.as_str(), + alt.reason.explain() + )); + } + } + for w in &self.warnings { + out.push_str(&format!(" ! {w}\n")); + } + if self.effects.established && !self.effects.effects.is_empty() { + out.push_str(&self.effects.render()); + } + out.push_str(&format!("Verification: {}\n", self.verification)); + out.push_str(&format!("Approval digest: {}\n", self.digest)); + } + PlanKind::Removal => { + out.push_str("Removal plan:\n"); + if let Some(app) = &self.application { + out.push_str(&format!(" application: {app}\n")); + } + out.push_str(&format!(" source: {}\n", self.source)); + out.push_str("Why:\n"); + out.push_str(&format!(" - {}\n", self.recommendation)); + for r in &self.rationale { + out.push_str(&format!(" - {r}\n")); + } + if self.effects.established && !self.effects.effects.is_empty() { + out.push_str(&self.effects.render()); + } + out.push_str(&format!("Verification: {}\n", self.verification)); + out.push_str(&format!("Approval digest: {}\n", self.digest)); + } + _ => { + out.push_str(&format!("Assistant Plan:\n {}\n", self.summary)); + for a in &self.actions { + out.push_str(&format!(" - {}\n", a.describe())); + } + if self.effects.established && !self.effects.effects.is_empty() { + out.push_str(&self.effects.render()); + } + out.push_str(&format!("Verification: {}\n", self.verification)); + out.push_str(&format!("Approval digest: {}\n", self.digest)); + } + } + out + } +} + +fn now_unix() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +pub fn effective_uid() -> u32 { + if std::env::var("PHOEBUS_ALLOW_UNPRIVILEGED_EXEC").as_deref() == Ok("1") { + return 0; + } + std::process::Command::new("id") + .arg("-u") + .output() + .ok() + .and_then(|o| String::from_utf8_lossy(&o.stdout).trim().parse().ok()) + .unwrap_or(1) +} + +/// Canonicalise a target root so two spellings of the same path compare equal. +/// When the path cannot be canonicalised (e.g. a not-yet-created target), fall +/// back to the lexical path rather than silently selecting `/`. +pub fn canonical_root(root: &Path) -> String { + match std::fs::canonicalize(root) { + Ok(p) => p.to_string_lossy().to_string(), + Err(_) => { + let p = if root.as_os_str().is_empty() { + Path::new("/") + } else { + root + }; + p.to_string_lossy().to_string() + } + } +} + +/// 128 bits of unpredictable data for a plan identifier/marker name. +fn random_token() -> String { + let mut bytes = [0u8; 16]; + let filled = std::fs::File::open("/dev/urandom") + .and_then(|mut f| { + use std::io::Read; + f.read_exact(&mut bytes) + }) + .is_ok(); + if !filled { + // Fallback that is still unique within a boot: time + pid + counter. + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + let mut hasher = Sha256::new(); + hasher.update(nanos.to_le_bytes()); + hasher.update(std::process::id().to_le_bytes()); + hasher.update(PLAN_COUNTER.fetch_add(1, Ordering::SeqCst).to_le_bytes()); + let digest = format!("{:x}", hasher.finalize()); + return digest[..PLAN_ID_HEX_LEN].to_string(); + } + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +/// A fresh, unpredictable plan identifier: `plan--<32 hex>`. +pub(crate) fn fresh_plan_id(prefix: &str) -> String { + let counter = PLAN_COUNTER.fetch_add(1, Ordering::SeqCst); + let mut hasher = Sha256::new(); + hasher.update(random_token().as_bytes()); + hasher.update(counter.to_le_bytes()); + let digest = format!("{:x}", hasher.finalize()); + format!("plan-{prefix}-{}", &digest[..PLAN_ID_HEX_LEN]) +} + +fn is_safe_plan_id(plan_id: &str) -> bool { + !plan_id.is_empty() + && plan_id.len() <= 128 + && plan_id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') +} + +pub mod execution; +pub mod plan; +#[cfg(test)] +mod tests; +pub mod validation; + +pub use execution::{execute_plan, execute_plan_privileged}; +pub use plan::{ + build_removal_plan, format_recommendation, plan_general, plan_install, plan_legacy_install, + plan_removal, plan_removal_with_ai, select_removal_copy, PlanStore, +}; +pub use validation::{compute_plan_digest, seal_plan, validate_prepared_plan}; diff --git a/installer-rs/crates/phoebus-installer/src/service/plan.rs b/installer-rs/crates/phoebus-installer/src/service/plan.rs new file mode 100644 index 0000000..89d5d57 --- /dev/null +++ b/installer-rs/crates/phoebus-installer/src/service/plan.rs @@ -0,0 +1,872 @@ +//! Plan staging and planning APIs: recommendation text, [`PlanStore`], and the +//! `plan_*` builders shared by the CLI and the desktop assistant. + +use std::io::Write; +use std::path::{Path, PathBuf}; + +use phoebus_ai::assistant::{complete_plan, run_assistant, AssistantPlan}; +use phoebus_ai::install::Evidence; +use phoebus_ai::provider::SystemFacts; +use phoebus_core::action::SystemAction; +use phoebus_core::effects::ResolvedPlan; +use phoebus_core::selection::{Backend, Candidate, SandboxLevel}; +use phoebus_executor::actions; +use phoebus_executor::chooser; +use phoebus_executor::error::{ExecError, Result}; +use phoebus_executor::exec::Exec; +use phoebus_executor::install::{self, AiInstall, InstallRequest}; + +use super::validation::{compute_plan_digest, seal_plan}; +use super::{ + canonical_root, effective_uid, fresh_plan_id, is_safe_plan_id, now_unix, random_token, + PlanClaim, PlanKind, PreparedPlan, DEFAULT_PLAN_TTL_SECONDS, +}; + +/// Produce an honest, evidence-based human recommendation for an application candidate. +pub fn format_recommendation(candidate: &Candidate, application: &str) -> String { + let source_name = match candidate.backend { + Backend::PortageBinary => "Gentoo binhost", + Backend::PortageSource => "Gentoo Portage", + Backend::PortageVendor => "Portage vendor binary", + Backend::Flatpak => "Flathub", + Backend::Snap => "Snap Store", + Backend::Nix => "Nixpkgs", + Backend::AppImage => "managed AppImage", + Backend::CustomEbuild => "Phoebus custom ebuild", + }; + + let sandbox_desc = match candidate.sandbox { + SandboxLevel::Strong => "strong application isolation", + SandboxLevel::Partial => "partial confinement", + SandboxLevel::None => "direct host integration (unconfined)", + }; + + let build_desc = if let Some(secs) = candidate.build_seconds { + if secs < 60 { + format!("fast install (~{secs}s)") + } else { + let mins = secs.div_ceil(60); + format!("compiles native binaries (~{mins} min build)") + } + } else { + match candidate.backend { + Backend::PortageBinary | Backend::Flatpak | Backend::Snap | Backend::AppImage => { + "pre-built binary package".to_string() + } + Backend::PortageSource => "source compilation (build time unmeasured)".to_string(), + _ => "pre-built binary".to_string(), + } + }; + + format!( + "Install {application} from {source_name}. Recommended for {sandbox_desc} and {build_desc}." + ) +} + +// ----------------------------------------------------------------------------- +// PlanStore +// ----------------------------------------------------------------------------- + +/// Protected, per-user plan storage. +/// +/// A plan is written with a 0600 mode inside a 0700 directory owned by the +/// reviewing user (or the broker for root). Reloading rejects a symlink, a +/// file owned by someone other than the initiator/root, or a group/world +/// writable file. Consumption uses an `O_EXCL` marker so two concurrent +/// executions cannot both run the same plan. +#[derive(Debug, Clone)] +pub struct PlanStore { + dir: PathBuf, + /// The uid a plan is expected to belong to. The privileged broker sets this + /// to the initiating user so it can read that user's plan while still + /// rejecting a file owned by anyone else. + expected_uid: Option, +} + +impl PlanStore { + /// Storage for a specific uid. Used by the privileged broker, which + /// recomputes the directory from the uid the caller passed rather than + /// trusting an arbitrary path. + pub fn for_uid(uid: u32) -> Self { + if let Ok(dir) = std::env::var("PHOEBUS_PLANS_DIR") { + return Self { + dir: PathBuf::from(dir), + expected_uid: Some(uid), + }; + } + let candidates: Vec = if uid == 0 { + vec![PathBuf::from("/run/phoebus/plans")] + } else { + // Prefer the canonical per-user runtime path so the privileged + // broker (which derives the same path from the uid) finds it. + let mut v = vec![PathBuf::from(format!("/run/user/{uid}/phoebus/plans"))]; + if let Ok(xdg) = std::env::var("XDG_RUNTIME_DIR") { + v.push(PathBuf::from(xdg).join("phoebus/plans")); + } + v + }; + for dir in candidates { + if std::fs::create_dir_all(&dir).is_ok() { + return Self { + dir, + expected_uid: Some(uid), + }; + } + } + let temp = std::env::temp_dir().join(format!("phoebus-plans-{uid}")); + let _ = std::fs::create_dir_all(&temp); + Self { + dir: temp, + expected_uid: Some(uid), + } + } + + pub fn for_current_user() -> Self { + Self::for_uid(effective_uid()) + } + + /// Explicit directory, for tests and callers that manage their own store. + pub fn with_dir(dir: impl Into) -> Self { + Self { + dir: dir.into(), + expected_uid: None, + } + } + + pub fn dir(&self) -> &Path { + &self.dir + } + + fn ensure_dir(&self) -> Result<()> { + std::fs::create_dir_all(&self.dir).map_err(|e| ExecError::io(self.dir.clone(), e))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&self.dir, std::fs::Permissions::from_mode(0o700)); + } + Ok(()) + } + + fn path(&self, plan_id: &str, suffix: &str) -> Result { + if !is_safe_plan_id(plan_id) { + return Err(ExecError::operation( + "service", + "plan path", + format!("unsafe plan identifier `{plan_id}`"), + )); + } + Ok(self.dir.join(format!("{plan_id}{suffix}"))) + } + + /// Write a plan atomically (temp file -> fsync -> rename) with mode 0600. + pub fn save(&self, plan: &mut PreparedPlan) -> Result { + seal_plan(plan); + let path = self.path(&plan.id, ".json")?; + self.ensure_dir()?; + let text = serde_json::to_string_pretty(plan) + .map_err(|e| ExecError::operation("service", "serialize plan", e.to_string()))?; + + let tmp = self.dir.join(format!(".{}.tmp", random_token())); + { + let mut opts = std::fs::OpenOptions::new(); + opts.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.mode(0o600); + } + let mut file = opts.open(&tmp).map_err(|e| ExecError::io(tmp.clone(), e))?; + file.write_all(text.as_bytes()) + .and_then(|_| file.flush()) + .and_then(|_| file.sync_all()) + .map_err(|e| ExecError::io(tmp.clone(), e))?; + } + std::fs::rename(&tmp, &path).map_err(|e| { + let _ = std::fs::remove_file(&tmp); + ExecError::io(path.clone(), e) + })?; + if let Ok(dir) = std::fs::File::open(&self.dir) { + let _ = dir.sync_all(); + } + Ok(path) + } + + /// Load a plan, rejecting malformed identifiers, symlinks and unsafe + /// ownership/permissions. The caller still has to validate the contents. + pub fn load(&self, plan_id: &str) -> Result { + let path = self.path(plan_id, ".json")?; + let meta = std::fs::symlink_metadata(&path).map_err(|_| { + ExecError::operation( + "service", + "load plan", + format!("plan `{plan_id}` not found, consumed or expired"), + ) + })?; + if meta.file_type().is_symlink() { + return Err(ExecError::operation( + "service", + "load plan", + "plan path is a symlink; refusing to follow it", + )); + } + if !meta.is_file() { + return Err(ExecError::operation( + "service", + "load plan", + "plan path is not a regular file", + )); + } + #[cfg(unix)] + { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + if meta.permissions().mode() & 0o022 != 0 { + return Err(ExecError::operation( + "service", + "load plan", + "plan file is group/world writable; refusing to trust it", + )); + } + let owner = meta.uid(); + let expected = self.expected_uid.unwrap_or_else(effective_uid); + // The broker runs as root but is reading the initiating user's plan, + // so the expected owner is the initiator, not root. A plan owned by + // a third party is rejected. + if owner != expected && owner != 0 { + return Err(ExecError::operation( + "service", + "load plan", + format!("plan file is owned by uid {owner}, not the expected uid {expected}"), + )); + } + } + let text = std::fs::read_to_string(&path).map_err(|e| ExecError::io(path.clone(), e))?; + let plan: PreparedPlan = serde_json::from_str(&text) + .map_err(|e| ExecError::operation("service", "deserialize plan", e.to_string()))?; + if plan.id != plan_id { + return Err(ExecError::operation( + "service", + "load plan", + "plan identifier does not match its storage name", + )); + } + Ok(plan) + } + + /// Atomically claim a plan for execution. Returns a guard that keeps the + /// marker on disk; a second claim (or a retry after a crash) fails. + pub fn claim(&self, plan_id: &str) -> Result { + let marker = self.path(plan_id, ".claim")?; + self.ensure_dir()?; + let mut opts = std::fs::OpenOptions::new(); + opts.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.mode(0o600); + } + opts.open(&marker).map_err(|e| { + ExecError::operation( + "service", + "claim plan", + format!("plan `{plan_id}` is already consumed or being executed ({e})"), + ) + })?; + Ok(PlanClaim { marker }) + } + + /// True when a plan has already been claimed (consumed) for execution. + pub fn is_claimed(&self, plan_id: &str) -> bool { + match self.path(plan_id, ".claim") { + Ok(p) => p.exists(), + Err(_) => true, + } + } +} + +// ----------------------------------------------------------------------------- +// Planning APIs +// ----------------------------------------------------------------------------- + +/// Plan an installation using AI investigation and policy checks. +pub fn plan_install( + plans: &PlanStore, + exec: &Exec, + root: &Path, + request: &InstallRequest, + session: &dyn phoebus_ai::install::InstallSession, + ai: Option<&AiInstall>, + facts: &SystemFacts, +) -> Result { + let ai = match ai { + Some(a) => a, + None => { + return Err(ExecError::operation( + "service", + "plan_install", + "No AI provider is configured. Specify a model or select deterministic legacy administration (--legacy --).", + )); + } + }; + + let resolved = install::resolve_with_ai(exec, root, request, session, ai, facts)?; + build_install_plan(plans, root, resolved, PlanKind::Install) +} + +/// Plan an installation deterministically without contacting a model. +pub fn plan_legacy_install( + plans: &PlanStore, + exec: &Exec, + root: &Path, + request: &InstallRequest, +) -> Result { + if request.backend.is_none() { + return Err(ExecError::operation( + "service", + "plan_legacy_install", + "Legacy install requires an explicit package source flag (--flatpak, --portage, --nix, --snap, --appimage, --ebuild)", + )); + } + let resolved = install::resolve_explicit(exec, root, request)?; + build_install_plan(plans, root, resolved, PlanKind::LegacyInstall) +} + +fn build_install_plan( + plans: &PlanStore, + root: &Path, + resolved: install::ResolvedInstall, + kind: PlanKind, +) -> Result { + let now = now_unix(); + let plan_id = fresh_plan_id("inst"); + + let rec = format_recommendation(&resolved.candidate, &resolved.request.application); + let source_display = match resolved.candidate.backend { + Backend::PortageBinary => "Gentoo binhost", + Backend::PortageSource => "Gentoo Portage", + Backend::PortageVendor => "Portage vendor", + Backend::Flatpak => "Flathub", + Backend::Snap => "Snap Store", + Backend::Nix => "Nixpkgs", + Backend::AppImage => "managed AppImage", + Backend::CustomEbuild => "Phoebus custom ebuild", + } + .to_string(); + + let digest = resolved.approval_digest(); + let actions = vec![resolved.action.clone()]; + let requires_root = resolved.action.is_mutating(); + // Normalize the stored effect digest so the per-step binding check sees a + // digest that matches the contents. + let mut effects = resolved.effects.clone(); + effects.recompute_digest(); + let step_effects = vec![effects.clone()]; + + let mut plan = PreparedPlan { + id: plan_id, + created_unix: now, + expires_unix: now + DEFAULT_PLAN_TTL_SECONDS, + kind, + summary: format!( + "install {} via {}", + resolved.request.application, + resolved.candidate.backend.as_str() + ), + recommendation: rec, + application: Some(resolved.request.application.clone()), + candidate: Some(resolved.candidate.clone()), + alternatives: resolved.alternatives.clone(), + rationale: resolved.rationale.clone(), + warnings: resolved.warnings.clone(), + actions, + effects, + step_effects, + digest, + verification: resolved.verification.clone(), + requires_root, + source: source_display, + executed: false, + target_root: canonical_root(root), + initiator_uid: effective_uid(), + integrity: String::new(), + }; + + plans.save(&mut plan)?; + Ok(plan) +} + +/// Deterministically choose which installed copy a removal targets. Shared by +/// the legacy and AI-first paths so ownership discovery and the ambiguity +/// policy cannot diverge. Ambiguity always requires an explicit lane flag. +pub fn select_removal_copy( + exec: &Exec, + root: &Path, + application: &str, + backend_filter: Option, +) -> Result { + let inspection = chooser::installed_copies(exec, root, application); + if inspection.copies.is_empty() { + return Err(ExecError::operation( + "service", + "plan_removal", + format!("`{application}` is not installed on this system"), + )); + } + + if let Some(b) = backend_filter { + return inspection + .copies + .into_iter() + .find(|c| c.backend == b.as_str()) + .ok_or_else(|| { + ExecError::operation( + "service", + "plan_removal", + format!( + "`{application}` is not installed via {} (found in other lanes)", + b.as_str() + ), + ) + }); + } + if inspection.copies.len() > 1 { + let details = inspection + .copies + .iter() + .map(|c| format!("{} ({})", c.id, c.backend)) + .collect::>() + .join(", "); + return Err(ExecError::operation( + "service", + "plan_removal", + format!( + "`{application}` is installed in multiple lanes: {details}. Specify which one to remove explicitly (e.g. sys remove {application} --flatpak or --portage)." + ), + )); + } + Ok(inspection.copies.into_iter().next().unwrap()) +} + +/// Plan an application removal across supported sources preserving user data by +/// default, without contacting a model (legacy mode only). +pub fn plan_removal( + plans: &PlanStore, + exec: &Exec, + root: &Path, + application: &str, + backend_filter: Option, +) -> Result { + let target_copy = select_removal_copy(exec, root, application, backend_filter)?; + build_removal_plan( + plans, + exec, + root, + application, + &target_copy, + Vec::new(), + Vec::new(), + ) +} + +/// Plan an application removal through the connected model (the default). The +/// deterministic discovery and ambiguity policy run first; the model must then +/// confirm exactly the discovered target. A model failure, or a proposal that +/// does not match the deterministic target, stops the workflow. +pub fn plan_removal_with_ai( + plans: &PlanStore, + exec: &Exec, + root: &Path, + application: &str, + backend_filter: Option, + ai: &AiInstall, + facts: &SystemFacts, +) -> Result { + let target_copy = select_removal_copy(exec, root, application, backend_filter)?; + let discovered = chooser::installed_copies(exec, root, application); + let list = discovered + .copies + .iter() + .map(|c| format!("{} ({})", c.id, c.backend)) + .collect::>() + .join(", "); + + let instruction = format!( + "The user asked to remove `{application}`. Read-only discovery found these installed \ + copies: [{list}]. The policy-selected target is `{}` in the {} lane. Confirm a removal \ + plan for exactly that copy by proposing the matching remove action; if the request is \ + ambiguous, propose no action and explain what clarification is needed.", + target_copy.id, target_copy.backend + ); + let assistant_plan: AssistantPlan = complete_plan( + ai.provider, + &ai.endpoint, + &ai.model, + facts, + &instruction, + ai.transport, + ) + .map_err(|e| ExecError::operation("service", "plan_removal_with_ai", e.to_string()))?; + + if assistant_plan.actions.len() != 1 + || !removal_action_matches(&assistant_plan.actions[0], &target_copy) + { + return Err(ExecError::operation( + "service", + "plan_removal_with_ai", + format!( + "the model did not confirm the discovered removal target `{}` ({}); no removal \ + plan was produced", + target_copy.id, target_copy.backend + ), + )); + } + + let mut rationale: Vec = assistant_plan + .rationale + .into_iter() + .map(|r| format!("AI: {}", r.reason)) + .collect(); + if rationale.is_empty() { + rationale.push(format!( + "AI confirmed removal of the discovered {} copy", + target_copy.backend + )); + } + + build_removal_plan( + plans, + exec, + root, + application, + &target_copy, + rationale, + Vec::new(), + ) +} + +/// Whether a proposed action is the correct removal of the discovered copy. +fn removal_action_matches(action: &SystemAction, copy: &chooser::InstalledCopy) -> bool { + match (action, copy.backend.as_str()) { + (SystemAction::FlatpakRemove { app_id }, "flatpak") => app_id == ©.id, + (SystemAction::SnapRemove { name }, "snap") => name == ©.id, + (SystemAction::AppImageRemove { name, .. }, "appimage") => name == ©.id, + (SystemAction::RemovePackage { atom }, _) + if copy.backend != "flatpak" + && copy.backend != "snap" + && copy.backend != "appimage" => + { + atom == ©.id + } + _ => false, + } +} + +/// Build a removal plan for a specific, already-discovered installed copy. +/// Used by both the deterministic (legacy) path and the AI-first path, so the +/// ownership discovery and policy validation are identical. +pub fn build_removal_plan( + plans: &PlanStore, + exec: &Exec, + root: &Path, + application: &str, + target_copy: &chooser::InstalledCopy, + rationale: Vec, + warnings: Vec, +) -> Result { + let action = match target_copy.backend.as_str() { + "flatpak" => SystemAction::FlatpakRemove { + app_id: target_copy.id.clone(), + }, + "snap" => SystemAction::SnapRemove { + name: target_copy.id.clone(), + }, + "appimage" => SystemAction::AppImageRemove { + name: target_copy.id.clone(), + // User data preserved by default + purge_data: false, + }, + _ => SystemAction::RemovePackage { + atom: target_copy.id.clone(), + }, + }; + + let mut effects = actions::resolve_effects(exec, &action, root)?; + effects.recompute_digest(); + let now = now_unix(); + let plan_id = fresh_plan_id("rem"); + let actions_vec = vec![action.clone()]; + let step_effects = vec![effects.clone()]; + let digest = compute_plan_digest(&actions_vec, None, &effects, &step_effects); + + let mut rationale = rationale; + rationale.insert( + 0, + format!( + "installed package {} detected in {} lane", + target_copy.id, target_copy.backend + ), + ); + rationale.push("preserves user configuration and data in home directory by default".into()); + + let mut plan = PreparedPlan { + id: plan_id, + created_unix: now, + expires_unix: now + DEFAULT_PLAN_TTL_SECONDS, + kind: PlanKind::Removal, + summary: format!("remove {} ({})", target_copy.id, target_copy.backend), + recommendation: format!( + "Remove application {} from {}. Application binaries will be uninstalled while user data in the home directory is preserved.", + target_copy.id, target_copy.backend + ), + application: Some(application.to_string()), + candidate: None, + alternatives: Vec::new(), + rationale, + warnings, + actions: actions_vec, + effects, + step_effects, + digest, + verification: format!( + "verify that `{}` ({}) is completely removed from the system", + target_copy.id, target_copy.backend + ), + requires_root: action.is_mutating(), + source: target_copy.backend.clone(), + executed: false, + target_root: canonical_root(root), + initiator_uid: effective_uid(), + integrity: String::new(), + }; + + plans.save(&mut plan)?; + Ok(plan) +} + +/// Rewrite a lane-selectable catalogue action to an explicit source, and refuse +/// an action that targets a different lane. A spanning action (history, +/// snapshots, services) is returned unchanged. +pub(super) fn constrain_action( + action: SystemAction, + constraint: Backend, +) -> std::result::Result { + Ok(match action { + SystemAction::SearchPackages { query, .. } => SystemAction::SearchPackages { + query, + backend: Some(constraint), + }, + SystemAction::ListPackages { filter, .. } => SystemAction::ListPackages { + backend: Some(constraint), + filter, + }, + SystemAction::PackageInfo { package, .. } => SystemAction::PackageInfo { + package, + backend: Some(constraint), + }, + SystemAction::CheckUpdates { .. } => SystemAction::CheckUpdates { + backend: Some(constraint), + }, + SystemAction::ApplyUpdates { .. } => SystemAction::ApplyUpdates { + backend: Some(constraint), + }, + SystemAction::CleanCache { .. } => SystemAction::CleanCache { + backend: Some(constraint), + }, + // Optional-backend discovery and selection requests must be *rewritten* + // to the constraint, not merely filtered afterwards: otherwise the + // resolver would still query every lane before the results are + // discarded. + SystemAction::DiscoverCandidates { + query, + kind, + gui, + requires_sandbox, + .. + } => SystemAction::DiscoverCandidates { + query, + kind, + backend: Some(constraint), + gui, + requires_sandbox, + }, + SystemAction::ChoosePackage { + name, + kind, + gui, + requires_sandbox, + .. + } => SystemAction::ChoosePackage { + name, + kind, + backend: Some(constraint), + gui, + requires_sandbox, + }, + // `InspectInstallation` has no lane field but probes every lane; under + // an explicit constraint it is refused rather than leaking other lanes. + SystemAction::InspectInstallation { .. } => { + return Err(format!( + "inspect_installation spans every package lane, but this request was constrained \ + to {}; use a lane-specific inventory instead", + constraint.as_str() + )); + } + other => { + if let Some(own) = other.backend() { + let matches = own == constraint || (own.is_portage() && constraint.is_portage()); + if !matches { + return Err(format!( + "`{}` targets the {} lane, but this request was constrained to {}", + other.describe(), + own.as_str(), + constraint.as_str() + )); + } + } + other + } + }) +} + +/// Plan general system administration tasks via the connected model. +/// +/// The model may run a bounded, read-only investigation (search, inventory, +/// information, update checks) before answering. An explicit `constraint` +/// forbids any action that targets a different package lane, so a source flag +/// constrains the AI workflow rather than bypassing it. +pub fn plan_general( + plans: &PlanStore, + exec: &Exec, + root: &Path, + query: &str, + facts: &SystemFacts, + ai: &AiInstall, + constraint: Option, +) -> Result { + let instruction = match constraint { + Some(backend) => format!( + "{query}\n\n[source constraint: only the `{}` lane may be used; do not use \ + another lane]", + backend.as_str() + ), + None => query.to_string(), + }; + let investigate = |requests: &[SystemAction]| -> Vec { + requests + .iter() + .map(|request| { + let output = match constraint { + Some(backend) => match constrain_action(request.clone(), backend) { + Ok(action) => match actions::execute(exec, &action, None, root) { + Ok(outcome) => outcome.output, + Err(e) => format!("investigation failed: {e}"), + }, + Err(msg) => format!("refused by the source constraint: {msg}"), + }, + None => match actions::execute(exec, request, None, root) { + Ok(outcome) => outcome.output, + Err(e) => format!("investigation failed: {e}"), + }, + }; + Evidence { + request: request.describe(), + output, + } + }) + .collect() + }; + let assistant_plan: AssistantPlan = run_assistant( + ai.provider, + &ai.endpoint, + &ai.model, + facts, + &instruction, + ai.transport, + &investigate, + &ai.limits, + ) + .map_err(|e| ExecError::operation("service", "run_assistant", e.to_string()))?; + + // Apply the source constraint to the final actions too: a lane-specific + // query is rewritten to the constraint, and an action that targets a + // different lane is refused before anything is planned. + let actions_list: Vec = match constraint { + Some(backend) => assistant_plan + .actions + .iter() + .cloned() + .map(|action| { + constrain_action(action, backend) + .map_err(|msg| ExecError::operation("service", "source constraint", msg)) + }) + .collect::>>()?, + None => assistant_plan.actions.clone(), + }; + + let mut combined_effects = ResolvedPlan { + established: true, + ..Default::default() + }; + let mut any_mutating = false; + let mut step_effects = Vec::new(); + + for act in &actions_list { + let mut eff = actions::resolve_effects(exec, act, root).map_err(|e| { + ExecError::operation( + "service", + "resolve_effects", + format!("could not resolve effects for `{}`: {e}", act.describe()), + ) + })?; + // Normalize the stored digest so the per-step binding check sees a + // digest that matches the contents. + eff.recompute_digest(); + if eff.established { + combined_effects.effects.extend(eff.effects.clone()); + combined_effects.cleanup.extend(eff.cleanup.clone()); + combined_effects.updates.extend(eff.updates.clone()); + combined_effects + .consequences + .extend(eff.consequences.clone()); + } + step_effects.push(eff); + any_mutating |= act.is_mutating(); + } + combined_effects.recompute_digest(); + + let now = now_unix(); + let plan_id = fresh_plan_id("gen"); + let digest = compute_plan_digest(&actions_list, None, &combined_effects, &step_effects); + let rationale_strings: Vec = assistant_plan + .rationale + .into_iter() + .map(|r| format!("{}: {}", r.action, r.reason)) + .collect(); + + let mut plan = PreparedPlan { + id: plan_id, + created_unix: now, + expires_unix: now + DEFAULT_PLAN_TTL_SECONDS, + kind: PlanKind::General, + summary: assistant_plan.summary.clone(), + recommendation: assistant_plan.summary, + application: None, + candidate: None, + alternatives: Vec::new(), + rationale: rationale_strings, + warnings: Vec::new(), + actions: actions_list, + effects: combined_effects, + step_effects, + digest, + verification: "verify execution of planned actions".into(), + requires_root: any_mutating, + source: "AI Assistant".into(), + executed: false, + target_root: canonical_root(root), + initiator_uid: effective_uid(), + integrity: String::new(), + }; + + plans.save(&mut plan)?; + Ok(plan) +} diff --git a/installer-rs/crates/phoebus-installer/src/service/tests.rs b/installer-rs/crates/phoebus-installer/src/service/tests.rs new file mode 100644 index 0000000..21a3eb6 --- /dev/null +++ b/installer-rs/crates/phoebus-installer/src/service/tests.rs @@ -0,0 +1,2111 @@ +//! Service-layer regression tests (moved verbatim from `service.rs`). + +use super::plan::constrain_action; +use super::validation::{plan_integrity, reviewed_steps, validate_effect_bindings}; +use super::*; +use crate::approval::{ApprovalIdentity, ApprovalLedger}; +use phoebus_ai::provider::SystemFacts; +use phoebus_core::action::SystemAction; +use phoebus_core::effects::parse_emerge_pretend; +use phoebus_core::effects::ResolvedPlan; +use phoebus_core::selection::Capability; +use phoebus_core::selection::{Backend, Candidate, SandboxLevel}; +use phoebus_core::Redactor; +use phoebus_executor::command::RecordingRunner; +use phoebus_executor::error::{ExecError, Result}; +use phoebus_executor::exec::Exec; +use phoebus_executor::install::{AiInstall, InstallRequest}; +use phoebus_executor::transaction; +use phoebus_executor::Logger; +use std::path::Path; +use tempfile::tempdir; + +fn make_test_exec(root: &Path) -> Exec { + let temp = tempdir().unwrap().keep(); + let logger = Logger::open(temp.join("test.log"), Redactor::new(), false); + Exec::new( + Box::new(RecordingRunner::new()), + logger, + false, + root.to_path_buf(), + temp, + ) +} + +fn sample_candidate() -> Candidate { + let mut cand = Candidate::new(Backend::Flatpak, "org.mozilla.firefox", "flathub"); + cand.version = Some("120.0".into()); + cand.verified = true; + cand.download_mib = Some(85); + cand.install_mib = Some(230); + cand.sandbox = SandboxLevel::Strong; + cand.wayland = Capability::Yes; + cand.desktop_integration = Capability::Yes; + cand.permissions = vec!["network".into()]; + cand +} + +#[test] +fn test_format_recommendation_honest() { + let cand = sample_candidate(); + let rec = format_recommendation(&cand, "firefox"); + assert!(rec.contains("Flathub")); + assert!(rec.contains("strong application isolation")); + assert!(rec.contains("pre-built binary")); + assert!(!rec.contains("avoids a lengthy build")); +} + +/// Build a sealed plan for validation tests. The canonical approval digest +/// is derived from the actions and reviewed effects, exactly as the +/// privileged boundary does; the trailing marker argument is retained only +/// so existing call sites read naturally and is ignored. +fn sealed( + id: &str, + kind: PlanKind, + actions: Vec, + _marker: &str, + target_root: &Path, + initiator_uid: u32, +) -> PreparedPlan { + let mut effects = ResolvedPlan::default(); + effects.recompute_digest(); + let step_effects = vec![effects.clone(); actions.len()]; + let digest = compute_plan_digest(&actions, None, &effects, &step_effects); + let mut plan = PreparedPlan { + id: id.into(), + created_unix: now_unix(), + expires_unix: now_unix() + 900, + kind, + summary: "test plan".into(), + recommendation: "rec".into(), + application: Some("firefox".into()), + candidate: None, + alternatives: Vec::new(), + rationale: Vec::new(), + warnings: Vec::new(), + actions, + effects, + step_effects, + digest, + verification: "verify".into(), + requires_root: false, + source: "test".into(), + executed: false, + target_root: canonical_root(target_root), + initiator_uid, + integrity: String::new(), + }; + seal_plan(&mut plan); + plan +} + +#[test] +fn plan_store_roundtrips_and_claims_once() { + let dir = tempdir().unwrap(); + let store = PlanStore::with_dir(dir.path()); + let mut plan = sealed( + "plan-abc", + PlanKind::General, + vec![SystemAction::History], + "d", + Path::new("/tmp"), + 0, + ); + store.save(&mut plan).unwrap(); + let loaded = store.load("plan-abc").unwrap(); + assert_eq!(loaded.id, "plan-abc"); + + let _claim = store.claim("plan-abc").unwrap(); + assert!(store.is_claimed("plan-abc")); + // A second claim (or a retry after a crash) must not run the mutation. + assert!(store.claim("plan-abc").is_err()); +} + +#[test] +fn concurrent_claims_allow_at_most_one_execution() { + let dir = tempdir().unwrap(); + let store = PlanStore::with_dir(dir.path()); + let mut plan = sealed( + "plan-race", + PlanKind::General, + vec![SystemAction::History], + "d", + Path::new("/tmp"), + 0, + ); + store.save(&mut plan).unwrap(); + + let handles: Vec<_> = (0..8) + .map(|_| { + let store = store.clone(); + std::thread::spawn(move || store.claim("plan-race").is_ok()) + }) + .collect(); + let successes = handles + .into_iter() + .map(|h| h.join().expect("claim thread panicked")) + .filter(|won| *won) + .count(); + assert_eq!(successes, 1, "exactly one claim may win"); +} + +#[test] +fn replacing_the_plan_after_review_is_rejected() { + let dir = tempdir().unwrap(); + let store = PlanStore::with_dir(dir.path()); + let root = tempdir().unwrap(); + let exec = make_test_exec(root.path()); + let uid = effective_uid(); + + let mut original = sealed( + "plan-replace", + PlanKind::General, + vec![SystemAction::History], + "reviewed-digest", + root.path(), + uid, + ); + store.save(&mut original).unwrap(); + + // An attacker (or a re-plan) replaces the stored plan under the same id. + let mut replacement = sealed( + "plan-replace", + PlanKind::General, + vec![SystemAction::EnableService { + name: "sshd".into(), + }], + "different-digest", + root.path(), + uid, + ); + replacement.requires_root = true; + seal_plan(&mut replacement); + store.save(&mut replacement).unwrap(); + + // The unprivileged caller's reviewed digest no longer matches. + let err = execute_plan( + &exec, + root.path(), + &store, + "plan-replace", + "reviewed-digest", + true, + ) + .unwrap_err(); + assert!(err.to_string().contains("digest mismatch"), "{err}"); + // And nothing was consumed. + assert!(!store.is_claimed("plan-replace")); +} + +#[test] +fn plan_store_rejects_traversal_and_bad_ids() { + let dir = tempdir().unwrap(); + let store = PlanStore::with_dir(dir.path()); + assert!(store.load("../escape").is_err()); + assert!(store.load("a/b").is_err()); + assert!(store.load("").is_err()); +} + +#[test] +fn plan_store_rejects_group_writable_files() { + use std::os::unix::fs::PermissionsExt; + let dir = tempdir().unwrap(); + let store = PlanStore::with_dir(dir.path()); + let mut plan = sealed( + "plan-mode", + PlanKind::General, + vec![SystemAction::History], + "d", + Path::new("/tmp"), + 0, + ); + let path = store.save(&mut plan).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o666)).unwrap(); + assert!(store.load("plan-mode").is_err()); +} + +#[test] +fn validation_rejects_tampering_expiry_replay_root_and_uid() { + let store_dir = tempdir().unwrap(); + let store = PlanStore::with_dir(store_dir.path()); + let root = tempdir().unwrap(); + let exec = make_test_exec(root.path()); + let uid = effective_uid(); + + // Baseline validates. + let mut plan = sealed( + "plan-ok", + PlanKind::General, + vec![SystemAction::History], + "same-digest", + root.path(), + uid, + ); + store.save(&mut plan).unwrap(); + let loaded = store.load("plan-ok").unwrap(); + validate_prepared_plan(&exec, root.path(), &loaded, Some(&loaded.digest), uid).unwrap(); + + // Tampering with any reviewed field breaks the seal. + let path = store_dir.path().join("plan-ok.json"); + let mut raw: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); + raw["summary"] = serde_json::json!("tampered"); + std::fs::write(&path, serde_json::to_string(&raw).unwrap()).unwrap(); + let tampered = store.load("plan-ok").unwrap(); + let err = validate_prepared_plan(&exec, root.path(), &tampered, None, uid).unwrap_err(); + assert!(err.to_string().contains("integrity"), "{err}"); + + // Expired. + let mut expired = sealed( + "plan-exp", + PlanKind::General, + vec![SystemAction::History], + "d", + root.path(), + uid, + ); + expired.expires_unix = 10; + seal_plan(&mut expired); + store.save(&mut expired).unwrap(); + let err = validate_prepared_plan( + &exec, + root.path(), + &store.load("plan-exp").unwrap(), + None, + uid, + ) + .unwrap_err(); + assert!(err.to_string().contains("expired"), "{err}"); + + // Replayed. + let mut replayed = sealed( + "plan-rep", + PlanKind::General, + vec![SystemAction::History], + "d", + root.path(), + uid, + ); + replayed.executed = true; + seal_plan(&mut replayed); + store.save(&mut replayed).unwrap(); + let err = validate_prepared_plan( + &exec, + root.path(), + &store.load("plan-rep").unwrap(), + None, + uid, + ) + .unwrap_err(); + assert!(err.to_string().contains("already been executed"), "{err}"); + + // Wrong target root: reviewed for /, executed against the temp root. + let mut wrong_root = sealed( + "plan-root", + PlanKind::General, + vec![SystemAction::History], + "d", + Path::new("/"), + uid, + ); + seal_plan(&mut wrong_root); + store.save(&mut wrong_root).unwrap(); + let err = validate_prepared_plan( + &exec, + root.path(), + &store.load("plan-root").unwrap(), + None, + uid, + ) + .unwrap_err(); + assert!(err.to_string().contains("target root mismatch"), "{err}"); + + // Wrong initiator uid. + let mut wrong_uid = sealed( + "plan-uid", + PlanKind::General, + vec![SystemAction::History], + "d", + root.path(), + uid, + ); + seal_plan(&mut wrong_uid); + store.save(&mut wrong_uid).unwrap(); + let err = validate_prepared_plan( + &exec, + root.path(), + &store.load("plan-uid").unwrap(), + None, + uid.wrapping_add(4242), + ) + .unwrap_err(); + assert!( + err.to_string().contains("cannot be executed by uid"), + "{err}" + ); +} + +#[test] +fn validation_rejects_digest_mismatch_and_malformed_action_set() { + let store_dir = tempdir().unwrap(); + let store = PlanStore::with_dir(store_dir.path()); + let root = tempdir().unwrap(); + let exec = make_test_exec(root.path()); + let uid = effective_uid(); + + let mut plan = sealed( + "plan-dig", + PlanKind::General, + vec![SystemAction::History], + "correct", + root.path(), + uid, + ); + store.save(&mut plan).unwrap(); + let err = validate_prepared_plan( + &exec, + root.path(), + &store.load("plan-dig").unwrap(), + Some("wrong"), + uid, + ) + .unwrap_err(); + assert!(err.to_string().contains("digest mismatch"), "{err}"); + + let mut empty = sealed( + "plan-empty", + PlanKind::General, + Vec::new(), + "d", + root.path(), + uid, + ); + seal_plan(&mut empty); + store.save(&mut empty).unwrap(); + let err = validate_prepared_plan( + &exec, + root.path(), + &store.load("plan-empty").unwrap(), + None, + uid, + ) + .unwrap_err(); + assert!(err.to_string().contains("no actions"), "{err}"); +} + +struct FlatpakRunner { + installed: std::sync::Arc, + /// When true, a successful `flatpak install` marks the app installed, + /// so verification can succeed. When false, verification always fails. + mark_on_install: bool, +} + +impl phoebus_executor::command::ProcessRunner for FlatpakRunner { + fn execute( + &self, + spec: &phoebus_executor::command::CommandSpec, + ) -> Result { + use std::time::Duration; + let ok = |s: String| phoebus_executor::command::CommandOutput { + status: 0, + success: true, + stdout: s.into_bytes(), + stderr: Vec::new(), + duration: Duration::from_millis(1), + }; + let invokes_flatpak_install = spec.args.iter().any(|a| a == "install") + && (spec.program == "flatpak" || spec.args.iter().any(|a| a == "flatpak")); + if invokes_flatpak_install { + if self.mark_on_install { + self.installed + .store(true, std::sync::atomic::Ordering::SeqCst); + } + return Ok(ok("installed\n".into())); + } + let installed = self.installed.load(std::sync::atomic::Ordering::SeqCst); + let is_flatpak = spec.program == "flatpak" || spec.args.iter().any(|a| a == "flatpak"); + if is_flatpak && spec.args.iter().any(|a| a == "search") { + Ok(ok("org.mozilla.firefox 128\n".into())) + } else if is_flatpak && spec.args.iter().any(|a| a == "list") { + if !installed { + return Ok(ok(String::new())); + } + // `--columns=application` (verification) vs the richer + // `application,name,version` (discovery). + if spec.args.iter().any(|a| a == "--columns=application") { + Ok(ok("org.mozilla.firefox\n".into())) + } else { + Ok(ok("org.mozilla.firefox Firefox 128\n".into())) + } + } else { + Ok(ok(String::new())) + } + } +} + +fn make_exec_with_runner( + root: &Path, + runner: Box, +) -> Exec { + let temp = tempdir().unwrap().keep(); + let logger = Logger::open(temp.join("test.log"), Redactor::new(), false); + Exec::new(runner, logger, false, root.to_path_buf(), temp) +} + +/// A target that actually has a Flatpak client, so lane availability +/// resolves from the target rather than the host. +fn install_fake_flatpak(root: &Path) { + use std::os::unix::fs::PermissionsExt; + let bin = root.join("usr/bin"); + std::fs::create_dir_all(&bin).unwrap(); + let flatpak = bin.join("flatpak"); + std::fs::write(&flatpak, "#!/bin/sh\n").unwrap(); + std::fs::set_permissions(&flatpak, std::fs::Permissions::from_mode(0o755)).unwrap(); +} + +#[test] +fn install_verification_failure_finishes_the_transaction_as_failed() { + let root = tempdir().unwrap(); + let installed = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let exec = make_exec_with_runner( + root.path(), + Box::new(FlatpakRunner { + installed: installed.clone(), + mark_on_install: false, + }), + ); + let store = PlanStore::with_dir(tempdir().unwrap().keep()); + let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); + install_fake_flatpak(root.path()); + + let mut request = InstallRequest::new("firefox"); + request.backend = Some(Backend::Flatpak); + let plan = plan_legacy_install(&store, &exec, root.path(), &request).unwrap(); + + // The install command "succeeds" but `flatpak list` never reports the + // app: verification must fail and the transaction must not say "ok". + let err = execute_plan_privileged( + &exec, + root.path(), + &store, + &approvals, + &plan.id, + &plan.digest, + plan.initiator_uid, + true, + ) + .unwrap_err(); + assert!(err.to_string().contains("Flatpak"), "{err}"); + + let log = transaction::read(root.path()).unwrap(); + assert_eq!( + log.records.len(), + 1, + "one transaction, not stuck in progress" + ); + assert!( + log.records[0].result.starts_with("verify failed"), + "{}", + log.records[0].result + ); + // The plan was consumed exactly once and cannot be retried. + assert!(execute_plan_privileged( + &exec, + root.path(), + &store, + &approvals, + &plan.id, + &plan.digest, + plan.initiator_uid, + true, + ) + .is_err()); +} + +#[test] +fn successful_install_finishes_ok_and_records_a_launch_command() { + let root = tempdir().unwrap(); + let installed = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let exec = make_exec_with_runner( + root.path(), + Box::new(FlatpakRunner { + installed: installed.clone(), + mark_on_install: true, + }), + ); + let store = PlanStore::with_dir(tempdir().unwrap().keep()); + let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); + install_fake_flatpak(root.path()); + let mut request = InstallRequest::new("firefox"); + request.backend = Some(Backend::Flatpak); + let plan = plan_legacy_install(&store, &exec, root.path(), &request).unwrap(); + + let outcome = execute_plan_privileged( + &exec, + root.path(), + &store, + &approvals, + &plan.id, + &plan.digest, + plan.initiator_uid, + true, + ) + .unwrap(); + assert!(outcome.completed); + assert_eq!( + outcome.launch, + Some(vec![ + "flatpak".into(), + "run".into(), + "org.mozilla.firefox".into() + ]) + ); + let log = transaction::read(root.path()).unwrap(); + assert_eq!(log.records[0].result, "ok"); +} + +#[test] +fn explicit_refusal_does_not_mutate_or_consume_the_plan() { + let root = tempdir().unwrap(); + let exec = make_test_exec(root.path()); + let store = PlanStore::with_dir(tempdir().unwrap().keep()); + let mut plan = sealed( + "plan-refuse", + PlanKind::General, + vec![SystemAction::EnableService { + name: "sshd".into(), + }], + "d", + root.path(), + effective_uid(), + ); + plan.requires_root = true; + seal_plan(&mut plan); + store.save(&mut plan).unwrap(); + + let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); + let err = execute_plan_privileged( + &exec, + root.path(), + &store, + &approvals, + &plan.id, + &plan.digest, + plan.initiator_uid, + false, + ) + .unwrap_err(); + assert!(matches!(err, ExecError::NotAuthorized(_)), "{err}"); + assert!( + !store.is_claimed(&plan.id), + "a refused plan is not consumed" + ); + // Refusal happens before the approval is claimed, so nothing is + // consumed in the broker ledger either. + let key = approval_identity(&plan, plan.initiator_uid).key; + assert!( + approvals.get(&key).unwrap().is_none(), + "a refused plan must not consume its approval" + ); +} + +/// The stable approval identity the broker derives for a plan. +fn approval_identity(plan: &PreparedPlan, uid: u32) -> ApprovalIdentity { + ApprovalIdentity::new( + plan.id.clone(), + plan.digest.clone(), + uid, + plan.target_root.clone(), + plan.expires_unix, + plan.actions.len(), + ) +} + +// ----------------------------------------------------------------------- +// Regression tests for the approval boundary and transaction truthfulness. +// ----------------------------------------------------------------------- + +const VIM_PRETEND: &str = "Calculating dependencies... done!\n\ + [ebuild N ] app-editors/vim-9.1.0\n\nTotal: 1 package\n"; +const WGET_PRETEND: &str = "Calculating dependencies... done!\n\ + [ebuild N ] net-misc/wget-1.24.5\n\nTotal: 1 package\n"; + +fn command_out(text: &str, success: bool) -> phoebus_executor::command::CommandOutput { + phoebus_executor::command::CommandOutput { + status: if success { 0 } else { 1 }, + success, + stdout: text.as_bytes().to_vec(), + stderr: Vec::new(), + duration: std::time::Duration::from_millis(1), + } +} + +struct SequenceRunner { + responses: std::sync::Mutex>, + fallback: phoebus_executor::command::CommandOutput, +} + +impl phoebus_executor::command::ProcessRunner for SequenceRunner { + fn execute( + &self, + _spec: &phoebus_executor::command::CommandSpec, + ) -> Result { + let mut responses = self.responses.lock().unwrap(); + if !responses.is_empty() { + return Ok(responses.remove(0)); + } + Ok(self.fallback.clone()) + } +} + +fn portage_install_plan( + id: &str, + action: SystemAction, + reviewed: ResolvedPlan, + root: &Path, + uid: u32, +) -> PreparedPlan { + let actions = vec![action]; + let mut reviewed = reviewed; + reviewed.recompute_digest(); + let step_effects = vec![reviewed.clone()]; + let digest = compute_plan_digest(&actions, None, &reviewed, &step_effects); + let mut plan = PreparedPlan { + id: id.into(), + created_unix: now_unix(), + expires_unix: now_unix() + 900, + kind: PlanKind::General, + summary: "install reviewed package".into(), + recommendation: "rec".into(), + application: Some("app-editors/vim".into()), + candidate: None, + alternatives: Vec::new(), + rationale: Vec::new(), + warnings: Vec::new(), + actions, + effects: reviewed, + step_effects, + digest, + verification: "verify".into(), + requires_root: true, + source: "test".into(), + executed: false, + target_root: canonical_root(root), + initiator_uid: uid, + integrity: String::new(), + }; + seal_plan(&mut plan); + plan +} + +fn ledger_entries(ledger: &ApprovalLedger) -> usize { + std::fs::read_dir(ledger.dir()) + .map(|d| d.flatten().count()) + .unwrap_or(0) +} + +#[test] +fn replacing_the_plan_during_authentication_is_rejected() { + let root = tempdir().unwrap(); + let exec = make_test_exec(root.path()); + let store = PlanStore::with_dir(tempdir().unwrap().keep()); + let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); + let uid = effective_uid(); + + let mut original = sealed( + "plan-replace", + PlanKind::General, + vec![SystemAction::History], + "reviewed-digest", + root.path(), + uid, + ); + store.save(&mut original).unwrap(); + let approved_digest = original.digest.clone(); + + // Replace the plan under the same identifier with a different action and + // a valid recomputed checksum. + let mut replacement = sealed( + "plan-replace", + PlanKind::General, + vec![SystemAction::EnableService { + name: "sshd".into(), + }], + "different-digest", + root.path(), + uid, + ); + replacement.requires_root = true; + seal_plan(&mut replacement); + assert_eq!( + replacement.integrity, + plan_integrity(&replacement), + "the replacement is self-consistent, yet must still be refused" + ); + store.save(&mut replacement).unwrap(); + + let err = execute_plan_privileged( + &exec, + root.path(), + &store, + &approvals, + "plan-replace", + &approved_digest, + uid, + true, + ) + .unwrap_err(); + assert!(err.to_string().contains("digest mismatch"), "{err}"); + // No system mutation and no approval consumed. + assert_eq!(ledger_entries(&approvals), 0, "nothing may be claimed"); +} + +#[test] +fn replay_is_rejected_after_the_user_deletes_their_plan_state() { + let root = tempdir().unwrap(); + let exec = make_test_exec(root.path()); + let store = PlanStore::with_dir(tempdir().unwrap().keep()); + let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); + let uid = effective_uid(); + + let mut plan = sealed( + "plan-replay", + PlanKind::General, + vec![SystemAction::History], + "d", + root.path(), + uid, + ); + let path = store.save(&mut plan).unwrap(); + let digest = plan.digest.clone(); + let bytes = std::fs::read(&path).unwrap(); + + execute_plan_privileged( + &exec, + root.path(), + &store, + &approvals, + "plan-replay", + &digest, + uid, + true, + ) + .unwrap(); + + // The user wipes their own plan and claim files and rewrites the plan + // with identical bytes (0600, as the store would): the approval is still + // consumed. + std::fs::remove_file(&path).unwrap(); + let _ = std::fs::remove_file(store.dir().join("plan-replay.claim")); + std::fs::write(&path, &bytes).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + + let err = execute_plan_privileged( + &exec, + root.path(), + &store, + &approvals, + "plan-replay", + &digest, + uid, + true, + ) + .unwrap_err(); + assert!(err.to_string().contains("already used"), "{err}"); +} + +#[test] +fn concurrent_privileged_executions_allow_at_most_one() { + let root = tempdir().unwrap().keep(); + let store = PlanStore::with_dir(tempdir().unwrap().keep()); + let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); + let uid = effective_uid(); + + let mut plan = sealed( + "plan-concurrent", + PlanKind::General, + vec![SystemAction::History], + "d", + &root, + uid, + ); + store.save(&mut plan).unwrap(); + let digest = plan.digest.clone(); + let id = plan.id.clone(); + + let handles: Vec<_> = (0..8) + .map(|_| { + let root = root.clone(); + let store = store.clone(); + let approvals = approvals.clone(); + let id = id.clone(); + let digest = digest.clone(); + std::thread::spawn(move || { + let exec = make_test_exec(&root); + execute_plan_privileged(&exec, &root, &store, &approvals, &id, &digest, uid, true) + .is_ok() + }) + }) + .collect(); + let successes = handles + .into_iter() + .map(|h| h.join().expect("execution thread panicked")) + .filter(|won| *won) + .count(); + assert_eq!(successes, 1, "exactly one execution may proceed"); +} + +#[test] +fn wrong_caller_root_and_expired_plans_are_rejected() { + let root = tempdir().unwrap(); + let other_root = tempdir().unwrap(); + let exec = make_test_exec(root.path()); + let store = PlanStore::with_dir(tempdir().unwrap().keep()); + let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); + let uid = effective_uid(); + + let mut plan = sealed( + "plan-guard", + PlanKind::General, + vec![SystemAction::History], + "d", + root.path(), + uid, + ); + store.save(&mut plan).unwrap(); + + let err = execute_plan_privileged( + &exec, + root.path(), + &store, + &approvals, + "plan-guard", + &plan.digest, + uid.wrapping_add(4242), + true, + ) + .unwrap_err(); + assert!( + err.to_string().contains("cannot be executed by uid"), + "{err}" + ); + + let err = execute_plan_privileged( + &exec, + other_root.path(), + &store, + &approvals, + "plan-guard", + &plan.digest, + uid, + true, + ) + .unwrap_err(); + assert!(err.to_string().contains("target root mismatch"), "{err}"); + + let mut expired = sealed( + "plan-expired", + PlanKind::General, + vec![SystemAction::History], + "d", + root.path(), + uid, + ); + expired.expires_unix = 1; + seal_plan(&mut expired); + store.save(&mut expired).unwrap(); + let err = execute_plan_privileged( + &exec, + root.path(), + &store, + &approvals, + "plan-expired", + &expired.digest, + uid, + true, + ) + .unwrap_err(); + assert!(err.to_string().contains("expired"), "{err}"); + assert_eq!(ledger_entries(&approvals), 0); +} + +#[test] +fn an_interrupted_operation_is_reconciled_and_cannot_be_retried() { + let root = tempdir().unwrap(); + let exec = make_test_exec(root.path()); + let store = PlanStore::with_dir(tempdir().unwrap().keep()); + let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); + let uid = effective_uid(); + + let mut plan = sealed( + "plan-interrupted", + PlanKind::General, + vec![SystemAction::History], + "d", + root.path(), + uid, + ); + store.save(&mut plan).unwrap(); + + // Simulate a crash after claiming but before finishing: the owning + // process is provably gone, so reconciliation recovers it. + let dead = crate::approval::ProcessIdentity { + pid: u32::MAX, + start_ticks: 1, + boot_id: String::new(), + }; + let identity = approval_identity(&plan, uid); + approvals.claim_with_owner(&identity, dead).unwrap(); + assert_eq!(approvals.reconcile_interrupted().unwrap(), 1); + assert_eq!( + approvals.get(&identity.key).unwrap().unwrap().status, + "interrupted" + ); + + let err = execute_plan_privileged( + &exec, + root.path(), + &store, + &approvals, + &plan.id, + &plan.digest, + uid, + true, + ) + .unwrap_err(); + assert!(err.to_string().contains("already used"), "{err}"); +} + +#[test] +fn stale_effects_between_validation_and_execution_abort_the_transaction() { + let root = tempdir().unwrap(); + let uid = effective_uid(); + let reviewed = parse_emerge_pretend(VIM_PRETEND); + let changed = parse_emerge_pretend(WGET_PRETEND); + let runner = SequenceRunner { + responses: std::sync::Mutex::new(vec![ + command_out(VIM_PRETEND, true), + command_out(WGET_PRETEND, true), + ]), + fallback: command_out(WGET_PRETEND, true), + }; + let exec = make_exec_with_runner(root.path(), Box::new(runner)); + let store = PlanStore::with_dir(tempdir().unwrap().keep()); + let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); + + let mut plan = portage_install_plan( + "plan-drift", + SystemAction::InstallPackage { + atom: "app-editors/vim".into(), + binary: None, + }, + reviewed, + root.path(), + uid, + ); + store.save(&mut plan).unwrap(); + let digest = plan.digest.clone(); + + let err = execute_plan_privileged( + &exec, + root.path(), + &store, + &approvals, + "plan-drift", + &digest, + uid, + true, + ) + .unwrap_err(); + assert!(err.to_string().contains("stale plan"), "{err}"); + + let log = transaction::read(root.path()).unwrap(); + assert_eq!(log.records.len(), 1); + assert!( + log.records[0].result.starts_with("stale plan"), + "{}", + log.records[0].result + ); + assert!(!changed.effects.is_empty()); +} + +#[test] +fn effect_resolution_failure_after_transaction_begin_is_terminal() { + let root = tempdir().unwrap(); + let uid = effective_uid(); + let reviewed = parse_emerge_pretend(VIM_PRETEND); + let runner = SequenceRunner { + responses: std::sync::Mutex::new(vec![ + command_out(VIM_PRETEND, true), + command_out("not valid emerge output\n", true), + ]), + fallback: command_out("not valid emerge output\n", true), + }; + let exec = make_exec_with_runner(root.path(), Box::new(runner)); + let store = PlanStore::with_dir(tempdir().unwrap().keep()); + let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); + + let mut plan = portage_install_plan( + "plan-resolve-fail", + SystemAction::InstallPackage { + atom: "app-editors/vim".into(), + binary: None, + }, + reviewed, + root.path(), + uid, + ); + store.save(&mut plan).unwrap(); + let digest = plan.digest.clone(); + + let err = execute_plan_privileged( + &exec, + root.path(), + &store, + &approvals, + "plan-resolve-fail", + &digest, + uid, + true, + ) + .unwrap_err(); + assert!( + err.to_string().contains("effect resolution failed"), + "{err}" + ); + + let log = transaction::read(root.path()).unwrap(); + assert_eq!(log.records.len(), 1); + assert!( + log.records[0].result.contains("effect resolution failed"), + "{}", + log.records[0].result + ); + let key = approval_identity(&plan, uid).key; + assert!( + approvals + .get(&key) + .unwrap() + .is_some_and(|r| r.status == "failed"), + "the approval must reach a terminal failed status" + ); +} + +struct FailFlatpakRunner; + +impl phoebus_executor::command::ProcessRunner for FailFlatpakRunner { + fn execute( + &self, + spec: &phoebus_executor::command::CommandSpec, + ) -> Result { + // The target is chrooted, so the real program is `chroot` and the + // wrapped tool appears in the arguments. + if spec.program == "flatpak" || spec.args.iter().any(|a| a == "flatpak") { + return Err(ExecError::operation("test", "flatpak", "flatpak exploded")); + } + Ok(command_out("ok\n", true)) + } +} + +#[test] +fn a_later_step_failure_after_an_earlier_success_is_recorded_truthfully() { + let root = tempdir().unwrap(); + let uid = effective_uid(); + let exec = make_exec_with_runner(root.path(), Box::new(FailFlatpakRunner)); + let store = PlanStore::with_dir(tempdir().unwrap().keep()); + let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); + + let mut plan = sealed( + "plan-two-step", + PlanKind::General, + vec![ + SystemAction::EnableService { + name: "sshd".into(), + }, + SystemAction::FlatpakInstall { + app_id: "org.example.App".into(), + }, + ], + "d", + root.path(), + uid, + ); + plan.requires_root = true; + // `sealed` already stores one normalized per-step effect per action. + seal_plan(&mut plan); + store.save(&mut plan).unwrap(); + let digest = plan.digest.clone(); + + let err = execute_plan_privileged( + &exec, + root.path(), + &store, + &approvals, + "plan-two-step", + &digest, + uid, + true, + ) + .unwrap_err(); + assert!(err.to_string().contains("action failed"), "{err}"); + + let log = transaction::read(root.path()).unwrap(); + assert_eq!(log.records.len(), 1); + assert!( + log.records[0].result.starts_with("failed"), + "{}", + log.records[0].result + ); + let (done, failed, _) = log.records[0].outcome_counts(); + assert_eq!(done, 1, "the earlier step completed"); + assert_eq!(failed, 1, "the later step failed"); +} + +// ----------------------------------------------------------------------- +// Adversarial approval-boundary tests. +// ----------------------------------------------------------------------- + +/// Build a plan whose digest is the canonical digest for its (actions, +/// candidate, effects), sealed for storage. +fn canonical_plan( + id: &str, + kind: PlanKind, + actions: Vec, + candidate: Option, + effects: ResolvedPlan, + root: &Path, + uid: u32, +) -> PreparedPlan { + let mut effects = effects; + effects.recompute_digest(); + let step_effects = vec![effects.clone(); actions.len()]; + let digest = compute_plan_digest(&actions, candidate.as_ref(), &effects, &step_effects); + let mut plan = PreparedPlan { + id: id.into(), + created_unix: now_unix(), + expires_unix: now_unix() + 900, + kind, + summary: "test plan".into(), + recommendation: "rec".into(), + application: Some("firefox".into()), + candidate, + alternatives: Vec::new(), + rationale: Vec::new(), + warnings: Vec::new(), + actions, + effects, + step_effects, + digest, + verification: "verify".into(), + requires_root: false, + source: "test".into(), + executed: false, + target_root: canonical_root(root), + initiator_uid: uid, + integrity: String::new(), + }; + seal_plan(&mut plan); + plan +} + +#[test] +fn a_general_plan_with_swapped_action_and_retained_approved_digest_is_rejected() { + let root = tempdir().unwrap(); + let uid = effective_uid(); + let reviewed = parse_emerge_pretend(VIM_PRETEND); + let substituted = parse_emerge_pretend(WGET_PRETEND); + let runner = RecordingRunner::new(); + let exec = make_exec_with_runner(root.path(), Box::new(runner.clone())); + let store = PlanStore::with_dir(tempdir().unwrap().keep()); + let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); + + let mut original = portage_install_plan( + "plan-swap", + SystemAction::InstallPackage { + atom: "app-editors/vim".into(), + binary: None, + }, + reviewed, + root.path(), + uid, + ); + store.save(&mut original).unwrap(); + let approved = original.digest.clone(); + + // The attacker swaps the action and its effects, recomputes the + // self-consistency seal, but deliberately retains the previously + // approved digest. + let mut forged = portage_install_plan( + "plan-swap", + SystemAction::InstallPackage { + atom: "net-misc/wget".into(), + binary: None, + }, + substituted, + root.path(), + uid, + ); + forged.digest = approved.clone(); + seal_plan(&mut forged); + store.save(&mut forged).unwrap(); + + let err = execute_plan_privileged( + &exec, + root.path(), + &store, + &approvals, + "plan-swap", + &approved, + uid, + true, + ) + .unwrap_err(); + assert!( + err.to_string().contains("digest does not match") + || err.to_string().contains("approval digest mismatch"), + "{err}" + ); + // Rejected before any command ran or any approval was consumed. + assert!(runner.recorded().is_empty(), "no command may run"); + assert_eq!(ledger_entries(&approvals), 0, "nothing may be claimed"); + assert!(transaction::read(root.path()).unwrap().records.is_empty()); + + // A more sophisticated forgery also recomputes the stored digest, but + // the independently preserved approved digest still differs. + let mut forged2 = portage_install_plan( + "plan-swap", + SystemAction::InstallPackage { + atom: "net-misc/wget".into(), + binary: None, + }, + parse_emerge_pretend(WGET_PRETEND), + root.path(), + uid, + ); + seal_plan(&mut forged2); + store.save(&mut forged2).unwrap(); + let err = execute_plan_privileged( + &exec, + root.path(), + &store, + &approvals, + "plan-swap", + &approved, + uid, + true, + ) + .unwrap_err(); + assert!(err.to_string().contains("digest"), "{err}"); + assert_eq!(ledger_entries(&approvals), 0); +} + +#[test] +fn canonical_digest_is_recomputed_for_every_plan_kind() { + let root = tempdir().unwrap(); + let uid = effective_uid(); + let exec = make_test_exec(root.path()); + let cand = sample_candidate(); + + // (kind, reviewed action, substituted action, candidate) + let cases: Vec<(PlanKind, SystemAction, SystemAction, Option)> = vec![ + ( + PlanKind::Install, + SystemAction::FlatpakInstall { + app_id: "org.mozilla.firefox".into(), + }, + SystemAction::FlatpakInstall { + app_id: "org.chromium.Chromium".into(), + }, + Some(cand.clone()), + ), + ( + PlanKind::LegacyInstall, + SystemAction::FlatpakInstall { + app_id: "org.mozilla.firefox".into(), + }, + SystemAction::FlatpakInstall { + app_id: "org.chromium.Chromium".into(), + }, + Some(cand.clone()), + ), + ( + PlanKind::Removal, + SystemAction::RemovePackage { + atom: "app-editors/vim".into(), + }, + SystemAction::RemovePackage { + atom: "net-misc/wget".into(), + }, + None, + ), + ( + PlanKind::General, + SystemAction::EnableService { + name: "sshd".into(), + }, + SystemAction::DisableService { + name: "sshd".into(), + }, + None, + ), + ( + PlanKind::Undo, + SystemAction::Undo { snapshot: None }, + SystemAction::Undo { + snapshot: Some("other-snapshot".into()), + }, + None, + ), + ]; + + for (idx, (kind, reviewed_action, substituted_action, candidate)) in + cases.into_iter().enumerate() + { + let id = format!("plan-kind-{idx}"); + let reviewed = canonical_plan( + &id, + kind, + vec![reviewed_action], + candidate, + ResolvedPlan::default(), + root.path(), + uid, + ); + let approved = reviewed.digest.clone(); + // Substitute the action, retain the approved digest, reseal. + let mut forged = canonical_plan( + &id, + kind, + vec![substituted_action], + reviewed.candidate.clone(), + ResolvedPlan::default(), + root.path(), + uid, + ); + forged.digest = approved.clone(); + seal_plan(&mut forged); + + let err = + validate_prepared_plan(&exec, root.path(), &forged, Some(&approved), uid).unwrap_err(); + assert!( + err.to_string().contains("digest"), + "kind {kind:?} must be rejected: {err}" + ); + } +} + +/// Execute a plan, then edit a presentation field, reseal, delete the user +/// claim and replay. The stable ledger identity must still refuse it. +fn replay_after_presentation_edit(field: &str) { + let root = tempdir().unwrap(); + let exec = make_test_exec(root.path()); + let store = PlanStore::with_dir(tempdir().unwrap().keep()); + let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); + let uid = effective_uid(); + + let mut plan = sealed( + "plan-replay-edit", + PlanKind::General, + vec![SystemAction::History], + "d", + root.path(), + uid, + ); + store.save(&mut plan).unwrap(); + let digest = plan.digest.clone(); + execute_plan_privileged( + &exec, + root.path(), + &store, + &approvals, + "plan-replay-edit", + &digest, + uid, + true, + ) + .unwrap(); + + // The user deletes their own claim and edits only a presentation field, + // then reseals. + let _ = std::fs::remove_file(store.dir().join("plan-replay-edit.claim")); + let mut tampered = store.load("plan-replay-edit").unwrap(); + match field { + "summary" => tampered.summary = "a completely different summary".into(), + "recommendation" => tampered.recommendation = "edited".into(), + "rationale" => tampered.rationale = vec!["edited rationale".into()], + "verification" => tampered.verification = "edited verification".into(), + other => panic!("unknown field {other}"), + } + seal_plan(&mut tampered); + store.save(&mut tampered).unwrap(); + + let err = execute_plan_privileged( + &exec, + root.path(), + &store, + &approvals, + "plan-replay-edit", + &digest, + uid, + true, + ) + .unwrap_err(); + assert!(err.to_string().contains("already used"), "{err}"); +} + +#[test] +fn replay_after_editing_only_the_summary_is_rejected() { + replay_after_presentation_edit("summary"); +} + +#[test] +fn replay_after_editing_other_presentation_fields_is_rejected() { + replay_after_presentation_edit("recommendation"); + replay_after_presentation_edit("rationale"); + replay_after_presentation_edit("verification"); +} + +#[test] +fn recreating_an_identical_plan_under_the_same_id_is_rejected() { + let root = tempdir().unwrap(); + let exec = make_test_exec(root.path()); + let store = PlanStore::with_dir(tempdir().unwrap().keep()); + let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); + let uid = effective_uid(); + + let mut plan = sealed( + "plan-identical", + PlanKind::General, + vec![SystemAction::History], + "d", + root.path(), + uid, + ); + let path = store.save(&mut plan).unwrap(); + let digest = plan.digest.clone(); + let bytes = std::fs::read(&path).unwrap(); + execute_plan_privileged( + &exec, + root.path(), + &store, + &approvals, + "plan-identical", + &digest, + uid, + true, + ) + .unwrap(); + + // Recreate byte-identical plan state under the original id. + std::fs::remove_file(&path).unwrap(); + let _ = std::fs::remove_file(store.dir().join("plan-identical.claim")); + std::fs::write(&path, &bytes).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + + let err = execute_plan_privileged( + &exec, + root.path(), + &store, + &approvals, + "plan-identical", + &digest, + uid, + true, + ) + .unwrap_err(); + assert!(err.to_string().contains("already used"), "{err}"); +} + +#[test] +fn a_newly_reviewed_identical_operation_with_a_new_id_is_allowed() { + let root = tempdir().unwrap(); + let exec = make_test_exec(root.path()); + let store = PlanStore::with_dir(tempdir().unwrap().keep()); + let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); + let uid = effective_uid(); + + // Two independently reviewed plans with identical content but distinct + // random identifiers: the first may not block the second. + for id in ["plan-fresh-a", "plan-fresh-b"] { + let mut plan = sealed( + id, + PlanKind::General, + vec![SystemAction::History], + "d", + root.path(), + uid, + ); + let digest = plan.digest.clone(); + store.save(&mut plan).unwrap(); + execute_plan_privileged( + &exec, + root.path(), + &store, + &approvals, + id, + &digest, + uid, + true, + ) + .unwrap_or_else(|e| panic!("{id} should be allowed: {e}")); + } +} + +#[test] +fn a_live_claim_is_not_reconciled_but_an_abandoned_one_is() { + let root = tempdir().unwrap(); + let uid = effective_uid(); + let store = PlanStore::with_dir(tempdir().unwrap().keep()); + let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); + + let mut live = sealed( + "plan-live", + PlanKind::General, + vec![SystemAction::History], + "d", + root.path(), + uid, + ); + store.save(&mut live).unwrap(); + let live_identity = approval_identity(&live, uid); + // Claimed with the real, currently running process. + approvals.claim(&live_identity).unwrap(); + + // A second broker starting must not mark the live operation interrupted. + assert_eq!(approvals.reconcile_interrupted().unwrap(), 0); + assert_eq!( + approvals.get(&live_identity.key).unwrap().unwrap().status, + "in_progress" + ); + + // An abandoned claim (owner gone) is recovered. + let mut dead = sealed( + "plan-dead", + PlanKind::General, + vec![SystemAction::History], + "d", + root.path(), + uid, + ); + store.save(&mut dead).unwrap(); + let dead_identity = approval_identity(&dead, uid); + approvals + .claim_with_owner( + &dead_identity, + crate::approval::ProcessIdentity { + pid: u32::MAX, + start_ticks: 1, + boot_id: String::new(), + }, + ) + .unwrap(); + assert_eq!(approvals.reconcile_interrupted().unwrap(), 1); + assert_eq!( + approvals.get(&dead_identity.key).unwrap().unwrap().status, + "interrupted" + ); +} + +// ----------------------------------------------------------------------- +// Per-step effect binding (step_effects must be bound by the approval). +// ----------------------------------------------------------------------- + +/// A General plan with one reviewed Portage effect per action, bound by the +/// canonical digest exactly as `plan_general` builds it. +fn general_portage_plan( + id: &str, + actions: Vec, + steps: Vec, + root: &Path, + uid: u32, +) -> PreparedPlan { + assert_eq!(actions.len(), steps.len()); + let steps: Vec = steps + .into_iter() + .map(|mut step| { + step.recompute_digest(); + step + }) + .collect(); + let mut combined = ResolvedPlan { + established: true, + ..Default::default() + }; + for step in &steps { + combined.effects.extend(step.effects.clone()); + combined.cleanup.extend(step.cleanup.clone()); + combined.updates.extend(step.updates.clone()); + combined.consequences.extend(step.consequences.clone()); + } + combined.recompute_digest(); + let digest = compute_plan_digest(&actions, None, &combined, &steps); + let mut plan = PreparedPlan { + id: id.into(), + created_unix: now_unix(), + expires_unix: now_unix() + 900, + kind: PlanKind::General, + summary: "reviewed portage plan".into(), + recommendation: "rec".into(), + application: None, + candidate: None, + alternatives: Vec::new(), + rationale: Vec::new(), + warnings: Vec::new(), + actions, + effects: combined, + step_effects: steps, + digest, + verification: "verify".into(), + requires_root: true, + source: "test".into(), + executed: false, + target_root: canonical_root(root), + initiator_uid: uid, + integrity: String::new(), + }; + seal_plan(&mut plan); + plan +} + +fn vim_action() -> SystemAction { + SystemAction::InstallPackage { + atom: "app-editors/vim".into(), + binary: None, + } +} + +fn wget_action() -> SystemAction { + SystemAction::InstallPackage { + atom: "net-misc/wget".into(), + binary: None, + } +} + +/// Assert no command ran, no approval was consumed and no transaction was +/// recorded — i.e. the plan was refused before any mutation. +fn assert_no_mutation(runner: &RecordingRunner, approvals: &ApprovalLedger, root: &Path) { + assert!(runner.recorded().is_empty(), "no command may run"); + assert_eq!(ledger_entries(approvals), 0, "no approval may be consumed"); + assert!( + transaction::read(root).unwrap().records.is_empty(), + "no transaction may be recorded" + ); +} + +#[test] +fn single_action_step_effect_tampering_is_rejected_before_mutation() { + let root = tempdir().unwrap(); + let uid = effective_uid(); + let runner = RecordingRunner::new(); + let exec = make_exec_with_runner(root.path(), Box::new(runner.clone())); + let store = PlanStore::with_dir(tempdir().unwrap().keep()); + let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); + + let mut reviewed = portage_install_plan( + "plan-step-single", + vim_action(), + parse_emerge_pretend(VIM_PRETEND), + root.path(), + uid, + ); + store.save(&mut reviewed).unwrap(); + let approved = reviewed.digest.clone(); + + // Variant A: change only `step_effects`; retain the original aggregate + // effects and the independently approved digest. + let mut forged = reviewed.clone(); + forged.step_effects = vec![parse_emerge_pretend(WGET_PRETEND)]; + seal_plan(&mut forged); + store.save(&mut forged).unwrap(); + + let err = execute_plan_privileged( + &exec, + root.path(), + &store, + &approvals, + "plan-step-single", + &approved, + uid, + true, + ) + .unwrap_err(); + assert!( + err.to_string().contains("aggregate") || err.to_string().contains("digest"), + "{err}" + ); + assert_no_mutation(&runner, &approvals, root.path()); + + // Variant B: also make the aggregate match the new step, but retain the + // approved digest. The canonical digest must still reject it. + let changed = parse_emerge_pretend(WGET_PRETEND); + let mut forged_b = reviewed.clone(); + forged_b.effects = changed.clone(); + forged_b.step_effects = vec![changed]; + seal_plan(&mut forged_b); + store.save(&mut forged_b).unwrap(); + + let err = execute_plan_privileged( + &exec, + root.path(), + &store, + &approvals, + "plan-step-single", + &approved, + uid, + true, + ) + .unwrap_err(); + assert!(err.to_string().contains("digest"), "{err}"); + assert_no_mutation(&runner, &approvals, root.path()); +} + +#[test] +fn multi_action_step_effect_tampering_is_rejected_before_mutation() { + let root = tempdir().unwrap(); + let uid = effective_uid(); + let runner = RecordingRunner::new(); + let exec = make_exec_with_runner(root.path(), Box::new(runner.clone())); + let store = PlanStore::with_dir(tempdir().unwrap().keep()); + let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); + + let mut reviewed = general_portage_plan( + "plan-step-multi", + vec![vim_action(), wget_action()], + vec![ + parse_emerge_pretend(VIM_PRETEND), + parse_emerge_pretend(WGET_PRETEND), + ], + root.path(), + uid, + ); + store.save(&mut reviewed).unwrap(); + let approved = reviewed.digest.clone(); + + // Variant A: swap one step's effects, retain the aggregate and digest. + let mut forged = reviewed.clone(); + forged.step_effects[0] = parse_emerge_pretend(WGET_PRETEND); + seal_plan(&mut forged); + store.save(&mut forged).unwrap(); + + let err = execute_plan_privileged( + &exec, + root.path(), + &store, + &approvals, + "plan-step-multi", + &approved, + uid, + true, + ) + .unwrap_err(); + assert!( + err.to_string().contains("aggregate") || err.to_string().contains("digest"), + "{err}" + ); + assert_no_mutation(&runner, &approvals, root.path()); + + // Variant B: make the aggregate consistent with the new steps, but keep + // the approved digest; the canonical digest must still reject it. + let new_steps = vec![ + parse_emerge_pretend(WGET_PRETEND), + parse_emerge_pretend(WGET_PRETEND), + ]; + let mut combined = ResolvedPlan { + established: true, + ..Default::default() + }; + for step in &new_steps { + combined.effects.extend(step.effects.clone()); + } + combined.recompute_digest(); + let mut forged_b = reviewed.clone(); + forged_b.effects = combined; + forged_b.step_effects = new_steps; + seal_plan(&mut forged_b); + store.save(&mut forged_b).unwrap(); + + let err = execute_plan_privileged( + &exec, + root.path(), + &store, + &approvals, + "plan-step-multi", + &approved, + uid, + true, + ) + .unwrap_err(); + assert!(err.to_string().contains("digest"), "{err}"); + assert_no_mutation(&runner, &approvals, root.path()); +} + +#[test] +fn a_legitimate_bound_multi_step_plan_still_validates() { + let root = tempdir().unwrap(); + let uid = effective_uid(); + // Live re-resolution returns the same reviewed effects for each step. + let runner = SequenceRunner { + responses: std::sync::Mutex::new(vec![ + command_out(VIM_PRETEND, true), + command_out(WGET_PRETEND, true), + ]), + fallback: command_out(WGET_PRETEND, true), + }; + let exec = make_exec_with_runner(root.path(), Box::new(runner)); + let store = PlanStore::with_dir(tempdir().unwrap().keep()); + + let mut plan = general_portage_plan( + "plan-legit-multi", + vec![vim_action(), wget_action()], + vec![ + parse_emerge_pretend(VIM_PRETEND), + parse_emerge_pretend(WGET_PRETEND), + ], + root.path(), + uid, + ); + store.save(&mut plan).unwrap(); + + validate_prepared_plan(&exec, root.path(), &plan, Some(&plan.digest), uid) + .expect("a legitimate bound multi-step plan must validate"); +} + +// ------------------------------------------------------------------ +// General assistant routing: read-only investigation + source constraint +// ------------------------------------------------------------------ + +fn general_ai<'a>(transport: &'a dyn phoebus_ai::provider::ModelTransport) -> AiInstall<'a> { + AiInstall { + provider: phoebus_ai::provider::ProviderKind::Local, + endpoint: "http://127.0.0.1:11434/v1/chat/completions".into(), + model: "m".into(), + transport, + limits: phoebus_ai::install::Limits::default(), + } +} + +#[test] +fn plan_general_investigates_with_read_only_tools_then_answers() { + use phoebus_ai::provider::{chat_response, ScriptedTransport}; + let transport = ScriptedTransport::new(vec![ + chat_response( + r#"{"version":1,"kind":"investigate","requests":[{"action":"search_packages","query":"chrome"}]}"#, + ), + chat_response(r#"{"version":1,"summary":"Two real candidates found.","actions":[]}"#), + ]); + let exec = make_test_exec(Path::new("/")); + let store = PlanStore::with_dir(tempdir().unwrap().keep()); + let plan = plan_general( + &store, + &exec, + Path::new("/"), + "search chrome", + &SystemFacts::default(), + &general_ai(&transport), + None, + ) + .unwrap(); + assert!(plan.actions.is_empty(), "an answer has no actions"); + assert_eq!(plan.summary, "Two real candidates found."); + assert!(!plan.requires_root, "a read-only answer needs no elevation"); + // Two model turns: investigate, then answer. + assert_eq!(transport.requests().len(), 2); + assert!(transport.requests()[1].contains("Package catalogue")); +} + +#[test] +fn plan_general_refuses_a_foreign_lane_under_a_constraint() { + use phoebus_ai::provider::{chat_response, ScriptedTransport}; + let transport = ScriptedTransport::new(vec![chat_response( + r#"{"version":1,"summary":"list flatpaks","actions":[{"action":"flatpak_list"}],"rationale":[{"action":"flatpak_list","reason":"asked"}]}"#, + )]); + let exec = make_test_exec(Path::new("/")); + let store = PlanStore::with_dir(tempdir().unwrap().keep()); + let err = plan_general( + &store, + &exec, + Path::new("/"), + "list flatpaks", + &SystemFacts::default(), + &general_ai(&transport), + Some(Backend::PortageSource), + ) + .unwrap_err(); + assert!(err.to_string().contains("constrained"), "{err}"); +} + +#[test] +fn plan_general_rewrites_a_laneless_query_to_the_constraint() { + use phoebus_ai::provider::{chat_response, ScriptedTransport}; + let transport = ScriptedTransport::new(vec![chat_response( + r#"{"version":1,"summary":"search","actions":[{"action":"search_packages","query":"chrome"}],"rationale":[{"action":"search_packages","reason":"asked"}]}"#, + )]); + let exec = make_test_exec(Path::new("/")); + let store = PlanStore::with_dir(tempdir().unwrap().keep()); + let plan = plan_general( + &store, + &exec, + Path::new("/"), + "search chrome", + &SystemFacts::default(), + &general_ai(&transport), + Some(Backend::Flatpak), + ) + .unwrap(); + assert_eq!( + plan.actions, + vec![SystemAction::SearchPackages { + query: "chrome".into(), + backend: Some(Backend::Flatpak), + }] + ); +} + +#[test] +fn effect_binding_aggregates_cleanup_intents_for_a_clean_cache_step() { + let root = tempdir().unwrap(); + let mut step = ResolvedPlan { + established: true, + ..Default::default() + }; + step.cleanup.push(phoebus_core::effects::CleanupEffect { + cleaner: "eclean-dist".into(), + items: vec!["app-misc/one".into()], + unavailable: false, + }); + let plan = general_portage_plan( + "plan-cleanup", + vec![SystemAction::CleanCache { backend: None }], + vec![step], + root.path(), + effective_uid(), + ); + let steps = reviewed_steps(&plan).unwrap(); + validate_effect_bindings(&plan, &steps) + .expect("cleanup intents must aggregate into the bound plan"); +} + +#[test] +fn effect_binding_aggregates_update_transactions() { + let root = tempdir().unwrap(); + let mut step = ResolvedPlan { + established: true, + ..Default::default() + }; + step.updates.push(phoebus_core::effects::UpdateTransaction { + source: phoebus_core::effects::UpdateSource::Flatpak, + identity: "app/org.mozilla.firefox/x86_64/stable".into(), + previous_version: Some("128".into()), + next_version: "129".into(), + previous_revision: Some("OLD".into()), + next_revision: Some("NEW".into()), + scope: Some("system".into()), + related: Vec::new(), + exact: true, + }); + let plan = general_portage_plan( + "plan-updates", + vec![SystemAction::ApplyUpdates { + backend: Some(Backend::Flatpak), + }], + vec![step], + root.path(), + effective_uid(), + ); + let steps = reviewed_steps(&plan).unwrap(); + validate_effect_bindings(&plan, &steps) + .expect("update transactions must aggregate into the bound plan"); +} + +#[test] +fn constrain_action_rewrites_optional_backend_discovery_before_querying() { + let discover = constrain_action( + SystemAction::DiscoverCandidates { + query: "chrome".into(), + kind: None, + backend: None, + gui: false, + requires_sandbox: false, + }, + Backend::Flatpak, + ) + .unwrap(); + assert_eq!(discover.backend(), Some(Backend::Flatpak)); + + let choose = constrain_action( + SystemAction::ChoosePackage { + name: "chrome".into(), + kind: None, + backend: None, + gui: false, + requires_sandbox: false, + }, + Backend::Flatpak, + ) + .unwrap(); + assert_eq!(choose.backend(), Some(Backend::Flatpak)); +} + +#[test] +fn constrain_action_refuses_portage_only_actions_under_another_lane() { + for action in [ + SystemAction::RemovePackage { + atom: "www-client/firefox".into(), + }, + SystemAction::UpdateSystem, + SystemAction::Depclean, + SystemAction::PackageOwners { + path: "/usr/bin/vim".into(), + }, + SystemAction::PackageDependencies { + package: "vim".into(), + reverse: false, + }, + SystemAction::InstallPackage { + atom: "vim".into(), + binary: None, + }, + SystemAction::InspectPackage { atom: "vim".into() }, + ] { + let err = constrain_action(action.clone(), Backend::Flatpak).unwrap_err(); + assert!( + err.contains("constrained") || err.contains("targets the"), + "{action:?} -> {err}" + ); + } +} + +#[test] +fn constrain_action_refuses_cross_lane_installation_inspection() { + let err = constrain_action( + SystemAction::InspectInstallation { + application: "firefox".into(), + }, + Backend::Flatpak, + ) + .unwrap_err(); + assert!(err.contains("spans every package lane"), "{err}"); +} + +#[test] +fn constrain_action_allows_spanning_non_package_actions() { + for action in [ + SystemAction::History, + SystemAction::RollbackStatus, + SystemAction::EnableService { + name: "sshd".into(), + }, + ] { + assert!(constrain_action(action, Backend::Flatpak).is_ok()); + } + // A Portage-only action is allowed when the constraint is Portage. + assert!(constrain_action(SystemAction::UpdateSystem, Backend::PortageSource).is_ok()); +} diff --git a/installer-rs/crates/phoebus-installer/src/service/validation.rs b/installer-rs/crates/phoebus-installer/src/service/validation.rs new file mode 100644 index 0000000..d0fd379 --- /dev/null +++ b/installer-rs/crates/phoebus-installer/src/service/validation.rs @@ -0,0 +1,451 @@ +//! Integrity seals, approval digests, and plan validation: the authoritative +//! privileged validation boundary shared by every execution path. + +use std::path::Path; + +use phoebus_core::action::SystemAction; +use phoebus_core::effects::ResolvedPlan; +use phoebus_core::selection::Candidate; +use phoebus_executor::actions; +use phoebus_executor::auth::Confirmation; +use phoebus_executor::chooser; +use phoebus_executor::error::{ExecError, Result}; +use phoebus_executor::exec::Exec; +use phoebus_executor::install::{self, InstallRequest, InstallSource}; +use sha2::{Digest, Sha256}; + +use super::{canonical_root, is_safe_plan_id, now_unix, PlanKind, PreparedPlan}; + +/// Recompute the self-consistency seal over every reviewed field. The stored +/// `integrity` value is deliberately excluded. A reload whose recomputation +/// differs was modified after it was approved. +pub(super) fn plan_integrity(plan: &PreparedPlan) -> String { + let mut hasher = Sha256::new(); + hasher.update(plan.id.as_bytes()); + hasher.update(b"\0"); + hasher.update(format!("{:?}", plan.kind).as_bytes()); + hasher.update(b"\0"); + hasher.update(plan.created_unix.to_le_bytes()); + hasher.update(plan.expires_unix.to_le_bytes()); + hasher.update(plan.digest.as_bytes()); + hasher.update(b"\0"); + hasher.update(plan.effects.digest.as_bytes()); + hasher.update(b"\0"); + if let Some(c) = &plan.candidate { + hasher.update(c.backend.as_str().as_bytes()); + hasher.update(b"\0"); + hasher.update(c.id.as_bytes()); + hasher.update(b"\0"); + hasher.update(c.version.as_deref().unwrap_or("").as_bytes()); + hasher.update(b"\0"); + } + for act in &plan.actions { + hasher.update(serde_json::to_string(act).unwrap_or_default().as_bytes()); + hasher.update(b"\0"); + } + for step in &plan.step_effects { + hasher.update(step.digest.as_bytes()); + hasher.update(b"\0"); + } + hasher.update(plan.target_root.as_bytes()); + hasher.update(b"\0"); + hasher.update(plan.source.as_bytes()); + hasher.update(b"\0"); + hasher.update(plan.initiator_uid.to_le_bytes()); + hasher.update(b"\0"); + hasher.update([plan.requires_root as u8]); + hasher.update([plan.executed as u8]); + // Everything the human reviewed is sealed, so a modified summary or + // verification statement cannot pass as the approved plan. + for field in [ + &plan.summary, + &plan.recommendation, + plan.application.as_deref().unwrap_or(""), + &plan.verification, + ] { + hasher.update(field.as_bytes()); + hasher.update(b"\0"); + } + for line in plan.rationale.iter().chain(plan.warnings.iter()) { + hasher.update(line.as_bytes()); + hasher.update(b"\0"); + } + for alt in &plan.alternatives { + hasher.update(serde_json::to_string(alt).unwrap_or_default().as_bytes()); + hasher.update(b"\0"); + } + format!("{:x}", hasher.finalize()) +} + +/// Compute and store the plan seal. Must be called before persistence. +pub fn seal_plan(plan: &mut PreparedPlan) { + plan.integrity = plan_integrity(plan); +} + +/// The canonical digest of a single step's material effects. +/// +/// The digest is *recomputed* from the effect list rather than read from the +/// stored `digest` field, so a plan owner cannot change a step's contents while +/// leaving its stored digest (and therefore the approval) intact. +fn step_effects_digest(step: &ResolvedPlan) -> String { + let mut normalized = step.clone(); + normalized.recompute_digest(); + normalized.digest +} + +/// The per-step reviewed effects that execution will actually trust. +/// +/// New plans always store one step per action. A single-action plan may fall +/// back to its aggregate effects for backward compatibility; a multi-action +/// plan without per-step effects cannot be bound and is refused. +pub(super) fn reviewed_steps(plan: &PreparedPlan) -> Result> { + if plan.step_effects.len() == plan.actions.len() && !plan.step_effects.is_empty() { + Ok(plan.step_effects.clone()) + } else if plan.actions.len() == 1 { + Ok(vec![plan.effects.clone()]) + } else { + Err(ExecError::operation( + "service", + "validate plan", + "plan is missing per-step effects; refusing to execute a multi-action plan whose \ + reviewed effects are not individually bound", + )) + } +} + +/// Verify that every stored per-step effect digest matches its actual contents +/// and that the aggregate effects are exactly the concatenation of the steps. +pub(super) fn validate_effect_bindings(plan: &PreparedPlan, steps: &[ResolvedPlan]) -> Result<()> { + for (idx, step) in steps.iter().enumerate() { + if step.digest != step_effects_digest(step) { + return Err(ExecError::operation( + "service", + "validate plan", + format!( + "the stored effect digest for step {idx} does not match its contents; the \ + plan was modified after it was reviewed" + ), + )); + } + } + let mut combined = ResolvedPlan { + established: true, + ..Default::default() + }; + for step in steps { + combined.effects.extend(step.effects.clone()); + combined.cleanup.extend(step.cleanup.clone()); + combined.updates.extend(step.updates.clone()); + combined.consequences.extend(step.consequences.clone()); + } + combined.recompute_digest(); + let mut aggregate = plan.effects.clone(); + aggregate.recompute_digest(); + if combined.digest != aggregate.digest { + return Err(ExecError::operation( + "service", + "validate plan", + "the aggregate effects are not consistent with the reviewed per-step effects; the \ + plan was modified after it was reviewed", + )); + } + Ok(()) +} + +/// Compute a cryptographic digest binding the exact actions, candidate, the +/// reviewed aggregate effects and every per-step effect that execution trusts. +pub fn compute_plan_digest( + actions: &[SystemAction], + candidate: Option<&Candidate>, + effects: &ResolvedPlan, + step_effects: &[ResolvedPlan], +) -> String { + // A single installed candidate binds through the install-specific digest. + // `validate_effect_bindings` separately requires that its one step equals + // the aggregate, so the step effects are bound transitively. + if let (Some(cand), Some(act)) = (candidate, actions.first()) { + if actions.len() == 1 { + return install::approval_digest_for(cand, act, effects); + } + } + + let mut hasher = Sha256::new(); + if let Some(c) = candidate { + hasher.update(c.backend.as_str().as_bytes()); + hasher.update(b"\0"); + hasher.update(c.id.as_bytes()); + hasher.update(b"\0"); + hasher.update(c.version.as_deref().unwrap_or("").as_bytes()); + hasher.update(b"\0"); + } + for act in actions { + hasher.update(serde_json::to_string(act).unwrap_or_default().as_bytes()); + hasher.update(b"\0"); + } + // Bind every material per-step effect execution will trust, recomputed from + // its contents so a retained approval cannot hide a changed schedule. + for step in step_effects { + hasher.update(step_effects_digest(step).as_bytes()); + hasher.update(b"\0"); + } + hasher.update(b"aggregate\0"); + if effects.established { + hasher.update(effects.digest.as_bytes()); + } else { + hasher.update(b"no-established-effects"); + } + format!("{:x}", hasher.finalize()) +} +// ----------------------------------------------------------------------------- +// Privileged validation boundary +// ----------------------------------------------------------------------------- + +pub(super) struct ServiceConfirm { + pub(super) assume_yes: bool, +} + +impl Confirmation for ServiceConfirm { + fn confirm_erase(&self, _preview: &str) -> Result { + Ok(self.assume_yes) + } + fn confirm_final(&self, _message: &str) -> Result { + Ok(self.assume_yes) + } +} + +/// The single authoritative validation boundary. Runs immediately before any +/// privileged mutation, in both the unprivileged pre-check and the broker after +/// authentication. It binds the approval to the exact actions, effects, +/// candidate, target root and initiating user, re-derives the plan seal, and +/// revalidates live state. Plan files are untrusted input. +pub fn validate_prepared_plan( + exec: &Exec, + root: &Path, + plan: &PreparedPlan, + expected_digest: Option<&str>, + initiator_uid: u32, +) -> Result<()> { + if plan.integrity.is_empty() || plan.integrity != plan_integrity(plan) { + return Err(ExecError::operation( + "service", + "validate plan", + "plan integrity check failed; the plan was modified after it was reviewed", + )); + } + if !is_safe_plan_id(&plan.id) { + return Err(ExecError::operation( + "service", + "validate plan", + "plan has an invalid identifier", + )); + } + if plan.executed { + return Err(ExecError::operation( + "service", + "validate plan", + "plan has already been executed; replayed plans are rejected", + )); + } + if now_unix() > plan.expires_unix { + return Err(ExecError::operation( + "service", + "validate plan", + "plan has expired; review and approve a fresh plan", + )); + } + if plan.actions.is_empty() { + return Err(ExecError::operation( + "service", + "validate plan", + "plan proposes no actions", + )); + } + // Independently recompute the canonical approval digest from the exact + // executable actions, candidate and reviewed material effects. The + // `integrity` seal stored beside the plan is a self-consistency check the + // owning user can recompute, so it is not authentication: the canonical + // digest is. It must match the digest stored in the plan *and* the + // independently supplied approval digest. This binds every plan kind + // (Install, LegacyInstall, Removal, General, Undo) to the reviewed actions, + // so retaining an old digest while swapping an action and resealing is + // rejected before any mutation. + // + // Execution trusts the per-step effects (`step_effects`), so those must be + // bound too: each stored effect digest must match its actual contents, the + // aggregate must be the concatenation of the steps, and the canonical + // digest must cover every step. This closes the "retain the approved digest, + // change only `step_effects`, reseal" gap for General and Undo plans. + let steps = reviewed_steps(plan)?; + validate_effect_bindings(plan, &steps)?; + let canonical = compute_plan_digest( + &plan.actions, + plan.candidate.as_ref(), + &plan.effects, + &steps, + ); + if plan.digest != canonical { + return Err(ExecError::operation( + "service", + "validate plan", + "plan digest does not match its reviewed actions and effects; the plan was \ + substituted or resealed and is refused", + )); + } + if let Some(digest) = expected_digest { + if !digest.is_empty() && canonical != digest { + return Err(ExecError::operation( + "service", + "validate plan", + "approval digest mismatch; the plan was altered or is not the one reviewed", + )); + } + } + if plan.target_root.is_empty() { + return Err(ExecError::operation( + "service", + "validate plan", + "plan does not record a target root; refusing to guess `/`", + )); + } + let want_root = canonical_root(root); + if plan.target_root != want_root { + return Err(ExecError::operation( + "service", + "validate plan", + format!( + "target root mismatch: the plan was reviewed for {} but execution targets {}", + plan.target_root, want_root + ), + )); + } + if plan.initiator_uid != initiator_uid { + return Err(ExecError::operation( + "service", + "validate plan", + format!( + "plan belongs to uid {} and cannot be executed by uid {initiator_uid}", + plan.initiator_uid + ), + )); + } + revalidate_plan_state(exec, root, plan) +} + +/// Revalidate a plan's material state against live metadata. A material change +/// invalidates the earlier approval. +fn revalidate_plan_state(exec: &Exec, root: &Path, plan: &PreparedPlan) -> Result<()> { + match plan.kind { + PlanKind::Install | PlanKind::LegacyInstall => { + let (Some(cand), Some(act)) = (&plan.candidate, plan.actions.first()) else { + return Err(ExecError::operation( + "service", + "revalidate", + "installation plan is missing its candidate or action", + )); + }; + let resolved = install::ResolvedInstall { + request: InstallRequest::new(plan.application.as_deref().unwrap_or("")), + candidate: cand.clone(), + action: act.clone(), + effects: plan.effects.clone(), + rationale: plan.rationale.clone(), + alternatives: plan.alternatives.clone(), + source: match plan.kind { + PlanKind::LegacyInstall => InstallSource::ExplicitBackend, + _ => InstallSource::AiRecommendation, + }, + warnings: plan.warnings.clone(), + verification: plan.verification.clone(), + }; + let current_digest = install::revalidate(exec, root, &resolved).map_err(|e| { + ExecError::operation( + "service", + "revalidate", + format!("the reviewed plan changed before execution ({e}); review again"), + ) + })?; + if current_digest != plan.digest { + return Err(ExecError::operation( + "service", + "revalidate", + "system state or package metadata changed materially since review; review again", + )); + } + } + PlanKind::Removal => { + let Some(app) = &plan.application else { + return Err(ExecError::operation( + "service", + "revalidate", + "removal plan has no application", + )); + }; + let check = chooser::installed_copies(exec, root, app); + if !check.copies.iter().any(|c| c.backend == plan.source) { + return Err(ExecError::operation( + "service", + "revalidate", + format!( + "`{app}` is no longer installed via {}; the removal plan is stale", + plan.source + ), + )); + } + if let Some(act) = plan.actions.first() { + let eff = actions::resolve_effects(exec, act, root)?; + if eff.established && plan.effects.established && eff.digest != plan.effects.digest + { + return Err(ExecError::operation( + "service", + "revalidate", + "the removal effects changed since review; review again", + )); + } + } + } + PlanKind::General | PlanKind::Undo => { + if plan.step_effects.len() == plan.actions.len() && !plan.step_effects.is_empty() { + // Compare each step against its own reviewed effects, never one + // action against the whole plan. + for (act, reviewed) in plan.actions.iter().zip(plan.step_effects.iter()) { + let eff = actions::resolve_effects(exec, act, root)?; + if reviewed.established && eff.established && reviewed.digest != eff.digest { + return Err(ExecError::operation( + "service", + "revalidate", + format!( + "effects for `{}` changed materially since review; review again", + act.describe() + ), + )); + } + } + } else { + // Older plans carried only the aggregate; recompute the same + // aggregate and compare, rather than mixing per-action digests. + let mut combined = ResolvedPlan { + established: true, + ..Default::default() + }; + for act in &plan.actions { + let eff = actions::resolve_effects(exec, act, root)?; + if eff.established { + combined.effects.extend(eff.effects); + combined.cleanup.extend(eff.cleanup); + combined.updates.extend(eff.updates); + combined.consequences.extend(eff.consequences); + } + } + combined.recompute_digest(); + if plan.effects.established && combined.digest != plan.effects.digest { + return Err(ExecError::operation( + "service", + "revalidate", + "system state or package effects changed materially since review; review again", + )); + } + } + } + } + Ok(()) +}