Files
wanderbooks/crates/ledger-store/tests/backup_tamper.rs
T
swaitsandGLM 5.3 acdcdd7bda test(store): backups against a hand, a bad disk or another program
Thirty-six tests over the backup code the weekly coverage floor found
unreached, each an error a person can hit (WB-backup-2, -4, -6, -7, -8,
-12, -13, -14, -17, -19, -20, -21):

- manifests misfiled or chained wrongly: a manifest copied under another
  number, delta links that break each rule of the chain, a manifest
  edited by hand (its check line remade) into every lie check_names and
  the proof refuse, a manifest dropped of its vault or its keys, a
  manifest grown past anything this program writes;
- pieces replaced: a piece moved to a later generation is taken when it
  hashes right and refused when it does not, a stored-file piece
  replaced by a folder is found by the proof's share and written again
  beside it, a sealed piece that is no piece (no magic, or nothing after
  the magic) is not opened and is made again;
- cuts of books that lie: a journal without its last line's end, one line
  longer than a chunk, lines the books do not count, a last line that is
  not the head, a folder of the books holding something no book keeps, a
  vault record set aside after one was written anew, books that change
  under a cut, a destination ahead whose journal is damaged;
- the bounds: a piece that keeps being damaged ends the backup in words
  after two repairs, a manifest number taken eight times ends in Busy, a
  proof mark that cannot be made costs only a proof again;
- the words for the rest: the access log backed up to its last whole
  line and begun again when it moves back, a key file that is not a key,
  a header edited by hand, a sealed set whose header is not downloaded,
  a set found by many roads with junk around it, holds_only_sealed for
  the settings, the local backup's byte-for-byte journal, drills that
  name a newest too damaged to date, books shorter than the newest
  backup, a folder renamed to another book's name, a step stopped while
  proving an older backup, a scratch folder in use, and the io seam that
  carries a stop through a callback without losing its words.

Co-Authored-By: GLM 5.3 <noreply@z.ai>
2026-12-02 13:41:44 -07:00

1852 lines
71 KiB
Rust

//! Backups against what a hand, a bad disk or another program can do to a
//! finished set or to the books themselves (WB-backup-2, WB-backup-4,
//! WB-backup-6, WB-backup-13, WB-backup-17, WB-backup-21): manifests
//! edited, misfiled or chained wrongly, pieces replaced by later
//! generations, a cut of books that lie about themselves, a local key
//! file that is not a key, and the plain words for every refusal.
use ledger_core::{AccountType, Currency, Money, Role, Side, TinFacts, TinType};
use ledger_store::Store;
use ledger_store::backup::{
BackupError, BackupKey, Ctx, Cut, Destination, drill, find, holds_only_sealed, prove_local,
save_file, verify_found, write_destination, write_local,
};
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
const PASS: &str = "correct horse battery staple";
/// Keys cost a moment to derive and the count of derivations is the
/// process's: the tests that read it, and every test that derives one,
/// take turns.
static KEYS: std::sync::Mutex<()> = std::sync::Mutex::new(());
fn one_at_a_time() -> std::sync::MutexGuard<'static, ()> {
KEYS.lock().unwrap_or_else(|e| e.into_inner())
}
fn usd(s: &str) -> Money {
Money::new(s.parse().unwrap(), Currency::USD)
}
/// A book with a few entries and a stored file.
fn book(dir: &Path) -> Store {
let mut s = Store::create(dir, Currency::USD).unwrap();
let cash = s
.add_account("1000", "Cash", AccountType::Asset, None, false)
.unwrap();
let cap = s
.add_account("3000", "Capital", AccountType::Equity, None, false)
.unwrap();
let e = s
.create_entry(
chrono::NaiveDate::from_ymd_opt(2026, 3, 1).unwrap(),
"Start",
)
.unwrap();
s.add_line(e, cash, Side::Debit, usd("100.00")).unwrap();
s.add_line(e, cap, Side::Credit, usd("100.00")).unwrap();
s.post_entry(e).unwrap();
s.attach_receipt(Some(e), "r.pdf", "application/pdf", b"%PDF-1.4 r", None)
.unwrap();
s
}
/// One more write to the books: an account and a stored file.
fn more(s: &mut Store, n: usize) {
s.add_account(
&format!("{}", 6000 + n),
&format!("Expense {n}"),
AccountType::Expense,
None,
false,
)
.unwrap();
s.attach_receipt(
None,
&format!("f{n}.txt"),
"text/plain",
format!("receipt number {n}").as_bytes(),
None,
)
.unwrap();
}
fn cut(dir: &Path, s: &Store) -> Cut {
Cut::take("acme", dir, s.head()).unwrap()
}
fn plain(folder: &Path) -> Destination {
Destination {
folder: folder.to_path_buf(),
key: None,
}
}
fn set_of(disk: &Path) -> PathBuf {
disk.join("wanderbooks-acme")
}
/// Every file under `root`, by relative path, with its bytes.
fn tree(root: &Path) -> BTreeMap<String, Vec<u8>> {
fn walk(base: &Path, dir: &Path, out: &mut BTreeMap<String, Vec<u8>>) {
for e in std::fs::read_dir(dir).unwrap() {
let p = e.unwrap().path();
if p.is_dir() {
walk(base, &p, out);
} else {
let rel = p
.strip_prefix(base)
.unwrap()
.to_string_lossy()
.replace('\\', "/");
out.insert(rel, std::fs::read(&p).unwrap());
}
}
}
let mut out = BTreeMap::new();
if root.is_dir() {
walk(root, root, &mut out);
}
out
}
fn copy_tree(from: &Path, to: &Path) {
std::fs::create_dir_all(to).unwrap();
for e in std::fs::read_dir(from).unwrap() {
let e = e.unwrap();
let (src, dst) = (e.path(), to.join(e.file_name()));
if src.is_dir() {
copy_tree(&src, &dst);
} else {
std::fs::copy(&src, &dst).unwrap();
}
}
}
/// Prove the backup at `source` and give the books it holds, built in a
/// scratch folder next to `root`.
fn prove(
source: &Path,
pass: Option<&str>,
root: &Path,
name: &str,
) -> Result<ledger_store::backup::Verified, BackupError> {
let found = find(source, pass, &Ctx::new())?;
verify_found(&found, &root.join(name), &Ctx::new())
}
fn sha(bytes: &[u8]) -> String {
hex::encode(Sha256::digest(bytes))
}
/// The manifest `n` of the set, as JSON.
fn manifest(set: &Path, n: u64) -> serde_json::Value {
let text = std::fs::read_to_string(set.join(format!("manifests/{n:06}.json"))).unwrap();
serde_json::from_str(text.lines().next().unwrap()).unwrap()
}
/// The manifest `n`'s body, edited by `edit` and written back under a
/// check line made right again: what a person who meant to change a
/// manifest, or a program that lied writing one, would leave.
fn edit_manifest(set: &Path, n: u64, edit: impl Fn(&mut serde_json::Value)) {
let path = set.join(format!("manifests/{n:06}.json"));
let text = std::fs::read_to_string(&path).unwrap();
let mut v: serde_json::Value = serde_json::from_str(text.lines().next().unwrap()).unwrap();
edit(&mut v);
let body = serde_json::to_string(&v).unwrap();
let check = sha(body.as_bytes());
std::fs::write(
&path,
format!("{body}\nwanderbooks-manifest-sha256 {check}\n"),
)
.unwrap();
}
/// A manifest body written whole as manifest `n` of the set.
fn put_manifest_body(set: &Path, n: u64, v: &serde_json::Value) {
let body = serde_json::to_string(v).unwrap();
let check = sha(body.as_bytes());
std::fs::write(
set.join(format!("manifests/{n:06}.json")),
format!("{body}\nwanderbooks-manifest-sha256 {check}\n"),
)
.unwrap();
}
/// The journal segment `n`'s manifest names (its pieces are whole lines).
fn journal_segment(set: &Path, n: u64) -> PathBuf {
let rel = manifest(set, n)["journal"]["segments"]
.as_array()
.unwrap()
.last()
.unwrap()["file"]
.as_str()
.unwrap()
.to_string();
set.join(rel)
}
// --- a manifest misfiled or chained wrongly ------------------------------
#[test]
fn a_manifest_read_under_another_number_is_no_manifest_of_that_number() {
// A manifest copied under the next number (a person copying files, a
// sync service duplicating one) still names its own number inside:
// WB-backup-2, a manifest is whole only as the number it is filed
// under. The older whole one stands.
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
std::fs::copy(
set_of(&disk).join("manifests/000001.json"),
set_of(&disk).join("manifests/000002.json"),
)
.unwrap();
let v = prove(&disk, None, dir.path(), "v").unwrap();
assert_eq!(v.number, 1);
assert_eq!(v.passed_over, 1);
assert_eq!(v.head, s.head());
}
#[test]
fn a_wrong_link_in_a_manifests_chain_is_refused_and_the_older_whole_one_stands() {
// A delta manifest names the one before it by number and by what its
// body hashes to, and only what is new (WB-backup-17). A hand-made
// link that breaks any of that makes the manifest unreadable, never a
// manifest that names something else; one that follows the rules
// reads whole.
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
let one = set_of(&disk);
let base_sha = sha(std::fs::read_to_string(one.join("manifests/000001.json"))
.unwrap()
.lines()
.next()
.unwrap()
.as_bytes());
let mut delta = manifest(&one, 1);
delta["number"] = serde_json::json!(2u64);
let wrong = |what: &str, edit: &dyn Fn(&mut serde_json::Value)| {
let mut v = delta.clone();
edit(&mut v);
put_manifest_body(&one, 2, &v);
let v = prove(&disk, None, dir.path(), &format!("v-{what}")).unwrap();
assert_eq!(v.number, 1, "{what}");
assert_eq!(v.passed_over, 1, "{what}");
};
// A depth and a share of base with no base named.
wrong("no-base", &|v| {
v["depth"] = serde_json::json!(1u32);
v["journal"]["keep"] = serde_json::json!(1u64);
});
// A base named but no depth.
wrong("no-depth", &|v| {
v["base"] = serde_json::json!({"number": 1u64, "sha256": base_sha});
v["depth"] = serde_json::json!(0u32);
});
// A base that is not the one it names.
wrong("not-named", &|v| {
v["base"] = serde_json::json!({"number": 1u64, "sha256": sha(b"another")});
v["depth"] = serde_json::json!(1u32);
});
// More of the base's segments than there are.
wrong("keeps-too-much", &|v| {
v["base"] = serde_json::json!({"number": 1u64, "sha256": base_sha});
v["depth"] = serde_json::json!(1u32);
v["journal"]["keep"] = serde_json::json!(2u64);
});
// One that follows the rules: only what is new (nothing), kept from
// its base, reads whole as the newest.
let mut ok = delta.clone();
ok["base"] = serde_json::json!({"number": 1u64, "sha256": base_sha});
ok["depth"] = serde_json::json!(1u32);
ok["journal"]["keep"] = serde_json::json!(1u64);
ok["journal"]["segments"] = serde_json::json!([]);
put_manifest_body(&one, 2, &ok);
let v = prove(&disk, None, dir.path(), "v-ok").unwrap();
assert_eq!(v.number, 2);
assert_eq!(v.passed_over, 0);
assert_eq!(v.head, s.head());
}
// --- a manifest edited to claim what its pieces do not say ----------------
#[test]
fn a_manifest_edited_by_hand_is_read_for_what_it_now_is() {
// WB-backup-2: a manifest carries its own check, but a check line can
// be made right again by hand. One that no longer reads, or names
// what it may not, leaves a set that says nothing is a backup; one
// that reads and claims what its pieces do not prove is named by the
// proof, in words.
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
let base = dir.path().join("base");
std::fs::create_dir(&base).unwrap();
write_destination(&plain(&base), &cut(&b, &s), true, &Ctx::new()).unwrap();
// A refusal at the reading of the manifest itself: no set is there.
let said = |what: &str, edit: &dyn Fn(&mut serde_json::Value)| -> BackupError {
let disk = dir.path().join(format!("d-{what}"));
copy_tree(&base, &disk);
edit_manifest(&set_of(&disk), 1, edit);
find(&disk, None, &Ctx::new()).map(|_| ()).unwrap_err()
};
// Not this program's form, and a form from the future.
assert_eq!(
said("form", &|v| {
v["format"] = serde_json::json!("someone-elses-backup");
}),
BackupError::NotABackup
);
assert_eq!(
said("version", &|v| {
v["version"] = serde_json::json!(2u32);
}),
BackupError::NotABackup
);
// Names a manifest may not name.
for what in [
("head-not-hash", 0usize),
("series-not-hash", 1),
("segments-lie", 2),
("piece-not-hash", 3),
("piece-outside", 4),
] {
let err = said(what.0, &|v| match what.1 {
0 => v["head"]["hash"] = serde_json::json!("no hash at all"),
1 => v["journal"]["sha256"] = serde_json::json!("no hash at all"),
2 => v["journal"]["bytes"] = serde_json::json!(1u64),
3 => v["journal"]["segments"][0]["sha256"] = serde_json::json!("no hash at all"),
_ => {
v["journal"]["segments"][0]["file"] =
serde_json::json!("journal/../../the books themselves")
}
});
assert_eq!(err, BackupError::NotABackup, "{what:?}");
}
// A manifest that reads and is whole to the eye, but claims what its
// pieces do not prove: the proof names the lie.
let words = |what: &str, edit: &dyn Fn(&mut serde_json::Value)| -> String {
let disk = dir.path().join(format!("d-{what}"));
copy_tree(&base, &disk);
edit_manifest(&set_of(&disk), 1, edit);
prove(&disk, None, dir.path(), "v").unwrap_err().to_string()
};
// A head the journal does not end at.
let w = words("head", &|v| {
v["head"]["hash"] = serde_json::json!(sha(b"another head entirely"));
});
assert!(w.contains("records another head"), "{w}");
// A series whose pieces add up to something else than it says.
let w = words("series", &|v| {
v["journal"]["sha256"] = serde_json::json!(sha(b"another series entirely"));
});
assert!(w.contains("don't add up to what its manifest says"), "{w}");
// An index that names none of the stored files the books hold.
let w = words("no-index", &|v| {
v["files"] =
serde_json::json!({"bytes": 0u64, "sha256": sha(b""), "segments": [], "keep": 0u64});
});
assert!(
w.contains("a stored file the books name isn't in it"),
"{w}"
);
// An index that is not an index: none of its lines a file's name.
let junk = b"junk, not a json line at all";
let w = words("bad-index", &|v| {
let seg = &mut v["files"]["segments"][0];
let path = seg["file"].as_str().unwrap().to_string();
std::fs::write(set_of(&dir.path().join("d-bad-index")).join(&path), junk).unwrap();
seg["sha256"] = serde_json::json!(sha(junk));
seg["stored"] = serde_json::json!(junk.len() as u64);
seg["bytes"] = serde_json::json!(junk.len() as u64);
v["files"]["bytes"] = serde_json::json!(junk.len() as u64);
v["files"]["sha256"] = serde_json::json!(sha(junk));
});
assert!(w.contains("index of stored files is damaged"), "{w}");
// And one whose lines name files by no hash.
let junk = b"{\"sha256\":\"no hash at all in here\",\"bytes\":1}";
let w = words("no-hash-index", &|v| {
let seg = &mut v["files"]["segments"][0];
let path = seg["file"].as_str().unwrap().to_string();
std::fs::write(
set_of(&dir.path().join("d-no-hash-index")).join(&path),
junk,
)
.unwrap();
seg["sha256"] = serde_json::json!(sha(junk));
seg["stored"] = serde_json::json!(junk.len() as u64);
seg["bytes"] = serde_json::json!(junk.len() as u64);
v["files"]["bytes"] = serde_json::json!(junk.len() as u64);
v["files"]["sha256"] = serde_json::json!(sha(junk));
});
assert!(w.contains("names a file by no hash"), "{w}");
// A manifest grown past anything this program writes is no manifest
// either: not read, not trusted for its size alone.
let disk = dir.path().join("d-too-big");
copy_tree(&base, &disk);
let f = std::fs::File::create(set_of(&disk).join("manifests/000001.json")).unwrap();
f.set_len(256 << 20).unwrap();
drop(f);
assert_eq!(
find(&disk, None, &Ctx::new()).map(|_| ()).unwrap_err(),
BackupError::NotABackup
);
// Untouched, the backup as made proves whole.
let v = prove(&base, None, dir.path(), "v-ok").unwrap();
assert_eq!(v.head, s.head());
}
#[test]
fn a_manifest_that_drops_the_vault_or_the_keys_is_refused() {
// WB-backup-2: every vault record the books name, and the key that
// opens them, must be in the backup; a manifest edited to say less is
// refused, in words, by the proof.
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
let record = b"a sealed tin record, party one".to_vec();
let party = s.add_party("Mo", &[Role::Member]).unwrap();
s.set_party_tin(
party,
Some(TinFacts {
tin_type: TinType::Ssn,
last4: "4915".into(),
vault_record: Some(sha(&record)),
purged: None,
}),
)
.unwrap();
std::fs::create_dir_all(b.join("vault")).unwrap();
std::fs::write(b.join("vault").join("tin-1.bin"), &record).unwrap();
std::fs::create_dir_all(b.join("keys")).unwrap();
std::fs::write(b.join("keys").join("legacy.key"), "ab".repeat(32)).unwrap();
let base = dir.path().join("base");
std::fs::create_dir(&base).unwrap();
write_destination(&plain(&base), &cut(&b, &s), true, &Ctx::new()).unwrap();
let w = {
let disk = dir.path().join("d-no-vault");
copy_tree(&base, &disk);
edit_manifest(&set_of(&disk), 1, |v| {
v["vault"] = serde_json::json!([]);
});
prove(&disk, None, dir.path(), "v").unwrap_err().to_string()
};
assert!(w.contains("a TIN record the books name isn't in it"), "{w}");
let w = {
let disk = dir.path().join("d-no-keys");
copy_tree(&base, &disk);
edit_manifest(&set_of(&disk), 1, |v| {
v["keys"] = serde_json::json!([]);
});
prove(&disk, None, dir.path(), "v").unwrap_err().to_string()
};
assert!(
w.contains("its TIN records are in it, but not the key that opens them"),
"{w}"
);
// A name no book keeps, inside a manifest that names it: the set
// says nothing is a backup.
let disk = dir.path().join("d-vault-name");
copy_tree(&base, &disk);
edit_manifest(&set_of(&disk), 1, |v| {
v["vault"][0]["name"] = serde_json::json!("../the books themselves");
});
assert_eq!(
find(&disk, None, &Ctx::new()).map(|_| ()).unwrap_err(),
BackupError::NotABackup
);
// Untouched: the backup as made proves whole.
let v = prove(&base, None, dir.path(), "v-ok").unwrap();
assert_eq!(v.head, s.head());
}
// --- a piece replaced by a later generation -------------------------------
#[test]
fn a_piece_is_taken_under_any_generation_whose_contents_hash_right() {
// WB-backup-6 and WB-backup-13: a piece found damaged is written
// again beside the damaged file, so a piece may live under many
// generations. A reader takes any generation that hashes right, and
// none that does not.
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
let seg = journal_segment(&set_of(&disk), 1);
let aside = seg.with_file_name(format!("{}.g1", seg.file_name().unwrap().to_string_lossy()));
// The piece moved aside by hand (a generation of it left in place):
// still the backup, whole.
std::fs::copy(&seg, &aside).unwrap();
let held = std::fs::read(&seg).unwrap();
std::fs::remove_file(&seg).unwrap();
let v = prove(&disk, None, dir.path(), "v").unwrap();
assert_eq!(v.number, 1);
assert_eq!(
std::fs::read(v.tree.join("journal.jsonl")).unwrap(),
std::fs::read(b.join("journal.jsonl")).unwrap()
);
// A generation that is damaged is no piece: refused, in words, never
// restored. The manifest still names a length the damaged one keeps.
let mut flipped = held.clone();
flipped[0] ^= 0x01;
std::fs::write(&aside, &flipped).unwrap();
let err = prove(&disk, None, dir.path(), "v2").unwrap_err();
let w = err.to_string();
assert!(w.contains("damaged or missing"), "{w}");
assert!(!dir.path().join("v2").exists(), "the scratch is removed");
}
#[test]
fn a_stored_file_replaced_by_a_folder_is_found_by_the_next_backups_proof() {
// A put takes what is at the piece's name as the piece; only the
// proof after the backup re-hashes it (WB-backup-12). A folder put in
// a piece's place is found by the share the proof re-reads, named,
// and written again beside it.
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
// Stored files, until one is in the share the proof after backup 2
// re-reads (its hash's first four digits, modulo sixteen).
let mut chosen: Option<(String, Vec<u8>)> = None;
for n in 0..400 {
let bytes = format!("a stored file, number {n}").into_bytes();
s.attach_receipt(None, &format!("s{n}.txt"), "text/plain", &bytes, None)
.unwrap();
let h = sha(&bytes);
if chosen.is_none() && u64::from_str_radix(&h[..4], 16).unwrap() % 16 == 2 {
chosen = Some((h, bytes));
}
if chosen.is_some() && n > 5 {
break;
}
}
let (h, held_bytes) = chosen.expect("some file is in the share");
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
let rel = format!("files/{}/{h}", &h[..2]);
let piece = set_of(&disk).join(&rel);
std::fs::remove_file(&piece).unwrap();
std::fs::create_dir(&piece).unwrap();
more(&mut s, 1);
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
assert!(w.new, "{w:?}");
assert_eq!(w.repaired, vec![rel.clone()], "{w:?}");
// The folder stays where it is; the piece is beside it, whole.
assert!(piece.is_dir());
assert_eq!(
std::fs::read(set_of(&disk).join(format!("{rel}.g1"))).unwrap(),
held_bytes
);
let v = prove(&disk, None, dir.path(), "v").unwrap();
assert_eq!(v.number, 2);
assert_eq!(v.head, s.head());
assert_eq!(v.passed_over, 0);
}
// --- a cut of books that lie about themselves -----------------------------
#[test]
fn a_cut_of_books_whose_journal_lies_about_itself_is_refused() {
// The cut is taken under the store's lock, but the books' folder is
// a folder: a journal edited by hand, or one that is not what the
// books count, is named for what it is (WB-backup-2: a manifest may
// only name what is really there).
let dir = tempfile::tempdir().unwrap();
let make = |name: &str| dir.path().join(name);
// A journal whose last line has no end: not a journal.
let torn = make("torn");
std::fs::create_dir(&torn).unwrap();
let line = br#"{"seq":1,"what":"a line without its end"}"#;
std::fs::write(torn.join("journal.jsonl"), line).unwrap();
let err = Cut::take("acme", &torn, (1, sha(line))).unwrap_err();
assert!(
matches!(err, BackupError::Io(std::io::ErrorKind::InvalidData)),
"{err:?}"
);
// A journal whose only line is longer than a chunk of the cut's
// reading: still read whole, from the end, in more than one piece.
let long = make("long");
std::fs::create_dir(&long).unwrap();
let big: Vec<u8> = std::iter::repeat_n(b'x', 70 * 1024).collect();
let mut with_end = big.clone();
with_end.push(b'\n');
std::fs::write(long.join("journal.jsonl"), &with_end).unwrap();
let c = Cut::take("acme", &long, (1, sha(&big))).unwrap();
assert_eq!(c.head(), &(1, sha(&big)));
// No journal at all, and the books count none: an empty book.
let none = make("none");
std::fs::create_dir(&none).unwrap();
Cut::take("acme", &none, (0, String::new())).unwrap();
// A journal with lines the books do not count.
std::fs::write(none.join("journal.jsonl"), b"{\"seq\":1}\n").unwrap();
let err = Cut::take("acme", &none, (0, String::new())).unwrap_err();
let w = err.to_string();
assert!(
w.contains("the journal has lines the books don't count"),
"{w}"
);
// A last line that is not the books' head.
let err = Cut::take("acme", &none, (1, sha(b"some other line"))).unwrap_err();
let w = err.to_string();
assert!(
w.contains("the journal's last line isn't the books' head"),
"{w}"
);
}
#[test]
fn a_book_folder_holding_something_no_book_keeps_is_not_cut() {
// WB-backup-21 keeps the form legal on every system; the same holds
// of a book's own folders: something a book never keeps is said, not
// silently carried into a backup.
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
// A folder inside the vault.
std::fs::create_dir_all(b.join("vault").join("not a record")).unwrap();
let err = Cut::take("acme", &b, s.head()).unwrap_err();
let w = err.to_string();
assert!(w.contains("holds something no book keeps"), "{w}");
std::fs::remove_dir_all(b.join("vault")).unwrap();
#[cfg(unix)]
{
// A vault this program cannot look into: the disk's own refusal.
use std::os::unix::fs::PermissionsExt;
std::fs::create_dir_all(b.join("vault")).unwrap();
std::fs::write(b.join("vault").join("tin-1.bin"), b"x").unwrap();
let mode = std::fs::metadata(b.join("vault")).unwrap().permissions();
std::fs::set_permissions(b.join("vault"), std::fs::Permissions::from_mode(0o000)).unwrap();
let err = Cut::take("acme", &b, s.head()).unwrap_err();
assert!(
matches!(err, BackupError::Io(std::io::ErrorKind::PermissionDenied)),
"{err:?}"
);
std::fs::set_permissions(b.join("vault"), mode).unwrap();
}
}
#[test]
fn a_vault_record_set_aside_after_one_was_written_anew_is_not_the_books_record() {
// WB-backup-20: while a call is between its first step and its last,
// the vault holds a record staged under a scratch name and an old one
// set aside. The set-aside one is still the books' record only while
// the new one is not there; once it is, it is the books' record alone.
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
let tag = "0123456789abcdef";
std::fs::create_dir_all(b.join("vault")).unwrap();
std::fs::write(
b.join("vault").join("tin-1.bin"),
b"the record, written anew",
)
.unwrap();
std::fs::write(
b.join("vault").join(format!("tin-1.purging-{tag}")),
b"the record, set aside",
)
.unwrap();
std::fs::write(
b.join("vault").join(format!("tin-2.staged-{tag}")),
b"staged, not committed",
)
.unwrap();
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
let v = prove(&disk, None, dir.path(), "v").unwrap();
let held: Vec<String> = std::fs::read_dir(v.tree.join("vault"))
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
.collect();
assert_eq!(held, vec!["tin-1.bin".to_string()], "{held:?}");
assert_eq!(
std::fs::read(v.tree.join("vault").join("tin-1.bin")).unwrap(),
b"the record, written anew"
);
}
// --- junk around the set and the destination ------------------------------
#[test]
fn a_set_found_by_many_roads_and_junk_around_it_is_skipped() {
// The read-me promises a restore pointed at the set's folder or the
// folder above it (WB-backup-1); nothing either side of those roads
// is read as a backup, and junk in a set's folders never stops one.
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
// Not there at all, and neither a file nor a folder.
assert_eq!(
find(&dir.path().join("nope"), None, &Ctx::new())
.map(|_| ())
.unwrap_err(),
BackupError::NotABackup
);
#[cfg(unix)]
{
assert_eq!(
find(std::path::Path::new("/dev/null"), None, &Ctx::new())
.map(|_| ())
.unwrap_err(),
BackupError::NotABackup
);
}
// The set's own folder: the read-me's other road.
let v = prove(&set_of(&disk), None, dir.path(), "v-set").unwrap();
assert_eq!(v.head, s.head());
assert_eq!(v.book.as_deref(), Some("acme"));
// Junk in the set: a file no manifest number has, and (on unix) a
// name no program can read as text. Neither is a manifest; the next
// backup numbers past both.
std::fs::write(set_of(&disk).join("manifests/not-a-number.json"), b"junk").unwrap();
#[cfg(unix)]
{
use std::os::unix::ffi::OsStringExt;
let name = std::ffi::OsString::from_vec(vec![0xff, 0xfe]);
std::fs::write(set_of(&disk).join("manifests").join(name), b"junk").unwrap();
}
let v = prove(&disk, None, dir.path(), "v-junk").unwrap();
assert_eq!(v.number, 1);
more(&mut s, 1);
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
assert_eq!(w.number, 2, "{w:?}");
// A plain set's name taken by a file in another destination: not a
// set, and never written over.
let other = dir.path().join("other");
std::fs::create_dir(&other).unwrap();
std::fs::write(other.join("wanderbooks-acme"), b"a file, not a set").unwrap();
assert_eq!(
write_destination(&plain(&other), &cut(&b, &s), false, &Ctx::new()).unwrap_err(),
BackupError::NoBackupThere
);
assert_eq!(
std::fs::read(other.join("wanderbooks-acme")).unwrap(),
b"a file, not a set"
);
}
#[test]
fn junk_in_the_books_own_blob_folders_is_skipped_by_a_cut() {
// The cut walks the folders as this program lays them out; anything
// else in them (a person's stray file) is not a stored file, and the
// backup still proves whole.
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
std::fs::write(b.join("blobs").join("stray.txt"), b"junk").unwrap();
std::fs::write(b.join("blobs").join("ab"), b"junk").unwrap();
let nested = b.join("blobs").join("aa").join("bb");
std::fs::create_dir_all(&nested).unwrap();
std::fs::write(nested.join("not a hash.txt"), b"junk").unwrap();
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
let v = prove(&disk, None, dir.path(), "v").unwrap();
assert_eq!(v.head, s.head());
let index = std::fs::read_to_string(
set_of(&disk).join(
manifest(&set_of(&disk), 1)["files"]["segments"][0]["file"]
.as_str()
.unwrap(),
),
)
.unwrap();
assert_eq!(
index.lines().count(),
1,
"only the real stored file: {index}"
);
#[cfg(unix)]
{
// A blobs folder this program cannot look into: the disk's own
// refusal, said as itself.
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(b.join("blobs")).unwrap().permissions();
std::fs::set_permissions(b.join("blobs"), std::fs::Permissions::from_mode(0o300)).unwrap();
let err = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap_err();
assert!(
matches!(err, BackupError::Io(std::io::ErrorKind::PermissionDenied)),
"{err:?}"
);
std::fs::set_permissions(b.join("blobs"), mode).unwrap();
}
}
// --- what a destination holds ----------------------------------------------
#[test]
fn holds_only_sealed_tells_what_a_destination_holds_for_these_books() {
// The settings' question, answered from the folders alone: were the
// backups made protected by a passphrase here, with no plain set of
// these books beside them (WB-backup-7)?
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
let empty = dir.path().join("empty");
std::fs::create_dir(&empty).unwrap();
assert!(!holds_only_sealed(&empty, "acme"));
assert!(!holds_only_sealed(&dir.path().join("missing"), "acme"));
let plain_disk = dir.path().join("plain");
std::fs::create_dir(&plain_disk).unwrap();
write_destination(&plain(&plain_disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
assert!(!holds_only_sealed(&plain_disk, "acme"));
let _turn = one_at_a_time();
let sealed_disk = dir.path().join("sealed");
std::fs::create_dir(&sealed_disk).unwrap();
let dest = Destination {
folder: sealed_disk.clone(),
key: Some(BackupKey::generate(PASS).unwrap()),
};
write_destination(&dest, &cut(&b, &s), true, &Ctx::new()).unwrap();
assert!(holds_only_sealed(&sealed_disk, "acme"));
let sealed_set = std::fs::read_dir(&sealed_disk)
.unwrap()
.flatten()
.find(|e| e.file_name().to_string_lossy().starts_with("sealed-"))
.unwrap()
.path();
// A plain set of other books beside it changes nothing for these.
copy_tree(
&plain_set_of(&plain_disk),
&sealed_disk.join("wanderbooks-other"),
);
assert!(holds_only_sealed(&sealed_disk, "acme"));
// A plain set of these books beside it does.
copy_tree(
&plain_set_of(&plain_disk),
&sealed_disk.join("wanderbooks-acme"),
);
assert!(!holds_only_sealed(&sealed_disk, "acme"));
// A folder named like a sealed set with no header in it is not one.
let odd = dir.path().join("odd");
copy_tree(&sealed_set, &odd);
std::fs::remove_file(odd.join("header.json")).unwrap();
assert!(!holds_only_sealed(&odd, "acme"));
}
/// The one plain set folder of a destination made by these tests.
fn plain_set_of(disk: &Path) -> PathBuf {
disk.join("wanderbooks-acme")
}
#[test]
fn a_sealed_folder_that_is_not_a_set_is_skipped_by_the_next_backup() {
// Sealed sets are found by their header, which this key opens
// (WB-backup-7); a folder named like one with nothing readable in it
// is passed by, and the backup goes where it went before.
let _turn = one_at_a_time();
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
let dest = Destination {
folder: disk.clone(),
key: Some(BackupKey::generate(PASS).unwrap()),
};
write_destination(&dest, &cut(&b, &s), true, &Ctx::new()).unwrap();
// A folder with no header, and one whose header is not a header.
std::fs::create_dir_all(disk.join("sealed-empty").join("manifests")).unwrap();
std::fs::create_dir_all(disk.join("sealed-junk").join("manifests")).unwrap();
std::fs::write(
disk.join("sealed-junk").join("header.json"),
b"not a header",
)
.unwrap();
let before = tree(&disk);
more(&mut s, 1);
let w = write_destination(&dest, &cut(&b, &s), true, &Ctx::new()).unwrap();
assert!(w.new && w.number == 2, "{w:?}");
// The real set is the one the backup went to; the junk folders are
// passed by and untouched.
let set = std::fs::read_dir(&disk)
.unwrap()
.flatten()
.map(|e| e.path())
.find(|p| p.join("manifests/000002").is_file())
.expect("the real set");
assert!(
set.file_name()
.unwrap()
.to_string_lossy()
.starts_with("sealed-")
);
assert_eq!(
std::fs::read(disk.join("sealed-junk").join("header.json")).unwrap(),
b"not a header"
);
let now = tree(&disk);
for (name, bytes) in &before {
assert_eq!(now.get(name), Some(bytes), "{name}");
}
}
// --- the access log ---------------------------------------------------------
/// One line of a book's access log: a JSON record naming the one before
/// it, in the log's own form.
fn access_line(seq: u64, prev: &str, subject: &str) -> (String, String) {
let v = serde_json::json!({
"action": "tool",
"prev": prev,
"principal": {"id": "", "kind": "unknown", "label": ""},
"seq": seq,
"subject": subject,
"ts": "2026-12-02T12:00:00Z",
});
let text = v.to_string();
(format!("{text}\n"), sha(text.as_bytes()))
}
#[test]
fn the_access_log_is_backed_up_to_its_last_whole_line_and_begun_again_when_it_moves_back() {
// WB-backup-1: a backup holds the journal, the stored files, the
// vault, the keys and the access log. The log's last line may be
// under way when the cut is taken, so the cut takes its whole lines;
// and a log that no longer continues the destination's series is
// begun again whole, never spliced to the old one.
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
let genesis = sha(b"wanderbooks-access-v1");
let (l1, h1) = access_line(1, &genesis, "books.list_accounts");
let (l2, h2) = access_line(2, &h1, "books.head");
let (l3, _) = access_line(3, &h2, "books.audit");
std::fs::write(
b.join("access.jsonl"),
format!("{l1}{l2}half a line under way"),
)
.unwrap();
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
let whole = format!("{l1}{l2}");
let v = prove(&disk, None, dir.path(), "v1").unwrap();
assert_eq!(
std::fs::read(v.tree.join("access.jsonl")).unwrap(),
whole.as_bytes(),
"the torn tail is not the books'"
);
assert_eq!(access_segments(&set_of(&disk), 1), 1);
// The log grows: the series grows by a segment (a manifest that
// chains names only what is new; read whole it is the two).
std::fs::write(b.join("access.jsonl"), format!("{l1}{l2}{l3}")).unwrap();
more(&mut s, 1);
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
assert!(w.new && w.number == 2, "{w:?}");
assert_eq!(access_segments(&set_of(&disk), 2), 2);
// The log rewritten, of the same length (a book restored from
// elsewhere carries another history of accesses): begun again whole,
// never spliced to the old.
let (m1, hm1) = access_line(1, &genesis, "books.some_other_19");
let (m2, hm2) = access_line(2, &hm1, "books.foot");
let (m3, _) = access_line(3, &hm2, "books.drill");
assert_eq!(m1.len(), l1.len());
assert_eq!(m2.len(), l2.len());
assert_eq!(m3.len(), l3.len());
let rewritten = format!("{m1}{m2}{m3}");
std::fs::write(b.join("access.jsonl"), &rewritten).unwrap();
more(&mut s, 2);
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
assert!(w.new, "{w:?}");
assert_eq!(access_segments(&set_of(&disk), 3), 1, "begun again whole");
let v = prove(&disk, None, dir.path(), "v3").unwrap();
assert_eq!(
std::fs::read(v.tree.join("access.jsonl")).unwrap(),
rewritten.as_bytes()
);
// Shorter than it was: begun again whole too.
std::fs::write(b.join("access.jsonl"), &m1).unwrap();
more(&mut s, 3);
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
assert!(w.new && w.number == 4, "{w:?}");
assert_eq!(access_segments(&set_of(&disk), 4), 1);
// Nothing in it but a line under way: nothing of it is the books'.
std::fs::write(b.join("access.jsonl"), b"half a line under way").unwrap();
more(&mut s, 4);
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
assert!(w.new, "{w:?}");
assert_eq!(access_segments(&set_of(&disk), 5), 0);
let v = prove(&disk, None, dir.path(), "v5").unwrap();
assert_eq!(std::fs::read(v.tree.join("access.jsonl")).unwrap(), b"");
// The log shrinks under the cut's own length: the books changed under
// the backup, and it is refused.
std::fs::write(b.join("access.jsonl"), &m1).unwrap();
let c = cut(&b, &s);
std::fs::write(b.join("access.jsonl"), b"").unwrap();
let err = write_destination(&plain(&disk), &c, true, &Ctx::new()).unwrap_err();
let w = err.to_string();
assert!(w.contains("the books' file is shorter than it was"), "{w}");
}
/// How many segments manifest `n`'s access series names, read whole: the
/// ones it keeps from its base and its own.
fn access_segments(set: &Path, n: u64) -> usize {
let a = &manifest(set, n)["access"];
a["keep"].as_u64().unwrap_or(0) as usize + a["segments"].as_array().unwrap().len()
}
#[test]
fn books_that_change_under_a_cut_are_refused() {
// The journal is append-only under the store's lock; a file shorter
// than the cut took it to be (a disk that lost its end) is refused,
// and nothing is written (WB-backup-2: a manifest only names what is
// really there).
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
let c = cut(&b, &s);
let held = std::fs::read(b.join("journal.jsonl")).unwrap();
std::fs::write(b.join("journal.jsonl"), &held[..held.len() - 8]).unwrap();
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
let err = write_destination(&plain(&disk), &c, true, &Ctx::new()).unwrap_err();
let w = err.to_string();
assert!(w.contains("the books' file is shorter than it was"), "{w}");
assert!(
!tree(&disk).keys().any(|n| n.starts_with("manifests/")),
"no manifest was written"
);
}
// --- a destination ahead, with damage in its past ---------------------------
#[test]
fn a_destination_ahead_whose_journal_is_damaged_is_said_as_damage() {
// WB-backup-4 tells books behind a destination from books that
// diverged by proving the live journal is the destination's prefix.
// A prefix whose bytes will not prove is damage, said as damage:
// never "ahead", never written.
let dir = tempfile::tempdir().unwrap();
let (b, old) = (dir.path().join("book"), dir.path().join("old"));
let mut s = book(&b);
copy_tree(&b, &old);
more(&mut s, 1);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
// The books as they were: the destination is ahead of them.
let old_store = Store::open(&old).unwrap();
let seg = journal_segment(&set_of(&disk), 1);
let mut bytes = std::fs::read(&seg).unwrap();
bytes[3] ^= 0x01;
std::fs::write(&seg, bytes).unwrap();
let err = write_destination(
&plain(&disk),
&Cut::take("acme", &old, old_store.head()).unwrap(),
true,
&Ctx::new(),
)
.unwrap_err();
let w = err.to_string();
assert!(w.contains("damaged or missing"), "{w}");
}
// --- the repair, and its bounds ---------------------------------------------
#[test]
fn a_piece_that_keeps_being_damaged_ends_the_backup_in_words_not_a_loop() {
// The proof after a backup writes a damaged piece again beside it, at
// most twice more (WB-backup-13). A disk that keeps eating every
// generation of the journal ends the backup with the words for it,
// never a loop, never a silent success.
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
let set = set_of(&disk);
let ctx = {
let set = set.clone();
Ctx::new().with_faults(Arc::new(move |kind, rel| {
if kind == "published" && rel.starts_with("journal/") {
let mut bytes = std::fs::read(set.join(rel)).unwrap();
let at = bytes.len() / 2;
bytes[at] ^= 0x55;
std::fs::write(set.join(rel), bytes).unwrap();
}
false
}))
};
let err = write_destination(&plain(&disk), &cut(&b, &s), true, &ctx).unwrap_err();
let w = err.to_string();
assert!(
w.contains("found damaged and could not be made whole again from the books"),
"{w}"
);
// Three generations were named and tried (the piece and two more
// beside it), each damaged as it landed.
let seg = journal_segment(&set, 1)
.file_name()
.unwrap()
.to_string_lossy()
.into_owned();
for g in ["", ".g1", ".g2"] {
let path = set.join("journal").join(format!("{seg}{g}"));
assert!(path.is_file(), "generation {g:?}: {path:?}");
}
}
#[test]
fn a_manifest_number_taken_again_and_again_ends_in_words_not_a_loop() {
// WB-backup-5: the only decision two writers share is the next
// manifest number, and the disk decides it. A rival that keeps taking
// every number this one reaches for ends the backup in words, having
// written no whole manifest.
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
let ctx = {
let set = set_of(&disk);
Ctx::new().with_faults(Arc::new(move |kind, rel| {
if kind == "create" && rel.starts_with("manifests/") {
// The rival's half-made manifest: its number is spent.
std::fs::create_dir_all(set.join("manifests")).unwrap();
let _ = std::fs::write(set.join(rel), b"{\"format\":\"wan");
}
false
}))
};
let err = write_destination(&plain(&disk), &cut(&b, &s), true, &ctx).unwrap_err();
assert_eq!(err, BackupError::Busy);
let words = err.to_string();
assert!(words.contains("another program kept writing"), "{words}");
// Eight numbers spent on half-made manifests, and no whole one.
let manifests = std::fs::read_dir(set_of(&disk).join("manifests"))
.unwrap()
.count();
assert_eq!(manifests, 8, "{manifests}");
assert!(
!tree(&disk)
.values()
.any(|b| b.starts_with(b"{\"format\":\"wanderbooks-backup\""))
);
}
#[test]
fn a_proof_mark_that_cannot_be_made_costs_only_a_proof_again() {
// WB-backup-12: a manifest is recorded good by a tiny mark. A
// destination that will not take the mark still takes the backup;
// the next one proves the same manifest again, and says nothing.
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
assert!(set_of(&disk).join("proofs/000001").is_file());
// The marks' folder is not a folder this program can make marks in.
std::fs::remove_dir_all(set_of(&disk).join("proofs")).unwrap();
std::fs::write(set_of(&disk).join("proofs"), b"not a folder").unwrap();
more(&mut s, 1);
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
assert!(w.new && w.number == 2, "{w:?}");
assert!(!set_of(&disk).join("proofs/000002").exists());
let v = prove(&disk, None, dir.path(), "v").unwrap();
assert_eq!(v.number, 2);
assert_eq!(v.head, s.head());
// With nothing new, the next backup proves manifest 2 again; a backup
// that was not proven is never said good (WB-backup-12).
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
assert!(!w.new && w.number == 2, "{w:?}");
}
// --- the single file ---------------------------------------------------------
#[test]
fn a_backup_file_that_cannot_be_made_is_not_left_behind() {
// WB-backup-8: the file is written aside and moved into place only
// when it has proved whole. A folder that will not take it leaves no
// file by its name and nothing half-made beside it.
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
// A folder that is not there at all.
let missing = dir.path().join("no/such/folder/acme.wbbackup");
let err = save_file(&missing, &cut(&b, &s), None, &Ctx::new()).unwrap_err();
assert!(
matches!(err, BackupError::Io(std::io::ErrorKind::NotFound)),
"{err:?}"
);
assert!(!dir.path().join("no").exists());
#[cfg(unix)]
{
// A folder the program cannot write into: the disk's refusal, and
// still nothing left behind.
use std::os::unix::fs::PermissionsExt;
let ro = dir.path().join("ro");
std::fs::create_dir(&ro).unwrap();
let mode = std::fs::metadata(&ro).unwrap().permissions();
std::fs::set_permissions(&ro, std::fs::Permissions::from_mode(0o500)).unwrap();
let err =
save_file(&ro.join("acme.wbbackup"), &cut(&b, &s), None, &Ctx::new()).unwrap_err();
assert!(
matches!(err, BackupError::Io(std::io::ErrorKind::PermissionDenied)),
"{err:?}"
);
std::fs::set_permissions(&ro, mode).unwrap();
assert!(std::fs::read_dir(&ro).unwrap().next().is_none());
}
let _ = s.head();
}
#[test]
fn two_vault_records_with_the_same_bytes_are_one_piece_in_a_backup_file() {
// WB-backup-1: pieces are named by what is in them, so two records
// with the same bytes are one piece twice-named, and the file form
// holds it once.
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
std::fs::create_dir_all(b.join("vault")).unwrap();
let same = b"two parties, one sealed record".to_vec();
std::fs::write(b.join("vault").join("tin-1.bin"), &same).unwrap();
std::fs::write(b.join("vault").join("tin-2.bin"), &same).unwrap();
let file = dir.path().join("acme.wbbackup");
save_file(&file, &cut(&b, &s), None, &Ctx::new()).unwrap();
let v = prove(&file, None, dir.path(), "v").unwrap();
for name in ["tin-1.bin", "tin-2.bin"] {
assert_eq!(
std::fs::read(v.tree.join("vault").join(name)).unwrap(),
same,
"{name}"
);
}
}
// --- the key, and where it is kept -------------------------------------------
#[test]
fn a_debug_print_of_a_key_or_a_step_says_nothing() {
// The key is never in a log and never in a backup (WB-backup-7), and
// a step's own print says nothing of what it runs under.
let _turn = one_at_a_time();
let key = BackupKey::generate(PASS).unwrap();
assert_eq!(format!("{key:?}"), "BackupKey(..)");
let dest = Destination {
folder: PathBuf::from("/some folder"),
key: Some(key),
};
let printed = format!("{dest:?}");
assert!(!printed.contains(PASS), "{printed}");
let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
let ctx = Ctx::new()
.with_stop(stop)
.with_faults(Arc::new(|_, _| false))
.with_trace(Arc::new(|_, _| ()));
assert_eq!(format!("{ctx:?}"), "Ctx");
}
#[test]
fn a_key_file_that_is_not_a_key_is_refused_and_a_missing_one_is_forgotten() {
// The key kept in the book's own folder (WB-backup-7) is read back
// only as what it is; anything else is said, and taking off a
// passphrase that is not there is fine.
let _turn = one_at_a_time();
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let _ = book(&b);
assert!(BackupKey::load(&b).unwrap().is_none());
BackupKey::forget(&b).unwrap();
// The file is a folder.
std::fs::create_dir_all(b.join("local").join("backup-key.json")).unwrap();
let err = BackupKey::load(&b).unwrap_err();
assert!(
matches!(err, BackupError::Io(std::io::ErrorKind::IsADirectory)),
"{err:?}"
);
let err = BackupKey::forget(&b).unwrap_err();
assert!(
matches!(err, BackupError::Io(std::io::ErrorKind::IsADirectory)),
"{err:?}"
);
std::fs::remove_dir_all(b.join("local").join("backup-key.json")).unwrap();
// Not the words of a key.
std::fs::create_dir_all(b.join("local")).unwrap();
std::fs::write(b.join("local").join("backup-key.json"), b"not a key").unwrap();
let err = BackupKey::load(&b).unwrap_err();
let w = err.to_string();
assert!(w.contains("key can't be read"), "{w}");
// Words of a key, from a program this one does not know.
std::fs::write(
b.join("local").join("backup-key.json"),
serde_json::json!({
"version": 2u32,
"kdf": {"alg": "argon2id", "m": 65536u32, "t": 3u32, "p": 1u32, "salt": "00".repeat(16)},
"master": "00".repeat(32)
})
.to_string(),
)
.unwrap();
let err = BackupKey::load(&b).unwrap_err();
let w = err.to_string();
assert!(w.contains("key can't be read"), "{w}");
// A key this program will not derive from.
std::fs::write(
b.join("local").join("backup-key.json"),
serde_json::json!({
"version": 1u32,
"kdf": {"alg": "argon2id", "m": 65536u32 * 8u32, "t": 3u32, "p": 1u32, "salt": "00".repeat(16)},
"master": "00".repeat(32)
})
.to_string(),
)
.unwrap();
let err = BackupKey::load(&b).unwrap_err();
let w = err.to_string();
assert!(w.contains("key can't be read"), "{w}");
// A real one, kept and taken off again.
let key = BackupKey::generate(PASS).unwrap();
key.store(&b).unwrap();
let held = BackupKey::load(&b).unwrap().expect("kept");
assert!(key.same_as(&held));
BackupKey::forget(&b).unwrap();
BackupKey::forget(&b).unwrap();
assert!(BackupKey::load(&b).unwrap().is_none());
}
#[test]
fn a_keys_fingerprint_tells_one_passphrases_backups_from_anothers() {
// The short public name of a key (WB-backup-7): the same key keeps
// it, another passphrase never shares it, and it opens nothing.
let _turn = one_at_a_time();
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let _ = book(&b);
let key = BackupKey::generate(PASS).unwrap();
let finger = key.fingerprint();
assert_eq!(finger.len(), 12);
assert!(finger.bytes().all(|c| c.is_ascii_hexdigit()), "{finger}");
key.store(&b).unwrap();
assert_eq!(BackupKey::load(&b).unwrap().unwrap().fingerprint(), finger);
let other = BackupKey::generate(PASS).unwrap();
assert_ne!(other.fingerprint(), finger);
}
#[test]
fn a_header_edited_by_hand_is_damaged_or_opens_nothing() {
// WB-backup-7: a wrong passphrase opens nothing and is told from
// damage. A header of a kind this program does not know, one whose
// sealed check was made to disagree with itself, and one that asks
// for a key this program won't derive (in two sets at once, costing
// nothing the second time): all damage, none of it a wrong
// passphrase, none of it guessed any faster.
let _turn = one_at_a_time();
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
let dest = Destination {
folder: disk.clone(),
key: Some(BackupKey::generate(PASS).unwrap()),
};
write_destination(&dest, &cut(&b, &s), true, &Ctx::new()).unwrap();
let set = std::fs::read_dir(&disk)
.unwrap()
.flatten()
.find(|e| e.file_name().to_string_lossy().starts_with("sealed-"))
.unwrap()
.path();
let header = set.join("header.json");
// A kind this program does not know.
edit_header(&header, |v| {
v["format"] = serde_json::json!("someone-elses-seal");
});
assert_eq!(
find(&disk, Some(PASS), &Ctx::new())
.map(|_| ())
.unwrap_err(),
BackupError::NotABackup
);
// A check made to disagree with what it is sealed to.
let original = std::fs::read(&header).unwrap();
edit_header(&header, |v| {
v["check_sha256"] = serde_json::json!(sha(b"another check"));
});
assert_eq!(
find(&disk, Some(PASS), &Ctx::new())
.map(|_| ())
.unwrap_err(),
BackupError::NotABackup
);
// A header that asks for more than a few times what this program
// spends, in two sets at once: refused before a key is derived, once
// per setting, not once per set.
std::fs::write(&header, &original).unwrap();
edit_header(&header, |v| {
v["kdf"]["m"] = serde_json::json!(65536u32 * 8u32);
});
copy_tree(&set, &disk.join("sealed-second"));
let derived = ledger_store::backup::key_derivations();
assert_eq!(
find(&disk, Some(PASS), &Ctx::new())
.map(|_| ())
.unwrap_err(),
BackupError::NotABackup
);
assert_eq!(ledger_store::backup::key_derivations(), derived);
}
/// The header's body, edited, written under its own check line made right
/// again (what a person who meant to would leave).
fn edit_header(header: &Path, edit: impl Fn(&mut serde_json::Value)) {
let text = std::fs::read_to_string(header).unwrap();
let mut v: serde_json::Value = serde_json::from_str(text.lines().next().unwrap()).unwrap();
edit(&mut v);
let body = serde_json::to_string(&v).unwrap();
let check = sha(body.as_bytes());
std::fs::write(
header,
format!("{body}\nwanderbooks-header-sha256 {check}\n"),
)
.unwrap();
}
#[test]
fn a_sealed_set_whose_header_is_not_downloaded_yet_is_waiting() {
// WB-backup-19: a file a sync service has not put on this computer
// is said as such, even when it is the header that would say what
// the set holds: never "needs a passphrase", never "not a backup".
let _turn = one_at_a_time();
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
let dest = Destination {
folder: disk.clone(),
key: Some(BackupKey::generate(PASS).unwrap()),
};
write_destination(&dest, &cut(&b, &s), true, &Ctx::new()).unwrap();
let set = std::fs::read_dir(&disk)
.unwrap()
.flatten()
.find(|e| e.file_name().to_string_lossy().starts_with("sealed-"))
.unwrap()
.path();
let header = set.join("header.json");
let stand_in = set.join(".header.json.icloud");
std::fs::rename(&header, &stand_in).unwrap();
for pass in [None, Some(PASS)] {
let err = find(&disk, pass, &Ctx::new()).map(|_| ()).unwrap_err();
assert_eq!(err, BackupError::NotDownloaded, "{pass:?}");
let w = err.to_string();
assert!(w.contains("not downloaded to this computer yet"), "{w}");
}
std::fs::rename(&stand_in, &header).unwrap();
let v = prove(&disk, Some(PASS), dir.path(), "v").unwrap();
assert_eq!(v.head, s.head());
}
// --- sealed pieces cut short, and pieces in many chunks ----------------------
#[test]
fn a_sealed_piece_that_is_no_piece_is_not_opened_and_is_made_again() {
// WB-backup-6: a piece that is not what its name says is found by the
// proof after the next backup and written again beside it, sealed
// pieces no less than plain ones. (A sealed set's pieces are named by
// the key, so the journal's is met by the trace of the first read.)
let _turn = one_at_a_time();
for junk in [
b"XXXXno magic here, but long enough".as_slice(),
b"WBS1\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00".as_slice(),
] {
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
let dest = Destination {
folder: disk.clone(),
key: Some(BackupKey::generate(PASS).unwrap()),
};
// The first piece a proof reads is the journal's; the trace of
// the backup's own proof names it.
let journal = Arc::new(std::sync::Mutex::new(None::<String>));
let ctx = {
let journal = journal.clone();
Ctx::new().with_trace(Arc::new(move |kind, rel| {
if kind == "read" && rel.starts_with("pieces/") {
let mut held = journal.lock().unwrap();
held.get_or_insert_with(|| rel.to_string());
}
}))
};
write_destination(&dest, &cut(&b, &s), true, &ctx).unwrap();
let rel = journal.lock().unwrap().clone().expect("the journal piece");
let set = std::fs::read_dir(&disk)
.unwrap()
.flatten()
.find(|e| e.file_name().to_string_lossy().starts_with("sealed-"))
.unwrap()
.path();
// The piece replaced by the same no-piece; the books do not move
// on, so the backup taken again names the same piece and meets
// the no-piece where it is.
let piece = set.join(rel.clone());
std::fs::write(&piece, junk).unwrap();
let w = write_destination(&dest, &cut(&b, &s), true, &Ctx::new()).unwrap();
assert!(w.new && w.number >= 2, "{w:?}");
assert!(!w.repaired.is_empty(), "{w:?}");
assert_eq!(w.repaired, vec![rel.clone()], "{w:?}");
assert!(set.join(format!("{rel}.g1")).is_file(), "{rel:?}");
// The no-piece is left where it is.
assert!(piece.is_file());
let v = prove(&disk, Some(PASS), dir.path(), "v").unwrap();
assert_eq!(v.head, s.head());
assert_eq!(v.number, w.number);
}
}
#[test]
fn a_stored_file_larger_than_a_chunks_worth_seals_and_opens_chunk_by_chunk() {
// Sealing is chunked with a counter and an end marker (WB-backup-7),
// so a piece may be any length; one and a half chunks round-trips.
let _turn = one_at_a_time();
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
let big: Vec<u8> = (0..1_572_864u64).map(|i| (i % 251) as u8).collect();
s.attach_receipt(None, "big.bin", "application/octet-stream", &big, None)
.unwrap();
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
let dest = Destination {
folder: disk.clone(),
key: Some(BackupKey::generate(PASS).unwrap()),
};
write_destination(&dest, &cut(&b, &s), true, &Ctx::new()).unwrap();
let v = prove(&disk, Some(PASS), dir.path(), "v").unwrap();
assert_eq!(v.blobs, 2);
let h = sha(&big);
let held = std::fs::read(v.tree.join("blobs").join(&h[..2]).join(&h[2..4]).join(&h)).unwrap();
assert_eq!(held, big);
}
// --- the local backup --------------------------------------------------------
#[test]
fn the_local_backup_must_hold_the_books_journal_byte_for_byte() {
// WB-backup-11: the local backup is proven before a format upgrade,
// and its proof is more than a backup's: the books' own journal,
// byte for byte. A journal changed by hand under an unchanged head
// is caught by that comparison alone.
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
std::fs::create_dir_all(b.join("keys")).unwrap();
std::fs::write(b.join("keys").join("legacy.key"), "ab".repeat(32)).unwrap();
let scratch = dir.path().join("check");
let c = cut(&b, &s);
write_local(&b, &c, &Ctx::new()).unwrap();
// A byte changed in an early line: the head (the last line's hash)
// does not move.
let held = std::fs::read(b.join("journal.jsonl")).unwrap();
let mut changed = held.clone();
changed[10] ^= 0x01;
std::fs::write(b.join("journal.jsonl"), &changed).unwrap();
let err = prove_local(&b, "acme", &s.head(), &scratch, &Ctx::new()).unwrap_err();
let w = err.to_string();
assert!(
w.contains("its journal isn't the books' own, byte for byte"),
"{w}"
);
assert!(!scratch.exists(), "the scratch folder is removed");
// Whole again: it proves, and the count of stored files is given.
std::fs::write(b.join("journal.jsonl"), &held).unwrap();
assert_eq!(
prove_local(&b, "acme", &s.head(), &scratch, &Ctx::new()).unwrap(),
1
);
}
#[test]
fn a_local_backup_into_a_book_folder_that_cannot_take_one_is_refused() {
// WB-backup-11: the local backup lives in the book's own folder; a
// folder that will not take it is said, and so is a key that cannot
// be kept there.
let _turn = one_at_a_time();
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(&b).unwrap().permissions();
std::fs::set_permissions(&b, std::fs::Permissions::from_mode(0o555)).unwrap();
let err = write_local(&b, &cut(&b, &s), &Ctx::new()).unwrap_err();
assert!(matches!(err, BackupError::Damaged(_)), "{err:?}");
let key = BackupKey::generate(PASS).unwrap();
let err = key.store(&b).unwrap_err();
assert!(matches!(err, BackupError::Damaged(_)), "{err:?}");
std::fs::set_permissions(&b, mode).unwrap();
}
}
// --- the drill ---------------------------------------------------------------
#[test]
fn a_drill_names_a_newest_too_damaged_to_say_when_it_is_from() {
// WB-backup-14: the drill proves the newest backup and no older one;
// when the newest's manifest cannot even be read for its date, the
// failure says the number and the older one's date.
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
for n in 0..3 {
more(&mut s, n);
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
}
// No destination at all.
assert_eq!(
drill(
&plain(&dir.path().join("no-disk")),
"acme",
&b.join("journal.jsonl"),
&dir.path().join("d"),
None,
&Ctx::new(),
)
.unwrap_err(),
BackupError::NoFolder
);
// The newest's manifest mangled past reading: no date can be said for
// it, only its number, and the older one's date.
let mangled = set_of(&disk).join("manifests/000003.json");
let mut bytes = std::fs::read(&mangled).unwrap();
bytes[12] ^= 0x01;
std::fs::write(&mangled, &bytes).unwrap();
let err = drill(
&plain(&disk),
"acme",
&b.join("journal.jsonl"),
&dir.path().join("d"),
None,
&Ctx::new(),
)
.unwrap_err();
let w = err.to_string();
assert!(w.contains("the newest backup (number 3) is damaged"), "{w}");
assert!(w.contains("an older one from"), "{w}");
assert!(!dir.path().join("d").exists(), "the scratch is removed");
}
#[test]
fn a_drill_of_books_shorter_than_the_newest_backup_says_not_their_history() {
// The live books must carry the newest backup's history (WB-backup-3:
// a restore of a whole manifest is a prefix of the books, and the
// drill checks it the other way round). Books restored from an older
// state than the destination holds are not the newest backup's
// history, and the drill says so rather than passing on an older one.
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
// The books as they stand: one backup, the drill passes.
let head = s.head();
assert_eq!(
drill(
&plain(&disk),
"acme",
&b.join("journal.jsonl"),
&dir.path().join("d1"),
None,
&Ctx::new(),
)
.unwrap(),
head
);
// The books move on and a second backup is made; a copy of the books
// as they were is now shorter than the newest backup holds.
more(&mut s, 1);
let short = dir.path().join("short");
copy_tree(&b, &short);
more(&mut s, 2);
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
let err = drill(
&plain(&disk),
"acme",
&short.join("journal.jsonl"),
&dir.path().join("d2"),
None,
&Ctx::new(),
)
.unwrap_err();
let w = err.to_string();
assert!(w.contains("its journal isn't this book's history"), "{w}");
assert!(!dir.path().join("d2").exists(), "the scratch is removed");
}
#[test]
fn a_drill_stopped_while_proving_an_older_backup_ends_cleanly() {
// WB-backup-9: a stopped step ends cleanly, scratch removed. The
// newest damaged and an older one being proven when the books close:
// the stop is the stop, not a word about damage.
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
for n in 0..3 {
more(&mut s, n);
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
}
// The newest's own segment damaged: the drill falls to older ones.
let seg = journal_segment(&set_of(&disk), 3);
let mut bytes = std::fs::read(&seg).unwrap();
bytes[3] ^= 0x01;
std::fs::write(&seg, bytes).unwrap();
let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
let replays = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let ctx = {
let (stop, replays) = (stop.clone(), replays.clone());
Ctx::new()
.with_stop(stop.clone())
.with_phase_watch(Arc::new(move |p: &str| {
if p == "replay" && replays.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0 {
stop.store(true, std::sync::atomic::Ordering::SeqCst);
}
}))
};
let scratch = dir.path().join("d");
let err = drill(
&plain(&disk),
"acme",
&b.join("journal.jsonl"),
&scratch,
None,
&ctx,
)
.unwrap_err();
assert!(matches!(err, BackupError::Cancelled(_)), "{err:?}");
assert!(!scratch.exists(), "the scratch folder is removed");
}
#[test]
fn a_drill_of_a_folder_renamed_to_another_books_name_is_not_that_books() {
// WB-backup-4: the books a set holds are what its manifest says, not
// its folder's name. A folder renamed by hand is refused for the
// books it now claims to be.
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
let renamed = disk.join("wanderbooks-other");
std::fs::rename(set_of(&disk), &renamed).unwrap();
let err = drill(
&plain(&disk),
"other",
&b.join("journal.jsonl"),
&dir.path().join("d"),
None,
&Ctx::new(),
)
.unwrap_err();
assert_eq!(err, BackupError::Elsewhere);
let w = err.to_string();
assert!(w.contains("diverged"), "{w}");
assert!(!dir.path().join("d").exists());
}
// --- the proof's scratch, and the store's own refusals -----------------------
#[test]
fn a_scratch_folder_that_is_not_new_is_refused() {
// The proof builds the books in a folder of its own making; one that
// is already there is in use, said as itself.
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
let scratch = dir.path().join("in-use");
std::fs::create_dir(&scratch).unwrap();
let found = find(&disk, None, &Ctx::new()).unwrap();
let err = verify_found(&found, &scratch, &Ctx::new()).unwrap_err();
let w = err.to_string();
assert!(w.contains("its scratch folder is in use"), "{w}");
}
#[test]
fn a_refusal_from_the_books_is_damaged_and_a_close_is_a_stop() {
// What the books say while a backup proves them (the proof opens
// them): a refusal is damage to the backup's claim, a closing is a
// stop of the step.
assert!(matches!(
BackupError::from(ledger_store::StoreError::Cancelled),
BackupError::Cancelled(what) if what == "verifying"
));
let w =
BackupError::from(ledger_store::StoreError::UnknownSubject("a receipt".into())).to_string();
assert!(w.contains("no a receipt to link to"), "{w}");
}