From 9f4529b07803fb821e680883dec7ac1961708ea7 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 17:19:12 -0700 Subject: [PATCH] feat(store): backups in plain folders, written once (P15 section 9, D-91, D-92) A backup is a folder holding one folder per set of books, made only of files that are written once: the journal and the access log as immutable segments, an index of stored files and the stored files under their hash, the vault and keys by content hash, and a manifest, written last, that makes a backup complete. It is built beside the git form for now. Accounting reasoning: the journal is append-only and a stored file never changes, so what the store's lock must fix is one look (its length, that its last line is the head, the vault and keys); the rest is read after it. A destination is written only when its newest whole manifest is a point on the live journal (byte-identical prefix); otherwise nothing is written. Two writers cannot corrupt it: pieces are named by what is in them, the manifest number is taken by exclusive create, the loser looks again. A passphrase (D-92) seals every piece with XChaCha20-Poly1305 in 1 MiB chunks, the key derived by Argon2id at the owner passphrase's own cost (64 MiB, 3 passes, 1 lane); names are made from the key and say nothing; the derived key is kept in the book's local/ folder, owner-only. "Save a backup..." is a zip of the same form (.wbbackup). New dependencies: none new to the tree. chacha20poly1305, zeroize and zip (deflate only) were already used by ledger-vault, the viewer and the packages; ledger-store now names them. Co-Authored-By: Claude Fable 5.2 --- Cargo.lock | 3 + crates/ledger-store/Cargo.toml | 8 + crates/ledger-store/src/backups/cut.rs | 212 ++++++ crates/ledger-store/src/backups/form.rs | 315 +++++++++ crates/ledger-store/src/backups/io.rs | 275 ++++++++ crates/ledger-store/src/backups/mod.rs | 274 ++++++++ crates/ledger-store/src/backups/read.rs | 805 ++++++++++++++++++++++ crates/ledger-store/src/backups/seal.rs | 448 ++++++++++++ crates/ledger-store/src/backups/single.rs | 199 ++++++ crates/ledger-store/src/backups/write.rs | 598 ++++++++++++++++ crates/ledger-store/src/lib.rs | 1 + crates/ledger-store/tests/backups.rs | 689 ++++++++++++++++++ 12 files changed, 3827 insertions(+) create mode 100644 crates/ledger-store/src/backups/cut.rs create mode 100644 crates/ledger-store/src/backups/form.rs create mode 100644 crates/ledger-store/src/backups/io.rs create mode 100644 crates/ledger-store/src/backups/mod.rs create mode 100644 crates/ledger-store/src/backups/read.rs create mode 100644 crates/ledger-store/src/backups/seal.rs create mode 100644 crates/ledger-store/src/backups/single.rs create mode 100644 crates/ledger-store/src/backups/write.rs create mode 100644 crates/ledger-store/tests/backups.rs diff --git a/Cargo.lock b/Cargo.lock index 7e52588d..7fff05de 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4262,6 +4262,7 @@ name = "ledger-store" version = "0.1.0" dependencies = [ "argon2", + "chacha20poly1305", "chrono", "criterion", "getrandom 0.2.17", @@ -4279,6 +4280,8 @@ dependencies = [ "tempfile", "thiserror 2.0.21", "windows-sys 0.61.2", + "zeroize", + "zip", ] [[package]] diff --git a/crates/ledger-store/Cargo.toml b/crates/ledger-store/Cargo.toml index 73df09d6..e7873a3d 100644 --- a/crates/ledger-store/Cargo.toml +++ b/crates/ledger-store/Cargo.toml @@ -25,6 +25,14 @@ hex = "0.4" getrandom = { version = "0.2", features = ["std"] } subtle = "2" argon2 = "0.6" +# A backup protected by a passphrase is sealed as the TIN vault is +# (XChaCha20-Poly1305, already in the tree); its key is kept off the +# page when this program is done with it (D-92). +chacha20poly1305 = "0.11" +zeroize = "1" +# "Save a backup..." is one file: a zip of the backup's folder form (the +# crate the viewer and the packages already use, deflate only). +zip = { version = "9.0.1", default-features = false, features = ["deflate"] } [target.'cfg(unix)'.dependencies] libc = "0.2" diff --git a/crates/ledger-store/src/backups/cut.rs b/crates/ledger-store/src/backups/cut.rs new file mode 100644 index 00000000..4a1837e5 --- /dev/null +++ b/crates/ledger-store/src/backups/cut.rs @@ -0,0 +1,212 @@ +//! A cut of the books: what a backup is made from, taken in one look +//! under the store's lock, and read from the book's folder after it. +//! +//! The journal is append-only and a stored file never changes once it is +//! there, so what the lock has to fix is small: how long the journal is +//! (and that its last line is the head), how much of the access log is +//! whole lines, and the vault and the keys, which can change. Everything +//! else is read afterwards, outside the lock, and cannot move: the bytes +//! of the journal before the cut's length are the same bytes a moment +//! later. + +use super::form::{IndexLine, is_plain_name, is_sha}; +use super::{BackupError, Ctx}; +use sha2::{Digest, Sha256}; +use std::io::{Read, Seek, SeekFrom}; +use std::path::{Path, PathBuf}; + +/// A cut of one book. Take it with the store's lock held ([`Cut::take`]). +#[derive(Debug, Clone)] +pub struct Cut { + book: String, + dir: PathBuf, + head: (u64, String), + pub(crate) journal_len: u64, + pub(crate) access_len: u64, + pub(crate) vault: Vec<(String, Vec)>, + pub(crate) keys: Vec<(String, Vec)>, +} + +/// The bytes of the last line of `path`, which is `len` long and ends in a +/// newline, read from the end. +fn last_line(path: &Path, len: u64) -> std::io::Result> { + let mut f = std::fs::File::open(path)?; + let mut tail: Vec = Vec::new(); + let mut at = len; + // Without the final newline; looking back for the one before it. + loop { + let step = at.min(64 * 1024); + at -= step; + f.seek(SeekFrom::Start(at))?; + let mut chunk = vec![0u8; step as usize]; + f.read_exact(&mut chunk)?; + chunk.extend_from_slice(&tail); + tail = chunk; + if tail.last() != Some(&b'\n') { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "the journal does not end in a whole line", + )); + } + let body = &tail[..tail.len() - 1]; + if let Some(i) = body.iter().rposition(|b| *b == b'\n') { + return Ok(body[i + 1..].to_vec()); + } + if at == 0 { + return Ok(body.to_vec()); + } + } +} + +/// How much of `path`, `len` long, is whole lines. +fn whole_lines(path: &Path, len: u64) -> std::io::Result { + let mut f = std::fs::File::open(path)?; + let mut at = len; + while at > 0 { + let step = at.min(64 * 1024); + at -= step; + f.seek(SeekFrom::Start(at))?; + let mut chunk = vec![0u8; step as usize]; + f.read_exact(&mut chunk)?; + if let Some(i) = chunk.iter().rposition(|b| *b == b'\n') { + return Ok(at + i as u64 + 1); + } + } + Ok(0) +} + +/// The plain files of a flat folder of a book, by name, with their bytes. +fn flat_files(dir: &Path) -> Result)>, BackupError> { + let entries = match std::fs::read_dir(dir) { + Ok(e) => e, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(e) => return Err(e.into()), + }; + let mut out = Vec::new(); + for entry in entries { + let entry = entry?; + let name = entry.file_name().to_string_lossy().into_owned(); + let meta = std::fs::symlink_metadata(entry.path())?; + if !meta.is_file() || !is_plain_name(&name) { + return Err(BackupError::Damaged(format!( + "a folder of the books holds something no book keeps ({name:?})" + ))); + } + out.push((name, std::fs::read(entry.path())?)); + } + out.sort(); + Ok(out) +} + +impl Cut { + /// Take a cut of the book `book` kept in `dir`, whose journal's head + /// is `head`. The caller holds the store's lock, so the journal is + /// whole lines and the vault matches it. + pub fn take(book: &str, dir: &Path, head: (u64, String)) -> Result { + let journal = dir.join(crate::JOURNAL_FILE); + let journal_len = match std::fs::metadata(&journal) { + Ok(m) => m.len(), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0, + Err(e) => return Err(e.into()), + }; + if head.0 == 0 { + if journal_len != 0 { + return Err(BackupError::Damaged( + "the journal has lines the books don't count".into(), + )); + } + } else { + let line = last_line(&journal, journal_len)?; + if hex::encode(Sha256::digest(&line)) != head.1 { + return Err(BackupError::Damaged( + "the journal's last line isn't the books' head".into(), + )); + } + } + let access = dir.join(crate::access::ACCESS_FILE); + let access_len = match std::fs::metadata(&access) { + Ok(m) => whole_lines(&access, m.len())?, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0, + Err(e) => return Err(e.into()), + }; + Ok(Cut { + book: book.to_string(), + dir: dir.to_path_buf(), + head, + journal_len, + access_len, + vault: flat_files(&dir.join(crate::root::VAULT_DIR))?, + keys: flat_files(&dir.join(crate::root::KEYS_DIR))?, + }) + } + + /// The books' id. + pub fn book(&self) -> &str { + &self.book + } + + /// The journal's head at the cut: seq and hash. + pub fn head(&self) -> &(u64, String) { + &self.head + } + + pub(crate) fn journal_path(&self) -> PathBuf { + self.dir.join(crate::JOURNAL_FILE) + } + + pub(crate) fn access_path(&self) -> PathBuf { + self.dir.join(crate::access::ACCESS_FILE) + } + + /// The stored files, by hash, with their lengths: those named as this + /// program names them (`blobs/ab/cd/`), nothing else. + pub(crate) fn stored_files(&self, ctx: &Ctx) -> Result, BackupError> { + let root = self.dir.join(crate::store::BLOBS_DIR); + let mut out = Vec::new(); + let level = |p: &Path| -> std::io::Result> { + match std::fs::read_dir(p) { + Ok(e) => e.collect(), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()), + Err(e) => Err(e), + } + }; + for a in level(&root)? { + ctx.check("listing the stored files")?; + let an = a.file_name().to_string_lossy().into_owned(); + if an.len() != 2 || !a.path().is_dir() { + continue; + } + for b in level(&a.path())? { + let bn = b.file_name().to_string_lossy().into_owned(); + if bn.len() != 2 || !b.path().is_dir() { + continue; + } + for f in level(&b.path())? { + let name = f.file_name().to_string_lossy().into_owned(); + let meta = std::fs::symlink_metadata(f.path())?; + if meta.is_file() + && is_sha(&name) + && name.starts_with(&an) + && name[2..].starts_with(&bn) + { + out.push(IndexLine { + sha256: name, + bytes: meta.len(), + }); + } + } + } + } + out.sort_by(|x, y| x.sha256.cmp(&y.sha256)); + Ok(out) + } + + /// Where a stored file is in the book. + pub(crate) fn blob_path(&self, sha: &str) -> PathBuf { + self.dir + .join(crate::store::BLOBS_DIR) + .join(&sha[0..2]) + .join(&sha[2..4]) + .join(sha) + } +} diff --git a/crates/ledger-store/src/backups/form.rs b/crates/ledger-store/src/backups/form.rs new file mode 100644 index 00000000..7a4f2ce8 --- /dev/null +++ b/crates/ledger-store/src/backups/form.rs @@ -0,0 +1,315 @@ +//! The records of a backup: pieces, series of pieces, and the manifest +//! that names them, and the names a piece is kept under. +//! +//! A *series* is what grows: the journal, the access log and the index of +//! stored files are each a run of immutable segments whose bytes, read one +//! after another, are the whole. A backup that has new lines adds a +//! segment; nothing already written is touched. + +use super::BackupError; +use super::seal::Keys; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +/// What a manifest says it is. +pub(crate) const FORMAT: &str = "wanderbooks-backup"; +/// The form's version. A reader refuses one it does not know. +pub(crate) const VERSION: u32 = 1; +/// The folder of manifests in a set. +pub(crate) const MANIFESTS: &str = "manifests"; +/// The words a person can open. +pub(crate) const READ_ME: &str = "READ-ME.txt"; +/// The sealed form's header: how to derive the key. +pub(crate) const HEADER: &str = "header.json"; +/// Where a sealed set keeps every piece, under names that say nothing. +pub(crate) const PIECES: &str = "pieces"; +/// A series with this many segments is next written whole as one: a +/// manifest stays small however long the books have been backed up. +pub(crate) const CONSOLIDATE_AT: usize = 200; + +/// The kinds of piece. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Kind { + /// A segment of the journal. + Journal, + /// A segment of the access log. + Access, + /// A segment of the index of stored files. + Index, + /// A stored file. + File, + /// A vault record. + Vault, + /// A key file. + Key, +} + +impl Kind { + pub(crate) fn dir(self) -> &'static str { + match self { + Kind::Journal => "journal", + Kind::Access => "access", + Kind::Index => "files-index", + Kind::File => "files", + Kind::Vault => "vault", + Kind::Key => "keys", + } + } +} + +/// One piece: a file of the set, by where it is, how long it is as it is +/// kept, and what is in it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) struct Piece { + /// Its path in the set. + pub file: String, + /// Its length as kept (sealed pieces are longer than their contents). + pub stored: u64, + /// Its contents' length. + pub bytes: u64, + /// Its contents' SHA-256, hex. + pub sha256: String, +} + +/// A run of segments, and what they make together. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) struct Series { + /// Bytes in all the segments. + pub bytes: u64, + /// SHA-256 of all of them, one after another, hex. + pub sha256: String, + /// The segments, in order. + pub segments: Vec, +} + +/// A file named by its place in a flat folder of a book (the vault, the +/// keys). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) struct Named { + /// Its name in the book's folder. + pub name: String, + /// Where it is kept. + #[serde(flatten)] + pub piece: Piece, +} + +/// The journal's head. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) struct Head { + /// Its last line's seq. + pub seq: u64, + /// Its last line's hash. + pub hash: String, +} + +/// What makes a backup whole: written last, and never again. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) struct Manifest { + /// [`FORMAT`]. + pub format: String, + /// [`VERSION`]. + pub version: u32, + /// The books' id, as they were backed up. + pub book: String, + /// Its number in the set: also its name. + pub number: u64, + /// When it was written (UTC). + pub written: String, + /// The journal's head it reaches. + pub head: Head, + /// The journal. + pub journal: Series, + /// The access log. + pub access: Series, + /// The index of stored files: one `{"sha256","bytes"}` per line. + pub files: Series, + /// How many stored files the index names, and their bytes. + pub file_count: u64, + /// Bytes of the stored files. + pub file_bytes: u64, + /// The vault's records. + pub vault: Vec, + /// The keys. + pub keys: Vec, +} + +/// A line of the index of stored files. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) struct IndexLine { + /// The file's SHA-256, hex. + pub sha256: String, + /// Its length. + pub bytes: u64, +} + +/// SHA-256, hex. +pub(crate) fn sha_hex(bytes: &[u8]) -> String { + hex::encode(Sha256::digest(bytes)) +} + +/// Whether `s` is a SHA-256 in hex as this program writes it. +pub(crate) fn is_sha(s: &str) -> bool { + s.len() == 64 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) +} + +/// A name in a book's flat folders: nothing that could leave the folder. +pub(crate) fn is_plain_name(s: &str) -> bool { + !s.is_empty() + && s.len() <= 200 + && s != "." + && s != ".." + && s.bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_')) +} + +/// The manifest's file name in a set, as its number. +pub(crate) fn manifest_path(number: u64, sealed: bool) -> String { + if sealed { + format!("{MANIFESTS}/{number:06}") + } else { + format!("{MANIFESTS}/{number:06}.json") + } +} + +/// The number a manifest file name carries, if it is one. +pub(crate) fn manifest_number(name: &str, sealed: bool) -> Option { + let digits = if sealed { + name + } else { + name.strip_suffix(".json")? + }; + if digits.len() < 6 || !digits.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + let n: u64 = digits.parse().ok()?; + // Exactly the name this program writes (no conflict copy of one, no + // other spelling of the same number). + (manifest_path(n, sealed) == format!("{MANIFESTS}/{name}")).then_some(n) +} + +/// Where a piece of `kind` whose contents hash to `sha` is kept, as the +/// `ordinal`th of its series. Sealed sets keep every piece under a name +/// made from the key and the hash: it says nothing of what the piece is. +pub(crate) fn piece_path(keys: Option<&Keys>, kind: Kind, ordinal: usize, sha: &str) -> String { + match keys { + Some(k) => format!("{PIECES}/{}", k.piece_name(kind.dir(), sha)), + None => match kind { + Kind::Journal | Kind::Access | Kind::Index => { + format!("{}/{:06}-{}", kind.dir(), ordinal + 1, &sha[..16]) + } + Kind::File => format!("{}/{}/{sha}", kind.dir(), &sha[..2]), + Kind::Vault | Kind::Key => format!("{}/{sha}", kind.dir()), + }, + } +} + +/// A manifest as written: its JSON, a newline, and a line that is the +/// SHA-256 of that JSON, so a short or changed one is known for what it is. +pub(crate) fn encode_manifest(m: &Manifest) -> Vec { + let body = serde_json::to_string(m).expect("a manifest serializes"); + let check = sha_hex(body.as_bytes()); + format!("{body}\nwanderbooks-manifest-sha256 {check}\n").into_bytes() +} + +/// A manifest read back, or why it is not one. +pub(crate) fn decode_manifest(bytes: &[u8]) -> Result { + let bad = || BackupError::Damaged("a manifest of the backup is cut short or changed".into()); + let text = std::str::from_utf8(bytes).map_err(|_| bad())?; + let text = text.strip_suffix('\n').ok_or_else(bad)?; + let (body, check) = text.rsplit_once('\n').ok_or_else(bad)?; + let check = check + .strip_prefix("wanderbooks-manifest-sha256 ") + .ok_or_else(bad)?; + if check != sha_hex(body.as_bytes()) { + return Err(bad()); + } + let m: Manifest = serde_json::from_str(body).map_err(|_| bad())?; + if m.format != FORMAT { + return Err(BackupError::Damaged( + "that isn't a wanderbooks backup".into(), + )); + } + if m.version != VERSION { + return Err(BackupError::Damaged( + "that backup was made by a newer wanderbooks: update to read it".into(), + )); + } + Ok(m) +} + +impl Manifest { + /// What this manifest holds, apart from its number and time: two with + /// the same content need not both be written. + pub(crate) fn same_content(&self, other: &Manifest) -> bool { + let mut a = self.clone(); + let mut b = other.clone(); + for m in [&mut a, &mut b] { + m.number = 0; + m.written.clear(); + } + a == b + } + + /// Every name in it is one this program would have written: nothing + /// that could lead out of the set or into another's. + pub(crate) fn check_names(&self, sealed: bool) -> Result<(), BackupError> { + let bad = |why: &str| BackupError::Damaged(format!("a manifest of the backup {why}")); + if !is_sha(&self.head.hash) && self.head.seq > 0 { + return Err(bad("has a head that is not a hash")); + } + for series in [&self.journal, &self.access, &self.files] { + if !is_sha(&series.sha256) && series.bytes > 0 { + return Err(bad("has a series that is not a hash")); + } + let total = series + .segments + .iter() + .fold(0u64, |a, s| a.saturating_add(s.bytes)); + if total != series.bytes { + return Err(bad("has segments that don't add up")); + } + for p in &series.segments { + self.check_piece(p, sealed)?; + } + } + for n in self.vault.iter().chain(&self.keys) { + if !is_plain_name(&n.name) { + return Err(bad("names a file no book keeps")); + } + self.check_piece(&n.piece, sealed)?; + } + Ok(()) + } + + fn check_piece(&self, p: &Piece, sealed: bool) -> Result<(), BackupError> { + let bad = |why: &str| BackupError::Damaged(format!("a manifest of the backup {why}")); + if !is_sha(&p.sha256) { + return Err(bad("has a piece that is not a hash")); + } + let ok_path = p.file.split('/').all(|part| { + !part.is_empty() + && part != "." + && part != ".." + && part + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_')) + }); + let starts = [ + "journal/", + "access/", + "files-index/", + "files/", + "vault/", + "keys/", + ]; + let right_place = if sealed { + p.file.starts_with(&format!("{PIECES}/")) + } else { + starts.iter().any(|s| p.file.starts_with(s)) + }; + if !ok_path || !right_place { + return Err(bad("names a piece outside the backup")); + } + Ok(()) + } +} diff --git a/crates/ledger-store/src/backups/io.rs b/crates/ledger-store/src/backups/io.rs new file mode 100644 index 00000000..2de10e1f --- /dev/null +++ b/crates/ledger-store/src/backups/io.rs @@ -0,0 +1,275 @@ +//! Where a backup's files live, behind one seam: a folder on a disk +//! ([`DirSet`]), or the one-file form ([`crate::backups::single`]). +//! +//! The only operations a backup needs of a place are four: list a folder, +//! ask how long a file is, read a file, and put a file there that was not +//! there. Nothing deletes, nothing replaces (INVARIANT 1 of the module). +//! +//! How a file is put (the whole of the argument for two writers): +//! +//! * It is written under a name no reader looks at (`.wb-tmp-…`, in the +//! folder it is for), synced, and then given its real name by a +//! *hard link*, which every disk and every network share this program +//! meets either does atomically and exclusively (the name is made, or +//! it exists already: Unix, NTFS, SMB, NFS) or refuses outright (FAT and +//! exFAT disks, some sync folders). A rename is not used for a manifest +//! because on Windows a rename replaces what is at the new name, and on +//! some network shares it does so without telling. +//! * Where hard links are refused, a *piece* (a file named by what is in +//! it) is moved into place by a rename when its name is free: two writers +//! racing for one piece write the same bytes, so whichever lands, the +//! piece is right. A *manifest* is created exclusively under its own name +//! (`create_new`) and written in place: a crash in the middle leaves a +//! short manifest, which no reader accepts (it carries its own check), +//! and its number is simply spent. +//! * A file that is there already is never touched: a piece is taken as +//! the piece (the next proof re-hashes it); a manifest number taken is +//! reported to the writer, which looks again and tries the next. +//! +//! The scratch names are the one thing this code removes from a +//! destination, and only the file it made itself a moment before; one left +//! by a process that died stays (a person may delete `.wb-tmp-*` by hand). + +use super::{BackupError, Ctx}; +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; + +/// What kind of file is being put: how an existing file at the name is met. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum PutKind { + /// Named by what is in it: if it is there, it is the one. + Piece, + /// One for the whole set, written once (the read-me, the header): if + /// it is there, it stays. + Once, + /// A manifest: the name is a number, taken exclusively. The decision + /// point of a backup. + Manifest, +} + +/// How a put came out. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Put { + /// This call made the file. + Created, + /// It was there already: untouched. + Existed, +} + +/// Fill a file: the callback writes its bytes. +pub(crate) type Fill<'a> = &'a mut dyn FnMut(&mut dyn Write) -> std::io::Result<()>; + +/// Where a set's files live. +pub(crate) trait SetIo: Send + Sync { + /// The names directly in `dir` (a path in the set, `/` between parts), + /// none if it is not there. + fn list(&self, dir: &str) -> std::io::Result>; + /// How long the file at `rel` is, None if it is not there. + fn len(&self, rel: &str) -> std::io::Result>; + /// Read the file at `rel` through `f`. + fn read_with( + &self, + rel: &str, + f: &mut dyn FnMut(&mut dyn Read) -> std::io::Result<()>, + ) -> std::io::Result<()>; + /// Put a file at `rel` that is not there ([`PutKind`]). + fn put(&self, rel: &str, kind: PutKind, fill: Fill<'_>) -> std::io::Result; +} + +/// A backup error carried through an `io::Error` (a callback that has to +/// stop the file it is writing). +#[derive(Debug)] +struct Carried(BackupError); + +impl std::fmt::Display for Carried { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.0.fmt(f) + } +} + +impl std::error::Error for Carried {} + +/// `e` as an `io::Error` a callback can return. +pub(crate) fn carry(e: BackupError) -> std::io::Error { + std::io::Error::other(Carried(e)) +} + +/// A backup error back out of an `io::Error` (one that was carried, or the +/// disk's own). +pub(crate) fn uncarry(e: std::io::Error) -> BackupError { + match e.get_ref().and_then(|i| i.downcast_ref::()) { + Some(c) => c.0.clone(), + None => BackupError::Io(e.kind()), + } +} + +/// A set that is a folder on a disk. +pub(crate) struct DirSet { + root: PathBuf, + ctx: Ctx, +} + +impl DirSet { + /// The set in the folder `root` (which need not exist yet). + pub(crate) fn new(root: PathBuf, ctx: Ctx) -> Self { + Self { root, ctx } + } + + fn path(&self, rel: &str) -> PathBuf { + let mut p = self.root.clone(); + for part in rel.split('/').filter(|s| !s.is_empty()) { + p.push(part); + } + p + } +} + +/// A name for a scratch file: unique to this process and moment. +fn scratch_name() -> String { + let mut r = [0u8; 6]; + let _ = getrandom::getrandom(&mut r); + format!( + ".wb-tmp-{}-{}", + std::process::id(), + r.iter().map(|b| format!("{b:02x}")).collect::() + ) +} + +/// Make a folder's entries durable (Unix; NTFS journals its own). +pub(crate) fn sync_dir(path: &Path) { + #[cfg(unix)] + if let Ok(dir) = std::fs::File::open(path) { + let _ = dir.sync_all(); + } + #[cfg(not(unix))] + let _ = path; +} + +/// Whether a link could not be made because the disk does not make them +/// (rather than because the name is taken). +fn link_unsupported(e: &std::io::Error) -> bool { + e.kind() != std::io::ErrorKind::AlreadyExists +} + +impl SetIo for DirSet { + fn list(&self, dir: &str) -> std::io::Result> { + match std::fs::read_dir(self.path(dir)) { + Ok(entries) => { + let mut out = Vec::new(); + for e in entries { + if let Some(n) = e?.file_name().to_str() { + out.push(n.to_string()); + } + } + out.sort(); + Ok(out) + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()), + Err(e) => Err(e), + } + } + + fn len(&self, rel: &str) -> std::io::Result> { + match std::fs::symlink_metadata(self.path(rel)) { + // A link is not a file of a backup: it could lead anywhere. + Ok(m) if m.is_file() => Ok(Some(m.len())), + Ok(_) => Ok(None), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(e), + } + } + + fn read_with( + &self, + rel: &str, + f: &mut dyn FnMut(&mut dyn Read) -> std::io::Result<()>, + ) -> std::io::Result<()> { + let path = self.path(rel); + let meta = std::fs::symlink_metadata(&path)?; + if !meta.is_file() { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "not a plain file", + )); + } + let mut file = std::fs::File::open(path)?; + f(&mut file) + } + + fn put(&self, rel: &str, kind: PutKind, fill: Fill<'_>) -> std::io::Result { + let path = self.path(rel); + let parent = path.parent().unwrap_or(&self.root).to_path_buf(); + std::fs::create_dir_all(&parent)?; + if kind != PutKind::Manifest && std::fs::symlink_metadata(&path).is_ok() { + return Ok(Put::Existed); + } + let tmp = parent.join(scratch_name()); + self.ctx.point("create", rel).map_err(carry)?; + let written = (|| -> std::io::Result<()> { + let mut file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&tmp)?; + { + let mut w = std::io::BufWriter::with_capacity(1 << 16, &mut file); + fill(&mut w)?; + w.flush()?; + } + file.sync_all() + })(); + if let Err(e) = written { + // Something of ours that failed on its own: its scratch file + // goes (a death, which `point` reports, leaves it). + let _ = std::fs::remove_file(&tmp); + return Err(e); + } + self.ctx.point("written", rel).map_err(carry)?; + let put = match std::fs::hard_link(&tmp, &path) { + Ok(()) => { + let _ = std::fs::remove_file(&tmp); + Put::Created + } + Err(e) if !link_unsupported(&e) => { + let _ = std::fs::remove_file(&tmp); + Put::Existed + } + Err(_) => { + // A disk that makes no links. + match kind { + PutKind::Manifest => { + let _ = std::fs::remove_file(&tmp); + match std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&path) + { + Ok(mut file) => { + { + let mut w = std::io::BufWriter::new(&mut file); + fill(&mut w)?; + w.flush()?; + } + file.sync_all()?; + Put::Created + } + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Put::Existed, + Err(e) => return Err(e), + } + } + PutKind::Piece | PutKind::Once => { + if std::fs::symlink_metadata(&path).is_ok() { + let _ = std::fs::remove_file(&tmp); + Put::Existed + } else { + std::fs::rename(&tmp, &path)?; + Put::Created + } + } + } + } + }; + sync_dir(&parent); + self.ctx.point("published", rel).map_err(carry)?; + Ok(put) + } +} diff --git a/crates/ledger-store/src/backups/mod.rs b/crates/ledger-store/src/backups/mod.rs new file mode 100644 index 00000000..83e849fe --- /dev/null +++ b/crates/ledger-store/src/backups/mod.rs @@ -0,0 +1,274 @@ +//! Backups in plain folders (plan/p15-app-and-relay.md section 9, D-91, +//! D-92): a backup is a folder the person picks, holding one folder per +//! set of books, made only of files that are written once. +//! +//! ```text +//! GOAL: a book's every write survives the loss of this computer, a +//! backup is proven whole before it is trusted or restored, and the +//! person needs nothing installed and nothing explained to have one. +//! SOURCE: plan/p15-app-and-relay.md section 9 (the form, D-91: git leaves +//! backups entirely; D-92: a passphrase, off by default), plan 3.7 +//! (what a backup holds, when it runs, the proof after it, the +//! weekly drill), 3.9 and D-39 (a proven local backup with the +//! keys before a format upgrade), WB-backup-1. +//! INVARIANTS: +//! 1. Nothing in a destination is ever deleted or rewritten. Every file +//! is put once (io.rs): a piece under a name made from what is in it, +//! a manifest under its number, taken exclusively. The one thing this +//! code removes from a destination is the scratch file it made itself +//! a moment before. So a destination only grows, a syncing service +//! never sees a file change under it, and an earlier state of the +//! books is always still there. +//! 2. A backup is whole when its manifest is in place, and not before. +//! The manifest is written last, after every piece it names is there; +//! a run that dies leaves pieces no manifest names, which are +//! harmless, and at most a short manifest, which no reader accepts +//! (it carries its own check) and whose number is spent. +//! 3. A manifest names every piece it needs, by where it is, how long it +//! is and what is in it (SHA-256). A reader takes the newest manifest +//! whose pieces are all there at the length it names, and the proof +//! (`verify`) re-hashes every one: the journal's chain replays, every +//! stored file re-hashes, every vault record the books name and the +//! key that opens them are there, the head is the one recorded. +//! 4. A backup is written only onto a destination whose newest whole +//! manifest is a point on the live journal (same line, same hash, +//! same place in the file). Otherwise the destination holds other +//! books or a different history of these, or a newer one than this +//! computer has: it is said, and nothing is written. +//! 5. Two programs, or two computers, writing one destination cannot +//! corrupt it: pieces are named by what is in them, so two writers of +//! one piece write the same bytes; the only decision is which of them +//! takes the next manifest number, and the disk decides it +//! (exclusive create). The loser looks again and goes on from what the +//! winner wrote, or finds there is nothing left to write. +//! 6. Each manifest stands alone: it names all its pieces, so a manifest +//! that is lost, or replaced by a sync service's conflict copy, +//! takes nothing else with it. +//! 7. With a passphrase every piece, every manifest, is sealed +//! (seal.rs); names say no more than counts and sizes; the key is +//! derived by a memory-hard function; this computer keeps it in the +//! book's `local/` folder, owner-only, never in a backup. A wrong +//! passphrase opens nothing, and is told from damage. +//! 8. A step that has to end when the books are let go looks for the +//! stop between pieces, and once per chunk of a file read; a stopped +//! backup leaves a destination that proves whole at its previous +//! manifest. +//! 9. Nothing here names a path of the data root: errors speak of "the +//! backup folder". +//! ``` + +use serde::{Deserialize, Serialize}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +mod cut; +mod form; +mod io; +mod read; +mod seal; +mod single; +mod write; + +pub use cut::Cut; +pub use read::list; +pub use read::{Candidate, Found, Verified, drill, find, prove_local, verify_found}; +pub use seal::BackupKey; +pub use single::{FILE_EXTENSION, save_file}; +pub use write::{Destination, Written, set_name_for, write_destination, write_local}; + +/// What a backup holds, of a book's folder. +pub const BACKED_UP: [&str; 5] = [ + crate::JOURNAL_FILE, + "blobs", + crate::root::VAULT_DIR, + crate::root::KEYS_DIR, + crate::access::ACCESS_FILE, +]; + +/// A book's own local backup, in its folder: the same form as a +/// destination, written under the store's lock before a format upgrade. +pub const LOCAL_DIR: &str = "local-backup"; + +/// Why a backup couldn't be made, proven or restored. Never names a path +/// of the data root (INVARIANT 9). +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum BackupError { + /// A folder that isn't there (an external disk not connected). + #[error("the backup folder isn't there (is its disk connected?)")] + NoFolder, + /// A folder that took these books' backups but holds none now (a disk + /// not mounted on its mount point, or a new disk). + #[error( + "the backup folder holds no backup of these books: connect the disk that does; if it is a new disk, back up now saying so (new_disk)" + )] + NoBackupThere, + /// The destination holds other books, or another history of these. + #[error( + "the backup folder holds a backup of other books, or of a different history of these: nothing was written there" + )] + Elsewhere, + /// The destination is ahead of these books. + #[error( + "the backup folder holds a newer backup of these books (through event {0}) than this computer has (event {1}): nothing was written there" + )] + Ahead(u64, u64), + /// Another program kept taking the next place in the destination. + #[error("another program kept writing to the backup folder: try again in a moment")] + Busy, + /// A backup that isn't whole. + #[error("that backup can't be trusted: {0}")] + Damaged(String), + /// The backup is protected by a passphrase and none was given. + #[error("that backup is protected by a passphrase: it needs the passphrase it was made with")] + NeedsPassphrase, + /// The passphrase given opens nothing. + #[error("that isn't the passphrase this backup was made with")] + WrongPassphrase, + /// A passphrase of a length not taken. + #[error( + "a backup passphrase is {} to {} characters long", + crate::passphrase::MIN_CHARS, + crate::passphrase::MAX_CHARS + )] + PassphraseLength, + /// More than one set of books is there, and which was not said. + #[error( + "that folder holds backups of more than one set of books ({0}): choose the folder of one" + )] + Several(String), + /// Nothing there is a backup. + #[error("there is no backup there")] + NotABackup, + /// Stopped because the books are closing. + #[error("{0} was stopped: the books are closing")] + Cancelled(String), + /// A test's death at a write point; never made otherwise. + #[doc(hidden)] + #[error("the program died here")] + Died, + /// The disk refused. + #[error("the backup couldn't be made: {0}")] + Io(std::io::ErrorKind), +} + +impl From for BackupError { + fn from(e: std::io::Error) -> Self { + io::uncarry(e) + } +} + +impl From for BackupError { + fn from(e: crate::StoreError) -> Self { + match e { + crate::StoreError::Cancelled => BackupError::Cancelled("verifying".into()), + e => BackupError::Damaged(e.to_string()), + } + } +} + +/// Told the name of each phase of a long step as it begins (the server's +/// test knob waits in them). +pub type PhaseWatch = Arc; + +/// A test's way to die at a write point: told the kind of point and the +/// file it is for, answers true to die there. +pub type Faults = Arc bool + Send + Sync>; + +/// What a step is run under: the stop it looks for (INVARIANT 8) and, in +/// tests, where it dies. +#[derive(Clone, Default)] +pub struct Ctx { + stop: Option>, + faults: Option, + phase: Option, +} + +impl std::fmt::Debug for Ctx { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Ctx") + } +} + +impl Ctx { + /// No stop, no faults. + pub fn new() -> Self { + Self::default() + } + + /// Stopped when `flag` is set. + pub fn with_stop(mut self, flag: Arc) -> Self { + self.stop = Some(flag); + self + } + + /// Dies where `faults` says (tests). + #[doc(hidden)] + pub fn with_faults(mut self, faults: Faults) -> Self { + self.faults = Some(faults); + self + } + + /// Told each phase of a long step as it begins. + pub fn with_phase_watch(mut self, watch: PhaseWatch) -> Self { + self.phase = Some(watch); + self + } + + /// A phase of a step begins. + pub(crate) fn phase(&self, name: &str) { + if let Some(w) = &self.phase { + w(name); + } + } + + /// The stop flag, if there is one. + pub fn stop_flag(&self) -> Option> { + self.stop.clone() + } + + /// Ok, or [`BackupError::Cancelled`] when a stop was asked for. + pub fn check(&self, what: &str) -> Result<(), BackupError> { + if self.stop.as_ref().is_some_and(|f| f.load(Ordering::SeqCst)) { + Err(BackupError::Cancelled(what.to_string())) + } else { + Ok(()) + } + } + + /// A write point: where a test's fault may die. + pub(crate) fn point(&self, kind: &str, rel: &str) -> Result<(), BackupError> { + match &self.faults { + Some(f) if f(kind, rel) => Err(BackupError::Died), + _ => Ok(()), + } + } +} + +/// What a person sees of a backup's standing in one line of the record: +/// serialisable pieces for the server. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Reached { + /// The journal seq the backup reaches. + pub seq: u64, + /// Its hash. + pub hash: String, + /// The number of the manifest that made it whole. + pub number: u64, +} + +/// The words in a set's READ-ME, for a person who opens the folder. +pub(crate) const READ_ME_TEXT: &str = "\ +This folder is a backup of a set of books kept with Wanderbooks. + +Nothing in it needs to be opened or changed by hand, and nothing in it is +ever deleted or rewritten by Wanderbooks: a backup only adds files. If your +disk is short of room you may delete the whole folder, but not parts of it. + +To get the books back, open Wanderbooks and choose Restore, then point it at +this folder (or at the folder above it). It checks everything before it +puts anything in place. + +If these backups are protected by a passphrase, the files here are sealed: +only Wanderbooks with that passphrase can read them, and nobody can recover +a forgotten passphrase. +"; diff --git a/crates/ledger-store/src/backups/read.rs b/crates/ledger-store/src/backups/read.rs new file mode 100644 index 00000000..6b5a0a04 --- /dev/null +++ b/crates/ledger-store/src/backups/read.rs @@ -0,0 +1,805 @@ +//! Reading a backup: finding the set, the newest manifest that is whole, +//! the proof (INVARIANT 3), and the books built from it in a scratch +//! folder, for a restore, a drill and the proof before a format upgrade. + +use super::form::*; +use super::io::{DirSet, SetIo, carry, uncarry}; +use super::seal::{BackupKey, Header, Keys, manifest_aad, piece_aad}; +use super::{BackupError, Ctx, Destination}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeSet; +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; + +/// The most a manifest or header may be before it is refused as no such +/// file: nothing this program writes comes near it. +const SMALL_MAX: u64 = 256 << 20; + +/// A set of backups of one set of books, open for reading. +pub(crate) struct Set { + pub(crate) io: Box, + pub(crate) keys: Option, + pub(crate) ctx: Ctx, +} + +/// A reader that looks for the stop before every read and hashes what it +/// gives. +pub(crate) struct Hashed<'a, R: Read> { + inner: R, + ctx: &'a Ctx, + pub(crate) hasher: Sha256, + pub(crate) count: u64, +} + +impl<'a, R: Read> Hashed<'a, R> { + pub(crate) fn new(inner: R, ctx: &'a Ctx) -> Self { + Self { + inner, + ctx, + hasher: Sha256::new(), + count: 0, + } + } +} + +impl Read for Hashed<'_, R> { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + self.ctx.check("backing up").map_err(carry)?; + let n = self.inner.read(buf)?; + self.hasher.update(&buf[..n]); + self.count += n as u64; + Ok(n) + } +} + +impl Set { + pub(crate) fn dir(path: PathBuf, keys: Option, ctx: &Ctx) -> Set { + Set { + io: Box::new(DirSet::new(path, ctx.clone())), + keys, + ctx: ctx.clone(), + } + } + + pub(crate) fn sealed(&self) -> bool { + self.keys.is_some() + } + + /// The numbers of the manifests there, ascending. + pub(crate) fn numbers(&self) -> Result, BackupError> { + let mut n: Vec = self + .io + .list(MANIFESTS)? + .iter() + .filter_map(|name| manifest_number(name, self.sealed())) + .collect(); + n.sort_unstable(); + Ok(n) + } + + fn read_small(&self, rel: &str) -> Result, BackupError> { + match self.io.len(rel)? { + Some(len) if len <= SMALL_MAX => {} + Some(_) => { + return Err(BackupError::Damaged(format!( + "{rel} is not a file of a backup" + ))); + } + None => return Err(BackupError::Damaged(format!("{rel} is missing"))), + } + let mut out = Vec::new(); + self.io.read_with(rel, &mut |r| { + r.take(SMALL_MAX).read_to_end(&mut out).map(|_| ()) + })?; + Ok(out) + } + + /// The manifest numbered `n`: read, opened, checked. + pub(crate) fn manifest(&self, n: u64) -> Result { + let raw = self.read_small(&manifest_path(n, self.sealed()))?; + let bytes = match &self.keys { + Some(k) => k.open_bytes(&raw, &manifest_aad(n))?, + None => raw, + }; + let m = decode_manifest(&bytes)?; + if m.number != n { + return Err(BackupError::Damaged( + "a manifest of the backup is under another number".into(), + )); + } + m.check_names(self.sealed())?; + Ok(m) + } + + /// Whether every piece `m` names, apart from the stored files, is + /// there at the length it names: the cheap look that decides which + /// manifest is the newest whole one. The proof re-hashes. + fn looks_whole(&self, m: &Manifest) -> Result { + let pieces = m + .journal + .segments + .iter() + .chain(&m.access.segments) + .chain(&m.files.segments) + .chain(m.vault.iter().map(|n| &n.piece)) + .chain(m.keys.iter().map(|n| &n.piece)); + for p in pieces { + if self.io.len(&p.file)? != Some(p.stored) { + return Ok(false); + } + } + Ok(true) + } + + /// The newest manifest that is whole to the eye (INVARIANT 3), and + /// how many newer ones were passed over. + pub(crate) fn newest_whole(&self) -> Result, BackupError> { + let numbers = self.numbers()?; + for (skipped, n) in numbers.iter().rev().enumerate() { + self.ctx.check("reading the backup")?; + if let Ok(m) = self.manifest(*n) + && self.looks_whole(&m)? + { + return Ok(Some((m, skipped))); + } + } + Ok(None) + } + + /// Every manifest that is whole to the eye, newest first. + pub(crate) fn whole_ones(&self) -> Result, BackupError> { + let mut out = Vec::new(); + for n in self.numbers()?.iter().rev() { + self.ctx.check("reading the backup")?; + if let Ok(m) = self.manifest(*n) + && self.looks_whole(&m)? + { + out.push(m); + } + } + Ok(out) + } + + /// The contents of the piece at `rel` (of `kind`, `bytes` long, hashing + /// to `sha`) handed to `sink`, proven as they go: a piece that is not + /// what its manifest says is an error. A sealed piece is opened first. + pub(crate) fn read_piece( + &self, + rel: &str, + kind: Kind, + bytes: u64, + sha: &str, + sink: &mut dyn FnMut(&[u8]) -> std::io::Result<()>, + ) -> Result<(), BackupError> { + let damaged = + || BackupError::Damaged(format!("a piece of the backup ({}) is damaged", short(sha))); + let mut hasher = Sha256::new(); + let mut count = 0u64; + let mut feed = |chunk: &[u8]| -> std::io::Result<()> { + hasher.update(chunk); + count += chunk.len() as u64; + sink(chunk) + }; + let ctx = self.ctx.clone(); + let opened: Result<(), BackupError> = match &self.keys { + None => { + let mut res: Result<(), BackupError> = Ok(()); + let io_res = self.io.read_with(rel, &mut |r| { + let mut r = r.take(bytes.saturating_add(1)); + let mut buf = vec![0u8; 1 << 16]; + loop { + ctx.check("reading the backup").map_err(carry)?; + let n = r.read(&mut buf)?; + if n == 0 { + return Ok(()); + } + feed(&buf[..n])?; + } + }); + if let Err(e) = io_res { + res = Err(uncarry(e)); + } + res + } + Some(keys) => { + let mut res: Result<(), BackupError> = Ok(()); + let aad = piece_aad(kind.dir(), sha); + let limit = Keys::sealed_len(bytes).saturating_add(1); + let io_res = self.io.read_with(rel, &mut |r| { + res = keys.open_stream(&mut r.take(limit), &aad, &mut |c| { + ctx.check("reading the backup").map_err(carry)?; + feed(c) + }); + Ok(()) + }); + match io_res { + Err(e) => Err(uncarry(e)), + Ok(()) => res, + } + } + }; + match opened { + Ok(()) => {} + Err(BackupError::Io(std::io::ErrorKind::NotFound)) => { + return Err(BackupError::Damaged(format!( + "a piece of the backup ({}) is missing", + short(sha) + ))); + } + Err(e) => return Err(e), + } + if count != bytes || hex::encode(hasher.finalize()) != sha { + return Err(damaged()); + } + Ok(()) + } + + /// A series read whole through `sink`, its segments and the whole + /// proven against the manifest. + pub(crate) fn read_series( + &self, + series: &Series, + kind: Kind, + sink: &mut dyn FnMut(&[u8]) -> std::io::Result<()>, + ) -> Result<(), BackupError> { + let mut total = Sha256::new(); + let mut bytes = 0u64; + for seg in &series.segments { + self.ctx.check("reading the backup")?; + self.read_piece(&seg.file, kind, seg.bytes, &seg.sha256, &mut |c| { + total.update(c); + bytes += c.len() as u64; + sink(c) + })?; + } + if bytes != series.bytes || (bytes > 0 && hex::encode(total.finalize()) != series.sha256) { + return Err(BackupError::Damaged( + "the backup's pieces don't add up to what its manifest says".into(), + )); + } + Ok(()) + } + + /// The index of stored files a manifest names. + pub(crate) fn index(&self, m: &Manifest) -> Result, BackupError> { + let mut text = Vec::new(); + self.read_series(&m.files, Kind::Index, &mut |c| { + text.extend_from_slice(c); + Ok(()) + })?; + let mut out = Vec::new(); + let mut seen = BTreeSet::new(); + for line in text.split(|b| *b == b'\n').filter(|l| !l.is_empty()) { + let l: IndexLine = serde_json::from_slice(line).map_err(|_| { + BackupError::Damaged("the backup's index of stored files is damaged".into()) + })?; + if !is_sha(&l.sha256) { + return Err(BackupError::Damaged( + "the backup's index of stored files names a file by no hash".into(), + )); + } + if seen.insert(l.sha256.clone()) { + out.push(l); + } + } + Ok(out) + } +} + +fn short(sha: &str) -> &str { + &sha[..12.min(sha.len())] +} + +/// A set found at a source, ready to be proven. +pub struct Found { + set: Set, + key: Option, + /// The books' id as the newest manifest says it. + pub book: Option, + /// Whether it is sealed. + pub sealed: bool, +} + +/// One set of books in a folder, as listed for a person to choose from. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Candidate { + /// The folder's name inside the destination. + pub folder: String, + /// The books' id, if it could be read (a sealed one needs the + /// passphrase first). + pub book: Option, + /// Sealed. + pub sealed: bool, +} + +fn open_header(set: &Set) -> Result, BackupError> { + match set.io.len(HEADER)? { + None => Ok(None), + Some(_) => Header::decode(&set.read_small(HEADER)?).map(Some), + } +} + +/// Open the set at `io`, plain or sealed, with `passphrase` for a sealed one. +fn open_set( + io: Box, + passphrase: Option<&str>, + ctx: &Ctx, +) -> Result<(Set, Option), BackupError> { + let probe = Set { + io, + keys: None, + ctx: ctx.clone(), + }; + let Some(header) = open_header(&probe)? else { + return Ok((probe, None)); + }; + let pass = passphrase.ok_or(BackupError::NeedsPassphrase)?; + let key = BackupKey::from_header(pass, &header)?; + let set = Set { + io: probe.io, + keys: Some(key.keys()), + ctx: ctx.clone(), + }; + Ok((set, Some(key))) +} + +fn found_from(set: Set, key: Option) -> Result { + let book = set.newest_whole()?.map(|(m, _)| m.book); + Ok(Found { + sealed: set.sealed(), + set, + key, + book, + }) +} + +/// The folders of `dir` that hold a set (a `manifests` folder inside). +fn set_folders(dir: &Path) -> Vec { + let mut out = Vec::new(); + if let Ok(entries) = std::fs::read_dir(dir) { + for e in entries.flatten() { + let p = e.path(); + if p.join(MANIFESTS).is_dir() + && let Some(n) = p.file_name().and_then(|n| n.to_str()) + { + out.push(n.to_string()); + } + } + } + out.sort(); + out +} + +/// Find the backup at `source`: a destination folder, a set's own folder, +/// or a single backup file. A sealed one needs `passphrase`. +pub fn find(source: &Path, passphrase: Option<&str>, ctx: &Ctx) -> Result { + let meta = std::fs::symlink_metadata(source).map_err(|e| match e.kind() { + std::io::ErrorKind::NotFound => BackupError::NotABackup, + _ => BackupError::from(e), + })?; + if meta.is_file() { + let (set, key) = open_set(super::single::open(source, ctx)?, passphrase, ctx)?; + return found_from(set, key); + } + if !meta.is_dir() { + return Err(BackupError::NotABackup); + } + if source.join(MANIFESTS).is_dir() { + let (set, key) = open_set( + Box::new(DirSet::new(source.to_path_buf(), ctx.clone())), + passphrase, + ctx, + )?; + return found_from(set, key); + } + let folders = set_folders(source); + let mut found: Vec<(String, Found)> = Vec::new(); + let mut wrong = false; + let mut needs = false; + for name in &folders { + match open_set( + Box::new(DirSet::new(source.join(name), ctx.clone())), + passphrase, + ctx, + ) { + Ok((set, key)) => found.push((name.clone(), found_from(set, key)?)), + Err(BackupError::WrongPassphrase) => wrong = true, + Err(BackupError::NeedsPassphrase) => needs = true, + // A folder that is not a whole set is not a candidate. + Err(BackupError::Damaged(_)) => {} + Err(e) => return Err(e), + } + } + // Only sets that hold a backup count. + found.retain(|(_, f)| f.book.is_some()); + match found.len() { + 1 => Ok(found.pop().expect("one").1), + 0 if wrong => Err(BackupError::WrongPassphrase), + 0 if needs => Err(BackupError::NeedsPassphrase), + 0 => Err(BackupError::NotABackup), + _ => Err(BackupError::Several( + found + .iter() + .map(|(n, f)| format!("{} ({n})", f.book.as_deref().unwrap_or("?"))) + .collect::>() + .join(", "), + )), + } +} + +/// Every set in a destination folder, for a person to choose from. +pub fn list(source: &Path) -> Vec { + let probe = |name: &str| -> Candidate { + let ctx = Ctx::new(); + let set = Set::dir(source.join(name), None, &ctx); + let sealed = set.io.len(HEADER).ok().flatten().is_some(); + let book = (!sealed) + .then(|| set.newest_whole().ok().flatten().map(|(m, _)| m.book)) + .flatten(); + Candidate { + folder: name.to_string(), + book, + sealed, + } + }; + set_folders(source).iter().map(|n| probe(n)).collect() +} + +/// A backup proven whole (INVARIANT 3). +#[derive(Debug, Clone)] +pub struct Verified { + /// Its journal's head: seq and hash. + pub head: (u64, String), + /// Stored files re-hashed. + pub blobs: u64, + /// The scratch folder the books were built in. + pub tree: PathBuf, + /// The id of the books it holds, as they were backed up. + pub book: Option, + /// Its manifest's number. + pub number: u64, + /// Newer manifests that were not whole and were passed over. + pub passed_over: usize, + /// The key, if it was sealed: for the restored books to carry on + /// backing up sealed. + pub key: Option, +} + +/// Write `bytes` as a new file in `dir` (a scratch folder of this program's +/// own: plain files, nothing removed). +fn put_scratch(dir: &Path, name: &str, bytes: &[u8]) -> std::io::Result<()> { + std::fs::create_dir_all(dir)?; + let mut f = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(dir.join(name))?; + f.write_all(bytes)?; + f.sync_all() +} + +/// Build the books of `m` in `scratch` (a new folder): the journal, the +/// access log, the vault and the keys, and, with `with_files`, every +/// stored file; every piece proven as it is read. Without `with_files` the +/// stored files are re-hashed and not kept (a drill). Returns the hashes of +/// the stored files proven. +fn materialize( + set: &Set, + m: &Manifest, + scratch: &Path, + with_files: bool, +) -> Result, BackupError> { + let ctx = &set.ctx; + std::fs::create_dir_all(scratch)?; + for (series, kind, name) in [ + (&m.journal, Kind::Journal, crate::JOURNAL_FILE), + (&m.access, Kind::Access, crate::access::ACCESS_FILE), + ] { + let mut f = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(scratch.join(name))?; + set.read_series(series, kind, &mut |c| f.write_all(c))?; + f.sync_all()?; + } + for (list, kind, dir) in [ + (&m.vault, Kind::Vault, crate::root::VAULT_DIR), + (&m.keys, Kind::Key, crate::root::KEYS_DIR), + ] { + for n in list { + let mut bytes = Vec::new(); + set.read_piece( + &n.piece.file, + kind, + n.piece.bytes, + &n.piece.sha256, + &mut |c| { + bytes.extend_from_slice(c); + Ok(()) + }, + )?; + put_scratch(&scratch.join(dir), &n.name, &bytes)?; + } + } + let mut proven = BTreeSet::new(); + for line in set.index(m)? { + ctx.check("reading the backup")?; + let rel = piece_path(set.keys.as_ref(), Kind::File, 0, &line.sha256); + if with_files { + let blob = scratch + .join(crate::store::BLOBS_DIR) + .join(&line.sha256[0..2]) + .join(&line.sha256[2..4]); + std::fs::create_dir_all(&blob)?; + let mut f = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(blob.join(&line.sha256))?; + set.read_piece(&rel, Kind::File, line.bytes, &line.sha256, &mut |c| { + f.write_all(c) + })?; + f.sync_all()?; + } else { + set.read_piece(&rel, Kind::File, line.bytes, &line.sha256, &mut |_| Ok(()))?; + } + proven.insert(line.sha256); + } + Ok(proven) +} + +/// Prove the books built in `scratch` from `m` (INVARIANT 3): the chain +/// replays, every stored file the books name is among those proven, every +/// vault record the books name and the key that opens them are there, the +/// head is the one the manifest records. +fn prove_books( + m: &Manifest, + scratch: &Path, + proven_files: &BTreeSet, + with_files: bool, + ctx: &Ctx, +) -> Result<(u64, (u64, String)), BackupError> { + ctx.phase("replay"); + let _stoppable = ctx.stop_flag().map(crate::cancel::scope); + let mut store = crate::Store::open(scratch)?; + ctx.phase("verify"); + store.verify_and_heal()?; + ctx.phase("blobs"); + let named: BTreeSet = store.stored_blob_shas()?.into_iter().collect(); + if let Some(missing) = named.iter().find(|s| !proven_files.contains(*s)) { + return Err(BackupError::Damaged(format!( + "a stored file the books name isn't in it ({})", + short(missing) + ))); + } + let blobs = if with_files { + store.verify_blobs()? + } else { + proven_files.len() as u64 + }; + let head = store.head(); + let tins: Vec = store + .ledger() + .parties() + .flat_map(|p| { + [ + p.tin.as_ref().and_then(|t| t.vault_record.clone()), + p.w9.as_ref().and_then(|w| w.vault_record.clone()), + ] + }) + .flatten() + .collect(); + drop(store); + ctx.phase("vault"); + if !tins.is_empty() { + let held: BTreeSet<&str> = m.vault.iter().map(|n| n.piece.sha256.as_str()).collect(); + if let Some(missing) = tins.iter().find(|h| !held.contains(h.as_str())) { + return Err(BackupError::Damaged(format!( + "a TIN record the books name isn't in it ({})", + short(missing) + ))); + } + if !m + .keys + .iter() + .any(|n| n.name == crate::root::LEGACY_KEY_FILE) + { + return Err(BackupError::Damaged( + "its TIN records are in it, but not the key that opens them".into(), + )); + } + } + if head.0 != m.head.seq || head.1 != m.head.hash { + return Err(BackupError::Damaged(format!( + "its journal ends at event {}, but the backup records another head", + head.0 + ))); + } + Ok((blobs, head)) +} + +/// Prove the backup found, building its books in `scratch` (a new folder): +/// the newest manifest that proves whole; a newer one that does not is +/// passed over and said. With `with_files`, every stored file is kept in +/// the scratch folder (a restore); without, they are re-hashed and not +/// kept (a drill). +pub fn verify_found( + found: &Found, + scratch: &Path, + with_files: bool, + ctx: &Ctx, +) -> Result { + if scratch.exists() { + return Err(BackupError::Damaged("its scratch folder is in use".into())); + } + let set = &found.set; + let mut passed = 0usize; + let mut last: Option = None; + for m in set.whole_ones()? { + ctx.phase("fetch"); + ctx.check("verifying")?; + let attempt = materialize(set, &m, scratch, with_files) + .and_then(|files| prove_books(&m, scratch, &files, with_files, ctx)); + match attempt { + Ok((blobs, head)) => { + return Ok(Verified { + head, + blobs, + tree: scratch.to_path_buf(), + book: Some(m.book.clone()), + number: m.number, + passed_over: passed, + key: found.key.clone(), + }); + } + Err(e @ (BackupError::Cancelled(_) | BackupError::Died)) => { + let _ = std::fs::remove_dir_all(scratch); + return Err(e); + } + Err(e) => { + // Not this one: another, older, may be whole. + let _ = std::fs::remove_dir_all(scratch); + passed += 1; + last = Some(e); + } + } + } + Err(last.unwrap_or(BackupError::NotABackup)) +} + +/// Whether the journal at `backup` is a byte prefix of the one at `live` +/// (a drill: the backup holds the book's history, nothing else). +pub fn is_prefix(live: &Path, backup: &Path, ctx: &Ctx) -> Result { + let mut a = std::fs::File::open(live)?; + let mut b = std::fs::File::open(backup)?; + let (mut x, mut y) = (vec![0u8; 64 * 1024], vec![0u8; 64 * 1024]); + loop { + ctx.check("comparing journals")?; + let n = b.read(&mut y)?; + if n == 0 { + return Ok(true); + } + let mut got = 0; + while got < n { + let m = a.read(&mut x[got..n])?; + if m == 0 { + return Ok(false); + } + got += m; + } + if x[..n] != y[..n] { + return Ok(false); + } + } +} + +/// A restore drill (INVARIANT 3): the backup of the book `book` in the +/// destination, its books built in `scratch` (a new folder, removed +/// after), proven whole, and its journal a byte prefix of `live` (the +/// book's journal now). Its head. +pub fn drill( + dest: &Destination, + book: &str, + live: &Path, + scratch: &Path, + ctx: &Ctx, +) -> Result<(u64, String), BackupError> { + if !dest.folder.is_dir() { + return Err(BackupError::NoFolder); + } + let set = super::write::locate(dest, book, ctx)?.ok_or(BackupError::NoBackupThere)?; + let found = Found { + sealed: set.sealed(), + book: Some(book.to_string()), + key: dest.key.clone(), + set, + }; + let checked = verify_found(&found, scratch, false, ctx).and_then(|v| { + ctx.phase("prefix"); + if v.book.as_deref() != Some(book) { + return Err(BackupError::Elsewhere); + } + match is_prefix(live, &v.tree.join(crate::JOURNAL_FILE), ctx) { + Ok(true) => Ok(v.head), + Ok(false) => Err(BackupError::Damaged( + "its journal isn't this book's history".into(), + )), + Err(e) => Err(e), + } + }); + let _ = std::fs::remove_dir_all(scratch); + checked +} + +/// Prove the book's own local backup (`local-backup/`, in its folder) +/// holds the book in `book_dir` exactly as it is now, its journal's head +/// `head` (INVARIANT 3, and more): proven as a restore proves a backup, +/// its head `head`, its journal the book's byte for byte, and its vault +/// and keys the book's, file for file and byte for byte. What the format +/// upgrade asks of the backup it makes first (plan/served.md 3.9: "a +/// verified local backup that includes the keys"). The caller holds the +/// store's lock, so the book can't move while it is compared. +pub fn prove_local( + book_dir: &Path, + book: &str, + head: &(u64, String), + scratch: &Path, + ctx: &Ctx, +) -> Result { + let dest = Destination { + folder: book_dir.join(super::LOCAL_DIR), + key: None, + }; + let set = super::write::locate(&dest, book, ctx)?.ok_or(BackupError::NoBackupThere)?; + let found = Found { + sealed: false, + book: Some(book.to_string()), + key: None, + set, + }; + let proven = verify_found(&found, scratch, false, ctx).and_then(|v| { + if v.head != *head { + return Err(BackupError::Damaged(format!( + "it holds the books through event {}, and they are at event {}", + v.head.0, head.0 + ))); + } + ctx.phase("compare"); + ctx.check("comparing")?; + if std::fs::read(book_dir.join(crate::JOURNAL_FILE)).unwrap_or_default() + != std::fs::read(v.tree.join(crate::JOURNAL_FILE))? + { + return Err(BackupError::Damaged( + "its journal isn't the books' own, byte for byte".into(), + )); + } + for kept in [crate::root::VAULT_DIR, crate::root::KEYS_DIR] { + if flat(&book_dir.join(kept))? != flat(&v.tree.join(kept))? { + return Err(BackupError::Damaged(format!( + "its {} isn't the books' own, file for file", + if kept == crate::root::KEYS_DIR { + "keys folder" + } else { + "TIN vault" + } + ))); + } + } + Ok(v.blobs) + }); + let _ = std::fs::remove_dir_all(scratch); + proven +} + +fn flat(dir: &Path) -> Result)>, BackupError> { + let mut out = Vec::new(); + if let Ok(entries) = std::fs::read_dir(dir) { + for e in entries { + let e = e?; + out.push(( + e.file_name().to_string_lossy().into_owned(), + std::fs::read(e.path())?, + )); + } + } + out.sort(); + Ok(out) +} diff --git a/crates/ledger-store/src/backups/seal.rs b/crates/ledger-store/src/backups/seal.rs new file mode 100644 index 00000000..4e23d170 --- /dev/null +++ b/crates/ledger-store/src/backups/seal.rs @@ -0,0 +1,448 @@ +//! A backup protected by a passphrase (D-92): the key, the header that +//! lets another computer derive it, the sealed form of a piece, and the +//! key kept privately on this computer. +//! +//! The passphrase is run through Argon2id (the same function and the same +//! cost as the owner passphrase, `passphrase.rs`: 64 MiB, 3 passes, 1 lane, +//! RFC 9106) with a random salt of its own. The 32 bytes it gives (the +//! *master*) are what this computer keeps, never the passphrase. Two keys +//! come from the master, each by SHA-256 of a label and the master: the +//! one pieces are sealed with, and the one their names are made with. +//! +//! A piece is sealed in chunks of 1 MiB with XChaCha20-Poly1305 (as the TIN +//! vault is): a random 16-byte prefix per piece and an 8-byte chunk +//! counter make each chunk's 24-byte nonce; each chunk's associated data +//! is the piece's identity (what is in it) and whether it is the last, so +//! a piece cut short, reordered, or put under another's name is not +//! opened. + +use super::BackupError; +use super::form::sha_hex; +use argon2::{Algorithm, Argon2, Params, Version}; +use chacha20poly1305::aead::{Aead, KeyInit, Payload}; +use chacha20poly1305::{XChaCha20Poly1305, XNonce}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::io::{Read, Write}; +use std::path::Path; +use zeroize::Zeroizing; + +/// The sealed piece's first bytes. +const MAGIC: &[u8; 4] = b"WBS1"; +/// Plaintext bytes in a chunk. +const CHUNK: usize = 1 << 20; +/// What a chunk's seal adds. +const TAG: usize = 16; +/// The salt's length. +const SALT_LEN: usize = 16; +/// The words the header's check seals: opening them tells a right +/// passphrase from a wrong one. +const CHECK_TEXT: &[u8] = b"wanderbooks backup key check"; +/// The local key file's folder in a book's folder, and its name. +pub(crate) const LOCAL_DIR: &str = "local"; +/// The key file's name. +pub(crate) const KEY_FILE: &str = "backup-key.json"; + +/// How the passphrase is stretched. Recorded in the header so another +/// computer derives the same key. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) struct Kdf { + pub alg: String, + pub m: u32, + pub t: u32, + pub p: u32, + /// Hex. + pub salt: String, +} + +/// The key a passphrase makes, with how it was made. Kept on this +/// computer in the book's `local/` folder; never in a backup, never in the +/// journal, never in a log (its `Debug` says nothing of the key). +#[derive(Clone)] +pub struct BackupKey { + kdf: Kdf, + master: Zeroizing<[u8; 32]>, +} + +impl std::fmt::Debug for BackupKey { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("BackupKey(..)") + } +} + +/// Whether `kdf` asks nothing weaker than this program's own cost, and +/// nothing a computer could not afford (a header changed by hand). +fn kdf_in_bounds(kdf: &Kdf) -> bool { + kdf.alg == "argon2id" + && (crate::passphrase::M_COST..=1024 * 1024).contains(&kdf.m) + && (crate::passphrase::T_COST..=16).contains(&kdf.t) + && (crate::passphrase::P_COST..=8).contains(&kdf.p) + && hex::decode(&kdf.salt).is_ok_and(|s| (SALT_LEN..=64).contains(&s.len())) +} + +fn stretch(passphrase: &str, kdf: &Kdf) -> Result, BackupError> { + if !kdf_in_bounds(kdf) { + return Err(BackupError::Damaged( + "its header asks for a key this program won't derive".into(), + )); + } + let salt = hex::decode(&kdf.salt).expect("checked"); + let params = Params::new(kdf.m, kdf.t, kdf.p, Some(32)) + .map_err(|_| BackupError::Damaged("its header's key settings are not valid".into()))?; + let mut out = Zeroizing::new([0u8; 32]); + Argon2::new(Algorithm::Argon2id, Version::V0x13, params) + .hash_password_into(passphrase.as_bytes(), &salt, &mut *out) + .map_err(|_| BackupError::Damaged("the key could not be derived".into()))?; + Ok(out) +} + +impl BackupKey { + /// A new key from `passphrase` with a salt of its own. + pub fn generate(passphrase: &str) -> Result { + crate::passphrase::check_length(passphrase).map_err(|_| BackupError::PassphraseLength)?; + let mut salt = [0u8; SALT_LEN]; + getrandom::getrandom(&mut salt) + .map_err(|e| BackupError::Io(std::io::Error::from(e).kind()))?; + let kdf = Kdf { + alg: "argon2id".into(), + m: crate::passphrase::M_COST, + t: crate::passphrase::T_COST, + p: crate::passphrase::P_COST, + salt: hex::encode(salt), + }; + let master = stretch(passphrase, &kdf)?; + Ok(Self { kdf, master }) + } + + fn label(&self, label: &str) -> Zeroizing<[u8; 32]> { + let mut h = Sha256::new(); + h.update(b"wanderbooks backup v1 "); + h.update(label.as_bytes()); + h.update(*self.master); + Zeroizing::new(h.finalize().into()) + } + + /// The sealing and naming keys. + pub(crate) fn keys(&self) -> Keys { + Keys { + enc: self.label("encryption"), + names: self.label("names"), + kdf: self.kdf.clone(), + } + } + + /// The same key as another: the same passphrase and salt. + pub fn same_as(&self, other: &BackupKey) -> bool { + use subtle::ConstantTimeEq; + self.kdf.salt == other.kdf.salt && bool::from(self.master.ct_eq(&*other.master)) + } + + /// Keep it, privately, in the book's folder (INVARIANT: owner-only). + pub fn store(&self, book_dir: &Path) -> Result<(), BackupError> { + let dir = crate::root::private_book_folder(book_dir, LOCAL_DIR) + .map_err(|e| BackupError::Damaged(e.to_string()))?; + #[derive(Serialize)] + struct OnDisk<'a> { + version: u32, + kdf: &'a Kdf, + master: String, + } + let text = Zeroizing::new( + serde_json::to_string_pretty(&OnDisk { + version: 1, + kdf: &self.kdf, + master: hex::encode(*self.master), + }) + .expect("a key serializes"), + ); + let tmp = dir.join(format!(".{KEY_FILE}.new")); + let _ = std::fs::remove_file(&tmp); + crate::root::write_new_private_file(&tmp, text.as_bytes())?; + std::fs::rename(&tmp, dir.join(KEY_FILE))?; + super::io::sync_dir(&dir); + Ok(()) + } + + /// The key kept for the book in `book_dir`, if one is. + pub fn load(book_dir: &Path) -> Result, BackupError> { + let path = book_dir.join(LOCAL_DIR).join(KEY_FILE); + let text = match std::fs::read_to_string(&path) { + Ok(t) => Zeroizing::new(t), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(e.into()), + }; + #[derive(Deserialize)] + struct OnDisk { + version: u32, + kdf: Kdf, + master: String, + } + let bad = || BackupError::Damaged("the backup passphrase's key can't be read".into()); + let on: OnDisk = serde_json::from_str(&text).map_err(|_| bad())?; + if on.version != 1 || !kdf_in_bounds(&on.kdf) { + return Err(bad()); + } + let master_hex = Zeroizing::new(on.master); + let raw = Zeroizing::new(hex::decode(master_hex.as_str()).map_err(|_| bad())?); + let master: [u8; 32] = raw.as_slice().try_into().map_err(|_| bad())?; + Ok(Some(Self { + kdf: on.kdf, + master: Zeroizing::new(master), + })) + } + + /// Forget it (the passphrase is taken off): the next backup is plain. + /// The file is removed from this computer only. + pub fn forget(book_dir: &Path) -> Result<(), BackupError> { + match std::fs::remove_file(book_dir.join(LOCAL_DIR).join(KEY_FILE)) { + Ok(()) => Ok(()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(e) => Err(e.into()), + } + } + + /// Derive the key `passphrase` makes from what a sealed set's header + /// says: [`BackupError::WrongPassphrase`] when it opens nothing, + /// [`BackupError::Damaged`] when the header itself is not whole. + pub(crate) fn from_header(passphrase: &str, header: &Header) -> Result { + let master = stretch(passphrase, &header.kdf)?; + let key = Self { + kdf: header.kdf.clone(), + master, + }; + key.keys().check(header)?; + Ok(key) + } +} + +/// The two keys a set uses. +pub(crate) struct Keys { + enc: Zeroizing<[u8; 32]>, + names: Zeroizing<[u8; 32]>, + kdf: Kdf, +} + +/// A sealed set's header: what another computer needs to derive the key, +/// and a sealed check that tells a wrong passphrase from damage. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) struct Header { + pub format: String, + pub version: u32, + pub cipher: String, + pub kdf: Kdf, + /// Hex of the check text, sealed. + pub check: String, + /// SHA-256 of the sealed check, hex: it differs from the check only if + /// the header was damaged. + pub check_sha256: String, +} + +const HEADER_FORMAT: &str = "wanderbooks-backup-header"; + +impl Header { + /// The header's file: JSON, a newline, and its own check line. + pub(crate) fn encode(&self) -> Vec { + let body = serde_json::to_string(self).expect("a header serializes"); + format!( + "{body}\nwanderbooks-header-sha256 {}\n", + sha_hex(body.as_bytes()) + ) + .into_bytes() + } + + /// A header read back, or why it is not one. + pub(crate) fn decode(bytes: &[u8]) -> Result { + let bad = + || BackupError::Damaged("the sealed backup's header is cut short or changed".into()); + let text = std::str::from_utf8(bytes).map_err(|_| bad())?; + let text = text.strip_suffix('\n').ok_or_else(bad)?; + let (body, check) = text.rsplit_once('\n').ok_or_else(bad)?; + if check.strip_prefix("wanderbooks-header-sha256 ") != Some(&sha_hex(body.as_bytes())) { + return Err(bad()); + } + let h: Header = serde_json::from_str(body).map_err(|_| bad())?; + if h.format != HEADER_FORMAT || h.version != 1 || h.cipher != "xchacha20poly1305-stream" { + return Err(BackupError::Damaged( + "the sealed backup's header is of a kind this program doesn't know".into(), + )); + } + Ok(h) + } +} + +impl Keys { + /// The header for a set sealed with these keys. + pub(crate) fn header(&self) -> Header { + let mut sealed = Vec::new(); + self.seal_stream(&mut &CHECK_TEXT[..], &mut sealed, b"wb1|header") + .expect("sealing into memory"); + Header { + format: HEADER_FORMAT.into(), + version: 1, + cipher: "xchacha20poly1305-stream".into(), + kdf: self.kdf.clone(), + check_sha256: sha_hex(&sealed), + check: hex::encode(sealed), + } + } + + /// Whether these keys open `header`'s check. + pub(crate) fn check(&self, header: &Header) -> Result<(), BackupError> { + let sealed = hex::decode(&header.check) + .ok() + .filter(|s| sha_hex(s) == header.check_sha256) + .ok_or_else(|| BackupError::Damaged("the sealed backup's header was changed".into()))?; + let mut plain = Vec::new(); + match self.open_stream(&mut &sealed[..], b"wb1|header", &mut |b| { + plain.extend_from_slice(b); + Ok(()) + }) { + Ok(()) if plain == CHECK_TEXT => Ok(()), + _ => Err(BackupError::WrongPassphrase), + } + } + + /// The name a piece is kept under: made from the key, the piece's + /// kind and its hash. + pub(crate) fn piece_name(&self, kind: &str, sha: &str) -> String { + let mut h = Sha256::new(); + h.update(*self.names); + h.update(kind.as_bytes()); + h.update([0]); + h.update(sha.as_bytes()); + hex::encode(h.finalize()) + } + + fn cipher(&self) -> XChaCha20Poly1305 { + XChaCha20Poly1305::new_from_slice(&self.enc[..]).expect("a 32-byte key") + } + + /// The length a piece of `plain` bytes is kept at. + pub(crate) fn sealed_len(plain: u64) -> u64 { + let chunks = plain.div_ceil(CHUNK as u64).max(1); + (MAGIC.len() + 16) as u64 + plain + chunks * TAG as u64 + } + + /// Seal all of `plain` into `out`, bound to `aad` (the piece's + /// identity). + pub(crate) fn seal_stream( + &self, + plain: &mut dyn Read, + out: &mut dyn Write, + aad: &[u8], + ) -> std::io::Result<()> { + let cipher = self.cipher(); + let mut prefix = [0u8; 16]; + getrandom::getrandom(&mut prefix).map_err(std::io::Error::from)?; + out.write_all(MAGIC)?; + out.write_all(&prefix)?; + let mut cur = read_full(plain, CHUNK)?; + let mut counter = 0u64; + loop { + let next = read_full(plain, CHUNK)?; + let last = next.is_empty(); + let mut nonce = [0u8; 24]; + nonce[..16].copy_from_slice(&prefix); + nonce[16..].copy_from_slice(&counter.to_be_bytes()); + let mut a = aad.to_vec(); + a.push(u8::from(last)); + let ct = cipher + .encrypt(&XNonce::from(nonce), Payload { msg: &cur, aad: &a }) + .map_err(|_| std::io::Error::other("sealing failed"))?; + out.write_all(&ct)?; + if last { + return Ok(()); + } + cur = next; + counter += 1; + } + } + + /// Open a sealed piece, handing its contents to `sink` chunk by chunk. + /// A wrong key, a changed byte, a piece cut short, or one bound to + /// another identity is an error before the contents are complete; the + /// caller discards what the sink had. + pub(crate) fn open_stream( + &self, + stored: &mut dyn Read, + aad: &[u8], + sink: &mut dyn FnMut(&[u8]) -> std::io::Result<()>, + ) -> Result<(), BackupError> { + let bad = + || BackupError::Damaged("a piece of the sealed backup is damaged or cut short".into()); + let cipher = self.cipher(); + let mut head = [0u8; 4 + 16]; + stored.read_exact(&mut head).map_err(|_| bad())?; + if &head[..4] != MAGIC { + return Err(bad()); + } + let prefix: [u8; 16] = head[4..].try_into().expect("16 bytes"); + let mut cur = read_full(stored, CHUNK + TAG).map_err(super::io::uncarry)?; + if cur.is_empty() { + return Err(bad()); + } + let mut counter = 0u64; + loop { + let next = read_full(stored, CHUNK + TAG).map_err(super::io::uncarry)?; + let last = next.is_empty(); + let mut nonce = [0u8; 24]; + nonce[..16].copy_from_slice(&prefix); + nonce[16..].copy_from_slice(&counter.to_be_bytes()); + let mut a = aad.to_vec(); + a.push(u8::from(last)); + let plain = cipher + .decrypt(&XNonce::from(nonce), Payload { msg: &cur, aad: &a }) + .map_err(|_| bad())?; + sink(&plain).map_err(super::io::uncarry)?; + if last { + return Ok(()); + } + cur = next; + counter += 1; + } + } + + /// A small file sealed whole. + pub(crate) fn seal_bytes(&self, plain: &[u8], aad: &[u8]) -> Vec { + let mut out = Vec::new(); + self.seal_stream(&mut &plain[..], &mut out, aad) + .expect("sealing into memory"); + out + } + + /// A small file opened whole. + pub(crate) fn open_bytes(&self, stored: &[u8], aad: &[u8]) -> Result, BackupError> { + let mut out = Vec::new(); + self.open_stream(&mut &stored[..], aad, &mut |b| { + out.extend_from_slice(b); + Ok(()) + })?; + Ok(out) + } +} + +/// Up to `n` bytes from `r`: fewer only at its end. +fn read_full(r: &mut dyn Read, n: usize) -> std::io::Result> { + let mut buf = vec![0u8; n]; + let mut got = 0; + while got < n { + match r.read(&mut buf[got..]) { + Ok(0) => break, + Ok(k) => got += k, + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} + Err(e) => return Err(e), + } + } + buf.truncate(got); + Ok(buf) +} + +/// A piece's identity: what it is bound to when sealed. +pub(crate) fn piece_aad(kind: &str, sha: &str) -> Vec { + format!("wb1|{kind}|{sha}").into_bytes() +} + +/// A manifest's identity. +pub(crate) fn manifest_aad(number: u64) -> Vec { + format!("wb1|manifest|{number}").into_bytes() +} diff --git a/crates/ledger-store/src/backups/single.rs b/crates/ledger-store/src/backups/single.rs new file mode 100644 index 00000000..46e04a56 --- /dev/null +++ b/crates/ledger-store/src/backups/single.rs @@ -0,0 +1,199 @@ +//! The backup as one file ("Save a backup..."): a zip of the folder form +//! of one set, holding one manifest and only the pieces it names. A zip is +//! a file any computer can carry and a person can open to see what is +//! inside. Sealed when the backups are: the pieces in it are the sealed +//! pieces, so the file says no more than a sealed folder does. +//! +//! The extension is `.wbbackup`. + +use super::cut::Cut; +use super::io::{Fill, Put, PutKind, SetIo}; +use super::read::Set; +use super::write::{Written, write_into_set}; +use super::{BackupError, Ctx}; +use std::collections::BTreeSet; +use std::io::Read; +use std::path::Path; +use std::sync::{Arc, Mutex}; + +/// The file's extension, without the dot. +pub const FILE_EXTENSION: &str = "wbbackup"; + +/// A set read from a zip. +struct ZipRead { + archive: Mutex>, +} + +fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +impl SetIo for ZipRead { + fn list(&self, dir: &str) -> std::io::Result> { + let prefix = format!("{}/", dir.trim_end_matches('/')); + let archive = lock(&self.archive); + let mut out: Vec = archive + .file_names() + .filter_map(|n| n.ok()) + .filter_map(|n| n.strip_prefix(prefix.as_str()).map(str::to_string)) + .filter(|rest| !rest.is_empty() && !rest.contains('/')) + .collect(); + out.sort(); + Ok(out) + } + + fn len(&self, rel: &str) -> std::io::Result> { + let mut archive = lock(&self.archive); + match archive.by_name(rel) { + Ok(f) if f.is_file() => Ok(Some(f.size())), + Ok(_) | Err(zip::result::ZipError::FileNotFound) => Ok(None), + Err(e) => Err(std::io::Error::other(e)), + } + } + + fn read_with( + &self, + rel: &str, + f: &mut dyn FnMut(&mut dyn Read) -> std::io::Result<()>, + ) -> std::io::Result<()> { + let mut archive = lock(&self.archive); + let mut file = archive + .by_name(rel) + .map_err(|_| std::io::Error::from(std::io::ErrorKind::NotFound))?; + f(&mut file) + } + + fn put(&self, _rel: &str, _kind: PutKind, _fill: Fill<'_>) -> std::io::Result { + Err(std::io::Error::other("a backup file is read only")) + } +} + +/// A zip being written. The writer is shared with [`save_file`], which +/// finishes it. +struct ZipWrite { + writer: Arc>>>, + names: Mutex>, +} + +impl SetIo for ZipWrite { + fn list(&self, _dir: &str) -> std::io::Result> { + Ok(Vec::new()) + } + + fn len(&self, _rel: &str) -> std::io::Result> { + Ok(None) + } + + fn read_with( + &self, + _rel: &str, + _f: &mut dyn FnMut(&mut dyn Read) -> std::io::Result<()>, + ) -> std::io::Result<()> { + Err(std::io::Error::from(std::io::ErrorKind::NotFound)) + } + + fn put(&self, rel: &str, _kind: PutKind, fill: Fill<'_>) -> std::io::Result { + if !lock(&self.names).insert(rel.to_string()) { + return Ok(Put::Existed); + } + // Text compresses; stored files and sealed pieces do not. + let text = ["journal/", "access/", "files-index/", "manifests/"] + .iter() + .any(|p| rel.starts_with(p)) + || rel == super::form::READ_ME; + let method = if text { + zip::CompressionMethod::Deflated + } else { + zip::CompressionMethod::Stored + }; + let options = zip::write::SimpleFileOptions::default() + .compression_method(method) + .large_file(true); + let mut guard = lock(&self.writer); + let writer = guard + .as_mut() + .ok_or_else(|| std::io::Error::other("the backup file is finished"))?; + writer + .start_file(rel, options) + .map_err(std::io::Error::other)?; + fill(writer)?; + Ok(Put::Created) + } +} + +/// Open a backup file for reading. +pub(crate) fn open(path: &Path, _ctx: &Ctx) -> Result, BackupError> { + let file = std::fs::File::open(path)?; + let archive = zip::ZipArchive::new(file).map_err(|_| BackupError::NotABackup)?; + Ok(Box::new(ZipRead { + archive: Mutex::new(archive), + })) +} + +/// Write the cut as one file at `path` (which must not be there): the same +/// contents as a backup folder, sealed when `key` is given. Written aside +/// and moved into place only when whole, so a file by that name is a +/// whole backup. +pub fn save_file( + path: &Path, + cut: &Cut, + key: Option<&super::BackupKey>, + ctx: &Ctx, +) -> Result { + if std::fs::symlink_metadata(path).is_ok() { + return Err(BackupError::Damaged( + "a file by that name is there already: choose another name".into(), + )); + } + let name = path + .file_name() + .and_then(|n| n.to_str()) + .ok_or(BackupError::NotABackup)?; + let aside = path.with_file_name(format!(".{name}.partial")); + let _ = std::fs::remove_file(&aside); + let file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&aside)?; + let shared = Arc::new(Mutex::new(Some(zip::ZipWriter::new(file)))); + let set = Set { + io: Box::new(ZipWrite { + writer: shared.clone(), + names: Mutex::new(BTreeSet::new()), + }), + keys: key.map(|k| k.keys()), + ctx: ctx.clone(), + }; + let result = write_into_set(&set, cut, ctx).and_then(|written| { + // The zip's directory, then the file's. + let writer = lock(&shared) + .take() + .ok_or_else(|| BackupError::Damaged("the backup file was finished twice".into()))?; + let file = writer + .finish() + .map_err(|e| BackupError::Io(std::io::Error::other(e).kind()))?; + file.sync_all()?; + Ok(written) + }); + match result { + Ok(written) => { + // Moved into place only if the name is still free. + let placed = std::fs::hard_link(&aside, path).or_else(|e| { + if e.kind() == std::io::ErrorKind::AlreadyExists + || std::fs::symlink_metadata(path).is_ok() + { + Err(std::io::Error::from(std::io::ErrorKind::AlreadyExists)) + } else { + std::fs::rename(&aside, path) + } + }); + let _ = std::fs::remove_file(&aside); + placed?; + Ok(written) + } + Err(e) => { + let _ = std::fs::remove_file(&aside); + Err(e) + } + } +} diff --git a/crates/ledger-store/src/backups/write.rs b/crates/ledger-store/src/backups/write.rs new file mode 100644 index 00000000..576c1afe --- /dev/null +++ b/crates/ledger-store/src/backups/write.rs @@ -0,0 +1,598 @@ +//! Writing a backup (INVARIANTS 1, 2, 4, 5 of the module): what is new +//! since the destination's newest whole manifest, as pieces, then the +//! manifest. + +use super::cut::Cut; +use super::form::*; +use super::io::{Fill, Put, PutKind, carry, uncarry}; +use super::read::{Hashed, Set}; +use super::seal::{BackupKey, Keys, piece_aad}; +use super::{BackupError, Ctx, READ_ME_TEXT}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; +use std::io::{Read, Seek, SeekFrom, Write}; +use std::path::{Path, PathBuf}; + +/// How many times a backup looks again after another program took the +/// manifest number it was about to take. +const ATTEMPTS: usize = 8; + +/// A sealed set's folder begins with this. +pub(crate) const SEALED_PREFIX: &str = "sealed-"; + +/// Where a backup goes: a folder the person chose, and the key if the +/// backups are protected by a passphrase. +#[derive(Debug, Clone)] +pub struct Destination { + /// The folder. + pub folder: PathBuf, + /// The key, when sealed. + pub key: Option, +} + +/// A backup written. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Written { + /// The manifest that is the backup: its number. + pub number: u64, + /// The head it reaches. + pub head: (u64, String), + /// False when the destination already held exactly these books: no + /// manifest was written. + pub new: bool, +} + +/// The folder a set of books has in a destination when it is not sealed: +/// named for the books. +pub fn set_name_for(book: &str) -> String { + book.to_string() +} + +/// The set of `book` in the destination: for a plain one, the folder named +/// for the books; for a sealed one, the folder whose header this key opens +/// and whose backups are these books' (or none yet). None when it is not +/// there. +pub(crate) fn locate( + dest: &Destination, + book: &str, + ctx: &Ctx, +) -> Result, BackupError> { + match &dest.key { + None => { + let dir = dest.folder.join(set_name_for(book)); + Ok(dir.is_dir().then(|| Set::dir(dir, None, ctx))) + } + Some(key) => { + let keys = key.keys(); + let Ok(entries) = std::fs::read_dir(&dest.folder) else { + return Ok(None); + }; + let mut names: Vec = entries + .flatten() + .filter_map(|e| e.file_name().to_str().map(str::to_string)) + .filter(|n| n.starts_with(SEALED_PREFIX)) + .collect(); + names.sort(); + for name in names { + let dir = dest.folder.join(&name); + let Ok(raw) = std::fs::read(dir.join(HEADER)) else { + continue; + }; + let Ok(header) = super::seal::Header::decode(&raw) else { + continue; + }; + if keys.check(&header).is_err() { + continue; + } + let set = Set::dir(dir, Some(key.keys()), ctx); + match set.newest_whole()? { + Some((m, _)) if m.book != book => continue, + _ => return Ok(Some(set)), + } + } + Ok(None) + } + } +} + +/// One thing to put before the manifest. +enum Plan { + /// A range of a live file: a segment of the journal or access log. + Range { + path: PathBuf, + from: u64, + to: u64, + kind: Kind, + piece: Piece, + }, + /// Bytes in hand: an index segment, a vault record, a key. + Bytes { + kind: Kind, + piece: Piece, + bytes: Vec, + }, + /// A stored file, in the book. + File { path: PathBuf, piece: Piece }, +} + +fn stored_len(keys: Option<&Keys>, plain: u64) -> u64 { + match keys { + Some(_) => Keys::sealed_len(plain), + None => plain, + } +} + +/// Hash `path` from 0 to `len`: the whole, the part before `mid`, and the +/// part from `mid`. +fn hash_range( + path: &Path, + len: u64, + mid: u64, + ctx: &Ctx, +) -> Result<(String, String, String), BackupError> { + let (mut all, mut before, mut after) = (Sha256::new(), Sha256::new(), Sha256::new()); + if len > 0 { + let mut f = std::fs::File::open(path)?; + let mut done = 0u64; + let mut buf = vec![0u8; 1 << 16]; + while done < len { + ctx.check("reading the books")?; + let want = (len - done).min(buf.len() as u64) as usize; + let n = f.read(&mut buf[..want])?; + if n == 0 { + return Err(BackupError::Damaged( + "the books' file is shorter than it was".into(), + )); + } + let chunk = &buf[..n]; + all.update(chunk); + let split = mid.saturating_sub(done).min(n as u64) as usize; + before.update(&chunk[..split]); + after.update(&chunk[split..]); + done += n as u64; + } + } + let h = |d: Sha256| hex::encode(d.finalize()); + Ok((h(all), h(before), h(after))) +} + +/// Grow the series of the live file `path` (`len` bytes of whole lines) +/// from `base`, the destination's: a new segment of the bytes it lacks. +/// The journal's must continue the destination's exactly (`strict`: +/// otherwise the books are not the same); an access log that does not is +/// begun again whole. +fn grow( + path: &Path, + len: u64, + base: Option<&Series>, + kind: Kind, + strict: bool, + keys: Option<&Keys>, + ctx: &Ctx, +) -> Result<(Series, Option), BackupError> { + let empty = Series::default(); + let mut base = base.unwrap_or(&empty); + if base.bytes > len { + // Only an access log can be shorter than it was (begun again). + if strict { + return Err(BackupError::Elsewhere); + } + base = ∅ + } + let (all, before, after) = hash_range(path, len, base.bytes, ctx)?; + if base.bytes > 0 && before != base.sha256 { + if strict { + return Err(BackupError::Elsewhere); + } + base = ∅ + } + if base.bytes == len { + return Ok((base.clone(), None)); + } + let consolidate = base.segments.len() >= CONSOLIDATE_AT; + // `after` was hashed from the base's end: with a different base, from + // the whole. + let (from, seg_sha, ordinal, mut segments) = if consolidate || base.bytes == 0 { + (0, all.clone(), 0, Vec::new()) + } else { + ( + base.bytes, + after, + base.segments.len(), + base.segments.clone(), + ) + }; + let bytes = len - from; + let piece = Piece { + file: piece_path(keys, kind, ordinal, &seg_sha), + stored: stored_len(keys, bytes), + bytes, + sha256: seg_sha, + }; + segments.push(piece.clone()); + Ok(( + Series { + bytes: len, + sha256: all, + segments, + }, + Some(Plan::Range { + path: path.to_path_buf(), + from, + to: len, + kind, + piece, + }), + )) +} + +/// `&mut dyn Write` as a `Write` that `io::copy` takes. +struct WriteAdapter<'a>(&'a mut dyn Write); + +impl Write for WriteAdapter<'_> { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.write(buf) + } + fn flush(&mut self) -> std::io::Result<()> { + self.0.flush() + } +} + +/// A piece put in the set: its contents from `plain`, sealed when the set +/// is, proven against `piece` as it is written. +fn put_piece( + set: &Set, + kind: Kind, + piece: &Piece, + plain: &mut dyn Read, + ctx: &Ctx, +) -> Result<(), BackupError> { + ctx.check("backing up")?; + let mut hashed = Hashed::new(plain, ctx); + let keys = set.keys.as_ref(); + let aad = piece_aad(kind.dir(), &piece.sha256); + let mut fill = |w: &mut dyn Write| -> std::io::Result<()> { + match keys { + Some(k) => k.seal_stream(&mut hashed, w, &aad)?, + None => { + std::io::copy(&mut hashed, &mut WriteAdapter(w))?; + } + } + if hashed.count != piece.bytes + || hex::encode(hashed.hasher.clone().finalize()) != piece.sha256 + { + return Err(carry(BackupError::Damaged( + "something of the books changed or was damaged while it was being backed up: try again" + .into(), + ))); + } + Ok(()) + }; + let fill_ref: Fill<'_> = &mut fill; + set.io + .put(&piece.file, PutKind::Piece, fill_ref) + .map_err(uncarry)?; + Ok(()) +} + +fn execute(set: &Set, plan: &Plan, ctx: &Ctx) -> Result<(), BackupError> { + match plan { + Plan::Range { + path, + from, + to, + kind, + piece, + } => { + let mut f = std::fs::File::open(path)?; + f.seek(SeekFrom::Start(*from))?; + put_piece(set, *kind, piece, &mut f.take(to - from), ctx) + } + Plan::Bytes { kind, piece, bytes } => put_piece(set, *kind, piece, &mut &bytes[..], ctx), + Plan::File { path, piece } => { + let mut f = std::fs::File::open(path)?; + put_piece(set, Kind::File, piece, &mut f, ctx) + } + } +} + +/// The index segment's text for `lines`. +fn index_text(lines: &[IndexLine]) -> Vec { + let mut out = Vec::new(); + for l in lines { + out.extend_from_slice(&serde_json::to_vec(l).expect("an index line serializes")); + out.push(b'\n'); + } + out +} + +fn named_pieces( + files: &[(String, Vec)], + kind: Kind, + keys: Option<&Keys>, + plans: &mut Vec, +) -> Vec { + files + .iter() + .map(|(name, bytes)| { + let sha = sha_hex(bytes); + let piece = Piece { + file: piece_path(keys, kind, 0, &sha), + stored: stored_len(keys, bytes.len() as u64), + bytes: bytes.len() as u64, + sha256: sha, + }; + plans.push(Plan::Bytes { + kind, + piece: piece.clone(), + bytes: bytes.clone(), + }); + Named { + name: name.clone(), + piece, + } + }) + .collect() +} + +/// What to put, and the manifest that says it is whole once it is there +/// (its number and time are the writer's, last). +fn plan( + set: &Set, + prev: Option<&Manifest>, + cut: &Cut, + ctx: &Ctx, +) -> Result<(Manifest, Vec), BackupError> { + let keys = set.keys.as_ref(); + let mut plans = Vec::new(); + if let Some(p) = prev { + if p.book != cut.book() { + return Err(BackupError::Elsewhere); + } + if p.journal.bytes > cut.journal_len { + return Err(BackupError::Ahead(p.head.seq, cut.head().0)); + } + } + let (journal, put) = grow( + &cut.journal_path(), + cut.journal_len, + prev.map(|p| &p.journal), + Kind::Journal, + true, + keys, + ctx, + )?; + plans.extend(put); + let (access, put) = grow( + &cut.access_path(), + cut.access_len, + prev.map(|p| &p.access), + Kind::Access, + false, + keys, + ctx, + )?; + plans.extend(put); + + // The index of stored files: the new ones, as a segment. + ctx.phase("files"); + let live = cut.stored_files(ctx)?; + let known: Vec = match prev { + Some(p) => set.index(p)?, + None => Vec::new(), + }; + let known_set: BTreeMap<&str, u64> = + known.iter().map(|l| (l.sha256.as_str(), l.bytes)).collect(); + let new: Vec = live + .into_iter() + .filter(|l| !known_set.contains_key(l.sha256.as_str())) + .collect(); + let (files, file_count, file_bytes) = match (prev, new.is_empty()) { + (_, true) => prev + .map(|p| (p.files.clone(), p.file_count, p.file_bytes)) + .unwrap_or_default(), + _ => { + let base = prev.map(|p| &p.files).cloned().unwrap_or_default(); + let consolidate = base.segments.len() >= CONSOLIDATE_AT; + let mut union: Vec = known.clone(); + union.extend(new.iter().cloned()); + let count = union.len() as u64; + let total = union.iter().fold(0u64, |a, l| a.saturating_add(l.bytes)); + let seg_lines = if consolidate { &union } else { &new }; + let text = index_text(seg_lines); + let seg_sha = sha_hex(&text); + let ordinal = if consolidate { 0 } else { base.segments.len() }; + let piece = Piece { + file: piece_path(keys, Kind::Index, ordinal, &seg_sha), + stored: stored_len(keys, text.len() as u64), + bytes: text.len() as u64, + sha256: seg_sha, + }; + let mut segments = if consolidate { + Vec::new() + } else { + base.segments.clone() + }; + segments.push(piece.clone()); + // The whole index's hash: the segments one after another. + let mut all_text = Vec::new(); + if !consolidate { + set.read_series(&base, Kind::Index, &mut |c| { + all_text.extend_from_slice(c); + Ok(()) + })?; + } + all_text.extend_from_slice(&text); + plans.push(Plan::Bytes { + kind: Kind::Index, + piece, + bytes: text, + }); + for l in &new { + plans.push(Plan::File { + path: cut.blob_path(&l.sha256), + piece: Piece { + file: piece_path(keys, Kind::File, 0, &l.sha256), + stored: stored_len(keys, l.bytes), + bytes: l.bytes, + sha256: l.sha256.clone(), + }, + }); + } + ( + Series { + bytes: all_text.len() as u64, + sha256: sha_hex(&all_text), + segments, + }, + count, + total, + ) + } + }; + let vault = named_pieces(&cut.vault, Kind::Vault, keys, &mut plans); + let keyed = named_pieces(&cut.keys, Kind::Key, keys, &mut plans); + let manifest = Manifest { + format: FORMAT.into(), + version: VERSION, + book: cut.book().to_string(), + number: 0, + written: String::new(), + head: Head { + seq: cut.head().0, + hash: cut.head().1.clone(), + }, + journal, + access, + files, + file_count, + file_bytes, + vault, + keys: keyed, + }; + Ok((manifest, plans)) +} + +/// The read-me, and for a sealed set its header: put once. +fn ensure_markers(set: &Set) -> Result<(), BackupError> { + set.io.put(READ_ME, PutKind::Once, &mut |w| { + w.write_all(READ_ME_TEXT.as_bytes()) + })?; + if let Some(keys) = &set.keys { + let header = keys.header(); + let bytes = header.encode(); + let put = set + .io + .put(HEADER, PutKind::Once, &mut |w| w.write_all(&bytes))?; + if put == Put::Existed { + // Another's header there already: ours only if it is the same + // key (the salt it was derived with). + let mut raw = Vec::new(); + set.io + .read_with(HEADER, &mut |r| r.read_to_end(&mut raw).map(|_| ()))?; + let theirs = super::seal::Header::decode(&raw)?; + if theirs.kdf != header.kdf { + return Err(BackupError::Elsewhere); + } + } + } + Ok(()) +} + +fn now() -> String { + chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true) +} + +/// Write the cut into the set (INVARIANTS 2, 4, 5). +pub(crate) fn write_into_set(set: &Set, cut: &Cut, ctx: &Ctx) -> Result { + ensure_markers(set)?; + for _ in 0..ATTEMPTS { + ctx.check("backing up")?; + let numbers = set.numbers()?; + let prev = set.newest_whole()?.map(|(m, _)| m); + let next = numbers.last().map_or(1, |n| n + 1); + ctx.phase("plan"); + let (mut manifest, plans) = plan(set, prev.as_ref(), cut, ctx)?; + if let Some(p) = &prev + && manifest.same_content(p) + { + return Ok(Written { + number: p.number, + head: cut.head().clone(), + new: false, + }); + } + ctx.phase("pieces"); + for p in &plans { + ctx.check("backing up")?; + execute(set, p, ctx)?; + } + manifest.number = next; + manifest.written = now(); + let mut bytes = encode_manifest(&manifest); + if let Some(k) = &set.keys { + bytes = k.seal_bytes(&bytes, &super::seal::manifest_aad(next)); + } + ctx.phase("manifest"); + ctx.check("backing up")?; + let put = set + .io + .put( + &manifest_path(next, set.sealed()), + PutKind::Manifest, + &mut |w| w.write_all(&bytes), + ) + .map_err(uncarry)?; + match put { + Put::Created => { + return Ok(Written { + number: next, + head: cut.head().clone(), + new: true, + }); + } + // Another program took the number: look again. + Put::Existed => continue, + } + } + Err(BackupError::Busy) +} + +/// Back the cut up to the destination (INVARIANTS 1 to 5). The destination +/// is made only when `may_create` (it never took a backup of these +/// books): one that took backups and is gone is a disk not connected, +/// never made again where the disk should be. +pub fn write_destination( + dest: &Destination, + cut: &Cut, + may_create: bool, + ctx: &Ctx, +) -> Result { + if !dest.folder.is_dir() { + return Err(BackupError::NoFolder); + } + let set = match locate(dest, cut.book(), ctx)? { + Some(set) => set, + None if !may_create => return Err(BackupError::NoBackupThere), + None => match &dest.key { + None => Set::dir(dest.folder.join(set_name_for(cut.book())), None, ctx), + Some(key) => { + let mut id = [0u8; 8]; + getrandom::getrandom(&mut id) + .map_err(|e| BackupError::Io(std::io::Error::from(e).kind()))?; + let name = format!("{SEALED_PREFIX}{}", hex::encode(id)); + Set::dir(dest.folder.join(name), Some(key.keys()), ctx) + } + }, + }; + write_into_set(&set, cut, ctx) +} + +/// Write the cut to the book's own local backup (`local-backup/` in its +/// folder, the same form, plain): what a format upgrade proves before it +/// begins. The caller holds the store's lock. +pub fn write_local(book_dir: &Path, cut: &Cut, ctx: &Ctx) -> Result { + let folder = crate::root::private_book_folder(book_dir, super::LOCAL_DIR) + .map_err(|e| BackupError::Damaged(e.to_string()))?; + write_destination(&Destination { folder, key: None }, cut, true, ctx) +} diff --git a/crates/ledger-store/src/lib.rs b/crates/ledger-store/src/lib.rs index f18c773a..eb6eb6ef 100644 --- a/crates/ledger-store/src/lib.rs +++ b/crates/ledger-store/src/lib.rs @@ -21,6 +21,7 @@ pub mod access; pub mod auth; pub mod backup; +pub mod backups; pub mod blob; pub mod cancel; pub mod chain; diff --git a/crates/ledger-store/tests/backups.rs b/crates/ledger-store/tests/backups.rs new file mode 100644 index 00000000..a73a7038 --- /dev/null +++ b/crates/ledger-store/tests/backups.rs @@ -0,0 +1,689 @@ +//! Backups in plain folders (WB-backup-1 to WB-backup-9): what a backup +//! is, that it only grows, that a restore of any whole manifest is a +//! prefix of the books, that two writers do not corrupt one destination, +//! that a program that dies at any write leaves a destination that proves +//! whole at its previous manifest, that a flipped or cut piece is never +//! restored, and that a wrong passphrase never yields books. + +use ledger_core::{AccountType, Currency, Money, Side}; +use ledger_store::Store; +use ledger_store::backups::{ + BackupError, BackupKey, Ctx, Cut, Destination, find, save_file, verify_found, write_destination, +}; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; + +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, + } +} + +/// Every file under `root`, by relative path, with its bytes. +fn tree(root: &Path) -> BTreeMap> { + fn walk(base: &Path, dir: &Path, out: &mut BTreeMap>) { + 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 +} + +/// 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 { + let found = find(source, pass, &Ctx::new())?; + verify_found(&found, &root.join(name), true, &Ctx::new()) +} + +#[test] +fn a_backup_is_the_book_and_proves_whole() { + 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 w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap(); + assert!(w.new); + assert_eq!(w.number, 1); + assert_eq!(w.head, s.head()); + + // The form on disk: a folder for the books, a read-me, one manifest, + // the journal as a segment, the stored file under its hash. + let t = tree(&disk); + let names: Vec<&String> = t.keys().collect(); + assert!(names.iter().any(|n| *n == "acme/READ-ME.txt"), "{names:?}"); + assert!(names.iter().any(|n| *n == "acme/manifests/000001.json")); + assert!(names.iter().any(|n| n.starts_with("acme/journal/000001-"))); + assert!(names.iter().any(|n| n.starts_with("acme/files/"))); + assert!(!names.iter().any(|n| n.contains(".git"))); + + // Nothing new: no manifest. + let again = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap(); + assert!(!again.new); + assert_eq!(again.number, 1); + assert_eq!(tree(&disk), t); + + // Proven, and the books it holds are the book. + let v = prove(&disk, None, dir.path(), "v1").unwrap(); + assert_eq!(v.head, s.head()); + assert_eq!(v.blobs, 1); + assert_eq!(v.book.as_deref(), Some("acme")); + assert_eq!( + std::fs::read(v.tree.join("journal.jsonl")).unwrap(), + std::fs::read(b.join("journal.jsonl")).unwrap() + ); + + // More writes: a new manifest and new pieces; the old ones untouched. + more(&mut s, 1); + let w2 = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap(); + assert_eq!(w2.number, 2); + let t2 = tree(&disk); + for (name, bytes) in &t { + assert_eq!(t2.get(name), Some(bytes), "{name} must not change"); + } + assert!(t2.len() > t.len()); + let v2 = prove(&disk, None, dir.path(), "v2").unwrap(); + assert_eq!(v2.head, s.head()); + assert_eq!(v2.blobs, 2); + // No scratch file of ours is left behind. + assert!(!t2.keys().any(|n| n.contains(".wb-tmp-"))); +} + +#[test] +fn a_destination_of_other_books_or_another_history_is_never_written() { + let dir = tempfile::tempdir().unwrap(); + let (b1, b2) = (dir.path().join("one"), dir.path().join("two")); + let (mut s1, s2) = (book(&b1), book(&b2)); + let disk = dir.path().join("disk"); + std::fs::create_dir(&disk).unwrap(); + write_destination(&plain(&disk), &cut(&b1, &s1), true, &Ctx::new()).unwrap(); + let before = tree(&disk); + // The same id, another history (a different journal from the start). + assert_eq!( + write_destination(&plain(&disk), &cut(&b2, &s2), true, &Ctx::new()).unwrap_err(), + BackupError::Elsewhere + ); + assert_eq!(tree(&disk), before); + // Books behind the destination: said, nothing written. + more(&mut s1, 1); + write_destination(&plain(&disk), &cut(&b1, &s1), true, &Ctx::new()).unwrap(); + let ahead = tree(&disk); + let b1_old = dir.path().join("one-old"); + let _old = book(&b1_old); + let err = + write_destination(&plain(&disk), &cut(&b1_old, &_old), true, &Ctx::new()).unwrap_err(); + assert!( + matches!(err, BackupError::Ahead(..) | BackupError::Elsewhere), + "{err:?}" + ); + assert_eq!(tree(&disk), ahead); +} + +#[test] +fn a_disk_that_is_gone_is_never_made_again_where_it_should_be() { + let dir = tempfile::tempdir().unwrap(); + let b = dir.path().join("book"); + let s = book(&b); + let missing = dir.path().join("nodisk"); + assert_eq!( + write_destination(&plain(&missing), &cut(&b, &s), true, &Ctx::new()).unwrap_err(), + BackupError::NoFolder + ); + // A mount point with nothing on it: the folder is there, the books' + // backup is not, and the caller says it never made one here. + let mount = dir.path().join("mount"); + std::fs::create_dir(&mount).unwrap(); + assert_eq!( + write_destination(&plain(&mount), &cut(&b, &s), false, &Ctx::new()).unwrap_err(), + BackupError::NoBackupThere + ); + assert!(tree(&mount).is_empty()); +} + +#[test] +fn a_stopped_backup_leaves_what_proved_whole_before() { + 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(); + more(&mut s, 1); + let stop = Arc::new(std::sync::atomic::AtomicBool::new(true)); + let err = write_destination( + &plain(&disk), + &cut(&b, &s), + true, + &Ctx::new().with_stop(stop), + ) + .unwrap_err(); + assert!(matches!(err, BackupError::Cancelled(_)), "{err:?}"); + let v = prove(&disk, None, dir.path(), "v").unwrap(); + assert_eq!(v.number, 1); +} + +// --- the passphrase -------------------------------------------------- + +const PASS: &str = "correct horse battery staple"; + +#[test] +fn a_sealed_backup_gives_away_counts_and_sizes_only() { + 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 key = BackupKey::generate(PASS).unwrap(); + let dest = Destination { + folder: disk.clone(), + key: Some(key), + }; + write_destination(&dest, &cut(&b, &s), true, &Ctx::new()).unwrap(); + for (name, bytes) in tree(&disk) { + for word in [ + "acme", "journal", "access", "vault", "keys", "blobs", "files", "receipt", "Cash", + ] { + // The read-me is plain words and says nothing of the books; + // nothing else carries a word of them, in its name or in it. + if !name.ends_with("READ-ME.txt") { + assert!(!name.contains(word), "{name} names {word}"); + assert!( + !String::from_utf8_lossy(&bytes).contains(word) + || name.ends_with("header.json"), + "{name} holds {word}" + ); + } + } + assert!(!bytes.windows(8).any(|w| w == b"PDF-1.4 "), "{name}"); + } + // Opened with the passphrase: the same books. + let v = prove(&disk, Some(PASS), dir.path(), "v").unwrap(); + assert_eq!(v.head, s.head()); + assert!(v.key.is_some()); +} + +#[test] +fn a_wrong_passphrase_never_yields_books_and_is_told_from_damage() { + 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(); + assert!(matches!( + find(&disk, None, &Ctx::new()), + Err(BackupError::NeedsPassphrase) + )); + assert!(matches!( + find(&disk, Some("not the right words at all"), &Ctx::new()), + Err(BackupError::WrongPassphrase) + )); + // A damaged header is damage, not a wrong passphrase. + 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 mut bytes = std::fs::read(&header).unwrap(); + bytes[40] ^= 1; + std::fs::write(&header, &bytes).unwrap(); + let err = find(&disk, Some(PASS), &Ctx::new()).err().unwrap(); + assert!( + matches!(err, BackupError::Damaged(_) | BackupError::NotABackup), + "{err:?}" + ); + assert!(!dir.path().join("v").exists()); +} + +#[test] +fn a_changed_passphrase_is_a_new_set_beside_the_old_which_is_untouched() { + 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 first = Destination { + folder: disk.clone(), + key: Some(BackupKey::generate(PASS).unwrap()), + }; + write_destination(&first, &cut(&b, &s), true, &Ctx::new()).unwrap(); + let before = tree(&disk); + more(&mut s, 1); + // Another passphrase: found no set of its own, so (the caller says it + // may) a new one is made; the first is not touched. + let second = Destination { + folder: disk.clone(), + key: Some(BackupKey::generate("an entirely different phrase").unwrap()), + }; + write_destination(&second, &cut(&b, &s), true, &Ctx::new()).unwrap(); + let after = tree(&disk); + for (name, bytes) in &before { + assert_eq!(after.get(name), Some(bytes), "{name}"); + } + let sets: Vec<_> = std::fs::read_dir(&disk).unwrap().flatten().collect(); + assert_eq!(sets.len(), 2); + // The old passphrase still opens the old set only when it is alone; + // with two sets, a passphrase opens the one that is its own. + let v = prove(&disk, Some("an entirely different phrase"), dir.path(), "v").unwrap(); + assert_eq!(v.head, s.head()); +} + +#[test] +fn the_key_is_kept_privately_and_only_there() { + let dir = tempfile::tempdir().unwrap(); + let b = dir.path().join("book"); + let s = book(&b); + let key = BackupKey::generate(PASS).unwrap(); + key.store(&b).unwrap(); + let loaded = BackupKey::load(&b).unwrap().expect("kept"); + assert!(key.same_as(&loaded)); + let file = b.join("local").join("backup-key.json"); + let text = std::fs::read_to_string(&file).unwrap(); + assert!(!text.contains(PASS)); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(&file).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o600); + let dir_mode = std::fs::metadata(file.parent().unwrap()) + .unwrap() + .permissions() + .mode() + & 0o777; + assert_eq!(dir_mode, 0o700); + } + // Never in a backup: not the journal, not the folder of the backup. + let disk = dir.path().join("disk"); + std::fs::create_dir(&disk).unwrap(); + write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap(); + let raw = text + .lines() + .find(|l| l.contains("master")) + .unwrap() + .to_string(); + let master = raw.split('"').nth(3).unwrap().to_string(); + for (name, bytes) in tree(&disk) { + assert!(!String::from_utf8_lossy(&bytes).contains(&master), "{name}"); + } + BackupKey::forget(&b).unwrap(); + assert!(BackupKey::load(&b).unwrap().is_none()); +} + +// --- the single file ------------------------------------------------- + +#[test] +fn a_single_file_holds_the_same_backup_plain_or_sealed() { + let dir = tempfile::tempdir().unwrap(); + let b = dir.path().join("book"); + let s = book(&b); + for (pass, name) in [(None, "plain.wbbackup"), (Some(PASS), "sealed.wbbackup")] { + let key = pass.map(|p| BackupKey::generate(p).unwrap()); + let file = dir.path().join(name); + let w = save_file(&file, &cut(&b, &s), key.as_ref(), &Ctx::new()).unwrap(); + assert_eq!(w.head, s.head()); + let v = prove(&file, pass, dir.path(), &format!("v-{name}")).unwrap(); + assert_eq!(v.head, s.head()); + assert_eq!(v.blobs, 1); + // A file by that name is not written over. + assert!(save_file(&file, &cut(&b, &s), key.as_ref(), &Ctx::new()).is_err()); + } + assert!(matches!( + find(&dir.path().join("sealed.wbbackup"), None, &Ctx::new()), + Err(BackupError::NeedsPassphrase) + )); + assert!(matches!( + find( + &dir.path().join("sealed.wbbackup"), + Some("a wrong passphrase here"), + &Ctx::new() + ), + Err(BackupError::WrongPassphrase) + )); + // Not a backup at all. + let junk = dir.path().join("junk.wbbackup"); + std::fs::write(&junk, b"not a zip").unwrap(); + assert!(matches!( + find(&junk, None, &Ctx::new()), + Err(BackupError::NotABackup) + )); +} + +// --- damage ------------------------------------------------------------ + +/// Every piece a manifest names, as paths under the set. +fn pieces(set: &Path) -> Vec { + tree(set) + .keys() + .filter(|n| { + !n.starts_with("manifests/") + && !n.ends_with("READ-ME.txt") + && !n.ends_with("header.json") + }) + .map(|n| set.join(n)) + .collect() +} + +#[test] +fn a_flipped_or_cut_piece_is_found_and_never_restored() { + for sealed in [false, true] { + 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 key = sealed.then(|| BackupKey::generate(PASS).unwrap()); + let dest = Destination { + folder: disk.clone(), + key, + }; + write_destination(&dest, &cut(&b, &s), true, &Ctx::new()).unwrap(); + let pass = sealed.then_some(PASS); + // Found once (a sealed backup's key takes a moment to derive). + let found = find(&disk, pass, &Ctx::new()).unwrap(); + let prove = |_: &Path, _: Option<&str>, root: &Path, name: &str| { + verify_found(&found, &root.join(name), true, &Ctx::new()) + }; + let set = std::fs::read_dir(&disk) + .unwrap() + .flatten() + .next() + .unwrap() + .path(); + for piece in pieces(&set) { + let original = std::fs::read(&piece).unwrap(); + for damage in 0..3 { + let mut bytes = original.clone(); + match damage { + 0 => { + let at = bytes.len() / 2; + bytes[at] ^= 0x01; + } + 1 => bytes.truncate(bytes.len().saturating_sub(1)), + _ => bytes.clear(), + } + std::fs::write(&piece, &bytes).unwrap(); + let scratch = format!("v-{damage}"); + let got = prove(&disk, pass, dir.path(), &scratch); + assert!( + got.is_err(), + "{} damage {damage} of {piece:?} was restored", + if sealed { "sealed" } else { "plain" } + ); + assert!(!dir.path().join(&scratch).exists(), "scratch left"); + } + std::fs::write(&piece, &original).unwrap(); + } + // Whole again once put back. + prove(&disk, pass, dir.path(), "ok").unwrap(); + // A manifest cut short or changed is no manifest. + let manifest = tree(&set) + .keys() + .find(|n| n.starts_with("manifests/")) + .cloned() + .unwrap(); + let mpath = set.join(&manifest); + let original = std::fs::read(&mpath).unwrap(); + std::fs::write(&mpath, &original[..original.len() / 2]).unwrap(); + assert!(prove(&disk, pass, dir.path(), "cut").is_err()); + std::fs::write(&mpath, &original).unwrap(); + } +} + +#[test] +fn a_damaged_newest_backup_falls_back_to_the_one_before_and_says_so() { + 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(); + let first_head = s.head(); + more(&mut s, 1); + write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap(); + // Flip a byte in the second journal segment. + let seg = tree(&disk.join("acme")) + .keys() + .filter(|n| n.starts_with("journal/")) + .max() + .cloned() + .unwrap(); + let path = disk.join("acme").join(&seg); + let mut bytes = std::fs::read(&path).unwrap(); + bytes[3] ^= 1; + std::fs::write(&path, bytes).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, first_head); +} + +// --- death at every write point -------------------------------------- + +#[test] +fn a_program_that_dies_at_any_write_leaves_what_proved_whole_before() { + let dir = tempfile::tempdir().unwrap(); + let b = dir.path().join("book"); + let mut s = book(&b); + let base_disk = dir.path().join("base"); + std::fs::create_dir(&base_disk).unwrap(); + write_destination(&plain(&base_disk), &cut(&b, &s), true, &Ctx::new()).unwrap(); + let first_head = s.head(); + more(&mut s, 1); + let c = cut(&b, &s); + + // How many write points a whole second backup has. + let counted = Arc::new(AtomicUsize::new(0)); + let probe = { + let disk = dir.path().join("probe"); + copy_tree(&base_disk, &disk); + let n = counted.clone(); + let ctx = Ctx::new().with_faults(Arc::new(move |_, _| { + n.fetch_add(1, Ordering::SeqCst); + false + })); + write_destination(&plain(&disk), &c, true, &ctx).unwrap(); + counted.load(Ordering::SeqCst) + }; + assert!(probe >= 6, "a second backup has several writes: {probe}"); + + for die_at in 0..probe { + let disk = dir.path().join(format!("died-{die_at}")); + copy_tree(&base_disk, &disk); + let n = Arc::new(AtomicUsize::new(0)); + let ctx = { + let n = n.clone(); + Ctx::new().with_faults(Arc::new(move |_, _| { + n.fetch_add(1, Ordering::SeqCst) == die_at + })) + }; + let err = write_destination(&plain(&disk), &c, true, &ctx).unwrap_err(); + assert_eq!(err, BackupError::Died, "point {die_at}"); + // What is left proves whole at the previous manifest, never a + // half-written one (before the manifest was in place), or at the + // new one (after). + let v = prove(&disk, None, dir.path(), &format!("r-{die_at}")).unwrap(); + assert!( + v.head == first_head || v.head == s.head(), + "point {die_at}: head {:?}", + v.head + ); + // A restore from what is left is a prefix of the books. + let restored = std::fs::read(v.tree.join("journal.jsonl")).unwrap(); + let live = std::fs::read(b.join("journal.jsonl")).unwrap(); + assert!(live.starts_with(&restored), "point {die_at}"); + // And the next run goes on from it (proven again at some points: + // each proof replays the books). + let w = write_destination(&plain(&disk), &c, true, &Ctx::new()).unwrap(); + assert_eq!(w.head, s.head()); + if die_at % 6 == 0 { + let again = prove(&disk, None, dir.path(), &format!("again-{die_at}")).unwrap(); + assert_eq!(again.head, s.head()); + } + } +} + +fn copy_tree(from: &Path, to: &Path) { + for (rel, bytes) in tree(from) { + let p = to.join(rel); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, bytes).unwrap(); + } + std::fs::create_dir_all(to).unwrap(); +} + +// --- two writers ------------------------------------------------------- + +#[test] +fn two_programs_writing_one_destination_do_not_corrupt_it() { + 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 round in 0..3 { + more(&mut s, round); + let c = cut(&b, &s); + let results: Vec<_> = std::thread::scope(|scope| { + let handles: Vec<_> = (0..3) + .map(|_| { + let (c, disk) = (c.clone(), disk.clone()); + scope.spawn(move || write_destination(&plain(&disk), &c, true, &Ctx::new())) + }) + .collect(); + handles.into_iter().map(|h| h.join().unwrap()).collect() + }); + for r in &results { + let w = r + .as_ref() + .unwrap_or_else(|e| panic!("round {round}: {e:?}")); + assert_eq!(w.head, s.head()); + } + // However they interleaved: whole, at these books, and every + // manifest there stands alone. + let v = prove(&disk, None, dir.path(), &format!("v{round}")).unwrap(); + assert_eq!(v.head, s.head()); + let set = disk.join("acme"); + for n in std::fs::read_dir(set.join("manifests")).unwrap().flatten() { + assert!(n.file_name().to_string_lossy().ends_with(".json")); + } + } +} + +#[test] +fn a_loser_of_a_manifest_number_goes_on_from_the_winner() { + // Another program takes the next number between this one's look and its + // write: this one looks again and finds nothing left to write. + 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 c = cut(&b, &s); + let rival_disk = disk.clone(); + let rival_cut = c.clone(); + let done = Arc::new(AtomicUsize::new(0)); + let ctx = { + let done = done.clone(); + Ctx::new().with_faults(Arc::new(move |kind, rel| { + // Just before this writer's manifest, the rival writes its own. + if kind == "create" + && rel.starts_with("manifests/") + && done.fetch_add(1, Ordering::SeqCst) == 0 + { + write_destination(&plain(&rival_disk), &rival_cut, true, &Ctx::new()).unwrap(); + } + false + })) + }; + let w = write_destination(&plain(&disk), &c, true, &ctx).unwrap(); + assert_eq!(w.head, s.head()); + assert!(!w.new, "the winner's manifest already says it"); + assert_eq!( + std::fs::read_dir(disk.join("acme/manifests")) + .unwrap() + .count(), + 1 + ); + prove(&disk, None, dir.path(), "v").unwrap(); +}