From fa39f773f085ed016cf095716a710560446685ef Mon Sep 17 00:00:00 2001 From: Phoebus Date: Thu, 24 Sep 2026 20:43:33 -0700 Subject: [PATCH] fix(admin): bind per-step reviewed effects into the canonical approval digest --- docs/CHANGELOG.md | 29 ++ docs/HANDOFF.md | 39 +- docs/STATUS.md | 1 + docs/adr/0014-privileged-approval-ledger.md | 25 +- .../phoebus-installer/src/assistant_bridge.rs | 10 +- .../crates/phoebus-installer/src/service.rs | 436 ++++++++++++++++-- installer/tests/vm/serial-driver.py | 10 +- 7 files changed, 488 insertions(+), 62 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 3e90391..10c873f 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -3,6 +3,35 @@ All notable changes are recorded here. The authoritative history is `git log`; this file is the curated, human-readable summary. +## 2026-09-25 — Bind per-step reviewed effects into the approval digest + +- **Per-step effect binding (`phoebus-installer::service`):** the canonical + approval digest now covers every per-step reviewed effect that execution + trusts, not just the actions and aggregate effects. At the privileged + boundary `validate_prepared_plan`: + - derives the effective per-step effects (`step_effects`, or the aggregate for + a single-action plan; a multi-action plan without per-step effects is + refused); + - verifies each stored effect digest by *recomputing* it from the effect + contents, so a step whose contents changed but whose stored digest did not + is rejected; + - verifies the aggregate effects are exactly the concatenation of the + per-step effects; + - feeds every per-step effect into `compute_plan_digest`, so the canonical + digest (compared with both `plan.digest` and the independently supplied + `--approval-digest`) changes whenever a step changes. + This closes the gap where a user-controlled General/Undo plan could retain its + approved digest, change only `step_effects` to match a different live + resolution, reseal the plan, and execute. Install/LegacyInstall keep their + install-specific digest, with the single step required to equal the aggregate; + Removal, General and Undo are bound per-step. Plan builders normalize stored + step digests so legitimate plans continue to validate, and the legitimate + allowance for changes caused by earlier approved steps is unchanged. +- **Adversarial tests:** single-action and multi-action General plans whose + `step_effects` are swapped (with and without a matching aggregate) while the + approved digest is retained are rejected before any command, ledger claim or + transaction; a legitimate bound multi-step plan still validates. + ## 2026-09-25 — Adversarial approval-boundary hardening (canonical digest, stable identity, recovery) - **Canonical approval digest recomputed at the privileged boundary.** The diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 0c06d8c..f05b9af 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -13,13 +13,20 @@ commit it. It should be short and current; use `git log` for detail. - **Current focus:** 1. **Canonical digest at the privileged boundary (`service::validate_prepared_plan`):** - Independently re-derives `compute_plan_digest(actions, candidate, - effects)` and requires it to equal both `plan.digest` and the supplied - `--approval-digest`. Covers Install, LegacyInstall, Removal, General and - Undo. The stored `integrity` seal is only a self-consistency check and is - never treated as authentication. - - Closes the "retain the approved digest, swap an action and effects, - recompute the seal" attack; rejected before any command runs or approval - is consumed. + effects, step_effects)` and requires it to equal both `plan.digest` and + the supplied `--approval-digest`. Covers Install, LegacyInstall, Removal, + General and Undo. The stored `integrity` seal is only a self-consistency + check and is never treated as authentication. + - **Per-step effect binding:** execution trusts `step_effects`, so the + canonical digest now hashes every step (contents recomputed, not read + from the stored digest); each stored step digest must match its contents, + and the aggregate must be the concatenation of the steps. A multi-action + plan without per-step effects is refused. Install/LegacyInstall keep the + install-specific digest with the single step required to equal the + aggregate. This closes the "retain the approved digest, change only + `step_effects`, recompute the seal" gap; rejected before any command runs + or approval is consumed. The earlier-step allowance in `approval_holds` + is unchanged. 2. **Stable approval identity (`phoebus_installer::approval`, ADR 0014):** - Ledger + `.claim` key = `approval_key(plan_id, canonical_digest, initiator_uid, target_root)`. Presentation fields (summary, rationale, @@ -47,15 +54,15 @@ commit it. It should be short and current; use `git log` for detail. `transaction::begin` reaches a terminal result. - **Last verified (this session):** - `cargo fmt --all -- --check` clean. - - `cargo test --workspace`: 598 passed, 0 failed. New adversarial tests: - swapped-action-with-retained-digest for every plan kind; replay rejected - after a summary edit / other presentation edits / recreating an identical - plan under the original id; a newly reviewed identical operation with a new - id allowed; live claim not reconciled while an abandoned one is; - reconcile-vs-finish race yields one immutable terminal; terminal status not - overwritten; elevated personal write chowns to the initiating user; a - symlinked component is refused; a non-root cross-uid personal write is - refused (unit and CLI). + - `cargo test --workspace`: 601 passed, 0 failed. New per-step binding + adversarial tests: single-action and multi-action General plans with + `step_effects` swapped (with and without a matching aggregate) while the + approved digest is retained are rejected before any command, ledger claim or + transaction; a legitimate bound multi-step plan still validates. The prior + session's adversarial tests (swapped action resealed for every plan kind; + replay after a summary/presentation edit or recreating an identical plan; + live-vs-abandoned reconciliation; reconcile-vs-finish; personal ownership; + cross-uid refusal) all still pass. - `cargo clippy --workspace --all-targets` exits 0 (only the pre-existing `result_large_err`, one arg-count and one `DiskPhase` lints remain). - `cargo build --release -p phoebus-installer` clean. diff --git a/docs/STATUS.md b/docs/STATUS.md index c189e8e..cfeb887 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -87,6 +87,7 @@ still not VM-verified. | Resolved package effects + approval binding (carried through execution) | yes | yes (empty vs unestablished; drift + prior-step allowance) | no | n/a | | Privileged approval ledger (replacement/replay/concurrency/interruption) | yes | yes (privileged entry point) | no | n/a | | Canonical digest recomputed at the privileged boundary (all plan kinds) | yes | yes (adversarial: swapped action resealed, every kind) | no | n/a | +| Per-step effect binding into the approval digest (contents + aggregate) | yes | yes (adversarial: step_effects swap rejected; legit multi-step validates) | no | n/a | | Stable approval identity (replay after presentation edit/reseal) | yes | yes (summary/other fields/identical id/concurrent/new-id) | no | n/a | | Live-safe monotonic recovery (owner liveness, immutable terminal) | yes | yes (live vs abandoned, reconcile/finish race) | no | n/a | | Personal preferences + alert state (user-owned, system-default precedence) | yes | yes (save/reload/isolation/precedence/failure) | no | no | diff --git a/docs/adr/0014-privileged-approval-ledger.md b/docs/adr/0014-privileged-approval-ledger.md index b4738e2..c0ce3a4 100644 --- a/docs/adr/0014-privileged-approval-ledger.md +++ b/docs/adr/0014-privileged-approval-ledger.md @@ -37,14 +37,23 @@ mint a new approval. ### The broker recomputes the canonical digest for every plan kind The privileged boundary independently derives the canonical approval digest from -the exact executable `actions`, the `candidate` and the reviewed material -`effects` (`compute_plan_digest`, the same function the planner used). It must -equal both the plan's stored digest and the independently supplied -`--approval-digest`. The integrity seal stored beside the plan is a -self-consistency check the owner can recompute, so it is never treated as -authentication. This binds Install, LegacyInstall, Removal, General and Undo -plans alike; retaining an approved digest while swapping an action and resealing -is rejected before any command runs or approval is consumed. +the exact executable `actions`, the `candidate`, the reviewed aggregate +`effects` and **every per-step effect execution trusts** (`compute_plan_digest`, +the same function the planner used). It must equal both the plan's stored digest +and the independently supplied `--approval-digest`. The integrity seal stored +beside the plan is a self-consistency check the owner can recompute, so it is +never treated as authentication. + +Execution trusts `step_effects`, so those are bound too: each stored per-step +effect digest is *recomputed from its contents* and must match, the aggregate +must be exactly the concatenation of the steps, and the canonical digest covers +every step. A multi-action plan without per-step effects is refused. +Install/LegacyInstall keep the install-specific digest with the single step +required to equal the aggregate. This binds Install, LegacyInstall, Removal, +General and Undo alike; retaining an approved digest while swapping an action or +a step's effects and resealing is rejected before any command runs or approval is +consumed. The earlier-approved-step allowance used during execution is +unchanged. ### Consumption is anchored by a stable approval identity diff --git a/installer-rs/crates/phoebus-installer/src/assistant_bridge.rs b/installer-rs/crates/phoebus-installer/src/assistant_bridge.rs index c90cf1f..0164b29 100644 --- a/installer-rs/crates/phoebus-installer/src/assistant_bridge.rs +++ b/installer-rs/crates/phoebus-installer/src/assistant_bridge.rs @@ -628,14 +628,16 @@ fn execute_action_helper( action: SystemAction, assume_yes: bool, ) -> BridgeResponse { - let effects = match actions::resolve_effects(exec, &action, root) { + let mut effects = match actions::resolve_effects(exec, &action, root) { Ok(plan) => plan, Err(e) => return BridgeResponse::err(id, format!("could not resolve effects: {e}")), }; + effects.recompute_digest(); let now = now_unix(); let actions_vec = vec![action.clone()]; - let digest = service::compute_plan_digest(&actions_vec, None, &effects); + let step_effects = vec![effects.clone()]; + let digest = service::compute_plan_digest(&actions_vec, None, &effects, &step_effects); let mut plan = PreparedPlan { id: service::fresh_plan_id("act"), created_unix: now, @@ -649,8 +651,8 @@ fn execute_action_helper( rationale: Vec::new(), warnings: Vec::new(), actions: actions_vec, - effects: effects.clone(), - step_effects: vec![effects], + effects, + step_effects, digest: digest.clone(), verification: "action completed".into(), requires_root: action.requires_root(), diff --git a/installer-rs/crates/phoebus-installer/src/service.rs b/installer-rs/crates/phoebus-installer/src/service.rs index 36c2e71..4d49231 100644 --- a/installer-rs/crates/phoebus-installer/src/service.rs +++ b/installer-rs/crates/phoebus-installer/src/service.rs @@ -389,12 +389,85 @@ pub fn seal_plan(plan: &mut PreparedPlan) { plan.integrity = plan_integrity(plan); } -/// Compute a cryptographic digest binding the exact actions, candidate, and effects. +/// 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.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); @@ -414,6 +487,13 @@ pub fn compute_plan_digest( 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 { @@ -755,7 +835,11 @@ fn build_install_plan( let digest = resolved.approval_digest(); let actions = vec![resolved.action.clone()]; let requires_root = resolved.action.is_mutating(); - let step_effects = vec![resolved.effects.clone()]; + // 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, @@ -774,7 +858,7 @@ fn build_install_plan( rationale: resolved.rationale.clone(), warnings: resolved.warnings.clone(), actions, - effects: resolved.effects.clone(), + effects, step_effects, digest, verification: resolved.verification.clone(), @@ -985,11 +1069,13 @@ pub fn build_removal_plan( }, }; - let effects = actions::resolve_effects(exec, &action, root)?; + 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 digest = compute_plan_digest(&actions_vec, None, &effects); + let step_effects = vec![effects.clone()]; + let digest = compute_plan_digest(&actions_vec, None, &effects, &step_effects); let mut rationale = rationale; rationale.insert( @@ -1017,8 +1103,8 @@ pub fn build_removal_plan( rationale, warnings, actions: actions_vec, - effects: effects.clone(), - step_effects: vec![effects], + effects, + step_effects, digest, verification: format!( "verify that `{}` ({}) is completely removed from the system", @@ -1063,13 +1149,16 @@ pub fn plan_general( let mut step_effects = Vec::new(); for act in &assistant_plan.actions { - let eff = actions::resolve_effects(exec, act, root).map_err(|e| { + 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 @@ -1083,7 +1172,12 @@ pub fn plan_general( let now = now_unix(); let plan_id = fresh_plan_id("gen"); - let digest = compute_plan_digest(&assistant_plan.actions, None, &combined_effects); + let digest = compute_plan_digest( + &assistant_plan.actions, + None, + &combined_effects, + &step_effects, + ); let rationale_strings: Vec = assistant_plan .rationale .into_iter() @@ -1176,6 +1270,13 @@ pub fn validate_prepared_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 @@ -1185,7 +1286,20 @@ pub fn validate_prepared_plan( // (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. - let canonical = compute_plan_digest(&plan.actions, plan.candidate.as_ref(), &plan.effects); + // + // 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", @@ -1231,13 +1345,6 @@ pub fn validate_prepared_plan( ), )); } - if plan.actions.is_empty() { - return Err(ExecError::operation( - "service", - "validate plan", - "plan proposes no actions", - )); - } revalidate_plan_state(exec, root, plan) } @@ -1603,13 +1710,9 @@ fn execute_claimed( // Carry the *reviewed* per-step effects forward. Freshly resolved effects // below are evidence to compare against these, never a replacement - // approval. - let reviewed_steps: Vec = - if plan.step_effects.len() == plan.actions.len() && !plan.step_effects.is_empty() { - plan.step_effects.clone() - } else { - vec![plan.effects.clone(); plan.actions.len()] - }; + // 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(); @@ -1915,8 +2018,10 @@ mod tests { target_root: &Path, initiator_uid: u32, ) -> PreparedPlan { - let effects = ResolvedPlan::default(); - let digest = compute_plan_digest(&actions, None, &effects); + 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(), @@ -1931,7 +2036,7 @@ mod tests { warnings: Vec::new(), actions, effects, - step_effects: Vec::new(), + step_effects, digest, verification: "verify".into(), requires_root: false, @@ -2500,7 +2605,10 @@ mod tests { uid: u32, ) -> PreparedPlan { let actions = vec![action]; - let digest = compute_plan_digest(&actions, None, &reviewed); + 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(), @@ -2514,8 +2622,8 @@ mod tests { rationale: Vec::new(), warnings: Vec::new(), actions, - effects: reviewed.clone(), - step_effects: vec![reviewed], + effects: reviewed, + step_effects, digest, verification: "verify".into(), requires_root: true, @@ -2968,7 +3076,7 @@ mod tests { uid, ); plan.requires_root = true; - plan.step_effects = vec![ResolvedPlan::default(), ResolvedPlan::default()]; + // `sealed` already stores one normalized per-step effect per action. seal_plan(&mut plan); store.save(&mut plan).unwrap(); let digest = plan.digest.clone(); @@ -3013,8 +3121,10 @@ mod tests { root: &Path, uid: u32, ) -> PreparedPlan { - let digest = compute_plan_digest(&actions, candidate.as_ref(), &effects); + 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(), @@ -3444,4 +3554,266 @@ mod tests { "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.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"); + } } diff --git a/installer/tests/vm/serial-driver.py b/installer/tests/vm/serial-driver.py index a65cb47..861f739 100644 --- a/installer/tests/vm/serial-driver.py +++ b/installer/tests/vm/serial-driver.py @@ -107,11 +107,17 @@ def do_install(results, paths, disks): child.sendline(f"curl -fsSL {url} -o /tmp/run.sh && bash /tmp/run.sh") child.expect([r"===INSTALL-RC=([0-9]+)===", "===FETCH-FAIL===", "Kernel panic", pexpect.EOF, pexpect.TIMEOUT], timeout=9000) - if "INSTALL-RC" in (child.after or ""): + # `child.after` is the matched pattern class (not a string) when EOF or + # TIMEOUT matched; handle that instead of raising a TypeError. + matched = child.after if isinstance(child.after, str) else "" + if "INSTALL-RC" in matched: rc = child.match.group(1) results.assert_true("install-rc-zero", rc == "0", f"INSTALL-RC={rc}") else: - results.fail("install-rc-zero", "install did not report a status") + results.fail( + "install-rc-zero", + f"install did not report a status (matched {matched!r})", + ) serial = paths.serial_log.read_text(errors="replace") results.assert_true("no-secret-leak", "SECRET_LEAK_FOUND" not in serial, "the guest reported a secret leak")