//! Backup sets, verification, pruning and restore. //! //! A set is a directory `set-` under the backup root. It holds `im.db` (a consistent snapshot of the //! database, see `store/snapshot.rs`), a `photos/` directory with a copy of every profile photo, //! `manifest.json`, and `manifest.mac`. The manifest names every file with its size and SHA-256. The MAC is //! HMAC-SHA256 over the exact manifest bytes, keyed with a subkey of the instance key, so a manifest cannot be //! rewritten to match changed files. A set is written under a temporary name and renamed into place only when //! its manifest and MAC are complete, so a half-written set is never mistaken for a good one. //! //! Verification checks the MAC first, in constant time, and reads nothing else from the manifest until it //! passes. Then it checks every hash, refuses a file the manifest does not list, refuses any entry in `photos/` //! that is not a photo name (see `photo::is_photo_name`) or not a regular file, and runs `PRAGMA //! integrity_check` and the migration check on a scratch copy, so the set itself is never written to. Restore //! verifies first and changes nothing when verification fails. It only replaces a database and a photo //! directory that lie inside the data directory, and it moves what it replaces into `data_dir/restore-/` //! rather than deleting it. The caller must hold the data-directory lock: a running server is never restored //! under. use std::fs::OpenOptions; use std::io::{Read, Write}; use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt}; use std::path::{Path, PathBuf}; use hmac::{Hmac, KeyInit, Mac}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use turso::Builder; use crate::error::{Error, Result}; use crate::photo::is_photo_name; use crate::secret; use crate::store::migrate::MIGRATIONS; use crate::store::{Store, col_int, col_text, db_err, fetch_all}; type HmacSha256 = Hmac; /// The only manifest format this build reads and writes. pub const FORMAT: u32 = 1; /// Name of the snapshot inside a set. pub const DB_FILE: &str = "im.db"; /// Name of the manifest inside a set. pub const MANIFEST_FILE: &str = "manifest.json"; /// Name of the manifest's MAC inside a set: lower-case hex HMAC-SHA256 of the manifest bytes. pub const MAC_FILE: &str = "manifest.mac"; /// Label of the manifest MAC subkey. The subkey is `secret::derive` of this label under the instance key, the /// same way recovery codes get theirs; the MAC itself is keyed with that subkey, never with the instance key. const MAC_SUBKEY_LABEL: &[u8] = b"im backup manifest v1"; /// Name of the photo directory inside a set, and beside the database in the data directory. pub const PHOTOS_DIR: &str = "photos"; /// Prefix of a finished set's directory name. Pruning only ever removes directories with this prefix. pub const SET_PREFIX: &str = "set-"; /// One file of a set: its name relative to the set, its size and its SHA-256 in lower-case hex. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct FileEntry { /// `im.db`, or `photos/`. pub name: String, /// Size in bytes. pub size: u64, /// Lower-case hex SHA-256 of the bytes. pub sha256: String, } /// The manifest of a set. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Manifest { /// Format number; see [`FORMAT`]. pub format: u32, /// When the set was written, UTC. pub created_at: String, /// The snapshot. pub database: FileEntry, /// Every photo that existed when the set was written. pub photos: Vec, } /// What a restore did. #[derive(Debug, Clone, PartialEq, Eq)] pub struct RestoreOutcome { /// Photos put back. pub photos: usize, /// The directory that holds the database and photos that were replaced. pub previous: PathBuf, } /// The HMAC over `bytes` under the manifest subkey of the instance key `key`. Its `verify_slice` is constant /// time, and its `finalize` gives the tag that is written to [`MAC_FILE`]. fn manifest_mac(key: &[u8; 32], bytes: &[u8]) -> HmacSha256 { let subkey = secret::derive(key, MAC_SUBKEY_LABEL); // HMAC accepts a key of any length, so construction cannot fail. let mut mac = ::new_from_slice(&subkey).expect("HMAC takes any key length"); mac.update(bytes); mac } /// Creates a directory that only this user may enter. fn private_dir(path: &Path) -> Result<()> { std::fs::DirBuilder::new() .mode(0o700) .create(path) .map_err(Error::from) } /// Creates a file that only this user may read, failing if it exists. fn private_file(path: &Path) -> Result { OpenOptions::new() .write(true) .create_new(true) .mode(0o600) .open(path) .map_err(Error::from) } /// Writes a complete set under `root` and returns its directory. `stamp` names it and must be safe in a /// file name: callers replace `:` and `.` in the time stamp. `key` is the instance key that keys the manifest /// MAC. pub async fn write_set( store: &Store, data_dir: &Path, root: &Path, stamp: &str, key: &[u8; 32], ) -> Result { std::fs::create_dir_all(root)?; let tmp = root.join(format!(".tmp-{stamp}")); let final_dir = root.join(format!("{SET_PREFIX}{stamp}")); if std::fs::symlink_metadata(&final_dir).is_ok() { return Err(Error::Conflict(format!("set {stamp} already exists"))); } private_dir(&tmp)?; match write_into(store, data_dir, &tmp, key).await { Ok(()) => { std::fs::rename(&tmp, &final_dir)?; Ok(final_dir) } Err(error) => { // A failed set was never complete. It is ours, so it is removed whole. let _ = std::fs::remove_dir_all(&tmp); Err(error) } } } /// Fills `dir` with the snapshot, the photos, the manifest and its MAC, then fsyncs the directory. async fn write_into(store: &Store, data_dir: &Path, dir: &Path, key: &[u8; 32]) -> Result<()> { let db_path = dir.join(DB_FILE); store.snapshot_to(&db_path).await?; // The snapshot holds every row, so it is private like the live database. std::fs::set_permissions(&db_path, std::fs::Permissions::from_mode(0o600))?; let database = file_entry(DB_FILE, &db_path)?; let photos_out = dir.join(PHOTOS_DIR); private_dir(&photos_out)?; let mut photos = Vec::new(); let photos_in = data_dir.join(PHOTOS_DIR); if std::fs::symlink_metadata(&photos_in).is_ok() { for name in photo_names(&photos_in)? { let source = photos_in.join(&name); let target = photos_out.join(&name); let mut out = private_file(&target)?; let mut input = std::fs::File::open(&source)?; std::io::copy(&mut input, &mut out)?; out.sync_all()?; photos.push(file_entry(&format!("{PHOTOS_DIR}/{name}"), &target)?); } } let manifest = Manifest { format: FORMAT, created_at: crate::time::now_stamp(), database, photos, }; let text = serde_json::to_string_pretty(&manifest) .map_err(|e| Error::Invalid(format!("manifest: {e}")))?; let mut file = private_file(&dir.join(MANIFEST_FILE))?; file.write_all(text.as_bytes())?; file.sync_all()?; // The MAC is written after the manifest it covers, so a set with a MAC always has its manifest. let tag = hex::encode(manifest_mac(key, text.as_bytes()).finalize().into_bytes()); let mut mac_file = private_file(&dir.join(MAC_FILE))?; mac_file.write_all(tag.as_bytes())?; mac_file.sync_all()?; std::fs::File::open(&photos_out)?.sync_all()?; std::fs::File::open(dir)?.sync_all()?; Ok(()) } /// The names of the photo files directly in `dir` when copying from the data directory. Links, /// sub-directories and any name that is not a photo name are skipped, so only real photos are backed up. fn photo_names(dir: &Path) -> Result> { let mut names = Vec::new(); for entry in std::fs::read_dir(dir)? { let entry = entry?; let meta = std::fs::symlink_metadata(entry.path())?; if meta.file_type().is_file() && let Some(name) = entry.file_name().to_str() && is_photo_name(name) { names.push(name.to_owned()); } } names.sort(); Ok(names) } /// Reads a file that must be a regular file, not a link. Returns its bytes. fn read_regular(path: &Path) -> Result> { if !std::fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_file()) { return Err(Error::Invalid(format!( "{} is not a regular file", path.display() ))); } Ok(std::fs::read(path)?) } /// Size and SHA-256 of a file, read in chunks. fn file_entry(name: &str, path: &Path) -> Result { let (size, sha256) = file_digest(path)?; Ok(FileEntry { name: name.to_owned(), size, sha256, }) } /// Size and SHA-256 of a file, read in chunks. fn file_digest(path: &Path) -> Result<(u64, String)> { let mut file = std::fs::File::open(path)?; let mut hasher = Sha256::new(); let mut size = 0u64; let mut buf = vec![0u8; 1 << 20]; loop { let n = file.read(&mut buf)?; if n == 0 { break; } size += n as u64; hasher.update(&buf[..n]); } Ok((size, hex::encode(hasher.finalize()))) } /// Removes the oldest sets under `root` until `keep` remain. Only real directories (not links) named /// `set-*` that hold a manifest file are touched, so a wrong `root` cannot cost unrelated data. Returns /// how many were removed. pub fn prune(root: &Path, keep: usize) -> Result { let is_set = |p: &Path| { let named = p .file_name() .and_then(|n| n.to_str()) .is_some_and(|n| n.starts_with(SET_PREFIX)); let real_dir = std::fs::symlink_metadata(p).is_ok_and(|m| m.file_type().is_dir()); let manifest = std::fs::symlink_metadata(p.join(MANIFEST_FILE)).is_ok_and(|m| m.file_type().is_file()); named && real_dir && manifest }; let mut sets: Vec = match std::fs::read_dir(root) { Ok(entries) => entries .filter_map(|e| e.ok().map(|e| e.path())) .filter(|p| is_set(p)) .collect(), Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(0), Err(e) => return Err(e.into()), }; // Names carry fixed-width UTC stamps, so name order is time order. sets.sort(); let excess = sets.len().saturating_sub(keep); for old in sets.iter().take(excess) { std::fs::remove_dir_all(old)?; } Ok(excess) } /// Reads a manifest, checking its MAC first. The MAC is compared in constant time over the exact bytes of /// `manifest.json`, and nothing in the manifest is parsed or trusted until it passes. Then the manifest must /// parse, be the known format, and name the snapshot `im.db`. pub fn read_manifest(set: &Path, key: &[u8; 32]) -> Result { let bytes = read_regular(&set.join(MANIFEST_FILE)) .map_err(|_| Error::Invalid("backup manifest is missing".into()))?; let tag = read_regular(&set.join(MAC_FILE)) .map_err(|_| Error::Invalid("backup manifest has no MAC".into()))?; let tag = hex::decode(String::from_utf8_lossy(&tag).trim()) .map_err(|_| Error::Invalid("backup manifest MAC is not valid".into()))?; manifest_mac(key, &bytes) .verify_slice(&tag) .map_err(|_| Error::Invalid("backup manifest does not match its MAC".into()))?; let manifest: Manifest = serde_json::from_slice(&bytes) .map_err(|_| Error::Invalid("backup manifest is not valid".into()))?; if manifest.format != FORMAT || manifest.database.name != DB_FILE { return Err(Error::Invalid("backup manifest is not valid".into())); } Ok(manifest) } /// Checks a set without changing it: the manifest MAC, every listed file matches its hash, no file is missing /// or unlisted, every entry in `photos/` is a regular file with a photo name, and the snapshot passes /// `PRAGMA integrity_check` with contiguous migrations. The snapshot is checked on a copy in `scratch`, so /// opening it cannot write WAL files into the set. pub async fn verify_set(set: &Path, scratch: &Path, key: &[u8; 32]) -> Result { let manifest = read_manifest(set, key)?; check_entry(set, &manifest.database)?; let mut listed = Vec::new(); for photo in &manifest.photos { let Some(id) = photo.name.strip_prefix("photos/") else { return Err(Error::Invalid( "backup manifest names a file outside photos".into(), )); }; if !is_photo_name(id) { return Err(Error::Invalid("backup manifest names an odd file".into())); } check_entry(set, photo)?; listed.push(id.to_owned()); } // Nothing may be in the set that the manifest does not name. Every entry of photos/ is checked, not // only the ones that look like photos: a stray name, a dot-file or a link is a refusal. let photos_dir = set.join(PHOTOS_DIR); // The manifest, its MAC and the snapshot, plus the photo directory when there is one. let mut expected = 3; if std::fs::symlink_metadata(&photos_dir).is_ok() { if !std::fs::symlink_metadata(&photos_dir)?.file_type().is_dir() { return Err(Error::Invalid("backup photos is not a directory".into())); } expected += 1; let mut found = Vec::new(); for entry in std::fs::read_dir(&photos_dir)? { let entry = entry?; let name = entry .file_name() .into_string() .map_err(|_| Error::Invalid("backup photos hold an odd file name".into()))?; if !is_photo_name(&name) { return Err(Error::Invalid( "backup photos hold a file that is not a photo".into(), )); } if !std::fs::symlink_metadata(entry.path())? .file_type() .is_file() { return Err(Error::Invalid( "backup photos hold a file that is not a regular file".into(), )); } found.push(name); } listed.sort(); found.sort(); if found != listed { return Err(Error::Invalid( "backup photos do not match its manifest".into(), )); } } let on_disk = std::fs::read_dir(set)?.count(); if on_disk != expected { return Err(Error::Invalid( "backup set holds files its manifest does not list".into(), )); } std::fs::create_dir_all(scratch)?; let copy = scratch.join("verify.db"); std::fs::copy(set.join(DB_FILE), ©)?; let checked = check_database(©).await; for suffix in ["", "-wal", "-shm"] { let _ = std::fs::remove_file(format!("{}{suffix}", copy.display())); } checked?; Ok(manifest) } /// Checks one listed file against its size and hash. fn check_entry(set: &Path, entry: &FileEntry) -> Result<()> { let path = set.join(&entry.name); let meta = std::fs::symlink_metadata(&path) .map_err(|_| Error::Invalid(format!("backup file {} is missing", entry.name)))?; if !meta.file_type().is_file() { return Err(Error::Invalid(format!( "backup file {} is not a file", entry.name ))); } let (size, sha256) = file_digest(&path)?; if size != entry.size || sha256 != entry.sha256 { return Err(Error::Invalid(format!( "backup file {} does not match its manifest", entry.name ))); } Ok(()) } /// Runs `PRAGMA integrity_check` on the database at `path` and checks that the recorded migrations are /// exactly `1..=N` for the N this build knows. pub async fn check_database(path: &Path) -> Result<()> { let text = path .to_str() .ok_or_else(|| Error::Config("database path is not UTF-8".into()))?; let db = Builder::new_local(text).build().await.map_err(db_err)?; let conn = db.connect().map_err(db_err)?; let checks = fetch_all(&conn, "PRAGMA integrity_check", (), |row| col_text(row, 0)).await?; if checks != ["ok"] { return Err(Error::Invalid(format!( "database integrity check failed: {checks:?}" ))); } let versions = fetch_all( &conn, "SELECT version FROM schema_migrations ORDER BY version", (), |row| col_int(row, 0), ) .await?; let expected: Vec = MIGRATIONS.iter().map(|(v, _)| i64::from(*v)).collect(); if versions != expected { return Err(Error::Invalid(format!( "database migrations are {versions:?}, expected {expected:?}" ))); } Ok(()) } /// Restores the database and photos from `set`. Verifies the whole set first, then moves the current /// database (with its sidecar files) and photo directory into `data_dir/restore-/`, and puts the /// set's copies in their place. `database` must lie inside `data_dir`. pub async fn restore( data_dir: &Path, database: &Path, set: &Path, stamp: &str, key: &[u8; 32], ) -> Result { let data_dir = std::fs::canonicalize(data_dir)?; let parent = database .parent() .filter(|p| !p.as_os_str().is_empty()) .unwrap_or(Path::new(".")); if !std::fs::canonicalize(parent)?.starts_with(&data_dir) { return Err(Error::Config( "restore only replaces a database inside data_dir".into(), )); } let previous = data_dir.join(format!("restore-{stamp}")); if std::fs::symlink_metadata(&previous).is_ok() { return Err(Error::Conflict(format!( "{} already exists", previous.display() ))); } let scratch = data_dir.join(format!(".verify-{stamp}")); let manifest = verify_set(set, &scratch, key).await; let _ = std::fs::remove_dir_all(&scratch); let manifest = manifest?; private_dir(&previous)?; // The database moves aside with its sidecars; the set's copy is staged and then renamed in. let staged = previous.join("incoming.db"); std::fs::copy(set.join(DB_FILE), &staged)?; std::fs::set_permissions(&staged, std::fs::Permissions::from_mode(0o600))?; std::fs::File::open(&staged)?.sync_all()?; for suffix in ["", "-wal", "-shm"] { let mut from = database.as_os_str().to_owned(); from.push(suffix); let from = PathBuf::from(from); if std::fs::symlink_metadata(&from).is_ok() { let mut to = previous.join("database"); to.as_mut_os_string().push(suffix); std::fs::rename(&from, &to)?; } } std::fs::rename(&staged, database)?; let photos = data_dir.join(PHOTOS_DIR); if std::fs::symlink_metadata(&photos).is_ok() { std::fs::rename(&photos, previous.join(PHOTOS_DIR))?; } private_dir(&photos)?; for photo in &manifest.photos { let id = photo.name.trim_start_matches("photos/"); let target = photos.join(id); std::fs::copy(set.join(&photo.name), &target)?; std::fs::File::open(&target)?.sync_all()?; } std::fs::File::open(&data_dir)?.sync_all()?; Ok(RestoreOutcome { photos: manifest.photos.len(), previous, }) } #[cfg(test)] mod tests { use super::*; /// The instance key the test sets are written and checked with. const KEY: [u8; 32] = [9u8; 32]; /// A store with one user and one photo, written as a set under `dir`. async fn sample_set(dir: &Path) -> (Store, PathBuf) { let store = Store::open(&dir.join("im.db")).await.unwrap(); store .create_first_admin("ada@example.com", "Ada", "h") .await .unwrap(); std::fs::create_dir_all(dir.join(PHOTOS_DIR)).unwrap(); std::fs::write(dir.join(PHOTOS_DIR).join("01HZXAMPLEPHOTO"), b"png-bytes").unwrap(); let set = write_set( &store, dir, &dir.join("backups"), "2026-10-28T10-00-00", &KEY, ) .await .unwrap(); (store, set) } #[tokio::test] async fn a_good_set_restores_and_a_tampered_one_is_refused() { let dir = tempfile::tempdir().unwrap(); let data = dir.path().join("data"); std::fs::create_dir_all(&data).unwrap(); let (_store, set) = sample_set(&data).await; let scratch = data.join("scratch"); // A changed photo in the set makes the whole set refuse, and nothing is replaced. let photo = set.join(PHOTOS_DIR).join("01HZXAMPLEPHOTO"); std::fs::write(&photo, b"evil-bytes").unwrap(); assert!(verify_set(&set, &scratch, &KEY).await.is_err()); let refused = restore(&data, &data.join("im.db"), &set, "t1", &KEY).await; assert!(refused.is_err()); assert!(!data.join("restore-t1").exists()); // Put the original bytes back: the set verifies and restores. std::fs::write(&photo, b"png-bytes").unwrap(); let outcome = restore(&data, &data.join("im.db"), &set, "t2", &KEY) .await .unwrap(); assert_eq!(outcome.photos, 1); assert_eq!( std::fs::read(data.join(PHOTOS_DIR).join("01HZXAMPLEPHOTO")).unwrap(), b"png-bytes" ); } #[tokio::test] async fn a_set_is_refused_under_another_key_or_with_a_stray_photo_entry() { let dir = tempfile::tempdir().unwrap(); let data = dir.path().join("data"); std::fs::create_dir_all(&data).unwrap(); let (_store, set) = sample_set(&data).await; let scratch = data.join("scratch"); // The MAC is keyed: the same set does not verify under any other instance key. assert!(verify_set(&set, &scratch, &KEY).await.is_ok()); assert!(verify_set(&set, &scratch, &[1u8; 32]).await.is_err()); // A dot-file in photos/ is refused, even though every listed photo is still there. std::fs::write(set.join(PHOTOS_DIR).join(".stray"), b"x").unwrap(); assert!(verify_set(&set, &scratch, &KEY).await.is_err()); } #[tokio::test] async fn prune_touches_only_real_sets_with_a_manifest() { let dir = tempfile::tempdir().unwrap(); let root = dir.path(); for name in ["set-1", "set-2", "set-3"] { std::fs::create_dir_all(root.join(name)).unwrap(); std::fs::write(root.join(name).join(MANIFEST_FILE), b"{}").unwrap(); } std::fs::create_dir_all(root.join("notes")).unwrap(); assert_eq!(prune(root, 2).unwrap(), 1); assert!(!root.join("set-1").exists()); assert!(root.join("set-2").exists() && root.join("set-3").exists()); assert!(root.join("notes").exists()); } }