From e82aaba5fbecfdb193d3b38dfc1c03697f2007c0 Mon Sep 17 00:00:00 2001 From: Phoebus Date: Sun, 20 Sep 2026 04:39:23 -0700 Subject: [PATCH] fix(executor): fail closed when a protective snapshot cannot be created High-risk sys actions now create their protective snapshot inside actions::execute and abort if the .snapshots subvolume exists but the snapshot fails, instead of warning and mutating anyway. Corrupt snapshot history is surfaced as an error rather than being silently treated as empty. --- .../crates/phoebus-core/src/snapshot.rs | 25 ++++++ .../crates/phoebus-executor/src/actions.rs | 77 ++++++++++++++++++- .../crates/phoebus-executor/src/snapshot.rs | 40 +++++++++- .../crates/phoebus-installer/src/bin/sys.rs | 22 ++---- 4 files changed, 143 insertions(+), 21 deletions(-) diff --git a/installer-rs/crates/phoebus-core/src/snapshot.rs b/installer-rs/crates/phoebus-core/src/snapshot.rs index 1161a90..a4f40b2 100644 --- a/installer-rs/crates/phoebus-core/src/snapshot.rs +++ b/installer-rs/crates/phoebus-core/src/snapshot.rs @@ -37,11 +37,19 @@ pub struct SnapshotHistory { } impl SnapshotHistory { + /// Load the transaction history. + /// + /// A missing or zero-length file is treated as empty. Any other read or + /// parse failure is returned, never silently discarded: hidden history + /// would let a caller believe no recovery point exists when one does. pub fn load(path: &Path) -> Result { if !path.exists() { return Ok(Self::default()); } let text = std::fs::read_to_string(path).map_err(|e| CoreError::io(path, e))?; + if text.trim().is_empty() { + return Ok(Self::default()); + } let history: SnapshotHistory = toml::from_str(&text)?; Ok(history) } @@ -136,4 +144,21 @@ mod tests { let history = SnapshotHistory::load(&dir.path().join("nope.toml")).unwrap(); assert!(history.records.is_empty()); } + + #[test] + fn empty_history_file_is_empty() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("empty.toml"); + std::fs::write(&path, " \n").unwrap(); + let history = SnapshotHistory::load(&path).unwrap(); + assert!(history.records.is_empty()); + } + + #[test] + fn corrupt_history_is_reported_not_hidden() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("corrupt.toml"); + std::fs::write(&path, "this is not = = toml [[[").unwrap(); + assert!(SnapshotHistory::load(&path).is_err()); + } } diff --git a/installer-rs/crates/phoebus-executor/src/actions.rs b/installer-rs/crates/phoebus-executor/src/actions.rs index ae0fbed..7069373 100644 --- a/installer-rs/crates/phoebus-executor/src/actions.rs +++ b/installer-rs/crates/phoebus-executor/src/actions.rs @@ -41,6 +41,23 @@ pub fn execute( if action.is_mutating() && auth.is_none() { return Err(ExecError::NotAuthorized(action.describe())); } + + // A protective snapshot must exist before a high-risk change. If the + // snapshots subvolume is present but the snapshot cannot be created, fail + // closed rather than proceed without a recovery point. A system without a + // `.snapshots` subvolume (e.g. a non-Btrfs root) is a warning, not a block. + if action.risk() == phoebus_core::action::Risk::High && !exec.dry_run { + if root.join(snapshot::SNAPSHOT_DIR).is_dir() { + let auth = auth.ok_or_else(|| ExecError::NotAuthorized(action.describe()))?; + snapshot::create_and_record(exec, auth, root, "/", &action.describe())?; + } else { + exec.logger.warn(format!( + "no {}/ subvolume; proceeding without a protective snapshot", + snapshot::SNAPSHOT_DIR + )); + } + } + let mut snapshot_id = None; let output = match action { SystemAction::InspectService { name } => { @@ -107,7 +124,7 @@ pub fn execute( ) } SystemAction::History => { - let history = snapshot::read_history(root); + let history = snapshot::read_history(root)?; if history.records.is_empty() { "no transaction history".to_string() } else { @@ -160,6 +177,64 @@ mod tests { execute(&exec, &action, None, Path::new("/")).unwrap(); } + #[test] + fn high_risk_action_snapshots_before_running() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner.clone()); + std::fs::create_dir_all(exec.root.join(snapshot::SNAPSHOT_DIR)).unwrap(); + let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap(); + execute( + &exec, + &SystemAction::UpdateSystem, + Some(&auth), + Path::new(&exec.root), + ) + .unwrap(); + let programs = runner.programs(); + let btrfs = programs + .iter() + .position(|p| p == "btrfs") + .expect("snapshot"); + let emerge = programs.iter().position(|p| p == "emerge").expect("emerge"); + assert!( + btrfs < emerge, + "protective snapshot must precede the mutation: {programs:?}" + ); + } + + #[test] + fn high_risk_action_aborts_when_protective_snapshot_fails() { + let runner = RecordingRunner::new(); + runner.fail("btrfs", "snapshot failed"); + let exec = make_exec(runner.clone()); + std::fs::create_dir_all(exec.root.join(snapshot::SNAPSHOT_DIR)).unwrap(); + let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap(); + let err = execute( + &exec, + &SystemAction::UpdateSystem, + Some(&auth), + Path::new(&exec.root), + ) + .unwrap_err(); + assert!(matches!(err, ExecError::Command { .. }), "got {err}"); + // The mutation must not run, and no snapshot may be recorded as + // committed when creation failed. + assert!(!runner.programs().iter().any(|p| p == "emerge")); + let history = snapshot::read_history(Path::new(&exec.root)).unwrap(); + assert!(history.records.is_empty()); + } + + #[test] + fn history_query_reports_corrupt_file() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner); + let path = crate::snapshot::history_path(Path::new(&exec.root)); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, "not = = toml [[[").unwrap(); + let err = execute(&exec, &SystemAction::History, None, Path::new(&exec.root)).unwrap_err(); + assert!(matches!(err, ExecError::Core(_)), "got {err}"); + } + #[test] fn enable_builds_separate_arguments() { let runner = RecordingRunner::new(); diff --git a/installer-rs/crates/phoebus-executor/src/snapshot.rs b/installer-rs/crates/phoebus-executor/src/snapshot.rs index 3248291..8e3d1e6 100644 --- a/installer-rs/crates/phoebus-executor/src/snapshot.rs +++ b/installer-rs/crates/phoebus-executor/src/snapshot.rs @@ -29,8 +29,26 @@ pub fn history_path(root: &Path) -> PathBuf { root.join(HISTORY_REL) } -pub fn read_history(root: &Path) -> SnapshotHistory { - SnapshotHistory::load(&history_path(root)).unwrap_or_default() +/// Read the transaction history, surfacing a corrupt file instead of hiding it. +/// +/// A missing or zero-length file is empty; anything else is an error so a +/// caller never mistakes an unreadable history for "no snapshots". +pub fn read_history(root: &Path) -> Result { + SnapshotHistory::load(&history_path(root)).map_err(ExecError::Core) +} + +/// The transaction history, or a logged warning and the last-known-empty +/// history. Only for read paths that must not fail a `sys` query. +pub fn read_history_lossy(exec: &Exec, root: &Path) -> SnapshotHistory { + match read_history(root) { + Ok(history) => history, + Err(e) => { + exec.logger.warn(format!( + "snapshot history is unreadable: {e}; treating as unavailable" + )); + SnapshotHistory::default() + } + } } pub fn write_history(root: &Path, history: &SnapshotHistory) -> Result<()> { @@ -86,7 +104,7 @@ pub fn create_and_record( ) -> Result { let mut record = create(exec, auth, root, source_subvol, operation)?; record.status = SnapshotStatus::Committed; - let mut history = read_history(root); + let mut history = read_history(root)?; history.append(record.clone()); write_history(root, &history)?; exec.logger @@ -151,8 +169,22 @@ mod tests { let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap(); let record = create_and_record(&exec, &auth, Path::new(&exec.root), "/", "risk").unwrap(); assert_eq!(record.status, SnapshotStatus::Committed); - let history = read_history(Path::new(&exec.root)); + let history = read_history(Path::new(&exec.root)).unwrap(); assert_eq!(history.records.len(), 1); assert_eq!(history.latest().unwrap().id, record.id); } + + #[test] + fn corrupt_history_is_surfaced() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner); + let history_path = history_path(Path::new(&exec.root)); + std::fs::create_dir_all(history_path.parent().unwrap()).unwrap(); + std::fs::write(&history_path, "not = = toml [[[").unwrap(); + assert!(read_history(Path::new(&exec.root)).is_err()); + // The lossy variant keeps read paths working but does not pretend the + // history was empty. + let lossy = read_history_lossy(&exec, Path::new(&exec.root)); + assert!(lossy.records.is_empty()); + } } diff --git a/installer-rs/crates/phoebus-installer/src/bin/sys.rs b/installer-rs/crates/phoebus-installer/src/bin/sys.rs index 5ec5c03..cca33f9 100644 --- a/installer-rs/crates/phoebus-installer/src/bin/sys.rs +++ b/installer-rs/crates/phoebus-installer/src/bin/sys.rs @@ -144,23 +144,13 @@ fn run() -> std::result::Result<(), Box> { None }; - // High-risk operations are preceded by a snapshot when the root is Btrfs. - if action.risk() == phoebus_core::action::Risk::High && cli.root.join(".snapshots").is_dir() { - if let Some(auth) = auth.as_ref() { - match phoebus_executor::snapshot::create_and_record( - &exec, - auth, - &cli.root, - "/", - &action.describe(), - ) { - Ok(record) => println!("created snapshot: {}", record.id), - Err(e) => eprintln!("warning: could not create snapshot: {e}"), - } - } - } - + // `actions::execute` creates a protective snapshot for high-risk actions + // and fails closed when the snapshots subvolume exists but creation fails, + // so there is a single, tested safety path. let outcome = actions::execute(&exec, &action, auth.as_ref(), &cli.root)?; + if let Some(id) = &outcome.snapshot { + println!("protective snapshot: {id}"); + } println!("{}", outcome.output); Ok(()) }