//! Backup sets and restore. //! //! A set is a directory `set-` under the backup root, made of `in.db` (a consistent snapshot of the //! database, see `store/snapshot.rs`), `manifest.json` and `manifest.mac`. The manifest names the snapshot //! with its size and SHA-256, and lists every blob with its size and SHA-256. The MAC file holds an //! HMAC-SHA256 over the exact manifest bytes, keyed with a subkey of the instance key (`in.key`, which lives //! in the data directory, not in the backup set). Someone who can write to the backup directory can //! rewrite the snapshot and the manifest, but cannot make a changed manifest pass the MAC without the key. //! Blob bytes are not copied: the blob tree stays where it is, and the manifest is how a later check knows //! what should be there. 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. //! //! Restore verifies before it changes anything: the MAC first, in constant time, before the manifest is //! parsed or trusted; then the manifest format, the snapshot's size and hash, and the snapshot's //! `integrity_check` on a scratch copy. Only then does it move the current database aside (into //! `data_dir/restore-/`, not deleted) and put the snapshot in its place. It only replaces a database //! that lies inside the data directory. Restore must run with the server stopped; the CLI takes the //! data-directory lock first. use std::fs::OpenOptions; use std::io::Write; use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; use std::path::{Path, PathBuf}; use std::sync::Arc; use hmac::{Hmac, KeyInit, Mac}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use subtle::ConstantTimeEq; use turso::Builder; use crate::blob::{self, BlobStore}; use crate::error::{Error, Result}; use crate::secret; use crate::store::{Store, col_text, db_err, fetch_all}; /// The only manifest format this build reads and writes. Format 1 had no MAC, so it is refused. pub const FORMAT: u32 = 2; /// Name of the snapshot file inside a set. pub const DB_FILE: &str = "in.db"; /// Name of the manifest file inside a set. pub const MANIFEST_FILE: &str = "manifest.json"; /// Name of the MAC file inside a set: lower-case hex HMAC-SHA256 of the exact bytes of [`MANIFEST_FILE`]. pub const MAC_FILE: &str = "manifest.mac"; /// Label that derives the manifest MAC key from the instance key. Distinct from every other use of the /// instance key, so a MAC made for one purpose is never valid for another. const MAC_LABEL: &[u8] = b"in backup manifest v1"; /// Prefix of a finished set's directory name. Pruning only ever removes directories with this prefix. pub const SET_PREFIX: &str = "set-"; /// The snapshot entry of a manifest. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct DbEntry { /// File name inside the set. Always [`DB_FILE`]. pub file: String, /// Size in bytes. pub size: u64, /// Lower-case hex SHA-256 of the file. pub sha256: String, } /// One blob entry of a manifest. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct BlobRecord { /// The blob key. pub key: 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: DbEntry, /// Every blob that existed when the set was written. pub blobs: Vec, } /// What a restore did. #[derive(Debug, Clone, PartialEq, Eq)] pub struct RestoreOutcome { /// Blobs the manifest lists. pub blobs_listed: usize, /// Blobs the manifest lists that are not in the blob tree now (for example, deleted after the set). pub blobs_missing: usize, /// Where the database it replaced was moved to, if there was one. pub previous: Option, } /// 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) } /// The lower-case hex HMAC-SHA256 of `bytes` under the manifest subkey of `key`. fn manifest_mac(key: &[u8; 32], bytes: &[u8]) -> String { let subkey = secret::derive_subkey(key, MAC_LABEL); let mut mac = as KeyInit>::new_from_slice(&subkey) .expect("HMAC accepts a key of any length"); mac.update(bytes); hex::encode(mac.finalize().into_bytes()) } /// Writes a complete set under `root` and returns its directory. `stamp` names it, and must be safe in a /// file name: callers pass a time stamp with `:` and `.` replaced. `key` is the instance key that signs the /// manifest. pub async fn write_set( store: &Store, blobs: &dyn BlobStore, 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)?; let outcome = write_into(store, blobs, &tmp, key).await; match outcome { Ok(()) => { std::fs::rename(&tmp, &final_dir)?; Ok(final_dir) } Err(error) => { // A failed set is removed whole; it is ours, and it was never a complete set. let _ = std::fs::remove_dir_all(&tmp); Err(error) } } } /// Fills `dir` with the snapshot, the manifest and its MAC, then fsyncs the directory. async fn write_into( store: &Store, blobs: &dyn BlobStore, dir: &Path, key: &[u8; 32], ) -> Result<()> { let db_path = dir.join(DB_FILE); store.snapshot_to(&db_path).await?; let (db_size, db_sha) = file_digest(&db_path)?; let mut records = Vec::new(); for (key, _, _) in blobs.list("").await? { // A blob deleted between the listing and the read is not part of the set, so `None` is skipped. if let Some((size, sha256)) = blob::digest(blobs, &key).await? { records.push(BlobRecord { key, size, sha256 }); } } let manifest = Manifest { format: FORMAT, created_at: crate::time::now_stamp(), database: DbEntry { file: DB_FILE.to_owned(), size: db_size, sha256: db_sha, }, blobs: records, }; let text = serde_json::to_string_pretty(&manifest) .map_err(|e| Error::Invalid(format!("manifest: {e}")))?; write_private(&dir.join(MANIFEST_FILE), text.as_bytes())?; write_private( &dir.join(MAC_FILE), manifest_mac(key, text.as_bytes()).as_bytes(), )?; std::fs::File::open(dir)?.sync_all()?; Ok(()) } /// Creates a new file that only this user may read, with `bytes`, and syncs it. fn write_private(path: &Path, bytes: &[u8]) -> Result<()> { let mut file = OpenOptions::new() .write(true) .create_new(true) .mode(0o600) .open(path)?; file.write_all(bytes)?; file.sync_all()?; Ok(()) } /// Copies `from` to `to`, which must not exist, with mode 0600. A restored database is never readable by /// others, scratch copies included. fn copy_private(from: &Path, to: &Path) -> Result<()> { let mut out = OpenOptions::new() .write(true) .create_new(true) .mode(0o600) .open(to)?; std::io::copy(&mut std::fs::File::open(from)?, &mut out)?; out.sync_all()?; Ok(()) } /// 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 = std::io::Read::read(&mut file, &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 and checks the manifest of a set. The MAC is compared first, in constant time, against the bytes /// on disk; only a manifest that passes is parsed. Then it refuses a format it does not know or a snapshot /// name that is not [`DB_FILE`]. pub fn read_manifest(set: &Path, key: &[u8; 32]) -> Result { let bytes = std::fs::read(set.join(MANIFEST_FILE)) .map_err(|_| Error::Invalid("backup_manifest_missing".into()))?; let stored = std::fs::read_to_string(set.join(MAC_FILE)) .map_err(|_| Error::Invalid("backup_mac_missing".into()))?; let expected = manifest_mac(key, &bytes); if !bool::from(expected.as_bytes().ct_eq(stored.trim().as_bytes())) { return Err(Error::Invalid("backup_mac_bad".into())); } let manifest: Manifest = serde_json::from_slice(&bytes).map_err(|_| Error::Invalid("backup_manifest_bad".into()))?; if manifest.format != FORMAT || manifest.database.file != DB_FILE { return Err(Error::Invalid("backup_manifest_bad".into())); } Ok(manifest) } /// Restores the database from `set` into `database`, which must lie inside `data_dir`. Verifies the /// manifest's MAC under `key`, then the manifest, the snapshot's size and hash, and its integrity before /// replacing anything. The previous database, with its sidecar files, is moved into /// `data_dir/restore-/`. `open_blobs` is called only once the set has passed every check, so a /// refused restore never creates the blob tree; it is called before the database is replaced. pub async fn restore( data_dir: &Path, database: &Path, set: &Path, open_blobs: impl FnOnce() -> Result>, key: &[u8; 32], stamp: &str, ) -> Result { let manifest = read_manifest(set, key)?; let source = set.join(DB_FILE); let (size, sha256) = file_digest(&source).map_err(|_| Error::Invalid("backup_snapshot_missing".into()))?; if size != manifest.database.size || sha256 != manifest.database.sha256 { return Err(Error::Invalid("backup_hash".into())); } let data_dir = std::fs::canonicalize(data_dir)?; let parent = database .parent() .filter(|p| !p.as_os_str().is_empty()) .unwrap_or(Path::new(".")); let parent = std::fs::canonicalize(parent)?; if !parent.starts_with(&data_dir) { return Err(Error::Config( "restore only replaces a database inside data_dir".into(), )); } // The scratch copy lives in the data directory's temp area and is checked before it is used. let scratch_dir = data_dir.join(crate::staging::TMP_DIR); std::fs::create_dir_all(&scratch_dir)?; let scratch = scratch_dir.join(format!("restore-{stamp}.db")); copy_private(&source, &scratch)?; crate::store::create_private_files(&scratch)?; let check = integrity_of(&scratch).await; remove_sidecars(&scratch)?; std::fs::remove_file(&scratch)?; match check? { true => {} false => return Err(Error::Invalid("backup_integrity".into())), } let blobs = open_blobs()?; // Keep the database we replace: move it aside, then move the verified copy into place. let previous = if database.exists() { let keep_dir = data_dir.join(format!("restore-{stamp}")); private_dir(&keep_dir)?; let kept = keep_dir.join(DB_FILE); std::fs::rename(database, &kept)?; for suffix in ["-wal", "-shm"] { let side = sidecar(database, suffix); if side.exists() { std::fs::rename(&side, sidecar(&kept, suffix))?; } } Some(kept) } else { None }; let staged = scratch_dir.join(format!("restore-{stamp}-final.db")); copy_private(&source, &staged)?; std::fs::rename(&staged, database)?; std::fs::File::open(&parent)?.sync_all()?; let mut missing = 0usize; for record in &manifest.blobs { if blobs.size(&record.key).await?.is_none() { missing += 1; } } Ok(RestoreOutcome { blobs_listed: manifest.blobs.len(), blobs_missing: missing, previous, }) } /// Whether the database at `path` passes `PRAGMA integrity_check`. Opening it may create sidecar files, /// which the caller removes. async fn integrity_of(path: &Path) -> Result { let text = path .to_str() .ok_or_else(|| Error::Config("scratch 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 rows = fetch_all(&conn, "PRAGMA integrity_check", (), |row| col_text(row, 0)).await?; Ok(rows == ["ok"]) } /// The path of a database's `-wal` or `-shm` sidecar. fn sidecar(path: &Path, suffix: &str) -> PathBuf { let mut name = path.as_os_str().to_owned(); name.push(suffix); PathBuf::from(name) } /// Removes the sidecars of a scratch file that this module created. fn remove_sidecars(path: &Path) -> Result<()> { for suffix in ["-wal", "-shm"] { let side = sidecar(path, suffix); if side.exists() { std::fs::remove_file(side)?; } } Ok(()) } #[cfg(test)] mod tests { use super::*; use crate::blob::local::LocalBlobs; use crate::store::test_support::store_with_member; /// Stands in for the instance key in these tests. const KEY: [u8; 32] = [9u8; 32]; /// Stands in for opening the blob tree in the refusal tests, which must never reach it. fn never_opened() -> Result> { unreachable!("a refused restore opens no blob tree") } /// Writes `manifest` into `set` and signs it with [`KEY`], as the writer would. fn sign_manifest(set: &Path, manifest: &Manifest) { let text = serde_json::to_string_pretty(manifest).unwrap(); std::fs::write(set.join(MANIFEST_FILE), &text).unwrap(); std::fs::write(set.join(MAC_FILE), manifest_mac(&KEY, text.as_bytes())).unwrap(); } /// A store with one setting and one blob, a backup set of it, and the blob store. async fn source_with_set() -> (tempfile::TempDir, Store, LocalBlobs, PathBuf) { let (dir, store) = store_with_member("ann").await; store.set_setting("probe", "kept").await.unwrap(); let blobs = LocalBlobs::new(dir.path().join("blobs")).unwrap(); let src = dir.path().join("src.bin"); std::fs::write(&src, b"bytes").unwrap(); blobs.put_file("files/ab/one", &src).await.unwrap(); let root = dir.path().join("backups"); let set = write_set( &store, &blobs, &root, "2026-10-28T00-00-00-000000000Z", &KEY, ) .await .unwrap(); (dir, store, blobs, set) } #[tokio::test] async fn restore_refuses_a_manifest_with_a_wrong_hash() { let (dir, _store, _blobs, set) = source_with_set().await; let mut manifest = read_manifest(&set, &KEY).unwrap(); manifest.database.sha256 = "0".repeat(64); // Signed with the right key, so only the snapshot hash check can refuse it. sign_manifest(&set, &manifest); let data = dir.path().join("data"); std::fs::create_dir_all(&data).unwrap(); let database = data.join("in.db"); let refused = restore( &data, &database, &set, never_opened, &KEY, "20261028T000000Z", ) .await; assert!(matches!(refused, Err(Error::Invalid(ref w)) if w == "backup_hash")); assert!( !database.exists(), "nothing is written when verification fails" ); } #[tokio::test] async fn restore_refuses_a_manifest_changed_without_the_key() { let (dir, _store, _blobs, set) = source_with_set().await; // Someone with write access edits the manifest and fixes the snapshot hash, but cannot re-sign it. let mut manifest = read_manifest(&set, &KEY).unwrap(); manifest.database.sha256 = "0".repeat(64); std::fs::write( set.join(MANIFEST_FILE), serde_json::to_string_pretty(&manifest).unwrap(), ) .unwrap(); let data = dir.path().join("data"); std::fs::create_dir_all(&data).unwrap(); let database = data.join("in.db"); let refused = restore( &data, &database, &set, never_opened, &KEY, "20261028T000002Z", ) .await; assert!(matches!(refused, Err(Error::Invalid(ref w)) if w == "backup_mac_bad")); assert!(!database.exists()); assert!( !data.join("blobs").exists(), "a refused restore creates no blob tree" ); } #[tokio::test] async fn restore_replaces_the_database_and_keeps_the_old_one() { let (dir, store, blobs, set) = source_with_set().await; drop(store); let data = dir.path().join("data"); std::fs::create_dir_all(&data).unwrap(); let database = data.join("in.db"); std::fs::write(&database, b"not a database").unwrap(); let open = || Ok(Arc::new(blobs.clone()) as Arc); let outcome = restore(&data, &database, &set, open, &KEY, "20261028T000001Z") .await .unwrap(); assert_eq!(outcome.blobs_listed, 1); assert_eq!(outcome.blobs_missing, 0); assert!(outcome.previous.unwrap().exists()); let restored = Store::open(&database).await.unwrap(); assert_eq!( restored.get_setting("probe").await.unwrap().as_deref(), Some("kept") ); } #[test] fn prune_keeps_the_newest_sets_and_leaves_other_directories_alone() { let dir = tempfile::tempdir().unwrap(); for stamp in ["a", "b", "c"] { let set = dir.path().join(format!("{SET_PREFIX}{stamp}")); std::fs::create_dir(&set).unwrap(); std::fs::write(set.join(MANIFEST_FILE), "{}").unwrap(); } std::fs::create_dir(dir.path().join("keep-me")).unwrap(); // Named like a set but holding no manifest: not ours, never removed. std::fs::create_dir(dir.path().join("set-0-not-a-backup")).unwrap(); assert_eq!(prune(dir.path(), 2).unwrap(), 1); assert!(dir.path().join("set-0-not-a-backup").exists()); assert!(!dir.path().join("set-a").exists()); assert!(dir.path().join("set-c").exists()); assert!(dir.path().join("keep-me").exists()); } }