forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

backup.rs581 lines, 22.7 KiBHistoryRawDownload
1//! Backup sets, verification, pruning and restore.
2//!
3//! A set is a directory `set-<stamp>` under the backup root. It holds `im.db` (a consistent snapshot of the
4//! database, see `store/snapshot.rs`), a `photos/` directory with a copy of every profile photo,
5//! `manifest.json`, and `manifest.mac`. The manifest names every file with its size and SHA-256. The MAC is
6//! HMAC-SHA256 over the exact manifest bytes, keyed with a subkey of the instance key, so a manifest cannot be
7//! rewritten to match changed files. A set is written under a temporary name and renamed into place only when
8//! its manifest and MAC are complete, so a half-written set is never mistaken for a good one.
9//!
10//! Verification checks the MAC first, in constant time, and reads nothing else from the manifest until it
11//! passes. Then it checks every hash, refuses a file the manifest does not list, refuses any entry in `photos/`
12//! that is not a photo name (see `photo::is_photo_name`) or not a regular file, and runs `PRAGMA
13//! integrity_check` and the migration check on a scratch copy, so the set itself is never written to. Restore
14//! verifies first and changes nothing when verification fails. It only replaces a database and a photo
15//! directory that lie inside the data directory, and it moves what it replaces into `data_dir/restore-<stamp>/`
16//! rather than deleting it. The caller must hold the data-directory lock: a running server is never restored
17//! under.
18
19use std::fs::OpenOptions;
20use std::io::{Read, Write};
21use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt};
22use std::path::{Path, PathBuf};
23
24use hmac::{Hmac, KeyInit, Mac};
25use serde::{Deserialize, Serialize};
26use sha2::{Digest, Sha256};
27use turso::Builder;
28
29use crate::error::{Error, Result};
30use crate::photo::is_photo_name;
31use crate::secret;
32use crate::store::migrate::MIGRATIONS;
33use crate::store::{Store, col_int, col_text, db_err, fetch_all};
34
35type HmacSha256 = Hmac<Sha256>;
36
37/// The only manifest format this build reads and writes.
38pub const FORMAT: u32 = 1;
39/// Name of the snapshot inside a set.
40pub const DB_FILE: &str = "im.db";
41/// Name of the manifest inside a set.
42pub const MANIFEST_FILE: &str = "manifest.json";
43/// Name of the manifest's MAC inside a set: lower-case hex HMAC-SHA256 of the manifest bytes.
44pub const MAC_FILE: &str = "manifest.mac";
45/// Label of the manifest MAC subkey. The subkey is `secret::derive` of this label under the instance key, the
46/// same way recovery codes get theirs; the MAC itself is keyed with that subkey, never with the instance key.
47const MAC_SUBKEY_LABEL: &[u8] = b"im backup manifest v1";
48/// Name of the photo directory inside a set, and beside the database in the data directory.
49pub const PHOTOS_DIR: &str = "photos";
50/// Prefix of a finished set's directory name. Pruning only ever removes directories with this prefix.
51pub const SET_PREFIX: &str = "set-";
52
53/// One file of a set: its name relative to the set, its size and its SHA-256 in lower-case hex.
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
55pub struct FileEntry {
56 /// `im.db`, or `photos/<user id>`.
57 pub name: String,
58 /// Size in bytes.
59 pub size: u64,
60 /// Lower-case hex SHA-256 of the bytes.
61 pub sha256: String,
62}
63
64/// The manifest of a set.
65#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
66pub struct Manifest {
67 /// Format number; see [`FORMAT`].
68 pub format: u32,
69 /// When the set was written, UTC.
70 pub created_at: String,
71 /// The snapshot.
72 pub database: FileEntry,
73 /// Every photo that existed when the set was written.
74 pub photos: Vec<FileEntry>,
75}
76
77/// What a restore did.
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct RestoreOutcome {
80 /// Photos put back.
81 pub photos: usize,
82 /// The directory that holds the database and photos that were replaced.
83 pub previous: PathBuf,
84}
85
86/// The HMAC over `bytes` under the manifest subkey of the instance key `key`. Its `verify_slice` is constant
87/// time, and its `finalize` gives the tag that is written to [`MAC_FILE`].
88fn manifest_mac(key: &[u8; 32], bytes: &[u8]) -> HmacSha256 {
89 let subkey = secret::derive(key, MAC_SUBKEY_LABEL);
90 // HMAC accepts a key of any length, so construction cannot fail.
91 let mut mac =
92 <HmacSha256 as KeyInit>::new_from_slice(&subkey).expect("HMAC takes any key length");
93 mac.update(bytes);
94 mac
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/// Creates a file that only this user may read, failing if it exists.
106fn private_file(path: &Path) -> Result<std::fs::File> {
107 OpenOptions::new()
108 .write(true)
109 .create_new(true)
110 .mode(0o600)
111 .open(path)
112 .map_err(Error::from)
113}
114
115/// Writes a complete set under `root` and returns its directory. `stamp` names it and must be safe in a
116/// file name: callers replace `:` and `.` in the time stamp. `key` is the instance key that keys the manifest
117/// MAC.
118pub async fn write_set(
119 store: &Store,
120 data_dir: &Path,
121 root: &Path,
122 stamp: &str,
123 key: &[u8; 32],
124) -> Result<PathBuf> {
125 std::fs::create_dir_all(root)?;
126 let tmp = root.join(format!(".tmp-{stamp}"));
127 let final_dir = root.join(format!("{SET_PREFIX}{stamp}"));
128 if std::fs::symlink_metadata(&final_dir).is_ok() {
129 return Err(Error::Conflict(format!("set {stamp} already exists")));
130 }
131 private_dir(&tmp)?;
132 match write_into(store, data_dir, &tmp, key).await {
133 Ok(()) => {
134 std::fs::rename(&tmp, &final_dir)?;
135 Ok(final_dir)
136 }
137 Err(error) => {
138 // A failed set was never complete. It is ours, so it is removed whole.
139 let _ = std::fs::remove_dir_all(&tmp);
140 Err(error)
141 }
142 }
143}
144
145/// Fills `dir` with the snapshot, the photos, the manifest and its MAC, then fsyncs the directory.
146async fn write_into(store: &Store, data_dir: &Path, dir: &Path, key: &[u8; 32]) -> Result<()> {
147 let db_path = dir.join(DB_FILE);
148 store.snapshot_to(&db_path).await?;
149 // The snapshot holds every row, so it is private like the live database.
150 std::fs::set_permissions(&db_path, std::fs::Permissions::from_mode(0o600))?;
151 let database = file_entry(DB_FILE, &db_path)?;
152
153 let photos_out = dir.join(PHOTOS_DIR);
154 private_dir(&photos_out)?;
155 let mut photos = Vec::new();
156 let photos_in = data_dir.join(PHOTOS_DIR);
157 if std::fs::symlink_metadata(&photos_in).is_ok() {
158 for name in photo_names(&photos_in)? {
159 let source = photos_in.join(&name);
160 let target = photos_out.join(&name);
161 let mut out = private_file(&target)?;
162 let mut input = std::fs::File::open(&source)?;
163 std::io::copy(&mut input, &mut out)?;
164 out.sync_all()?;
165 photos.push(file_entry(&format!("{PHOTOS_DIR}/{name}"), &target)?);
166 }
167 }
168
169 let manifest = Manifest {
170 format: FORMAT,
171 created_at: crate::time::now_stamp(),
172 database,
173 photos,
174 };
175 let text = serde_json::to_string_pretty(&manifest)
176 .map_err(|e| Error::Invalid(format!("manifest: {e}")))?;
177 let mut file = private_file(&dir.join(MANIFEST_FILE))?;
178 file.write_all(text.as_bytes())?;
179 file.sync_all()?;
180 // The MAC is written after the manifest it covers, so a set with a MAC always has its manifest.
181 let tag = hex::encode(manifest_mac(key, text.as_bytes()).finalize().into_bytes());
182 let mut mac_file = private_file(&dir.join(MAC_FILE))?;
183 mac_file.write_all(tag.as_bytes())?;
184 mac_file.sync_all()?;
185 std::fs::File::open(&photos_out)?.sync_all()?;
186 std::fs::File::open(dir)?.sync_all()?;
187 Ok(())
188}
189
190/// The names of the photo files directly in `dir` when copying from the data directory. Links,
191/// sub-directories and any name that is not a photo name are skipped, so only real photos are backed up.
192fn photo_names(dir: &Path) -> Result<Vec<String>> {
193 let mut names = Vec::new();
194 for entry in std::fs::read_dir(dir)? {
195 let entry = entry?;
196 let meta = std::fs::symlink_metadata(entry.path())?;
197 if meta.file_type().is_file()
198 && let Some(name) = entry.file_name().to_str()
199 && is_photo_name(name)
200 {
201 names.push(name.to_owned());
202 }
203 }
204 names.sort();
205 Ok(names)
206}
207
208/// Reads a file that must be a regular file, not a link. Returns its bytes.
209fn read_regular(path: &Path) -> Result<Vec<u8>> {
210 if !std::fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_file()) {
211 return Err(Error::Invalid(format!(
212 "{} is not a regular file",
213 path.display()
214 )));
215 }
216 Ok(std::fs::read(path)?)
217}
218
219/// Size and SHA-256 of a file, read in chunks.
220fn file_entry(name: &str, path: &Path) -> Result<FileEntry> {
221 let (size, sha256) = file_digest(path)?;
222 Ok(FileEntry {
223 name: name.to_owned(),
224 size,
225 sha256,
226 })
227}
228
229/// Size and SHA-256 of a file, read in chunks.
230fn file_digest(path: &Path) -> Result<(u64, String)> {
231 let mut file = std::fs::File::open(path)?;
232 let mut hasher = Sha256::new();
233 let mut size = 0u64;
234 let mut buf = vec![0u8; 1 << 20];
235 loop {
236 let n = file.read(&mut buf)?;
237 if n == 0 {
238 break;
239 }
240 size += n as u64;
241 hasher.update(&buf[..n]);
242 }
243 Ok((size, hex::encode(hasher.finalize())))
244}
245
246/// Removes the oldest sets under `root` until `keep` remain. Only real directories (not links) named
247/// `set-*` that hold a manifest file are touched, so a wrong `root` cannot cost unrelated data. Returns
248/// how many were removed.
249pub fn prune(root: &Path, keep: usize) -> Result<usize> {
250 let is_set = |p: &Path| {
251 let named = p
252 .file_name()
253 .and_then(|n| n.to_str())
254 .is_some_and(|n| n.starts_with(SET_PREFIX));
255 let real_dir = std::fs::symlink_metadata(p).is_ok_and(|m| m.file_type().is_dir());
256 let manifest =
257 std::fs::symlink_metadata(p.join(MANIFEST_FILE)).is_ok_and(|m| m.file_type().is_file());
258 named && real_dir && manifest
259 };
260 let mut sets: Vec<PathBuf> = match std::fs::read_dir(root) {
261 Ok(entries) => entries
262 .filter_map(|e| e.ok().map(|e| e.path()))
263 .filter(|p| is_set(p))
264 .collect(),
265 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(0),
266 Err(e) => return Err(e.into()),
267 };
268 // Names carry fixed-width UTC stamps, so name order is time order.
269 sets.sort();
270 let excess = sets.len().saturating_sub(keep);
271 for old in sets.iter().take(excess) {
272 std::fs::remove_dir_all(old)?;
273 }
274 Ok(excess)
275}
276
277/// Reads a manifest, checking its MAC first. The MAC is compared in constant time over the exact bytes of
278/// `manifest.json`, and nothing in the manifest is parsed or trusted until it passes. Then the manifest must
279/// parse, be the known format, and name the snapshot `im.db`.
280pub fn read_manifest(set: &Path, key: &[u8; 32]) -> Result<Manifest> {
281 let bytes = read_regular(&set.join(MANIFEST_FILE))
282 .map_err(|_| Error::Invalid("backup manifest is missing".into()))?;
283 let tag = read_regular(&set.join(MAC_FILE))
284 .map_err(|_| Error::Invalid("backup manifest has no MAC".into()))?;
285 let tag = hex::decode(String::from_utf8_lossy(&tag).trim())
286 .map_err(|_| Error::Invalid("backup manifest MAC is not valid".into()))?;
287 manifest_mac(key, &bytes)
288 .verify_slice(&tag)
289 .map_err(|_| Error::Invalid("backup manifest does not match its MAC".into()))?;
290 let manifest: Manifest = serde_json::from_slice(&bytes)
291 .map_err(|_| Error::Invalid("backup manifest is not valid".into()))?;
292 if manifest.format != FORMAT || manifest.database.name != DB_FILE {
293 return Err(Error::Invalid("backup manifest is not valid".into()));
294 }
295 Ok(manifest)
296}
297
298/// Checks a set without changing it: the manifest MAC, every listed file matches its hash, no file is missing
299/// or unlisted, every entry in `photos/` is a regular file with a photo name, and the snapshot passes
300/// `PRAGMA integrity_check` with contiguous migrations. The snapshot is checked on a copy in `scratch`, so
301/// opening it cannot write WAL files into the set.
302pub async fn verify_set(set: &Path, scratch: &Path, key: &[u8; 32]) -> Result<Manifest> {
303 let manifest = read_manifest(set, key)?;
304 check_entry(set, &manifest.database)?;
305 let mut listed = Vec::new();
306 for photo in &manifest.photos {
307 let Some(id) = photo.name.strip_prefix("photos/") else {
308 return Err(Error::Invalid(
309 "backup manifest names a file outside photos".into(),
310 ));
311 };
312 if !is_photo_name(id) {
313 return Err(Error::Invalid("backup manifest names an odd file".into()));
314 }
315 check_entry(set, photo)?;
316 listed.push(id.to_owned());
317 }
318 // Nothing may be in the set that the manifest does not name. Every entry of photos/ is checked, not
319 // only the ones that look like photos: a stray name, a dot-file or a link is a refusal.
320 let photos_dir = set.join(PHOTOS_DIR);
321 // The manifest, its MAC and the snapshot, plus the photo directory when there is one.
322 let mut expected = 3;
323 if std::fs::symlink_metadata(&photos_dir).is_ok() {
324 if !std::fs::symlink_metadata(&photos_dir)?.file_type().is_dir() {
325 return Err(Error::Invalid("backup photos is not a directory".into()));
326 }
327 expected += 1;
328 let mut found = Vec::new();
329 for entry in std::fs::read_dir(&photos_dir)? {
330 let entry = entry?;
331 let name = entry
332 .file_name()
333 .into_string()
334 .map_err(|_| Error::Invalid("backup photos hold an odd file name".into()))?;
335 if !is_photo_name(&name) {
336 return Err(Error::Invalid(
337 "backup photos hold a file that is not a photo".into(),
338 ));
339 }
340 if !std::fs::symlink_metadata(entry.path())?
341 .file_type()
342 .is_file()
343 {
344 return Err(Error::Invalid(
345 "backup photos hold a file that is not a regular file".into(),
346 ));
347 }
348 found.push(name);
349 }
350 listed.sort();
351 found.sort();
352 if found != listed {
353 return Err(Error::Invalid(
354 "backup photos do not match its manifest".into(),
355 ));
356 }
357 }
358 let on_disk = std::fs::read_dir(set)?.count();
359 if on_disk != expected {
360 return Err(Error::Invalid(
361 "backup set holds files its manifest does not list".into(),
362 ));
363 }
364 std::fs::create_dir_all(scratch)?;
365 let copy = scratch.join("verify.db");
366 std::fs::copy(set.join(DB_FILE), &copy)?;
367 let checked = check_database(&copy).await;
368 for suffix in ["", "-wal", "-shm"] {
369 let _ = std::fs::remove_file(format!("{}{suffix}", copy.display()));
370 }
371 checked?;
372 Ok(manifest)
373}
374
375/// Checks one listed file against its size and hash.
376fn check_entry(set: &Path, entry: &FileEntry) -> Result<()> {
377 let path = set.join(&entry.name);
378 let meta = std::fs::symlink_metadata(&path)
379 .map_err(|_| Error::Invalid(format!("backup file {} is missing", entry.name)))?;
380 if !meta.file_type().is_file() {
381 return Err(Error::Invalid(format!(
382 "backup file {} is not a file",
383 entry.name
384 )));
385 }
386 let (size, sha256) = file_digest(&path)?;
387 if size != entry.size || sha256 != entry.sha256 {
388 return Err(Error::Invalid(format!(
389 "backup file {} does not match its manifest",
390 entry.name
391 )));
392 }
393 Ok(())
394}
395
396/// Runs `PRAGMA integrity_check` on the database at `path` and checks that the recorded migrations are
397/// exactly `1..=N` for the N this build knows.
398pub async fn check_database(path: &Path) -> Result<()> {
399 let text = path
400 .to_str()
401 .ok_or_else(|| Error::Config("database path is not UTF-8".into()))?;
402 let db = Builder::new_local(text).build().await.map_err(db_err)?;
403 let conn = db.connect().map_err(db_err)?;
404 let checks = fetch_all(&conn, "PRAGMA integrity_check", (), |row| col_text(row, 0)).await?;
405 if checks != ["ok"] {
406 return Err(Error::Invalid(format!(
407 "database integrity check failed: {checks:?}"
408 )));
409 }
410 let versions = fetch_all(
411 &conn,
412 "SELECT version FROM schema_migrations ORDER BY version",
413 (),
414 |row| col_int(row, 0),
415 )
416 .await?;
417 let expected: Vec<i64> = MIGRATIONS.iter().map(|(v, _)| i64::from(*v)).collect();
418 if versions != expected {
419 return Err(Error::Invalid(format!(
420 "database migrations are {versions:?}, expected {expected:?}"
421 )));
422 }
423 Ok(())
424}
425
426/// Restores the database and photos from `set`. Verifies the whole set first, then moves the current
427/// database (with its sidecar files) and photo directory into `data_dir/restore-<stamp>/`, and puts the
428/// set's copies in their place. `database` must lie inside `data_dir`.
429pub async fn restore(
430 data_dir: &Path,
431 database: &Path,
432 set: &Path,
433 stamp: &str,
434 key: &[u8; 32],
435) -> Result<RestoreOutcome> {
436 let data_dir = std::fs::canonicalize(data_dir)?;
437 let parent = database
438 .parent()
439 .filter(|p| !p.as_os_str().is_empty())
440 .unwrap_or(Path::new("."));
441 if !std::fs::canonicalize(parent)?.starts_with(&data_dir) {
442 return Err(Error::Config(
443 "restore only replaces a database inside data_dir".into(),
444 ));
445 }
446 let previous = data_dir.join(format!("restore-{stamp}"));
447 if std::fs::symlink_metadata(&previous).is_ok() {
448 return Err(Error::Conflict(format!(
449 "{} already exists",
450 previous.display()
451 )));
452 }
453 let scratch = data_dir.join(format!(".verify-{stamp}"));
454 let manifest = verify_set(set, &scratch, key).await;
455 let _ = std::fs::remove_dir_all(&scratch);
456 let manifest = manifest?;
457
458 private_dir(&previous)?;
459 // The database moves aside with its sidecars; the set's copy is staged and then renamed in.
460 let staged = previous.join("incoming.db");
461 std::fs::copy(set.join(DB_FILE), &staged)?;
462 std::fs::set_permissions(&staged, std::fs::Permissions::from_mode(0o600))?;
463 std::fs::File::open(&staged)?.sync_all()?;
464 for suffix in ["", "-wal", "-shm"] {
465 let mut from = database.as_os_str().to_owned();
466 from.push(suffix);
467 let from = PathBuf::from(from);
468 if std::fs::symlink_metadata(&from).is_ok() {
469 let mut to = previous.join("database");
470 to.as_mut_os_string().push(suffix);
471 std::fs::rename(&from, &to)?;
472 }
473 }
474 std::fs::rename(&staged, database)?;
475
476 let photos = data_dir.join(PHOTOS_DIR);
477 if std::fs::symlink_metadata(&photos).is_ok() {
478 std::fs::rename(&photos, previous.join(PHOTOS_DIR))?;
479 }
480 private_dir(&photos)?;
481 for photo in &manifest.photos {
482 let id = photo.name.trim_start_matches("photos/");
483 let target = photos.join(id);
484 std::fs::copy(set.join(&photo.name), &target)?;
485 std::fs::File::open(&target)?.sync_all()?;
486 }
487 std::fs::File::open(&data_dir)?.sync_all()?;
488 Ok(RestoreOutcome {
489 photos: manifest.photos.len(),
490 previous,
491 })
492}
493
494#[cfg(test)]
495mod tests {
496 use super::*;
497
498 /// The instance key the test sets are written and checked with.
499 const KEY: [u8; 32] = [9u8; 32];
500
501 /// A store with one user and one photo, written as a set under `dir`.
502 async fn sample_set(dir: &Path) -> (Store, PathBuf) {
503 let store = Store::open(&dir.join("im.db")).await.unwrap();
504 store
505 .create_first_admin("ada@example.com", "Ada", "h")
506 .await
507 .unwrap();
508 std::fs::create_dir_all(dir.join(PHOTOS_DIR)).unwrap();
509 std::fs::write(dir.join(PHOTOS_DIR).join("01HZXAMPLEPHOTO"), b"png-bytes").unwrap();
510 let set = write_set(
511 &store,
512 dir,
513 &dir.join("backups"),
514 "2026-10-28T10-00-00",
515 &KEY,
516 )
517 .await
518 .unwrap();
519 (store, set)
520 }
521
522 #[tokio::test]
523 async fn a_good_set_restores_and_a_tampered_one_is_refused() {
524 let dir = tempfile::tempdir().unwrap();
525 let data = dir.path().join("data");
526 std::fs::create_dir_all(&data).unwrap();
527 let (_store, set) = sample_set(&data).await;
528 let scratch = data.join("scratch");
529
530 // A changed photo in the set makes the whole set refuse, and nothing is replaced.
531 let photo = set.join(PHOTOS_DIR).join("01HZXAMPLEPHOTO");
532 std::fs::write(&photo, b"evil-bytes").unwrap();
533 assert!(verify_set(&set, &scratch, &KEY).await.is_err());
534 let refused = restore(&data, &data.join("im.db"), &set, "t1", &KEY).await;
535 assert!(refused.is_err());
536 assert!(!data.join("restore-t1").exists());
537
538 // Put the original bytes back: the set verifies and restores.
539 std::fs::write(&photo, b"png-bytes").unwrap();
540 let outcome = restore(&data, &data.join("im.db"), &set, "t2", &KEY)
541 .await
542 .unwrap();
543 assert_eq!(outcome.photos, 1);
544 assert_eq!(
545 std::fs::read(data.join(PHOTOS_DIR).join("01HZXAMPLEPHOTO")).unwrap(),
546 b"png-bytes"
547 );
548 }
549
550 #[tokio::test]
551 async fn a_set_is_refused_under_another_key_or_with_a_stray_photo_entry() {
552 let dir = tempfile::tempdir().unwrap();
553 let data = dir.path().join("data");
554 std::fs::create_dir_all(&data).unwrap();
555 let (_store, set) = sample_set(&data).await;
556 let scratch = data.join("scratch");
557
558 // The MAC is keyed: the same set does not verify under any other instance key.
559 assert!(verify_set(&set, &scratch, &KEY).await.is_ok());
560 assert!(verify_set(&set, &scratch, &[1u8; 32]).await.is_err());
561
562 // A dot-file in photos/ is refused, even though every listed photo is still there.
563 std::fs::write(set.join(PHOTOS_DIR).join(".stray"), b"x").unwrap();
564 assert!(verify_set(&set, &scratch, &KEY).await.is_err());
565 }
566
567 #[tokio::test]
568 async fn prune_touches_only_real_sets_with_a_manifest() {
569 let dir = tempfile::tempdir().unwrap();
570 let root = dir.path();
571 for name in ["set-1", "set-2", "set-3"] {
572 std::fs::create_dir_all(root.join(name)).unwrap();
573 std::fs::write(root.join(name).join(MANIFEST_FILE), b"{}").unwrap();
574 }
575 std::fs::create_dir_all(root.join("notes")).unwrap();
576 assert_eq!(prune(root, 2).unwrap(), 1);
577 assert!(!root.join("set-1").exists());
578 assert!(root.join("set-2").exists() && root.join("set-3").exists());
579 assert!(root.join("notes").exists());
580 }
581}