forge
Explore
Log in

Don't you dare go Hollow

in

Clone
★ 0

0 watching0 forksRustAGPL-3.0528.7 KiB9215377Tahinli27 days ago37 commits

backup.rs529 lines, 19.8 KiBHistoryRawDownload
1//! Backup sets and restore.
2//!
3//! A set is a directory `set-<stamp>` under the backup root, made of `in.db` (a consistent snapshot of the
4//! database, see `store/snapshot.rs`), `manifest.json` and `manifest.mac`. The manifest names the snapshot
5//! with its size and SHA-256, and lists every blob with its size and SHA-256. The MAC file holds an
6//! HMAC-SHA256 over the exact manifest bytes, keyed with a subkey of the instance key (`in.key`, which lives
7//! in the data directory, not in the backup set). Someone who can write to the backup directory can
8//! rewrite the snapshot and the manifest, but cannot make a changed manifest pass the MAC without the key.
9//! Blob bytes are not copied: the blob tree stays where it is, and the manifest is how a later check knows
10//! what should be there. A set is written under a temporary name and renamed into place only when its
11//! manifest and MAC are complete, so a half-written set is never mistaken for a good one.
12//!
13//! Restore verifies before it changes anything: the MAC first, in constant time, before the manifest is
14//! parsed or trusted; then the manifest format, the snapshot's size and hash, and the snapshot's
15//! `integrity_check` on a scratch copy. Only then does it move the current database aside (into
16//! `data_dir/restore-<stamp>/`, not deleted) and put the snapshot in its place. It only replaces a database
17//! that lies inside the data directory. Restore must run with the server stopped; the CLI takes the
18//! data-directory lock first.
19
20use std::fs::OpenOptions;
21use std::io::Write;
22use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt};
23use std::path::{Path, PathBuf};
24use std::sync::Arc;
25
26use hmac::{Hmac, KeyInit, Mac};
27use serde::{Deserialize, Serialize};
28use sha2::{Digest, Sha256};
29use subtle::ConstantTimeEq;
30use turso::Builder;
31
32use crate::blob::{self, BlobStore};
33use crate::error::{Error, Result};
34use crate::secret;
35use crate::store::{Store, col_text, db_err, fetch_all};
36
37/// The only manifest format this build reads and writes. Format 1 had no MAC, so it is refused.
38pub const FORMAT: u32 = 2;
39/// Name of the snapshot file inside a set.
40pub const DB_FILE: &str = "in.db";
41/// Name of the manifest file inside a set.
42pub const MANIFEST_FILE: &str = "manifest.json";
43/// Name of the MAC file inside a set: lower-case hex HMAC-SHA256 of the exact bytes of [`MANIFEST_FILE`].
44pub const MAC_FILE: &str = "manifest.mac";
45/// Label that derives the manifest MAC key from the instance key. Distinct from every other use of the
46/// instance key, so a MAC made for one purpose is never valid for another.
47const MAC_LABEL: &[u8] = b"in backup manifest v1";
48/// Prefix of a finished set's directory name. Pruning only ever removes directories with this prefix.
49pub const SET_PREFIX: &str = "set-";
50
51/// The snapshot entry of a manifest.
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53pub struct DbEntry {
54 /// File name inside the set. Always [`DB_FILE`].
55 pub file: String,
56 /// Size in bytes.
57 pub size: u64,
58 /// Lower-case hex SHA-256 of the file.
59 pub sha256: String,
60}
61
62/// One blob entry of a manifest.
63#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
64pub struct BlobRecord {
65 /// The blob key.
66 pub key: String,
67 /// Size in bytes.
68 pub size: u64,
69 /// Lower-case hex SHA-256 of the bytes.
70 pub sha256: String,
71}
72
73/// The manifest of a set.
74#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
75pub struct Manifest {
76 /// Format number; see [`FORMAT`].
77 pub format: u32,
78 /// When the set was written, UTC.
79 pub created_at: String,
80 /// The snapshot.
81 pub database: DbEntry,
82 /// Every blob that existed when the set was written.
83 pub blobs: Vec<BlobRecord>,
84}
85
86/// What a restore did.
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub struct RestoreOutcome {
89 /// Blobs the manifest lists.
90 pub blobs_listed: usize,
91 /// Blobs the manifest lists that are not in the blob tree now (for example, deleted after the set).
92 pub blobs_missing: usize,
93 /// Where the database it replaced was moved to, if there was one.
94 pub previous: Option<PathBuf>,
95}
96
97/// Creates a directory that only this user may enter.
98fn private_dir(path: &Path) -> Result<()> {
99 std::fs::DirBuilder::new()
100 .mode(0o700)
101 .create(path)
102 .map_err(Error::from)
103}
104
105/// The lower-case hex HMAC-SHA256 of `bytes` under the manifest subkey of `key`.
106fn manifest_mac(key: &[u8; 32], bytes: &[u8]) -> String {
107 let subkey = secret::derive_subkey(key, MAC_LABEL);
108 let mut mac = <Hmac<Sha256> as KeyInit>::new_from_slice(&subkey)
109 .expect("HMAC accepts a key of any length");
110 mac.update(bytes);
111 hex::encode(mac.finalize().into_bytes())
112}
113
114/// Writes a complete set under `root` and returns its directory. `stamp` names it, and must be safe in a
115/// file name: callers pass a time stamp with `:` and `.` replaced. `key` is the instance key that signs the
116/// manifest.
117pub async fn write_set(
118 store: &Store,
119 blobs: &dyn BlobStore,
120 root: &Path,
121 stamp: &str,
122 key: &[u8; 32],
123) -> Result<PathBuf> {
124 std::fs::create_dir_all(root)?;
125 let tmp = root.join(format!(".tmp-{stamp}"));
126 let final_dir = root.join(format!("{SET_PREFIX}{stamp}"));
127 if std::fs::symlink_metadata(&final_dir).is_ok() {
128 return Err(Error::Conflict(format!("set {stamp} already exists")));
129 }
130 private_dir(&tmp)?;
131 let outcome = write_into(store, blobs, &tmp, key).await;
132 match outcome {
133 Ok(()) => {
134 std::fs::rename(&tmp, &final_dir)?;
135 Ok(final_dir)
136 }
137 Err(error) => {
138 // A failed set is removed whole; it is ours, and it was never a complete set.
139 let _ = std::fs::remove_dir_all(&tmp);
140 Err(error)
141 }
142 }
143}
144
145/// Fills `dir` with the snapshot, the manifest and its MAC, then fsyncs the directory.
146async fn write_into(
147 store: &Store,
148 blobs: &dyn BlobStore,
149 dir: &Path,
150 key: &[u8; 32],
151) -> Result<()> {
152 let db_path = dir.join(DB_FILE);
153 store.snapshot_to(&db_path).await?;
154 let (db_size, db_sha) = file_digest(&db_path)?;
155 let mut records = Vec::new();
156 for (key, _, _) in blobs.list("").await? {
157 // A blob deleted between the listing and the read is not part of the set, so `None` is skipped.
158 if let Some((size, sha256)) = blob::digest(blobs, &key).await? {
159 records.push(BlobRecord { key, size, sha256 });
160 }
161 }
162 let manifest = Manifest {
163 format: FORMAT,
164 created_at: crate::time::now_stamp(),
165 database: DbEntry {
166 file: DB_FILE.to_owned(),
167 size: db_size,
168 sha256: db_sha,
169 },
170 blobs: records,
171 };
172 let text = serde_json::to_string_pretty(&manifest)
173 .map_err(|e| Error::Invalid(format!("manifest: {e}")))?;
174 write_private(&dir.join(MANIFEST_FILE), text.as_bytes())?;
175 write_private(
176 &dir.join(MAC_FILE),
177 manifest_mac(key, text.as_bytes()).as_bytes(),
178 )?;
179 std::fs::File::open(dir)?.sync_all()?;
180 Ok(())
181}
182
183/// Creates a new file that only this user may read, with `bytes`, and syncs it.
184fn write_private(path: &Path, bytes: &[u8]) -> Result<()> {
185 let mut file = OpenOptions::new()
186 .write(true)
187 .create_new(true)
188 .mode(0o600)
189 .open(path)?;
190 file.write_all(bytes)?;
191 file.sync_all()?;
192 Ok(())
193}
194
195/// Copies `from` to `to`, which must not exist, with mode 0600. A restored database is never readable by
196/// others, scratch copies included.
197fn copy_private(from: &Path, to: &Path) -> Result<()> {
198 let mut out = OpenOptions::new()
199 .write(true)
200 .create_new(true)
201 .mode(0o600)
202 .open(to)?;
203 std::io::copy(&mut std::fs::File::open(from)?, &mut out)?;
204 out.sync_all()?;
205 Ok(())
206}
207
208/// Size and SHA-256 of a file, read in chunks.
209fn file_digest(path: &Path) -> Result<(u64, String)> {
210 let mut file = std::fs::File::open(path)?;
211 let mut hasher = Sha256::new();
212 let mut size = 0u64;
213 let mut buf = vec![0u8; 1 << 20];
214 loop {
215 let n = std::io::Read::read(&mut file, &mut buf)?;
216 if n == 0 {
217 break;
218 }
219 size += n as u64;
220 hasher.update(&buf[..n]);
221 }
222 Ok((size, hex::encode(hasher.finalize())))
223}
224
225/// Removes the oldest sets under `root` until `keep` remain. Only real directories (not links) named
226/// `set-*` that hold a manifest file are touched, so a wrong `root` cannot cost unrelated data.
227/// Returns how many were removed.
228pub fn prune(root: &Path, keep: usize) -> Result<usize> {
229 let is_set = |p: &Path| {
230 let named = p
231 .file_name()
232 .and_then(|n| n.to_str())
233 .is_some_and(|n| n.starts_with(SET_PREFIX));
234 let real_dir = std::fs::symlink_metadata(p).is_ok_and(|m| m.file_type().is_dir());
235 let manifest =
236 std::fs::symlink_metadata(p.join(MANIFEST_FILE)).is_ok_and(|m| m.file_type().is_file());
237 named && real_dir && manifest
238 };
239 let mut sets: Vec<PathBuf> = match std::fs::read_dir(root) {
240 Ok(entries) => entries
241 .filter_map(|e| e.ok().map(|e| e.path()))
242 .filter(|p| is_set(p))
243 .collect(),
244 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(0),
245 Err(e) => return Err(e.into()),
246 };
247 // Names carry fixed-width UTC stamps, so name order is time order.
248 sets.sort();
249 let excess = sets.len().saturating_sub(keep);
250 for old in sets.iter().take(excess) {
251 std::fs::remove_dir_all(old)?;
252 }
253 Ok(excess)
254}
255
256/// Reads and checks the manifest of a set. The MAC is compared first, in constant time, against the bytes
257/// on disk; only a manifest that passes is parsed. Then it refuses a format it does not know or a snapshot
258/// name that is not [`DB_FILE`].
259pub fn read_manifest(set: &Path, key: &[u8; 32]) -> Result<Manifest> {
260 let bytes = std::fs::read(set.join(MANIFEST_FILE))
261 .map_err(|_| Error::Invalid("backup_manifest_missing".into()))?;
262 let stored = std::fs::read_to_string(set.join(MAC_FILE))
263 .map_err(|_| Error::Invalid("backup_mac_missing".into()))?;
264 let expected = manifest_mac(key, &bytes);
265 if !bool::from(expected.as_bytes().ct_eq(stored.trim().as_bytes())) {
266 return Err(Error::Invalid("backup_mac_bad".into()));
267 }
268 let manifest: Manifest =
269 serde_json::from_slice(&bytes).map_err(|_| Error::Invalid("backup_manifest_bad".into()))?;
270 if manifest.format != FORMAT || manifest.database.file != DB_FILE {
271 return Err(Error::Invalid("backup_manifest_bad".into()));
272 }
273 Ok(manifest)
274}
275
276/// Restores the database from `set` into `database`, which must lie inside `data_dir`. Verifies the
277/// manifest's MAC under `key`, then the manifest, the snapshot's size and hash, and its integrity before
278/// replacing anything. The previous database, with its sidecar files, is moved into
279/// `data_dir/restore-<stamp>/`. `open_blobs` is called only once the set has passed every check, so a
280/// refused restore never creates the blob tree; it is called before the database is replaced.
281pub async fn restore(
282 data_dir: &Path,
283 database: &Path,
284 set: &Path,
285 open_blobs: impl FnOnce() -> Result<Arc<dyn BlobStore>>,
286 key: &[u8; 32],
287 stamp: &str,
288) -> Result<RestoreOutcome> {
289 let manifest = read_manifest(set, key)?;
290 let source = set.join(DB_FILE);
291 let (size, sha256) =
292 file_digest(&source).map_err(|_| Error::Invalid("backup_snapshot_missing".into()))?;
293 if size != manifest.database.size || sha256 != manifest.database.sha256 {
294 return Err(Error::Invalid("backup_hash".into()));
295 }
296
297 let data_dir = std::fs::canonicalize(data_dir)?;
298 let parent = database
299 .parent()
300 .filter(|p| !p.as_os_str().is_empty())
301 .unwrap_or(Path::new("."));
302 let parent = std::fs::canonicalize(parent)?;
303 if !parent.starts_with(&data_dir) {
304 return Err(Error::Config(
305 "restore only replaces a database inside data_dir".into(),
306 ));
307 }
308
309 // The scratch copy lives in the data directory's temp area and is checked before it is used.
310 let scratch_dir = data_dir.join(crate::staging::TMP_DIR);
311 std::fs::create_dir_all(&scratch_dir)?;
312 let scratch = scratch_dir.join(format!("restore-{stamp}.db"));
313 copy_private(&source, &scratch)?;
314 crate::store::create_private_files(&scratch)?;
315 let check = integrity_of(&scratch).await;
316 remove_sidecars(&scratch)?;
317 std::fs::remove_file(&scratch)?;
318 match check? {
319 true => {}
320 false => return Err(Error::Invalid("backup_integrity".into())),
321 }
322 let blobs = open_blobs()?;
323
324 // Keep the database we replace: move it aside, then move the verified copy into place.
325 let previous = if database.exists() {
326 let keep_dir = data_dir.join(format!("restore-{stamp}"));
327 private_dir(&keep_dir)?;
328 let kept = keep_dir.join(DB_FILE);
329 std::fs::rename(database, &kept)?;
330 for suffix in ["-wal", "-shm"] {
331 let side = sidecar(database, suffix);
332 if side.exists() {
333 std::fs::rename(&side, sidecar(&kept, suffix))?;
334 }
335 }
336 Some(kept)
337 } else {
338 None
339 };
340 let staged = scratch_dir.join(format!("restore-{stamp}-final.db"));
341 copy_private(&source, &staged)?;
342 std::fs::rename(&staged, database)?;
343 std::fs::File::open(&parent)?.sync_all()?;
344
345 let mut missing = 0usize;
346 for record in &manifest.blobs {
347 if blobs.size(&record.key).await?.is_none() {
348 missing += 1;
349 }
350 }
351 Ok(RestoreOutcome {
352 blobs_listed: manifest.blobs.len(),
353 blobs_missing: missing,
354 previous,
355 })
356}
357
358/// Whether the database at `path` passes `PRAGMA integrity_check`. Opening it may create sidecar files,
359/// which the caller removes.
360async fn integrity_of(path: &Path) -> Result<bool> {
361 let text = path
362 .to_str()
363 .ok_or_else(|| Error::Config("scratch path is not UTF-8".into()))?;
364 let db = Builder::new_local(text).build().await.map_err(db_err)?;
365 let conn = db.connect().map_err(db_err)?;
366 let rows = fetch_all(&conn, "PRAGMA integrity_check", (), |row| col_text(row, 0)).await?;
367 Ok(rows == ["ok"])
368}
369
370/// The path of a database's `-wal` or `-shm` sidecar.
371fn sidecar(path: &Path, suffix: &str) -> PathBuf {
372 let mut name = path.as_os_str().to_owned();
373 name.push(suffix);
374 PathBuf::from(name)
375}
376
377/// Removes the sidecars of a scratch file that this module created.
378fn remove_sidecars(path: &Path) -> Result<()> {
379 for suffix in ["-wal", "-shm"] {
380 let side = sidecar(path, suffix);
381 if side.exists() {
382 std::fs::remove_file(side)?;
383 }
384 }
385 Ok(())
386}
387
388#[cfg(test)]
389mod tests {
390 use super::*;
391 use crate::blob::local::LocalBlobs;
392 use crate::store::test_support::store_with_member;
393
394 /// Stands in for the instance key in these tests.
395 const KEY: [u8; 32] = [9u8; 32];
396
397 /// Stands in for opening the blob tree in the refusal tests, which must never reach it.
398 fn never_opened() -> Result<Arc<dyn BlobStore>> {
399 unreachable!("a refused restore opens no blob tree")
400 }
401
402 /// Writes `manifest` into `set` and signs it with [`KEY`], as the writer would.
403 fn sign_manifest(set: &Path, manifest: &Manifest) {
404 let text = serde_json::to_string_pretty(manifest).unwrap();
405 std::fs::write(set.join(MANIFEST_FILE), &text).unwrap();
406 std::fs::write(set.join(MAC_FILE), manifest_mac(&KEY, text.as_bytes())).unwrap();
407 }
408
409 /// A store with one setting and one blob, a backup set of it, and the blob store.
410 async fn source_with_set() -> (tempfile::TempDir, Store, LocalBlobs, PathBuf) {
411 let (dir, store) = store_with_member("ann").await;
412 store.set_setting("probe", "kept").await.unwrap();
413 let blobs = LocalBlobs::new(dir.path().join("blobs")).unwrap();
414 let src = dir.path().join("src.bin");
415 std::fs::write(&src, b"bytes").unwrap();
416 blobs.put_file("files/ab/one", &src).await.unwrap();
417 let root = dir.path().join("backups");
418 let set = write_set(
419 &store,
420 &blobs,
421 &root,
422 "2026-10-28T00-00-00-000000000Z",
423 &KEY,
424 )
425 .await
426 .unwrap();
427 (dir, store, blobs, set)
428 }
429
430 #[tokio::test]
431 async fn restore_refuses_a_manifest_with_a_wrong_hash() {
432 let (dir, _store, _blobs, set) = source_with_set().await;
433 let mut manifest = read_manifest(&set, &KEY).unwrap();
434 manifest.database.sha256 = "0".repeat(64);
435 // Signed with the right key, so only the snapshot hash check can refuse it.
436 sign_manifest(&set, &manifest);
437
438 let data = dir.path().join("data");
439 std::fs::create_dir_all(&data).unwrap();
440 let database = data.join("in.db");
441 let refused = restore(
442 &data,
443 &database,
444 &set,
445 never_opened,
446 &KEY,
447 "20261028T000000Z",
448 )
449 .await;
450 assert!(matches!(refused, Err(Error::Invalid(ref w)) if w == "backup_hash"));
451 assert!(
452 !database.exists(),
453 "nothing is written when verification fails"
454 );
455 }
456
457 #[tokio::test]
458 async fn restore_refuses_a_manifest_changed_without_the_key() {
459 let (dir, _store, _blobs, set) = source_with_set().await;
460 // Someone with write access edits the manifest and fixes the snapshot hash, but cannot re-sign it.
461 let mut manifest = read_manifest(&set, &KEY).unwrap();
462 manifest.database.sha256 = "0".repeat(64);
463 std::fs::write(
464 set.join(MANIFEST_FILE),
465 serde_json::to_string_pretty(&manifest).unwrap(),
466 )
467 .unwrap();
468
469 let data = dir.path().join("data");
470 std::fs::create_dir_all(&data).unwrap();
471 let database = data.join("in.db");
472 let refused = restore(
473 &data,
474 &database,
475 &set,
476 never_opened,
477 &KEY,
478 "20261028T000002Z",
479 )
480 .await;
481 assert!(matches!(refused, Err(Error::Invalid(ref w)) if w == "backup_mac_bad"));
482 assert!(!database.exists());
483 assert!(
484 !data.join("blobs").exists(),
485 "a refused restore creates no blob tree"
486 );
487 }
488
489 #[tokio::test]
490 async fn restore_replaces_the_database_and_keeps_the_old_one() {
491 let (dir, store, blobs, set) = source_with_set().await;
492 drop(store);
493 let data = dir.path().join("data");
494 std::fs::create_dir_all(&data).unwrap();
495 let database = data.join("in.db");
496 std::fs::write(&database, b"not a database").unwrap();
497
498 let open = || Ok(Arc::new(blobs.clone()) as Arc<dyn BlobStore>);
499 let outcome = restore(&data, &database, &set, open, &KEY, "20261028T000001Z")
500 .await
501 .unwrap();
502 assert_eq!(outcome.blobs_listed, 1);
503 assert_eq!(outcome.blobs_missing, 0);
504 assert!(outcome.previous.unwrap().exists());
505 let restored = Store::open(&database).await.unwrap();
506 assert_eq!(
507 restored.get_setting("probe").await.unwrap().as_deref(),
508 Some("kept")
509 );
510 }
511
512 #[test]
513 fn prune_keeps_the_newest_sets_and_leaves_other_directories_alone() {
514 let dir = tempfile::tempdir().unwrap();
515 for stamp in ["a", "b", "c"] {
516 let set = dir.path().join(format!("{SET_PREFIX}{stamp}"));
517 std::fs::create_dir(&set).unwrap();
518 std::fs::write(set.join(MANIFEST_FILE), "{}").unwrap();
519 }
520 std::fs::create_dir(dir.path().join("keep-me")).unwrap();
521 // Named like a set but holding no manifest: not ours, never removed.
522 std::fs::create_dir(dir.path().join("set-0-not-a-backup")).unwrap();
523 assert_eq!(prune(dir.path(), 2).unwrap(), 1);
524 assert!(dir.path().join("set-0-not-a-backup").exists());
525 assert!(!dir.path().join("set-a").exists());
526 assert!(dir.path().join("set-c").exists());
527 assert!(dir.path().join("keep-me").exists());
528 }
529}