//! `iz restore --from `: replaces the database and the attachments with a verified backup set. //! //! Order: verify the set with `manifest::verify_set`, which checks the manifest's MAC under the instance key before //! it trusts the manifest; check that the configured database is a regular file //! inside the data directory; copy the set's `iz.db` and attachments into a staging directory inside the data //! directory and check each copy against the manifest; run `integrity_check` and the migration check on the //! staged database. Nothing outside the staging directory changes until then. Only after that are the current //! `iz.db`, `iz.db-wal`, `iz.db-shm` and `attachments` moved aside under a UTC stamp (kept, never deleted) and //! the staged files moved into place. If a move fails, the moves made so far are undone. //! //! Every path is joined from the data directory and fixed names; the only names taken from the set are the //! ones `verify_set` checked, and they are used only after they parse as canonical ULIDs. use std::fs::{DirBuilder, Permissions}; use std::os::unix::fs::{DirBuilderExt, PermissionsExt}; use std::path::{Path, PathBuf}; use std::process::ExitCode; use iz_core::config::Config; use iz_core::manifest::{self, Manifest}; use iz_core::staging::{ATTACHMENTS_DIR, blob_path}; use iz_core::store::export::{ReadOnly, migrations_problem}; use iz_core::store::new_id; use super::{describe, existing_data_dir, fail, file_stamp, instance_key, take_lock}; /// The database file name inside a backup set. Fixed: the set writer uses this name too. const SET_DB: &str = "iz.db"; /// The directory name prefix of the staging directory inside the data directory. const STAGING_PREFIX: &str = "restore-staging-"; /// Runs the restore and maps its outcome to an exit status. pub async fn run(config_path: &Path, from: &Path) -> ExitCode { let config = match Config::load(config_path) { Ok(config) => config, Err(error) => return fail(describe(&error)), }; if let Err(error) = std::fs::create_dir_all(&config.data_dir) .and_then(|()| std::fs::set_permissions(&config.data_dir, Permissions::from_mode(0o700))) { return fail(format!( "the data directory {} cannot be created: {error}", config.data_dir.display() )); } let data_dir = match existing_data_dir(&config) { Ok(dir) => dir, Err(message) => return fail(message), }; let _lock = match take_lock(&data_dir) { Ok(lock) => lock, Err(code) => return code, }; let key = match instance_key(&data_dir) { Ok(key) => key, Err(message) => return fail(message), }; match restore(&config, &data_dir, from, &key).await { Ok(summary) => { println!("{summary}"); ExitCode::SUCCESS } Err(message) => fail(message), } } /// A canonical ULID name from a set. `None` for anything else, so a name is used only when it is the /// exact text the store would have written. fn canonical_id(name: &str) -> Option { // `blob_path` accepts exactly the canonical ULID text, so it is the one check for ids. blob_path(Path::new("."), name) .ok() .map(|_| name.to_owned()) } /// The files a restore takes from a set: `iz.db`, and `attachments/` for each canonical id. Any other /// listed file is refused, so a set cannot smuggle a file into the data directory. fn plan_set(manifest: &Manifest) -> Result, String> { let mut attachments = Vec::new(); let mut has_db = false; for file in &manifest.files { if file.path == SET_DB { has_db = true; } else if let Some(id) = file .path .strip_prefix("attachments/") .and_then(canonical_id) { attachments.push(id); } else { return Err(format!("the set lists an unexpected file: {}", file.path)); } } if !has_db { return Err(format!("the set has no {SET_DB}")); } Ok(attachments) } /// The database path, joined from the canonical parent directory and the file name. Refused unless it is /// inside the data directory and is not a link, so the restore cannot replace a file outside it. fn database_target(config: &Config, data_dir: &Path) -> Result { let name = config.database.file_name().ok_or_else(|| { format!( "the database path has no file name: {}", config.database.display() ) })?; let parent = config .database .parent() .filter(|p| !p.as_os_str().is_empty()) .unwrap_or_else(|| Path::new(".")); let parent = parent.canonicalize().map_err(|error| { format!( "the database directory {} cannot be used: {error}", parent.display() ) })?; if !parent.starts_with(data_dir) { return Err(format!( "the database {} is outside the data directory; restore refuses to replace it", config.database.display() )); } let target = parent.join(name); if let Ok(meta) = std::fs::symlink_metadata(&target) && !meta.file_type().is_file() { return Err(format!( "the database {} is not a regular file", target.display() )); } Ok(target) } /// Copies `source` to `dest` (created new, mode 0600), then checks the copy against the manifest entry /// for `relative` so a set changed during the copy is refused. fn copy_checked( manifest: &Manifest, relative: &str, source: &Path, dest: &Path, ) -> Result<(), String> { let expected = manifest .files .iter() .find(|file| file.path == relative) .ok_or_else(|| format!("the set does not list {relative}"))?; std::fs::copy(source, dest).map_err(|error| format!("cannot copy {relative}: {error}"))?; std::fs::set_permissions(dest, Permissions::from_mode(0o600)) .map_err(|error| format!("cannot set the mode of {}: {error}", dest.display()))?; let (size, digest) = manifest::digest_file(dest) .map_err(|error| format!("cannot read the copy of {relative}: {}", describe(&error)))?; if size != expected.size || digest != expected.sha256 { return Err(format!("the set changed while it was copied: {relative}")); } Ok(()) } /// The staging directory and what it holds, so a failure can remove exactly what was made. struct Staging { dir: PathBuf, } impl Staging { /// Makes a new staging directory with a fresh name inside the data directory, mode 0700. fn create(data_dir: &Path) -> Result { let dir = data_dir.join(format!("{STAGING_PREFIX}{}", new_id())); DirBuilder::new() .mode(0o700) .create(&dir) .map_err(|error| format!("cannot create {}: {error}", dir.display()))?; Ok(Staging { dir }) } /// Removes the files a restore puts in the staging directory, then the directory. It removes only /// regular files directly inside it and inside its `attachments` directory, and leaves anything else /// in place. fn discard(&self) { let _ = remove_regular_files(&self.dir); let attachments = self.dir.join(ATTACHMENTS_DIR); let _ = remove_regular_files(&attachments); let _ = std::fs::remove_dir(&attachments); let _ = std::fs::remove_dir(&self.dir); } } /// Removes every regular file directly inside `dir`. Links and directories are not touched. fn remove_regular_files(dir: &Path) -> std::io::Result<()> { for entry in std::fs::read_dir(dir)? { let entry = entry?; if entry.file_type()?.is_file() { std::fs::remove_file(entry.path())?; } } Ok(()) } /// Checks the staged database: `integrity_check` says `ok` and the migrations are contiguous. Its sidecars /// are removed when empty; a sidecar with bytes is refused. async fn check_staged(staged_db: &Path) -> Result<(), String> { { let db = ReadOnly::open(staged_db) .await .map_err(|error| describe(&error))?; let rows = db .integrity_check() .await .map_err(|error| describe(&error))?; if rows != ["ok"] { return Err(format!( "the set's database fails integrity_check: {}", rows.join("; ") )); } let versions = db .migration_versions() .await .map_err(|error| describe(&error))?; if let Some(problem) = migrations_problem(&versions) { return Err(format!("the set's database is refused: {problem}")); } } for suffix in ["-wal", "-shm"] { let mut sidecar = staged_db.as_os_str().to_owned(); sidecar.push(suffix); let sidecar = PathBuf::from(sidecar); match std::fs::symlink_metadata(&sidecar) { Err(_) => {} Ok(meta) if meta.len() == 0 => { std::fs::remove_file(&sidecar) .map_err(|error| format!("cannot remove {}: {error}", sidecar.display()))?; } Ok(meta) => { return Err(format!( "the staged database has {} bytes in {}", meta.len(), sidecar.display() )); } } } Ok(()) } /// The whole restore. Returns the summary line on success. async fn restore( config: &Config, data_dir: &Path, from: &Path, key: &[u8; 32], ) -> Result { let manifest = manifest::verify_set(from, key).map_err(|error| describe(&error))?; let attachment_ids = plan_set(&manifest)?; let db_target = database_target(config, data_dir)?; let attachments_dir = data_dir.join(ATTACHMENTS_DIR); if let Ok(meta) = std::fs::symlink_metadata(&attachments_dir) && !meta.file_type().is_dir() { return Err(format!("{} is not a directory", attachments_dir.display())); } // Stage and check everything first. A failure here removes the staging directory and changes nothing else. let staging = Staging::create(data_dir)?; let staged = stage(&staging, from, &manifest, &attachment_ids).await; if let Err(message) = staged { staging.discard(); return Err(message); } let stamp = file_stamp(); let result = swap_into_place(&staging.dir, &db_target, data_dir, &stamp); match result { Ok(moved) => { if let Err(error) = std::fs::remove_dir(&staging.dir) { eprintln!( "iz: the staging directory {} could not be removed: {error}", staging.dir.display() ); } Ok(format!( "restored from {}: {} attachments; previous files kept as {}", from.display(), attachment_ids.len(), moved.join(", ") )) } Err(message) => { staging.discard(); Err(message) } } } /// Copies the set's files into the staging directory and checks them. The staging directory always gets /// an `attachments` directory, even when the set has none, so the swap is the same in both cases. async fn stage( staging: &Staging, from: &Path, manifest: &Manifest, attachment_ids: &[String], ) -> Result<(), String> { let staged_db = staging.dir.join(SET_DB); copy_checked(manifest, SET_DB, &from.join(SET_DB), &staged_db)?; let staged_attachments = staging.dir.join(ATTACHMENTS_DIR); DirBuilder::new() .mode(0o700) .create(&staged_attachments) .map_err(|error| format!("cannot create {}: {error}", staged_attachments.display()))?; for id in attachment_ids { let relative = format!("{ATTACHMENTS_DIR}/{id}"); copy_checked( manifest, &relative, &from.join(ATTACHMENTS_DIR).join(id), &staged_attachments.join(id), )?; } check_staged(&staged_db).await } /// One move made by the swap, so it can be undone. enum Move { /// An existing file or directory moved aside, from, to. Aside(PathBuf, PathBuf), /// A staged file moved into place, from, to. Placed(PathBuf, PathBuf), } /// Moves the current database files and attachments aside, then the staged ones into place. Returns the /// names the old files were kept under. If any move fails, the moves made so far are reversed. fn swap_into_place( staging: &Path, db_target: &Path, data_dir: &Path, stamp: &str, ) -> Result, String> { let attachments = data_dir.join(ATTACHMENTS_DIR); let mut old: Vec<(PathBuf, PathBuf)> = Vec::new(); for current in [ db_target.to_path_buf(), with_suffix(db_target, "-wal"), with_suffix(db_target, "-shm"), attachments.clone(), ] { if std::fs::symlink_metadata(¤t).is_ok() { let aside = with_suffix(¤t, &format!(".{stamp}")); if std::fs::symlink_metadata(&aside).is_ok() { return Err(format!( "{} already exists; nothing was changed", aside.display() )); } old.push((current, aside)); } } let staged_db = staging.join(SET_DB); let staged_attachments = staging.join(ATTACHMENTS_DIR); let mut done: Vec = Vec::new(); let outcome = (|| -> std::io::Result<()> { for (current, aside) in &old { std::fs::rename(current, aside)?; done.push(Move::Aside(current.clone(), aside.clone())); } std::fs::rename(&staged_db, db_target)?; done.push(Move::Placed(staged_db.clone(), db_target.to_path_buf())); std::fs::rename(&staged_attachments, &attachments)?; done.push(Move::Placed( staged_attachments.clone(), attachments.clone(), )); std::fs::File::open(data_dir)?.sync_all() })(); match outcome { Ok(()) => Ok(old .iter() .map(|(_, aside)| aside.display().to_string()) .collect()), Err(error) => { // Undo in reverse. A failure to undo is reported with the paths, so the operator can finish by hand. let mut stuck = Vec::new(); for step in done.into_iter().rev() { // An aside file goes back to its original name; a placed file goes back to staging. let undone = match &step { Move::Aside(original, aside) => std::fs::rename(aside, original), Move::Placed(staged, target) => std::fs::rename(target, staged), }; if let Err(undo_error) = undone { stuck.push(undo_error.to_string()); } } if stuck.is_empty() { Err(format!("restore failed and was undone: {error}")) } else { Err(format!( "restore failed: {error}; some moves could not be undone: {}", stuck.join("; ") )) } } } } /// `path` with `suffix` appended to its file name. fn with_suffix(path: &Path, suffix: &str) -> PathBuf { let mut text = path.as_os_str().to_owned(); text.push(suffix); PathBuf::from(text) } #[cfg(test)] mod tests { use super::*; use iz_core::manifest::write_manifest; /// A set with a file that a manifest does not list, or whose bytes changed after the manifest was /// written, must not be restored: nothing in the data directory may change. #[tokio::test] async fn restore_refuses_a_tampered_set_and_changes_nothing() { let root = tempfile::tempdir().expect("temp dir"); let set = root.path().join("set"); let data = root.path().join("data"); std::fs::create_dir_all(&set).expect("set dir"); std::fs::create_dir_all(&data).expect("data dir"); let key = [5u8; 32]; let db = data.join("iz.db"); std::fs::write(&db, b"current database").expect("current db"); std::fs::write(set.join(SET_DB), b"backup database bytes").expect("set db"); write_manifest( &set, &key, "2026-10-28T00:00:00.000000000Z", "test", &[SET_DB.to_owned()], ) .expect("manifest"); // Tamper after the manifest is written. let mut bytes = std::fs::read(set.join(SET_DB)).expect("read"); bytes[0] ^= 0x01; std::fs::write(set.join(SET_DB), bytes).expect("tamper"); let config = Config::parse(&format!( "database = \"{}\"\ndata_dir = \"{}\"\nlisten = \"127.0.0.1:7654\"\nbase_url = \"http://127.0.0.1:7654\"\n", db.display(), data.display(), )) .expect("config"); let error = restore( &config, &data.canonicalize().expect("canonical"), &set, &key, ) .await .expect_err("tampered set must be refused"); assert!( error.contains("changed since the set was written"), "got: {error}" ); assert_eq!( std::fs::read(&db).expect("db still there"), b"current database" ); let entries: Vec<_> = std::fs::read_dir(&data) .expect("list") .map(|e| e.expect("entry").file_name()) .collect(); assert_eq!(entries.len(), 1, "only the database remains: {entries:?}"); } }