phoebus_os/installer-rs/crates/phoebus-installer/src/service/validation.rs
Phoebus 1bf31c5a72 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).
2026-09-25 18:34:36 -07:00

451 lines
18 KiB
Rust

//! 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<Vec<ResolvedPlan>> {
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<bool> {
Ok(self.assume_yes)
}
fn confirm_final(&self, _message: &str) -> Result<bool> {
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(())
}