phoebus_os/installer-rs/crates/phoebus-executor/src/snapshot.rs
Phoebus e82aaba5fb 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.
2026-09-20 04:39:23 -07:00

190 lines
6.6 KiB
Rust

//! Btrfs snapshot creation and transaction history.
//!
//! Snapshots are read-only and live under the `@snapshots` subvolume
//! (`/.snapshots`). A record is appended to the history before the operation
//! and marked committed only afterwards. Real rollback (default-subvolume
//! switching plus `/boot` handling) is deliberately *not* implemented here; the
//! foundations are.
//!
//! `/home` is a separate subvolume and is intentionally not snapshotted by
//! default, so a future system rollback cannot discard user documents.
use std::path::{Path, PathBuf};
use phoebus_core::snapshot::{snapshot_name, SnapshotHistory, SnapshotRecord, SnapshotStatus};
use crate::auth::DestructiveAuthorization;
use crate::command::CommandSpec;
use crate::error::{ExecError, Result};
use crate::exec::Exec;
pub const SNAPSHOT_DIR: &str = ".snapshots";
pub const HISTORY_REL: &str = "var/lib/phoebus/snapshot-history.toml";
pub fn snapshots_path(root: &Path) -> PathBuf {
root.join(SNAPSHOT_DIR)
}
pub fn history_path(root: &Path) -> PathBuf {
root.join(HISTORY_REL)
}
/// 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> {
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<()> {
history.save(&history_path(root)).map_err(ExecError::Core)
}
fn now_unix() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
/// Create a read-only snapshot of `source_subvol` (usually the mounted root).
pub fn create(
exec: &Exec,
_auth: &DestructiveAuthorization,
root: &Path,
source_subvol: &str,
operation: &str,
) -> Result<SnapshotRecord> {
let dir = snapshots_path(root);
std::fs::create_dir_all(&dir).map_err(|e| ExecError::io(dir.clone(), e))?;
let unix = now_unix();
let name = snapshot_name("@", unix, operation);
let dest = dir.join(&name);
exec.run(
CommandSpec::new("snapshot", format!("create snapshot {name}"), "btrfs")
.args(["subvolume", "snapshot", "-r"])
.arg(source_subvol)
.arg(dest.to_string_lossy().to_string()),
)?;
let record = SnapshotRecord {
id: name.clone(),
created_unix: unix,
operation: operation.to_string(),
source_subvol: source_subvol.to_string(),
snapshot_subvol: name,
status: SnapshotStatus::Created,
};
Ok(record)
}
/// Create a snapshot and record it as committed in the history.
pub fn create_and_record(
exec: &Exec,
auth: &DestructiveAuthorization,
root: &Path,
source_subvol: &str,
operation: &str,
) -> Result<SnapshotRecord> {
let mut record = create(exec, auth, root, source_subvol, operation)?;
record.status = SnapshotStatus::Committed;
let mut history = read_history(root)?;
history.append(record.clone());
write_history(root, &history)?;
exec.logger
.info(format!("snapshot committed: {}", record.id));
Ok(record)
}
pub fn list(_exec: &Exec, root: &Path) -> Result<Vec<String>> {
let dir = snapshots_path(root);
if !dir.is_dir() {
return Ok(Vec::new());
}
let mut names: Vec<String> = std::fs::read_dir(&dir)
.map_err(|e| ExecError::io(dir.clone(), e))?
.flatten()
.map(|e| e.file_name().to_string_lossy().to_string())
.collect();
names.sort();
Ok(names)
}
pub fn delete(exec: &Exec, _auth: &DestructiveAuthorization, root: &Path, id: &str) -> Result<()> {
let target = snapshots_path(root).join(id);
exec.run(
CommandSpec::new("snapshot", format!("delete snapshot {id}"), "btrfs")
.args(["subvolume", "delete"])
.arg(target.to_string_lossy().to_string()),
)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::command::RecordingRunner;
use crate::log::Logger;
use phoebus_core::Redactor;
fn make_exec(runner: RecordingRunner) -> Exec {
let path = tempfile::tempdir().unwrap().keep();
let logger = Logger::open(path.join("l.log"), Redactor::new(), false);
Exec::new(Box::new(runner), logger, false, path.join("root"), path)
}
#[test]
fn create_uses_readonly_btrfs_snapshot() {
let runner = RecordingRunner::new();
let exec = make_exec(runner.clone());
let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap();
let record = create(&exec, &auth, Path::new(&exec.root), "/", "sys update").unwrap();
assert_eq!(record.status, SnapshotStatus::Created);
let spec = &runner.recorded()[0];
assert_eq!(spec.program, "btrfs");
assert_eq!(&spec.args[0..3], &["subvolume", "snapshot", "-r"]);
assert!(spec.args.iter().any(|a| a.contains(".snapshots")));
}
#[test]
fn create_and_record_commits_history() {
let runner = RecordingRunner::new();
let exec = make_exec(runner.clone());
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)).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());
}
}