From 9f4529b07803fb821e680883dec7ac1961708ea7 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 17:19:12 -0700 Subject: [PATCH 01/19] 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(); +} From a6cd89d2a675ae902e31f3e8abe08d5b61ccfb43 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 17:42:05 -0700 Subject: [PATCH 02/19] refactor: the server, restore and the window's seams on the plain-folder backup; git removed from the store Restore reads a destination folder, a set's folder, or a backup file with an optional passphrase; the server cuts the books under the store's lock and writes the folder outside it; the format upgrade proves a local backup in the book's folder (the same form) before it moves the format. The old backup (git processes, their locks, the output drain) and every test of it are gone; what each test protected is held by the new form's tests (table in the report). Old settings and an old history in a book's folder are said in the status and left alone. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-cli/src/main.rs | 13 +- crates/ledger-cli/tests/backups.rs | 829 ++-- crates/ledger-cli/tests/book_open_close.rs | 694 +-- crates/ledger-gui/src/owner.rs | 52 +- crates/ledger-gui/tests/assistants.rs | 8 +- crates/ledger-gui/tests/dock.rs | 8 +- crates/ledger-gui/tests/format_upgrade.rs | 1 + crates/ledger-gui/tests/host_holds.rs | 8 +- crates/ledger-gui/tests/owner_menu.rs | 12 +- crates/ledger-gui/tests/serving.rs | 16 +- crates/ledger-gui/tests/sidenav.rs | 8 +- crates/ledger-gui/tests/tabs.rs | 10 +- crates/ledger-gui/tests/update_notice.rs | 8 +- crates/ledger-gui/tests/web_connect.rs | 1 + crates/ledger-gui/tests/welcome.rs | 8 +- crates/ledger-host/src/commands.rs | 93 +- crates/ledger-mcp/src/admin.rs | 25 +- crates/ledger-mcp/src/backup.rs | 811 ++-- crates/ledger-mcp/src/local.rs | 163 +- crates/ledger-mcp/src/tools/backup.rs | 21 +- crates/ledger-store/src/backup.rs | 3932 ----------------- .../src/{backups => backup}/cut.rs | 0 .../src/{backups => backup}/form.rs | 0 .../src/{backups => backup}/io.rs | 2 +- .../src/{backups => backup}/mod.rs | 0 .../src/{backups => backup}/read.rs | 0 .../src/{backups => backup}/seal.rs | 7 + .../src/{backups => backup}/single.rs | 0 .../src/{backups => backup}/write.rs | 0 crates/ledger-store/src/drain.rs | 370 -- crates/ledger-store/src/git_locks.rs | 554 --- crates/ledger-store/src/lib.rs | 3 - crates/ledger-store/src/root.rs | 75 +- .../tests/{backups.rs => backup.rs} | 4 +- crates/ledger-store/tests/root.rs | 50 +- 35 files changed, 1150 insertions(+), 6636 deletions(-) delete mode 100644 crates/ledger-store/src/backup.rs rename crates/ledger-store/src/{backups => backup}/cut.rs (100%) rename crates/ledger-store/src/{backups => backup}/form.rs (100%) rename crates/ledger-store/src/{backups => backup}/io.rs (99%) rename crates/ledger-store/src/{backups => backup}/mod.rs (100%) rename crates/ledger-store/src/{backups => backup}/read.rs (100%) rename crates/ledger-store/src/{backups => backup}/seal.rs (98%) rename crates/ledger-store/src/{backups => backup}/single.rs (100%) rename crates/ledger-store/src/{backups => backup}/write.rs (100%) delete mode 100644 crates/ledger-store/src/drain.rs delete mode 100644 crates/ledger-store/src/git_locks.rs rename crates/ledger-store/tests/{backups.rs => backup.rs} (99%) diff --git a/crates/ledger-cli/src/main.rs b/crates/ledger-cli/src/main.rs index 3bc9c36b..1026a006 100644 --- a/crates/ledger-cli/src/main.rs +++ b/crates/ledger-cli/src/main.rs @@ -307,10 +307,17 @@ impl ledger_gui::owner::Owner for ViewerOwner { source: &str, id: Option, replace: bool, + passphrase: Option, ) -> Result { - let p = ledger_host::commands::plan_restore(&self.common, source, id, replace, false)?; + let pass = passphrase.map(|p| ledger_mcp::admin::Passphrase(p.0.clone())); + let p = + ledger_host::commands::plan_restore(&self.common, source, id, replace, false, pass)?; Ok(ledger_gui::owner::RestorePlan { source: p.source, + passphrase: p + .passphrase + .as_ref() + .map(|p| ledger_gui::owner::Secret(p.0.clone())), id: p.id, replace: p.replace, head: p.head, @@ -323,6 +330,10 @@ impl ledger_gui::owner::Owner for ViewerOwner { &self.common, &ledger_host::commands::RestorePlan { source: plan.source.clone(), + passphrase: plan + .passphrase + .as_ref() + .map(|p| ledger_mcp::admin::Passphrase(p.0.clone())), id: plan.id.clone(), replace: plan.replace, head: plan.head.clone(), diff --git a/crates/ledger-cli/tests/backups.rs b/crates/ledger-cli/tests/backups.rs index 0d71ead9..bc04aea7 100644 --- a/crates/ledger-cli/tests/backups.rs +++ b/crates/ledger-cli/tests/backups.rs @@ -1,12 +1,12 @@ -//! The server's backups (plan 3.7, D-30, D-31): every book served from the -//! data root backs itself up to the targets its settings name, a while -//! after it is written, when it opens, before it closes, and when asked. -//! Oracles: the INVARIANTS of ledger-mcp backup.rs and ledger-store -//! backup.rs, and plan 3.7's named tests. +//! The server's backups (plan 3.7, D-91): every book served from the data +//! root backs itself up to the folder its settings name, a while after it +//! is written, when it opens, before it closes, and when asked. Oracles: +//! the INVARIANTS of ledger-mcp backup.rs and ledger-store backup, and +//! plan 3.7's named tests. #![cfg(unix)] use ledger_mcp::admin::{self, Request, Response}; -use ledger_store::backup::{self, Git}; +use ledger_store::backup::{Ctx, find, verify_found}; use ledger_store::root::{BookId, Root}; use rmcp::ServiceExt; use rmcp::model::{CallToolRequestParams, ClientConfig}; @@ -85,18 +85,6 @@ impl Home { std::fs::create_dir_all(p.parent().unwrap()).unwrap(); p } - - /// A bare repository standing for the private git remote. - fn remote(&self) -> PathBuf { - let p = self.outside("remote.git"); - let out = Command::new("git") - .args(["init", "-q", "--bare", "-b", "main"]) - .arg(&p) - .output() - .unwrap(); - assert!(out.status.success(), "{out:?}"); - p - } } /// A running `wanderbooks server`, ended (kill) when dropped. @@ -281,19 +269,13 @@ async fn head(c: &Client) -> u64 { .unwrap() } -/// Name the backup targets in the book's settings. -async fn set_targets(c: &Client, remote: Option<&Path>, folder: Option<&Path>) { - let mut changes = Vec::new(); - if let Some(r) = remote { - changes.push(json!({"key": "backup.git_remote", "value": r.display().to_string()})); - } - if let Some(f) = folder { - changes.push(json!({"key": "backup.folder", "value": f.display().to_string()})); - } +/// Name the backup folder in the book's settings. +async fn set_folder(c: &Client, folder: &Path) { call( c, "books.set_setting", - json!({"changes": changes, "decided_by": "Test Owner", "note": "Backups."}), + json!({"changes": [{"key": "backup.folder", "value": folder.display().to_string()}], + "decided_by": "Test Owner", "note": "Backups."}), ) .await .unwrap(); @@ -377,16 +359,14 @@ async fn backed_up(c: &Client, within: Duration) -> Value { } } -/// Prove the backup at `source` whole; its head. +/// Prove the backup at `source` (a destination folder, a set's folder, or a +/// file) whole; its head. fn proven(home: &Home, source: &Path, tag: &str) -> (u64, String) { let scratch = home.outside(&format!("scratch-{tag}")); - let v = backup::verify( - &Git::find().unwrap(), - &source.display().to_string(), - &scratch, - ) - .unwrap_or_else(|e| panic!("{tag}: {e}")); - v.head + let found = find(source, None, &Ctx::new()).unwrap_or_else(|e| panic!("{tag}: {e}")); + verify_found(&found, &scratch, false, &Ctx::new()) + .unwrap_or_else(|e| panic!("{tag}: {e}")) + .head } fn live_head(home: &Home, book: &str) -> (u64, String) { @@ -394,63 +374,56 @@ fn live_head(home: &Home, book: &str) -> (u64, String) { (s.journal_seq(), s.head_hash().to_string()) } +const ALL: [&str; 4] = ["read", "write", "post", "admin"]; + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn a_book_backs_itself_up_to_both_targets_soon_after_a_write() { - let home = Home::new("both"); +async fn a_book_backs_itself_up_to_its_folder_soon_after_a_write() { + let home = Home::new("folder"); let server = Server::start(&home, Duration::from_millis(300)); home.create("acme"); - let c = connect( - &home, - "acme", - home.token("acme", &["read", "write", "post", "admin"]), - ) - .await; + let c = connect(&home, "acme", home.token("acme", &ALL)).await; // None set up: said, and nothing is stale. let s = call(&c, "books.backup", json!({})).await.unwrap(); assert_eq!(s["targets"], json!([])); - assert!( - s["note"].as_str().unwrap().contains("backup.git_remote"), - "{s}" - ); - // books.start says so too. + assert!(s["note"].as_str().unwrap().contains("backup.folder"), "{s}"); let steps = |v: Value| v["next_steps"].to_string(); let start = steps(call(&c, "books.start", json!({})).await.unwrap()); assert!(start.contains("No backups are set up"), "{start}"); - let (remote, folder) = (home.remote(), home.outside("disk")); + let folder = home.outside("disk"); std::fs::create_dir_all(&folder).unwrap(); - set_targets(&c, Some(&remote), Some(&folder)).await; + set_folder(&c, &folder).await; post_one(&c, 7).await; let s = backed_up(&c, Duration::from_secs(30)).await; assert_eq!(s["note"], Value::Null); let targets = s["targets"].as_array().unwrap(); - assert_eq!(targets.len(), 2, "{s}"); - for t in targets { - assert_eq!(t["stale"], false, "{t}"); - assert_eq!(t["last_error"], Value::Null, "{t}"); - assert!(t["last_ok_at"].is_string(), "{t}"); - } + assert_eq!(targets.len(), 1, "{s}"); + assert_eq!(targets[0]["stale"], false, "{s}"); + assert_eq!(targets[0]["sealed"], false, "{s}"); + assert_eq!(targets[0]["last_error"], Value::Null, "{s}"); + assert!(targets[0]["last_ok_at"].is_string(), "{s}"); let start = steps(call(&c, "books.start", json!({})).await.unwrap()); assert!(!start.contains("books.backup"), "{start}"); - // backup_does_not_advance_head: the books' head is what was written. + // The books' head is what was written, and the folder holds them whole + // at it: a folder for the books, plain files, nothing about git. let live = live_head(&home, "acme"); assert_eq!(s["head_seq"].as_u64(), Some(live.0)); - // Each target holds the books whole, at their head. - assert_eq!(proven(&home, &remote, "remote"), live); - assert_eq!(proven(&home, &folder.join("acme.git"), "folder"), live); + assert_eq!(proven(&home, &folder, "folder"), live); + assert!(folder.join("acme").join("READ-ME.txt").is_file()); // Its journal is the live journal's beginning (a drill's check). - let tree = home.outside("scratch-folder"); + let scratch = home.outside("scratch-prefix"); + let found = find(&folder, None, &Ctx::new()).unwrap(); + let v = verify_found(&found, &scratch, false, &Ctx::new()).unwrap(); assert!( - backup::is_prefix( - &home.book_dir("acme").join(ledger_store::JOURNAL_FILE), - &tree.join(ledger_store::JOURNAL_FILE) - ) - .unwrap() + std::fs::read(home.book_dir("acme").join(ledger_store::JOURNAL_FILE)) + .unwrap() + .starts_with(&std::fs::read(v.tree.join(ledger_store::JOURNAL_FILE)).unwrap()) ); - // Nothing an agent is shown names the data root. + // Nothing an agent is shown names the data root, or git. assert!( !s.to_string().contains(&home.root().display().to_string()), "{s}" ); + assert!(!s.to_string().to_lowercase().contains("git"), "{s}"); drop(c); assert!(server.close().success()); } @@ -464,31 +437,18 @@ async fn closing_backs_the_books_up_and_opening_catches_up() { let server = Server::start(&home, Duration::from_secs(3600)); home.create("acme"); settle().await; - let c = connect( - &home, - "acme", - home.token("acme", &["read", "write", "post", "admin"]), - ) - .await; - set_targets(&c, None, Some(&folder)).await; + let c = connect(&home, "acme", home.token("acme", &ALL)).await; + set_folder(&c, &folder).await; post_one(&c, 3).await; drop(c); assert!(server.close().success()); - let live = live_head(&home, "acme"); - assert_eq!(proven(&home, &folder.join("acme.git"), "closed"), live); - - // archive_catches_up_at_start: a backup target named while the server - // was down (here: the folder was missing then made) is caught up when - // the books open. + assert_eq!(proven(&home, &folder, "closed"), live_head(&home, "acme")); + // A folder named while the server was down, then made, is caught up + // when the books open. let late = home.outside("late"); let server = Server::start(&home, Duration::from_secs(3600)); - let c = connect( - &home, - "acme", - home.token("acme", &["read", "write", "post", "admin"]), - ) - .await; - set_targets(&c, None, Some(&late)).await; + let c = connect(&home, "acme", home.token("acme", &ALL)).await; + set_folder(&c, &late).await; // The folder doesn't exist: said plainly, the books unharmed. let s = call(&c, "books.back_up_now", json!({})).await.unwrap(); let err = s["targets"][0]["last_error"] @@ -496,27 +456,19 @@ async fn closing_backs_the_books_up_and_opening_catches_up() { .unwrap_or_default() .to_string(); assert!(err.contains("folder"), "{s}"); + assert_eq!(s["targets"][0]["disconnected"], true, "{s}"); let start = call(&c, "books.start", json!({})).await.unwrap()["next_steps"].to_string(); assert!(start.contains("behind or failing"), "{start}"); assert!(!err.contains(&home.root().display().to_string()), "{err}"); drop(c); assert!(server.close().success()); - // The disk is connected while the books are closed: the books catch - // up when they open. std::fs::create_dir_all(&late).unwrap(); let server = Server::start(&home, Duration::from_secs(3600)); - let c = connect( - &home, - "acme", - home.token("acme", &["read", "write", "post", "admin"]), - ) - .await; + let c = connect(&home, "acme", home.token("acme", &ALL)).await; let s = backed_up(&c, Duration::from_secs(30)).await; assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}"); - assert_eq!( - proven(&home, &late.join("acme.git"), "late"), - live_head(&home, "acme") - ); + assert_eq!(s["targets"][0]["disconnected"], false, "{s}"); + assert_eq!(proven(&home, &late, "late"), live_head(&home, "acme")); drop(c); assert!(server.close().success()); } @@ -528,13 +480,8 @@ async fn backing_up_now_needs_admin_and_never_moves_the_head() { std::fs::create_dir_all(&folder).unwrap(); let server = Server::start(&home, Duration::from_secs(3600)); home.create("acme"); - let admin = connect( - &home, - "acme", - home.token("acme", &["read", "write", "post", "admin"]), - ) - .await; - set_targets(&admin, None, Some(&folder)).await; + let admin = connect(&home, "acme", home.token("acme", &ALL)).await; + set_folder(&admin, &folder).await; post_one(&admin, 2).await; let before = head(&admin).await; // A reader sees the standing but can't back up. @@ -544,74 +491,81 @@ async fn backing_up_now_needs_admin_and_never_moves_the_head() { .await .unwrap_err(); assert!(refused.contains("admin"), "{refused}"); - // Twice: the second has nothing new to commit, and still answers. + // Twice: the second has nothing new to write, and still answers. for _ in 0..2 { let s = call(&admin, "books.back_up_now", json!({})).await.unwrap(); assert_eq!(s["targets"][0]["through_seq"].as_u64(), Some(before), "{s}"); assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}"); } assert_eq!(head(&admin).await, before); - assert_eq!( - proven(&home, &folder.join("acme.git"), "now"), - live_head(&home, "acme") - ); + assert_eq!(proven(&home, &folder, "now"), live_head(&home, "acme")); drop((admin, reader)); assert!(server.close().success()); } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn a_backup_that_moved_on_is_never_overwritten() { - let home = Home::new("diverged"); - let remote = home.remote(); - let server = Server::start(&home, Duration::from_secs(3600)); - home.create("acme"); - home.create("other"); - // Another book's history in the remote first. - let other = connect( - &home, - "other", - home.token("other", &["read", "write", "post", "admin"]), - ) - .await; - set_targets(&other, Some(&remote), None).await; - post_one(&other, 9).await; - let s = call(&other, "books.back_up_now", json!({})).await.unwrap(); +async fn a_backup_of_another_history_is_never_written_over() { + // Two computers whose books have one id and different histories, one + // folder: the second's backup is refused, the folder unchanged. + let (a, b) = (Home::new("div-a"), Home::new("div-b")); + let folder = a.outside("disk"); + std::fs::create_dir_all(&folder).unwrap(); + let (sa, sb) = ( + Server::start(&a, Duration::from_secs(3600)), + Server::start(&b, Duration::from_secs(3600)), + ); + a.create("acme"); + b.create("acme"); + let ca = connect(&a, "acme", a.token("acme", &ALL)).await; + set_folder(&ca, &folder).await; + post_one(&ca, 9).await; + let s = call(&ca, "books.back_up_now", json!({})).await.unwrap(); assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}"); - let theirs = proven(&home, &remote, "theirs"); - // This book's push is refused, the remote unchanged. - let acme = connect( - &home, - "acme", - home.token("acme", &["read", "write", "post", "admin"]), - ) - .await; - set_targets(&acme, Some(&remote), None).await; - post_one(&acme, 1).await; - let s = call(&acme, "books.back_up_now", json!({})).await.unwrap(); - assert!(s["targets"][0]["last_error"].is_string(), "{s}"); + let theirs = proven(&a, &folder, "theirs"); + let cb = connect(&b, "acme", b.token("acme", &ALL)).await; + set_folder(&cb, &folder).await; + post_one(&cb, 1).await; + let s = call(&cb, "books.back_up_now", json!({})).await.unwrap(); + assert!( + s["targets"][0]["last_error"] + .as_str() + .unwrap() + .contains("different history"), + "{s}" + ); assert_eq!(s["targets"][0]["through_seq"], Value::Null, "{s}"); - assert_eq!(proven(&home, &remote, "after"), theirs); - drop((other, acme)); - assert!(server.close().success()); + assert_eq!(proven(&a, &folder, "after"), theirs); + drop((ca, cb)); + assert!(sa.close().success()); + assert!(sb.close().success()); } /// Restore `source` as `id`: the preview, then (if it was one) the /// restore confirmed against its head. Ok(what was restored) or Err(why). fn restore(home: &Home, id: &str, source: &Path, replace: bool) -> Result { + restore_with(home, id, source, replace, None) +} + +fn restore_with( + home: &Home, + id: &str, + source: &Path, + replace: bool, + passphrase: Option<&str>, +) -> Result { let request = |expect_head: Option<(u64, String)>| Request::Restore { id: id.into(), source: source.display().to_string(), replace, confirmed: expect_head.is_some(), expect_head, + passphrase: passphrase.map(|p| admin::Passphrase(p.to_string())), }; let preview = match home.admin(request(None)) { Response::RestorePreview(p) => p, Response::Refused(why) => return Err(why), other => panic!("{other:?}"), }; - // (Whether books of that id exist is said; the restore itself refuses - // over them, or replacing none.) match home.admin(request(Some(preview.head.clone()))) { Response::Restored(r) => { assert_eq!(r.head, preview.head); @@ -639,42 +593,43 @@ async fn figures(c: &Client) -> Value { }) } -/// A git command in `dir` with an identity, for making damaged backups. -fn git(dir: &Path, args: &[&str]) { - let out = Command::new("git") - .arg("-C") - .arg(dir) - .args([ - "-c", - "user.name=t", - "-c", - "user.email=t@t.invalid", - "-c", - "commit.gpgsign=false", - ]) - .args(args) - .output() - .unwrap(); - assert!(out.status.success(), "{args:?}: {out:?}"); -} - -/// A backup of acme (two entries, a receipt each) in the folder target. +/// A backup of acme (two entries, a receipt each) in the folder. async fn backed_up_acme(home: &Home) -> (PathBuf, Value) { settle().await; let folder = home.outside("disk"); std::fs::create_dir_all(&folder).unwrap(); - let c = connect( - home, - "acme", - home.token("acme", &["read", "write", "post", "admin"]), - ) - .await; - set_targets(&c, None, Some(&folder)).await; + let c = connect(home, "acme", home.token("acme", &ALL)).await; + set_folder(&c, &folder).await; post_one(&c, 4).await; post_one(&c, 5).await; let s = call(&c, "books.back_up_now", json!({})).await.unwrap(); assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}"); - (folder.join("acme.git"), figures(&c).await) + (folder, figures(&c).await) +} + +/// The files under `dir` whose path (below it) starts with `prefix`. +fn files_below(dir: &Path, prefix: &str) -> Vec { + fn walk(dir: &Path, out: &mut Vec) { + for e in std::fs::read_dir(dir).unwrap() { + let p = e.unwrap().path(); + if p.is_dir() { + walk(&p, out); + } else { + out.push(p); + } + } + } + let mut all = Vec::new(); + walk(dir, &mut all); + all.retain(|p| { + p.strip_prefix(dir) + .unwrap() + .to_string_lossy() + .replace('\\', "/") + .starts_with(prefix) + }); + all.sort(); + all } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] @@ -682,9 +637,9 @@ async fn restore_beside_existing_books_and_on_a_clean_install() { let home = Home::new("beside"); let server = Server::start(&home, Duration::from_secs(3600)); home.create("acme"); - let (backup, want) = backed_up_acme(&home).await; + let (folder, want) = backed_up_acme(&home).await; // Beside: its own books, the same figures and head. - let r = restore(&home, "acme-copy", &backup, false).unwrap(); + let r = restore(&home, "acme-copy", &folder, false).unwrap(); assert_eq!(r.replaced, None); assert_eq!(r.head, live_head(&home, "acme")); let copy = connect( @@ -694,23 +649,23 @@ async fn restore_beside_existing_books_and_on_a_clean_install() { ) .await; assert_eq!(figures(©).await, want); - // Its own backups carry on from the restored history: to the folder - // under its own name. + // Its own backups carry on in the same folder, under its own name; the + // original's stay as they were. + let orig = proven(&home, &folder.join("acme"), "orig-before"); let s = call(©, "books.back_up_now", json!({})).await.unwrap(); assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}"); - let folder = backup.parent().unwrap(); assert_eq!( - proven(&home, &folder.join("acme-copy.git"), "copy"), + proven(&home, &folder.join("acme-copy"), "copy"), live_head(&home, "acme-copy") ); + assert_eq!(proven(&home, &folder.join("acme"), "orig-after"), orig); drop(copy); assert!(server.close().success()); - // restore_on_clean_install: another computer's root, nothing in it. let other = Home::new("clean"); let server = Server::start(&other, Duration::from_secs(3600)); assert_eq!(books_held(&other), Vec::::new()); - let r = restore(&other, "acme", &backup, false).unwrap(); + let r = restore(&other, "acme", &folder.join("acme"), false).unwrap(); assert_eq!(r.head, live_head(&home, "acme")); let c = connect(&other, "acme", other.token("acme", &["read"])).await; assert_eq!(figures(&c).await, want); @@ -723,29 +678,21 @@ async fn restore_never_overwrites_and_replacing_keeps_the_old_books() { let home = Home::new("replace"); let server = Server::start(&home, Duration::from_secs(3600)); home.create("acme"); - let (backup, want) = backed_up_acme(&home).await; + let (folder, want) = backed_up_acme(&home).await; let at_backup = live_head(&home, "acme"); - // The books move on past the backup. - let c = connect( - &home, - "acme", - home.token("acme", &["read", "write", "post", "admin"]), - ) - .await; + let c = connect(&home, "acme", home.token("acme", &ALL)).await; post_one(&c, 6).await; let moved_on = live_head(&home, "acme"); assert!(moved_on.0 > at_backup.0); // Not over them. - let refused = restore(&home, "acme", &backup, false).unwrap_err(); + let refused = restore(&home, "acme", &folder, false).unwrap_err(); assert!(refused.contains("already books called"), "{refused}"); assert_eq!(live_head(&home, "acme"), moved_on); // Replacing books that aren't there is refused too. - let refused = restore(&home, "nobody", &backup, true).unwrap_err(); + let refused = restore(&home, "nobody", &folder, true).unwrap_err(); assert!(refused.contains("no books called"), "{refused}"); // Replacing: the old books kept whole in legacy/, the backup in place. - let r = restore(&home, "acme", &backup, true).unwrap(); - // The restored books are new to the server: backed up as books just - // opened, unasked. + let r = restore(&home, "acme", &folder, true).unwrap(); let fresh = connect(&home, "acme", home.token("acme", &["read"])).await; let deadline = Instant::now() + Duration::from_secs(30); loop { @@ -764,24 +711,14 @@ async fn restore_never_overwrites_and_replacing_keeps_the_old_books() { let old = ledger_store::Snapshot::load(&kept).unwrap(); assert_eq!((old.journal_seq(), old.head_hash().to_string()), moved_on); assert_eq!(live_head(&home, "acme"), at_backup); - // The session of before never reaches the old books: refused, or - // (its client opening a new session) the restored ones. - if let Ok(start) = call(&c, "books.start", json!({})).await { - assert_eq!(start["head"]["seq"].as_u64(), Some(at_backup.0), "{start}"); - } - let c = connect( - &home, - "acme", - home.token("acme", &["read", "write", "post", "admin"]), - ) - .await; + let c = connect(&home, "acme", home.token("acme", &ALL)).await; assert_eq!(figures(&c).await, want); - // And it is written to and backed up as before (the backup's history - // carries on: a fast-forward). + // And it is written to and backed up as before: the folder's backup of + // these books goes on from where it was. post_one(&c, 7).await; let s = call(&c, "books.back_up_now", json!({})).await.unwrap(); assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}"); - assert_eq!(proven(&home, &backup, "after"), live_head(&home, "acme")); + assert_eq!(proven(&home, &folder, "after"), live_head(&home, "acme")); drop(c); assert!(server.close().success()); } @@ -791,7 +728,7 @@ async fn restore_refuses_a_damaged_backup_and_writes_nothing() { let home = Home::new("damaged"); let server = Server::start(&home, Duration::from_secs(3600)); home.create("acme"); - let (backup, _) = backed_up_acme(&home).await; + let (folder, _) = backed_up_acme(&home).await; let before = books_held(&home); let books = home.root().join("books"); let names = || { @@ -803,90 +740,74 @@ async fn restore_refuses_a_damaged_backup_and_writes_nothing() { v }; let listed = names(); - // Each damage in a backup of its own, made from the good one. + // Each damage in a copy of its own, made from the good one. type Spoil<'a> = (&'a str, &'a dyn Fn(&Path)); - let damage: [Spoil; 4] = [ - ("flipped", &|w: &Path| { - let j = w.join(ledger_store::JOURNAL_FILE); - let text = std::fs::read_to_string(&j).unwrap(); - std::fs::write(&j, text.replacen("entry 4", "entry 9", 1)).unwrap(); - git(w, &["commit", "-qam", &git_subject(w)]); + let damage: [Spoil; 5] = [ + ("flipped", &|set: &Path| { + let j = &files_below(set, "journal/")[0]; + let mut b = std::fs::read(j).unwrap(); + let mid = b.len() / 2; + b[mid] ^= 1; + std::fs::write(j, b).unwrap(); }), - ("no-blob", &|w: &Path| { - git(w, &["rm", "-rq", "blobs"]); - git(w, &["commit", "-qm", &git_subject(w)]); + ("no-files", &|set: &Path| { + for f in files_below(set, "files/") { + std::fs::remove_file(f).unwrap(); + } }), - ("cut", &|w: &Path| { - let j = w.join(ledger_store::JOURNAL_FILE); - let mut bytes = std::fs::read(&j).unwrap(); - bytes.truncate(bytes.len() - 10); - std::fs::write(&j, bytes).unwrap(); - git(w, &["commit", "-qam", &git_subject(w)]); + ("cut", &|set: &Path| { + let j = &files_below(set, "journal/")[0]; + let mut b = std::fs::read(j).unwrap(); + b.truncate(b.len() - 10); + std::fs::write(j, b).unwrap(); }), - ("head", &|w: &Path| { - git( - w, - &["commit", "-q", "--allow-empty", "-m", "seq 99 head 00"], - ); + ("manifest-cut", &|set: &Path| { + for f in files_below(set, "manifests/") { + let b = std::fs::read(&f).unwrap(); + std::fs::write(&f, &b[..b.len() / 2]).unwrap(); + } + }), + ("no-manifest", &|set: &Path| { + for f in files_below(set, "manifests/") { + std::fs::remove_file(f).unwrap(); + } }), ]; for (tag, spoil) in damage { - let work = home.outside(&format!("work-{tag}")); - let out = Command::new("git") - .args(["clone", "-q"]) - .arg(&backup) - .arg(&work) - .output() - .unwrap(); - assert!(out.status.success(), "{out:?}"); - spoil(&work); - let bad = home.outside(&format!("bad-{tag}.git")); - let out = Command::new("git") - .args(["clone", "-q", "--bare"]) - .arg(&work) - .arg(&bad) - .output() - .unwrap(); - assert!(out.status.success(), "{out:?}"); - let why = restore(&home, "acme-bad", &bad, false).unwrap_err(); - assert!( - why.contains("can't be restored") || why.contains("can't be trusted"), - "{tag}: {why}" - ); + let copy = home.outside(&format!("bad-{tag}")); + copy_dir(&folder.join("acme"), ©); + spoil(©); + let why = restore(&home, "acme-bad", ©, false).unwrap_err(); + assert!(why.contains("can't be restored"), "{tag}: {why}"); assert!( !why.contains(&home.root().display().to_string()), "{tag}: {why}" ); - assert!(!why.contains(&bad.display().to_string()), "{tag}: {why}"); + assert!(!why.contains(©.display().to_string()), "{tag}: {why}"); assert_eq!(books_held(&home), before, "{tag}"); assert_eq!(names(), listed, "{tag}"); } - // An address that isn't a backup: said, nothing written. + // A place that isn't a backup: said, nothing written. let why = restore(&home, "acme-bad", &home.outside("nothing-here"), false).unwrap_err(); assert!(!why.contains("nothing-here"), "{why}"); assert_eq!(names(), listed); assert!(server.close().success()); } -/// The subject a backup commit of `w`'s journal would have. -fn git_subject(w: &Path) -> String { - let s = ledger_store::Snapshot::load(w); - match s { - Ok(s) => format!("seq {} head {}", s.journal_seq(), s.head_hash()), - // A journal that no longer loads: the subject it had. - Err(_) => { - let out = Command::new("git") - .arg("-C") - .arg(w) - .args(["log", "-1", "--format=%s"]) - .output() - .unwrap(); - String::from_utf8_lossy(&out.stdout).trim().to_string() +fn copy_dir(from: &Path, to: &Path) { + std::fs::create_dir_all(to).unwrap(); + for e in std::fs::read_dir(from).unwrap() { + let e = e.unwrap(); + let target = to.join(e.file_name()); + if e.path().is_dir() { + copy_dir(&e.path(), &target); + } else { + std::fs::copy(e.path(), target).unwrap(); } } } -/// Wait until every target's backup has been drilled. +/// Wait until the folder's backup has been drilled. async fn drilled(c: &Client) -> Value { let deadline = Instant::now() + Duration::from_secs(60); loop { @@ -905,9 +826,8 @@ async fn opening_the_books_drills_a_backup_never_drilled() { let home = Home::new("drill"); let server = Server::start(&home, Duration::from_secs(3600)); home.create("acme"); - let (backup, _) = backed_up_acme(&home).await; + let (folder, _) = backed_up_acme(&home).await; assert!(server.close().success()); - // Opening the books drills a backup never drilled. let server = Server::start_with( &home, Duration::from_secs(3600), @@ -918,8 +838,7 @@ async fn opening_the_books_drills_a_backup_never_drilled() { assert_eq!(s["targets"][0]["drill_error"], Value::Null, "{s}"); let start = call(&c, "books.start", json!({})).await.unwrap()["next_steps"].to_string(); assert!(!start.contains("books.backup"), "{start}"); - // Its backup was proven where it is: the record names the head. - assert!(proven(&home, &backup, "drilled").0 > 0); + assert!(proven(&home, &folder, "drilled").0 > 0); drop(c); assert!(server.close().success()); } @@ -929,24 +848,16 @@ async fn restore_drill_failure_is_flagged() { let home = Home::new("drill-bad"); let server = Server::start(&home, Duration::from_secs(3600)); home.create("acme"); - let (backup, _) = backed_up_acme(&home).await; + let (folder, _) = backed_up_acme(&home).await; assert!(server.close().success()); // The backup is changed behind the books' back. - let work = home.outside("tamper"); - let out = Command::new("git") - .args(["clone", "-q"]) - .arg(&backup) - .arg(&work) - .output() - .unwrap(); - assert!(out.status.success(), "{out:?}"); - let j = work.join(ledger_store::JOURNAL_FILE); - let text = std::fs::read_to_string(&j).unwrap(); - std::fs::write(&j, text.replacen("entry 4", "entry 9", 1)).unwrap(); - git(&work, &["commit", "-qam", "seq 0 head x"]); - git(&work, &["push", "-q", "origin", "HEAD:main"]); - // Opening the books: nothing is pushed over it, and its first drill - // fails, said in books.backup and books.start. + let j = &files_below(&folder.join("acme"), "journal/")[0]; + let mut b = std::fs::read(j).unwrap(); + let mid = b.len() / 2; + b[mid] ^= 1; + std::fs::write(j, b).unwrap(); + // Opening the books: its first drill fails, said in books.backup and + // books.start. let server = Server::start_with( &home, Duration::from_secs(3600), @@ -955,7 +866,6 @@ async fn restore_drill_failure_is_flagged() { let c = connect(&home, "acme", home.token("acme", &["read", "admin"])).await; let s = drilled(&c).await; assert!(s["targets"][0]["drill_error"].is_string(), "{s}"); - assert!(s["targets"][0]["last_error"].is_string(), "{s}"); let start = call(&c, "books.start", json!({})).await.unwrap()["next_steps"].to_string(); assert!(start.contains("behind or failing"), "{start}"); drop(c); @@ -968,12 +878,7 @@ async fn a_write_waits_for_the_quiet_before_it_is_backed_up() { let server = Server::start(&home, Duration::from_secs(3600)); home.create("acme"); backed_up_acme(&home).await; - let c = connect( - &home, - "acme", - home.token("acme", &["read", "write", "post", "admin"]), - ) - .await; + let c = connect(&home, "acme", home.token("acme", &ALL)).await; post_one(&c, 8).await; // Several looks of the loop later, still not: the writing hasn't // stopped for long enough. @@ -994,13 +899,14 @@ async fn a_restore_is_of_the_backup_previewed_only() { let home = Home::new("previewed"); let server = Server::start(&home, Duration::from_secs(3600)); home.create("acme"); - let (backup, _) = backed_up_acme(&home).await; + let (folder, _) = backed_up_acme(&home).await; let request = |expect_head: Option<(u64, String)>, confirmed| Request::Restore { id: "copy".into(), - source: backup.display().to_string(), + source: folder.display().to_string(), replace: false, confirmed, expect_head, + passphrase: None, }; // A preview leaves nothing behind in the books' folder, and clears // what a restore that never finished left. @@ -1022,12 +928,7 @@ async fn a_restore_is_of_the_backup_previewed_only() { other => panic!("{other:?}"), } // The backup moves on after the preview: refused, nothing written. - let c = connect( - &home, - "acme", - home.token("acme", &["read", "write", "post", "admin"]), - ) - .await; + let c = connect(&home, "acme", home.token("acme", &ALL)).await; post_one(&c, 9).await; call(&c, "books.back_up_now", json!({})).await.unwrap(); match home.admin(request(Some(previewed), true)) { @@ -1045,12 +946,7 @@ async fn a_restore_brings_the_vault_and_its_key() { let home = Home::new("vault"); let server = Server::start(&home, Duration::from_secs(3600)); home.create("acme"); - let c = connect( - &home, - "acme", - home.token("acme", &["read", "write", "post", "admin"]), - ) - .await; + let c = connect(&home, "acme", home.token("acme", &ALL)).await; call( &c, "books.add_party", @@ -1065,17 +961,18 @@ async fn a_restore_brings_the_vault_and_its_key() { ) .await .unwrap(); - let (backup, want) = backed_up_acme(&home).await; + let (folder, want) = backed_up_acme(&home).await; drop(c); assert!(server.close().success()); let other = Home::new("vault-clean"); let server = Server::start(&other, Duration::from_secs(3600)); let request = |expect_head: Option<(u64, String)>| Request::Restore { id: "acme".into(), - source: backup.display().to_string(), + source: folder.display().to_string(), replace: false, confirmed: expect_head.is_some(), expect_head, + passphrase: None, }; let preview = match other.admin(request(None)) { Response::RestorePreview(p) => p, @@ -1114,32 +1011,18 @@ async fn a_restore_brings_the_vault_and_its_key() { assert_eq!(party["party"]["tin"]["in_vault"], true, "{party}"); drop(c); assert!(server.close().success()); - - // A backup without the vault's key, or without a TIN record the books - // name, is not whole. + // A backup missing the vault's key, or the TIN record the books name, + // is not whole: refused, nothing restored. let third = Home::new("vault-short"); let server = Server::start(&third, Duration::from_secs(3600)); - for (gone, said) in [("keys", "key"), ("vault", "TIN record")] { - let work = home.outside(&format!("no-{gone}")); - let out = Command::new("git") - .args(["clone", "-q"]) - .arg(&backup) - .arg(&work) - .output() - .unwrap(); - assert!(out.status.success(), "{out:?}"); - git(&work, &["rm", "-rq", gone]); - git(&work, &["commit", "-qm", &git_subject(&work)]); - let bad = home.outside(&format!("no-{gone}.git")); - let out = Command::new("git") - .args(["clone", "-q", "--bare"]) - .arg(&work) - .arg(&bad) - .output() - .unwrap(); - assert!(out.status.success(), "{out:?}"); - let why = restore(&third, "acme", &bad, false).unwrap_err(); - assert!(why.contains(said), "{gone}: {why}"); + for gone in ["keys/", "vault/"] { + let copy = home.outside(&format!("no-{}", gone.trim_end_matches('/'))); + copy_dir(&folder.join("acme"), ©); + for f in files_below(©, gone) { + std::fs::remove_file(f).unwrap(); + } + let why = restore(&third, "acme", ©, false).unwrap_err(); + assert!(why.contains("can't be restored"), "{gone}: {why}"); assert_eq!(books_held(&third), Vec::::new()); } assert!(server.close().success()); @@ -1150,29 +1033,15 @@ async fn a_replacing_restore_that_fails_leaves_the_books_open() { let home = Home::new("replace-bad"); let server = Server::start(&home, Duration::from_secs(3600)); home.create("acme"); - let (backup, want) = backed_up_acme(&home).await; + let (folder, want) = backed_up_acme(&home).await; let before = live_head(&home, "acme"); - // A backup whose head isn't the one it records. - let work = home.outside("work"); - let out = Command::new("git") - .args(["clone", "-q"]) - .arg(&backup) - .arg(&work) - .output() - .unwrap(); - assert!(out.status.success(), "{out:?}"); - git( - &work, - &["commit", "-q", "--allow-empty", "-m", "seq 99 head 00"], - ); - let bad = home.outside("bad.git"); - let out = Command::new("git") - .args(["clone", "-q", "--bare"]) - .arg(&work) - .arg(&bad) - .output() - .unwrap(); - assert!(out.status.success(), "{out:?}"); + let bad = home.outside("bad"); + copy_dir(&folder.join("acme"), &bad); + let j = &files_below(&bad, "journal/")[0]; + let mut b = std::fs::read(j).unwrap(); + let mid = b.len() / 2; + b[mid] ^= 1; + std::fs::write(j, b).unwrap(); // Its preview is refused; so is a confirm (sent without one), which // lets the books go first, then fails: they are open again, as they // were, nothing moved to legacy. @@ -1183,6 +1052,7 @@ async fn a_replacing_restore_that_fails_leaves_the_books_open() { replace: true, confirmed: true, expect_head: Some(before.clone()), + passphrase: None, }) { Response::Refused(why) => why, other => panic!("{other:?}"), @@ -1198,12 +1068,7 @@ async fn a_replacing_restore_that_fails_leaves_the_books_open() { assert_eq!(live_head(&home, "acme"), before); let legacy = home.root().join("legacy"); assert!(!legacy.exists() || std::fs::read_dir(&legacy).unwrap().count() == 0); - let c = connect( - &home, - "acme", - home.token("acme", &["read", "write", "post", "admin"]), - ) - .await; + let c = connect(&home, "acme", home.token("acme", &ALL)).await; assert_eq!(figures(&c).await, want); post_one(&c, 3).await; drop(c); @@ -1219,154 +1084,37 @@ fn records(home: &Home, book: &str) -> Vec { .collect() } -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn books_restored_beside_their_original_leave_its_repository_alone() { - let home = Home::new("beside-remote"); - let server = Server::start(&home, Duration::from_secs(3600)); - home.create("acme"); - settle().await; - let (remote, folder) = (home.remote(), home.outside("disk")); - std::fs::create_dir_all(&folder).unwrap(); - let c = connect( - &home, - "acme", - home.token("acme", &["read", "write", "post", "admin"]), - ) - .await; - set_targets(&c, Some(&remote), Some(&folder)).await; - post_one(&c, 1).await; - let s = call(&c, "books.back_up_now", json!({})).await.unwrap(); - assert!( - s["targets"] - .as_array() - .unwrap() - .iter() - .all(|t| t["last_error"].is_null()), - "{s}" - ); - // A copy beside them, from their repository. - let r = restore(&home, "copy", &remote, false).unwrap(); - assert_eq!(r.origin.as_deref(), Some("acme")); - let copy = connect( - &home, - "copy", - home.token("copy", &["read", "write", "post", "admin"]), - ) - .await; - post_one(©, 2).await; - let s = call(©, "books.back_up_now", json!({})).await.unwrap(); - let by = |kind: &str| { - s["targets"] - .as_array() - .unwrap() - .iter() - .find(|t| t["target"] == kind) - .unwrap() - .clone() - }; - // Its own folder repository; the shared one paused, and said. - assert_eq!(by("folder")["last_error"], Value::Null, "{s}"); - assert!( - by("repository")["last_error"] - .as_str() - .unwrap() - .contains("restored as a copy"), - "{s}" - ); - let start = call(©, "books.start", json!({})).await.unwrap()["next_steps"].to_string(); - assert!(start.contains("behind or failing"), "{start}"); - // The original carries on backing up there. - post_one(&c, 3).await; - let s = call(&c, "books.back_up_now", json!({})).await.unwrap(); - assert!( - s["targets"] - .as_array() - .unwrap() - .iter() - .all(|t| t["last_error"].is_null()), - "{s}" - ); - assert_eq!(proven(&home, &remote, "orig"), live_head(&home, "acme")); - // Naming a repository of its own ends the pause. - let own = home.outside("own.git"); - let out = Command::new("git") - .args(["init", "-q", "--bare", "-b", "main"]) - .arg(&own) - .output() - .unwrap(); - assert!(out.status.success(), "{out:?}"); - set_targets(©, Some(&own), None).await; - let s = call(©, "books.back_up_now", json!({})).await.unwrap(); - assert!( - s["targets"] - .as_array() - .unwrap() - .iter() - .all(|t| t["last_error"].is_null()), - "{s}" - ); - drop((c, copy)); - assert!(server.close().success()); -} - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn restored_books_never_make_their_backup_folder_again() { let home = Home::new("restore-mount"); let server = Server::start(&home, Duration::from_secs(3600)); home.create("acme"); - settle().await; - let (remote, folder) = (home.remote(), home.outside("disk")); - std::fs::create_dir_all(&folder).unwrap(); - let c = connect( - &home, - "acme", - home.token("acme", &["read", "write", "post", "admin"]), - ) - .await; - set_targets(&c, Some(&remote), Some(&folder)).await; - post_one(&c, 1).await; - call(&c, "books.back_up_now", json!({})).await.unwrap(); - drop(c); + let (folder, _) = backed_up_acme(&home).await; assert!(server.close().success()); // On another computer, its backup disk not mounted (the mount point - // there, empty): restored from the repository. - std::fs::rename(folder.join("acme.git"), home.outside("unmounted.git")).unwrap(); + // there, empty): restored from a copy of the backup. + let copy = home.outside("copy-of-disk"); + copy_dir(&folder, ©); + std::fs::rename(folder.join("acme"), home.outside("unmounted")).unwrap(); let other = Home::new("restore-mount-new"); let server = Server::start(&other, Duration::from_secs(3600)); - restore(&other, "acme", &remote, false).unwrap(); + restore(&other, "acme", ©, false).unwrap(); let c = connect(&other, "acme", other.token("acme", &["read", "admin"])).await; let s = call(&c, "books.back_up_now", json!({})).await.unwrap(); - let by = |kind: &str| { - s["targets"] - .as_array() - .unwrap() - .iter() - .find(|t| t["target"] == kind) - .unwrap() - .clone() - }; assert!( - by("folder")["last_error"] + s["targets"][0]["last_error"] .as_str() .unwrap() .contains("holds no backup"), "{s}" ); - assert!(!folder.join("acme.git").exists(), "made on the wrong disk"); - assert_eq!(by("repository")["last_error"], Value::Null, "{s}"); + assert!(!folder.join("acme").exists(), "made on the wrong disk"); // The human says it's a new disk: begun there again. let s = call(&c, "books.back_up_now", json!({"new_disk": true})) .await .unwrap(); - assert!( - s["targets"] - .as_array() - .unwrap() - .iter() - .all(|t| t["last_error"].is_null()), - "{s}" - ); - assert!(folder.join("acme.git").join("HEAD").is_file()); + assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}"); + assert!(folder.join("acme").join("manifests").is_dir()); drop(c); assert!(server.close().success()); } @@ -1376,7 +1124,7 @@ async fn a_damaged_backup_record_never_keeps_the_books_shut() { let home = Home::new("damaged-record"); let server = Server::start(&home, Duration::from_secs(3600)); home.create("acme"); - backed_up_acme(&home).await; + let (folder, _) = backed_up_acme(&home).await; assert!(server.close().success()); let log = home.book_dir("acme").join("ops").join("backup.jsonl"); let text = std::fs::read_to_string(&log).unwrap(); @@ -1395,12 +1143,11 @@ async fn a_damaged_backup_record_never_keeps_the_books_shut() { let c = connect(&home, "acme", home.token("acme", &["read", "admin"])).await; let s = call(&c, "books.back_up_now", json!({})).await.unwrap(); assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}"); - // What it knew of whose backups the folder holds was kept: gone, the - // folder's backup is a disk not connected, never made again. drop(c); assert!(server.close().success()); - let folder = home.outside("disk"); - std::fs::rename(folder.join("acme.git"), home.outside("away.git")).unwrap(); + // What it knew of whose backups the folder holds was kept: gone, the + // folder's backup is a disk not connected, never made again. + std::fs::rename(folder.join("acme"), home.outside("away")).unwrap(); let server = Server::start(&home, Duration::from_secs(3600)); let c = connect(&home, "acme", home.token("acme", &["read", "admin"])).await; let s = call(&c, "books.back_up_now", json!({})).await.unwrap(); @@ -1411,57 +1158,81 @@ async fn a_damaged_backup_record_never_keeps_the_books_shut() { .contains("holds no backup"), "{s}" ); - assert!(!folder.join("acme.git").exists()); + assert!(!folder.join("acme").exists()); drop(c); assert!(server.close().success()); } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn a_failing_target_waits_while_the_others_carry_on() { - let home = Home::new("one-failing"); +async fn a_failing_destination_is_not_tried_again_after_each_write() { + let home = Home::new("failing"); let server = Server::start(&home, Duration::from_millis(300)); home.create("acme"); settle().await; - let remote = home.remote(); let unplugged = home.outside("unplugged"); - let c = connect( - &home, - "acme", - home.token("acme", &["read", "write", "post", "admin"]), - ) - .await; - set_targets(&c, Some(&remote), Some(&unplugged)).await; + let c = connect(&home, "acme", home.token("acme", &ALL)).await; + set_folder(&c, &unplugged).await; let s = call(&c, "books.back_up_now", json!({})).await.unwrap(); - let folder_fails = |home: &Home| { + let pushes = |home: &Home| { records(home, "acme") .iter() - .filter(|r| r["kind"] == "push" && r["target"] == "folder") + .filter(|r| r["kind"] == "push") .count() }; - let before = folder_fails(&home); + let before = pushes(&home); assert!(before >= 1, "{s}"); - // Writes: backed up to the repository soon after each, the folder not - // tried again (it failed lately). + // Writes: the folder isn't tried again while it failed lately. for n in 0..3 { post_one(&c, 10 + n).await; - let deadline = Instant::now() + Duration::from_secs(30); - loop { - let s = call(&c, "books.backup", json!({})).await.unwrap(); - let remote_t = s["targets"] - .as_array() - .unwrap() - .iter() - .find(|t| t["target"] == "repository") - .unwrap() - .clone(); - if remote_t["through_seq"] == s["head_seq"] { - break; - } - assert!(Instant::now() < deadline, "not backed up: {s}"); - tokio::time::sleep(Duration::from_millis(100)).await; - } + tokio::time::sleep(Duration::from_millis(1500)).await; } - assert_eq!(folder_fails(&home), before); + assert_eq!(pushes(&home), before); + drop(c); + assert!(server.close().success()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn old_settings_and_an_old_backup_history_are_left_alone_and_said() { + // Books that name a private repository, and carry an old backup + // history in their folder: they open and work; the status says plainly + // what is no longer used; nothing of the old is read, moved or deleted. + let home = Home::new("old-forms"); + let server = Server::start(&home, Duration::from_secs(3600)); + home.create("acme"); + settle().await; + let c = connect(&home, "acme", home.token("acme", &ALL)).await; + call( + &c, + "books.set_setting", + json!({"changes": [{"key": "backup.git_remote", "value": "https://example.invalid/books"}], + "decided_by": "Test Owner", "note": "Old."}), + ) + .await + .unwrap(); + let old = home.book_dir("acme").join("archive.git"); + drop(c); + assert!(server.close().success()); + std::fs::create_dir_all(old.join("objects")).unwrap(); + std::fs::write(old.join("HEAD"), "ref: refs/heads/main\n").unwrap(); + let before = std::fs::read(old.join("HEAD")).unwrap(); + let server = Server::start(&home, Duration::from_secs(3600)); + let c = connect(&home, "acme", home.token("acme", &ALL)).await; + let s = call(&c, "books.backup", json!({})).await.unwrap(); + let note = s["note"].as_str().unwrap().to_string(); + assert!(note.contains("private repository"), "{note}"); + assert!(note.contains("no longer"), "{note}"); + assert!(note.contains("older backup folder"), "{note}"); + assert!(!note.to_lowercase().contains("git"), "{note}"); + // The books work, and back up to a folder when one is named; the old + // is untouched. + let folder = home.outside("disk"); + std::fs::create_dir_all(&folder).unwrap(); + set_folder(&c, &folder).await; + post_one(&c, 1).await; + let s = call(&c, "books.back_up_now", json!({})).await.unwrap(); + assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}"); + assert_eq!(std::fs::read(old.join("HEAD")).unwrap(), before); + assert!(folder.join("acme").join("manifests").is_dir()); drop(c); assert!(server.close().success()); } diff --git a/crates/ledger-cli/tests/book_open_close.rs b/crates/ledger-cli/tests/book_open_close.rs index 5869cd31..076a1e91 100644 --- a/crates/ledger-cli/tests/book_open_close.rs +++ b/crates/ledger-cli/tests/book_open_close.rs @@ -377,41 +377,6 @@ fn agent( } } -/// What the server's git commands did, from the file it was told to write -/// them to (`WANDERBOOKS_GIT_TIMINGS`): the slowest ten by how long the -/// command ran plus how long its pipes took to close, then every line of the -/// last hundred. Each line: when (ms since the server's first git), the -/// command, its exit, how many git commands were running as it began, -/// `spawn` (how long starting it took, including waiting its turn), -/// `ran` (start to exit), `pipes` (exit until what it wrote was in hand), -/// and for each of stdout and stderr how that wait ended (`eof`: the pipe -/// closed; `held-open`: another process still held it, nothing was left in -/// it; `limit`: 10 s passed) and how many bytes. -fn say_git_timings(file: &std::path::Path) { - let text = std::fs::read_to_string(file).unwrap_or_default(); - let lines: Vec<&str> = text.lines().collect(); - let ms = |line: &str, key: &str| -> u64 { - line.split_whitespace() - .find_map(|w| w.strip_prefix(key)) - .and_then(|v| v.trim_end_matches("ms").parse().ok()) - .unwrap_or(0) - }; - let mut slow: Vec<&&str> = lines.iter().collect(); - slow.sort_by_key(|l| std::cmp::Reverse(ms(l, "ran=") + ms(l, "pipes=") + ms(l, "spawn="))); - eprintln!( - "git commands of the server: {} lines in {}; the slowest:", - lines.len(), - file.display() - ); - for l in slow.iter().take(10) { - eprintln!(" {l}"); - } - eprintln!("the last {}:", lines.len().min(100)); - for l in &lines[lines.len().saturating_sub(100)..] { - eprintln!(" {l}"); - } -} - /// Many agents call two books (journaled drafts and reads) while one book /// is closed and opened again, over and over. Afterwards both journals are /// replayed and checked: every acknowledged draft is in its book's journal @@ -428,14 +393,9 @@ fn closing_and_opening_a_book_over_and_over_loses_and_duplicates_nothing() { // Every timer of the server runs every few milliseconds, and the // hammered book has a backup target, which backs it up and drills it // as it is written: the writers a close must stop are all at work. - // Every git command the server runs is written here as it ends (how - // long it ran, how long its pipes took to close after it ended): the - // portable jobs run this on machines nobody can look at, and a close - // that is slow there is told with these lines, not guessed at. - let timings = home.dir.path().join("git-timings.log"); let server = Server::start_full( &home, - &[("WANDERBOOKS_GIT_TIMINGS", timings.as_path())], + &[], &[ "--timers", "10", @@ -532,9 +492,6 @@ fn closing_and_opening_a_book_over_and_over_loses_and_duplicates_nothing() { let closed = close_book(&home, A); let took = began.elapsed(); eprintln!("cycle {cycle}: the close took {took:?}"); - if closed != CloseOutcome::Closed || took > Duration::from_secs(10) { - say_git_timings(&timings); - } assert_eq!( closed, CloseOutcome::Closed, @@ -1181,73 +1138,43 @@ fn a_call_whose_answer_was_never_read_is_on_record_as_having_run() { assert!(server.close().success()); } -/// A stand-in `git` for the server's PATH: it runs the real one, unless -/// the test has said otherwise with a file beside it: `stall` (it waits, -/// recording itself in `stalled`, until the file is gone, then in -/// `resumed`), which is how a backup is made slow. -#[cfg(unix)] -fn shim_git(home: &Home) -> PathBuf { - use std::os::unix::fs::PermissionsExt; - let dir = home.dir.path().join("shim"); - std::fs::create_dir_all(&dir).unwrap(); - let real = ["/usr/bin/git", "/bin/git", "/usr/local/bin/git"] - .into_iter() - .find(|p| std::path::Path::new(p).is_file()) - .expect("git is installed"); - let exe = dir.join("git"); - std::fs::write( - &exe, - format!( - "#!/bin/sh\ndir=\"$(dirname \"$0\")\"\necho \"$$ $*\" >> \"$dir/calls\"\nif [ -e \"$dir/stall\" ]; then\n echo $$ >> \"$dir/stalled\"\n while [ -e \"$dir/stall\" ]; do sleep 0.05; done\n echo $$ >> \"$dir/resumed\"\nfi\nexec {real} \"$@\"\n" - ), - ) - .unwrap(); - std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap(); - dir +/// The test knob that holds a backup at each phase, as a slow disk would: +/// while this file is in the book's `ops/` (and the server was given +/// `--slow-steps`), a backup waits until the stop it runs under is asked +/// for. Each wait is a line of [`reached`]. +fn stall_file(home: &Home, id: &str) -> PathBuf { + home.book_dir(id).join("ops").join("slow-backup") } -/// Whether process `pid` is still there. -#[cfg(unix)] -fn alive(pid: u32) -> bool { - // `ps` on Linux and macOS alike (there is no /proc on macOS, where a - // test of "is it gone" would pass whatever the server had done): its - // state is empty for a process that isn't there, and starts with Z for - // one that has ended and is not yet reaped. - let out = std::process::Command::new("ps") - .args(["-o", "stat=", "-p", &pid.to_string()]) - .output() - .expect("ps runs"); - let state = String::from_utf8_lossy(&out.stdout); - let state = state.trim(); - !state.is_empty() && !state.starts_with('Z') +/// How many times a backup of `id` has reached a phase and waited. +fn reached(home: &Home, id: &str) -> usize { + std::fs::read_to_string(home.book_dir(id).join("ops").join("slow-backup-reached")) + .unwrap_or_default() + .lines() + .count() } -/// The server, with the stand-in git first on its PATH. -#[cfg(unix)] -fn server_with_shim(home: &Home, shim: &std::path::Path, args: &[&str]) -> Server { - let path = std::env::join_paths([ - shim, - std::path::Path::new("/usr/bin"), - std::path::Path::new("/bin"), - ]) - .unwrap(); - let path: PathBuf = path.into(); - Server::start_full(home, &[("PATH", path.as_path())], args) +/// The folder a backup of `id` to `disk` lives in, proven whole: its head. +fn proven_head(home: &Home, disk: &std::path::Path, tag: &str) -> (u64, String) { + use ledger_store::backup::{Ctx, find, verify_found}; + let scratch = home.dir.path().join(format!("scratch-{tag}")); + let found = find(disk, None, &Ctx::new()).unwrap_or_else(|e| panic!("{tag}: {e}")); + verify_found(&found, &scratch, false, &Ctx::new()) + .unwrap_or_else(|e| panic!("{tag}: {e}")) + .head } -/// A book with a backup target whose backup is slow: the close is not -/// answered while the backup's work runs. Its bound lapses, git is -/// stopped (with all it started), the close waits for that to be done, -/// and says the backup wasn't whole. Nothing of the backup runs after the -/// answer, though the stall is lifted: a git left running would go on. -#[cfg(unix)] +/// A book with a backup folder whose backup is slow: the close is not +/// answered while the backup's work runs. Its bound lapses, the copy is +/// stopped at its next piece, the close waits for that to be done, and +/// says the backup wasn't whole. The folder still proves whole at the +/// backup before, and nothing of the backup runs after the answer, though +/// the stall is lifted: a copy left running would go on. #[test] fn a_close_is_not_answered_while_its_backup_still_runs() { let home = Home::new("close-slow-backup"); - let shim = shim_git(&home); - let server = server_with_shim( + let server = Server::start_with( &home, - &shim, &[ "--close-backup", "1200", @@ -1255,6 +1182,8 @@ fn a_close_is_not_answered_while_its_backup_still_runs() { "3600000", "--timers", "20", + "--slow-steps", + "600000", ], ); home.create(A, "USD"); @@ -1263,10 +1192,19 @@ fn a_close_is_not_answered_while_its_backup_still_runs() { let mut w = Wire::new(&home, A); w.initialize("owner"); set_backup_folder(&mut w, &disk); + draft(&mut w, "kept"); + match home.admin(Request::BackUpNow { + id: A.into(), + new_disk: false, + }) { + Response::BackedUp { targets, .. } => assert!(targets[0].problem.is_none(), "{targets:?}"), + other => panic!("{other:?}"), + } + let kept = proven_head(&home, &disk, "before"); draft(&mut w, "moves the head past the last backup"); w.end(); - // From here every git waits. - std::fs::write(shim.join("stall"), b"").unwrap(); + // From here every backup waits. + std::fs::write(stall_file(&home, A), b"").unwrap(); let started = std::time::Instant::now(); let outcome = close_book(&home, A); let took = started.elapsed(); @@ -1282,36 +1220,24 @@ fn a_close_is_not_answered_while_its_backup_still_runs() { } other => panic!("a stopped backup was answered as {other:?}"), } - // Answered: the git that was stalled is gone, with what it started. - let stalled: Vec = std::fs::read_to_string(shim.join("stalled")) - .unwrap_or_default() - .lines() - .filter_map(|l| l.trim().parse().ok()) - .collect(); - assert!(!stalled.is_empty(), "the backup never reached git"); - for pid in &stalled { - assert!( - !alive(*pid), - "git {pid} still runs after the close was answered" - ); - } + assert!(reached(&home, A) > 0, "the backup never reached a phase"); + // The folder proves whole at the backup before. + assert_eq!(proven_head(&home, &disk, "after"), kept); let at_close = tree_of(&home.book_dir(A)); + let in_folder = tree_of(&disk); // The stall is lifted: anything that had survived would go on now. - std::fs::remove_file(shim.join("stall")).unwrap(); + std::fs::remove_file(stall_file(&home, A)).unwrap(); stands_still( &home, A, Duration::from_millis(500), "after the close was answered", ); - assert!( - !shim.join("resumed").exists(), - "a git went on after the close was answered" - ); assert_eq!( moved(&at_close, &tree_of(&home.book_dir(A))), Vec::::new() ); + assert_eq!(moved(&in_folder, &tree_of(&disk)), Vec::::new()); // Opened again, the book's backup record is a whole chain, and it // backs up (nothing of the old backups is in its way). assert_eq!(open_book(&home, A), OpenOutcome::Opened); @@ -1331,23 +1257,12 @@ fn a_close_is_not_answered_while_its_backup_still_runs() { /// A backup that fails (its disk isn't there) closes the book all the same, /// quickly, and says so: never a plain "closed" for a backup that wasn't /// made; and nothing runs after. -#[cfg(unix)] #[test] fn a_close_whose_backup_fails_says_so_and_leaves_nothing_running() { let home = Home::new("close-failing-backup"); - let shim = shim_git(&home); // The timers look once an hour, so none runs a backup of its own: the - // first look is at the server's start, before any book is made here. A - // timer's backup that a close hurried could have its git miss the - // terminate grace under heavy load, be killed, and leave a lock in the - // target's folder, which the close's own backup would then truthfully - // fail against (`ClosedBackupIncomplete`): the plain `Closed` asserted - // below is of the close's backup alone. - let server = server_with_shim( - &home, - &shim, - &["--backup-quiet", "3600000", "--timers", "3600000"], - ); + // first look is at the server's start, before any book is made here. + let server = Server::start_with(&home, &["--backup-quiet", "3600000", "--timers", "3600000"]); home.create(A, "USD"); let unplugged = home.dir.path().join("elsewhere").join("unplugged"); std::fs::create_dir_all(unplugged.parent().unwrap()).unwrap(); @@ -1369,10 +1284,6 @@ fn a_close_whose_backup_fails_says_so_and_leaves_nothing_running() { } assert_eq!(listed(&home, A), (false, true, None)); let at_close = tree_of(&home.book_dir(A)); - let calls = std::fs::read_to_string(shim.join("calls")) - .unwrap_or_default() - .lines() - .count(); stands_still( &home, A, @@ -1383,14 +1294,6 @@ fn a_close_whose_backup_fails_says_so_and_leaves_nothing_running() { moved(&at_close, &tree_of(&home.book_dir(A))), Vec::::new() ); - assert_eq!( - std::fs::read_to_string(shim.join("calls")) - .unwrap_or_default() - .lines() - .count(), - calls, - "git was run after the close was answered" - ); // The same book, backed up fine, is answered plainly. assert_eq!(open_book(&home, A), OpenOutcome::Opened); std::fs::create_dir(&unplugged).unwrap(); @@ -1788,7 +1691,7 @@ fn a_running_call_is_never_cut_when_the_grace_runs_out() { assert!(server.close().success()); } -/// A backup of `id`, taken now to its folder target; the repository. +/// A backup of `id`, taken now to its folder; the folder of its set. #[cfg(unix)] fn backed_up_to_folder(home: &Home, w: &mut Wire, id: &str) -> PathBuf { let disk = home.dir.path().join("disk"); @@ -1802,7 +1705,7 @@ fn backed_up_to_folder(home: &Home, w: &mut Wire, id: &str) -> PathBuf { Response::BackedUp { targets, .. } => assert!(targets[0].problem.is_none(), "{targets:?}"), other => panic!("{other:?}"), } - disk.join(format!("{id}.git")) + disk.join(id) } /// A restore over an open book lets go of it as a close does: what is @@ -1840,6 +1743,7 @@ fn a_restore_over_an_open_book_waits_for_what_is_inside_it() { replace: true, confirmed: false, expect_head: None, + passphrase: None, }) { Response::RestorePreview(p) => p, other => panic!("{other:?}"), @@ -1855,6 +1759,7 @@ fn a_restore_over_an_open_book_waits_for_what_is_inside_it() { replace: true, confirmed: true, expect_head: Some(preview.head), + passphrase: None, }, ) .unwrap() @@ -1961,6 +1866,7 @@ fn a_restore_over_an_open_book_is_not_held_by_a_stalled_upload() { replace: true, confirmed: false, expect_head: None, + passphrase: None, }) { Response::RestorePreview(p) => p, other => panic!("{other:?}"), @@ -1972,6 +1878,7 @@ fn a_restore_over_an_open_book_is_not_held_by_a_stalled_upload() { replace: true, confirmed: true, expect_head: Some(preview.head), + passphrase: None, }) { Response::Restored(r) => r, other => panic!("{other:?}"), @@ -2458,7 +2365,7 @@ fn a_close_stops_a_slow_drill_instead_of_waiting_for_it() { "the last backup waited behind the drill" ); // The stated bound, as a sum of its parts: the grace, the answers' - // grace, the last backup's bound, and the stop of a step (git's kill + // grace, the last backup's bound, and the stop of a step (the copy's stop // and its group's end, 2 s; its pipes, 10 s; the lock settling, 1.5 s). let bound = Duration::from_millis(2 * grace + last_backup) + Duration::from_millis(13_500); assert!(took < bound, "{took:?} past the stated bound {bound:?}"); @@ -2486,229 +2393,6 @@ fn a_close_stops_a_slow_drill_instead_of_waiting_for_it() { .expect("the backup record is a whole chain"); } -/// A stand-in `git` that is the real one with a hooks folder of its own -/// (every `core.hooksPath=/dev/null` it is given, in its arguments and in -/// the `--receive-pack` command of a push to a folder, names it instead), -/// where a `reference-transaction` hook waits, while `slow-commit` (for the -/// book's archive) or `slow-push` (for any other repository) exists in the -/// shim folder, at the point where git holds its ref locks. `hooked` has a -/// line per hook that waited. A real git, killed inside real work. While -/// `deaf` exists in the shim folder when a git begins, that git (and all it -/// starts) has SIGTERM blocked, a mask every child inherits: the signal stays -/// pending and only the kill ends it (a stopped process is not enough: -/// macOS acts on a SIGTERM sent to one, where Linux holds it). -#[cfg(unix)] -fn slow_real_git(home: &Home) -> PathBuf { - use std::os::unix::fs::PermissionsExt; - let dir = home.dir.path().join("slow-shim"); - let hooks = dir.join("hooks"); - std::fs::create_dir_all(&hooks).unwrap(); - let real = ["/usr/bin/git", "/bin/git", "/usr/local/bin/git"] - .into_iter() - .find(|p| std::path::Path::new(p).is_file()) - .expect("git is installed"); - let hook = hooks.join("reference-transaction"); - std::fs::write( - &hook, - "#!/bin/sh\ncat >/dev/null\n[ \"$1\" = prepared ] || exit 0\nd=\"$(dirname \"$0\")/..\"\ncase \"$GIT_DIR $PWD\" in *archive.git*) f=slow-commit ;; *) f=slow-push ;; esac\nif [ -e \"$d/$f\" ]; then\n echo $$ >> \"$d/hooked\"\n while [ -e \"$d/$f\" ]; do sleep 0.05; done\nfi\nexit 0\n", - ) - .unwrap(); - std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap(); - let exe = dir.join("git"); - std::fs::write( - &exe, - format!( - "#!/bin/sh\nn=$#\nwhile [ $n -gt 0 ]; do\n a=\"$1\"; shift\n case \"$a\" in\n *core.hooksPath=/dev/null*) a=$(printf '%s' \"$a\" | sed 's|core.hooksPath=/dev/null|core.hooksPath={}|g') ;;\n esac\n set -- \"$@\" \"$a\"\n n=$((n-1))\ndone\nif [ -e '{dir}/deaf' ]; then exec perl -MPOSIX -e 'sigprocmask(SIG_BLOCK, POSIX::SigSet->new(SIGTERM)) or die; exec @ARGV or die' {real} \"$@\"; fi\nexec {real} \"$@\"\n", - hooks.display(), - dir = dir.display(), - ), - ) - .unwrap(); - std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap(); - dir -} - -/// Every `*.lock` file under a bare repository. -#[cfg(unix)] -fn locks_under(repo: &std::path::Path) -> Vec { - tree_of(repo) - .into_keys() - .filter(|k| k.ends_with(".lock")) - .collect() -} - -#[cfg(unix)] -fn fsck_of(repo: &std::path::Path) { - let out = std::process::Command::new("git") - .arg(format!("--git-dir={}", repo.display())) - .args(["fsck", "--strict"]) - .output() - .unwrap(); - assert!( - out.status.success(), - "{} isn't whole: {}", - repo.display(), - String::from_utf8_lossy(&out.stderr) - ); -} - -/// A close that stops real git inside a commit, and inside a push to a -/// folder, leaves no lock for anyone to remove: git is sent SIGTERM and -/// removes its own locks, so there is nothing for the server to clean up -/// (the backup's record holds no `lock_removed` or `lock_left`), the book -/// opened again at once backs up with no step by hand, and both -/// repositories pass `git fsck` (ledger_store::backup INVARIANT 5). -#[cfg(unix)] -#[test] -fn a_close_that_stops_git_in_a_commit_or_a_push_leaves_no_lock_and_the_next_backup_succeeds() { - let home = Home::new("close-git-locks"); - let shim = slow_real_git(&home); - // The close's bound lapses with git held inside its ref update, and - // what the test proves needs git to have got there first: the bound is - // long enough for the slowest machine to run every git before the - // update (a push, on a macOS runner, comes after a dozen of them and - // took longer than 1.5 s), as in the test of a lock a kill leaves. The - // hook holds git until the bound ends it, so each close takes the bound. - let server = server_with_shim( - &home, - &shim, - &[ - "--close-backup", - "8000", - "--backup-quiet", - "3600000", - "--timers", - "20", - ], - ); - home.create(A, "USD"); - let disk = home.dir.path().join("disk"); - std::fs::create_dir_all(&disk).unwrap(); - let mut w = Wire::new(&home, A); - w.initialize("owner"); - set_backup_folder(&mut w, &disk); - draft(&mut w, "to be backed up inside a commit"); - w.end(); - let archive = home.book_dir(A).join("archive.git"); - let target = disk.join(format!("{A}.git")); - let record = || { - std::fs::read_to_string(home.book_dir(A).join("ops").join("backup.jsonl")) - .unwrap_or_default() - }; - // 0. Inside the making of the archive itself (`git init`): a lock in - // a repository that isn't one yet stops every later `init`. - std::fs::write(shim.join("slow-commit"), b"").unwrap(); - let outcome = close_book(&home, A); - assert!( - matches!(outcome, CloseOutcome::ClosedBackupIncomplete(_)), - "{outcome:?}" - ); - assert!( - shim.join("hooked").exists(), - "git never reached its ref update before the close's bound ran out: {outcome:?}" - ); - assert_eq!(locks_under(&archive), Vec::::new()); - assert!( - !record().contains("lock_removed") && !record().contains("lock_left"), - "git removed its own locks: nothing was cleaned up here: {}", - record() - ); - std::fs::remove_file(shim.join("slow-commit")).unwrap(); - std::fs::remove_file(shim.join("hooked")).unwrap(); - assert_eq!(open_book(&home, A), OpenOutcome::Opened); - let mut w = Wire::new(&home, A); - w.initialize("owner"); - draft(&mut w, "to be backed up inside a commit"); - w.end(); - match home.admin(Request::BackUpNow { - id: A.into(), - new_disk: false, - }) { - Response::BackedUp { targets, .. } => { - assert!(targets.iter().all(|t| t.problem.is_none()), "{targets:?}"); - } - other => panic!("{other:?}"), - } - let mut w = Wire::new(&home, A); - w.initialize("owner"); - draft(&mut w, "to be committed inside a commit"); - w.end(); - // 1. Inside the commit's ref update. - std::fs::write(shim.join("slow-commit"), b"").unwrap(); - let outcome = close_book(&home, A); - assert!( - matches!(outcome, CloseOutcome::ClosedBackupIncomplete(_)), - "{outcome:?}" - ); - assert!( - shim.join("hooked").exists(), - "git never reached its ref update before the close's bound ran out: {outcome:?}" - ); - assert_eq!(locks_under(&archive), Vec::::new()); - assert!( - !record().contains("lock_removed") && !record().contains("lock_left"), - "git removed its own locks: nothing was cleaned up here: {}", - record() - ); - std::fs::remove_file(shim.join("slow-commit")).unwrap(); - std::fs::remove_file(shim.join("hooked")).unwrap(); - assert_eq!(open_book(&home, A), OpenOutcome::Opened); - let status = home.admin(Request::BackUpNow { - id: A.into(), - new_disk: false, - }); - match &status { - Response::BackedUp { targets, .. } => { - assert!(targets.iter().all(|t| t.problem.is_none()), "{status:?}"); - } - other => panic!("{other:?}"), - } - fsck_of(&archive); - fsck_of(&target); - // 2. Inside the push's ref update at the folder. - let mut w = Wire::new(&home, A); - w.initialize("owner"); - draft(&mut w, "to be pushed inside a push"); - w.end(); - std::fs::write(shim.join("slow-push"), b"").unwrap(); - let outcome = close_book(&home, A); - assert!( - matches!(outcome, CloseOutcome::ClosedBackupIncomplete(_)), - "{outcome:?}" - ); - assert!( - shim.join("hooked").exists(), - "git never reached its ref update before the close's bound ran out: {outcome:?}" - ); - assert_eq!(locks_under(&target), Vec::::new()); - assert_eq!(locks_under(&archive), Vec::::new()); - assert!( - !record().contains("lock_removed") && !record().contains("lock_left"), - "git removed its own locks: nothing was cleaned up here: {}", - record() - ); - std::fs::remove_file(shim.join("slow-push")).unwrap(); - assert_eq!(open_book(&home, A), OpenOutcome::Opened); - let status = home.admin(Request::BackUpNow { - id: A.into(), - new_disk: false, - }); - match &status { - Response::BackedUp { targets, .. } => { - assert!(targets.iter().all(|t| t.problem.is_none()), "{status:?}"); - } - other => panic!("{other:?}"), - } - fsck_of(&archive); - fsck_of(&target); - ledger_store::chain::read( - &home.book_dir(A).join("ops").join("backup.jsonl"), - "wanderbooks-backup-v1", - ) - .expect("the backup record is a whole chain"); - assert!(server.close().success()); -} - /// A tool call sent on `w`'s session, its whole body written and its answer /// not yet read: the connection it went out on. #[cfg(unix)] @@ -2734,24 +2418,6 @@ fn call_unanswered(home: &Home, w: &Wire, id: u64, tool: &str, args: Value) -> r raw } -/// Hold every process of the group `pid` leads still (SIGSTOP), so that none -/// goes on while the stop is being asked for. That git can't end on SIGTERM, -/// holding its locks, is made on purpose by the shim's `deaf` file, not by -/// this: macOS acts on a SIGTERM sent to a stopped process. -#[cfg(unix)] -fn freeze_group_of(pid: u32) { - let out = std::process::Command::new("ps") - .args(["-o", "pgid=", "-p", &pid.to_string()]) - .output() - .unwrap(); - let group: i32 = String::from_utf8_lossy(&out.stdout) - .trim() - .parse() - .expect("ps names the group"); - // SAFETY: stopping the group of a git this test's server started. - assert_eq!(unsafe { libc::kill(-group, libc::SIGSTOP) }, 0); -} - /// The most a close may take in these tests where what it stops would /// otherwise run for ever (a stall that is never lifted): a guard against a /// hang, not a measure of speed. That the close ends at all, with the stall @@ -2770,21 +2436,19 @@ fn backup_record_of(home: &Home, id: &str) -> Vec .records } -/// A backup call that is running (git stalled) when a close begins is -/// STOPPED by it, not waited for: the call is answered, while git is still -/// stalled, that it was stopped because the books are closing; its access -/// record says `refused: stopped_by_close`; the backup records `stopped` -/// and no result of the run's own (nothing it was doing is recorded as -/// done); git and all it started are gone; and the close's own last -/// backup is made as always (local.rs INVARIANT 10). -#[cfg(unix)] +/// A backup call that is running (its copy stalled) when a close begins is +/// STOPPED by it, not waited for: the call is answered, while the copy is +/// still stalled, that it was stopped because the books are closing; its +/// access record says `refused: stopped_by_close`; the backup records +/// `stopped` and no result of the run's own (nothing it was doing is +/// recorded as done); the folder still proves whole at the backup before; +/// and the close's own last backup is made as always (local.rs INVARIANT +/// 10). #[test] fn a_close_stops_a_running_backup_call_and_says_so() { let home = Home::new("close-stops-backup-call"); - let shim = shim_git(&home); - let server = server_with_shim( + let server = Server::start_with( &home, - &shim, &[ "--close-backup", "20000", @@ -2792,6 +2456,8 @@ fn a_close_stops_a_running_backup_call_and_says_so() { "3600000", "--timers", "20", + "--slow-steps", + "600000", ], ); home.create(A, "USD"); @@ -2800,18 +2466,27 @@ fn a_close_stops_a_running_backup_call_and_says_so() { let mut w = Wire::new(&home, A); w.initialize("owner"); set_backup_folder(&mut w, &disk); + draft(&mut w, "kept"); + match home.admin(Request::BackUpNow { + id: A.into(), + new_disk: false, + }) { + Response::BackedUp { targets, .. } => assert!(targets[0].problem.is_none(), "{targets:?}"), + other => panic!("{other:?}"), + } + let kept = proven_head(&home, &disk, "before"); draft(&mut w, "moves the head"); - std::fs::write(shim.join("stall"), b"").unwrap(); - let mut call = call_unanswered(&home, &w, 4, "books.back_up_now", json!({})); - wait_for("the call reached git", Duration::from_secs(60), || { - shim.join("stalled").exists() + std::fs::write(stall_file(&home, A), b"").unwrap(); + let mut call = call_unanswered(&home, &w, 5, "books.back_up_now", json!({})); + wait_for("the call reached a phase", Duration::from_secs(60), || { + reached(&home, A) > 0 }); let started = std::time::Instant::now(); let closing = std::thread::spawn({ let admin = home.run().join("admin.sock"); move || ledger_mcp::admin::call(&admin, Request::CloseBook { id: A.into() }).unwrap() }); - // Answered with git still stalled: stopped by the close, not let go. + // Answered with the copy still stalled: stopped by the close, not let go. let (status, said) = call.answer(); assert_eq!(status, 200, "{said}"); assert!( @@ -2819,22 +2494,17 @@ fn a_close_stops_a_running_backup_call_and_says_so() { && said.contains("nothing it was doing is recorded as done"), "{said}" ); - assert!(shim.join("stall").exists(), "the stall was lifted first"); + assert!(stall_file(&home, A).exists(), "the stall was lifted first"); // Lifted now, so the close's own last backup can run. - std::fs::remove_file(shim.join("stall")).unwrap(); + std::fs::remove_file(stall_file(&home, A)).unwrap(); match closing.join().unwrap() { Response::CloseBook { outcome, .. } => assert_eq!(outcome, CloseOutcome::Closed), other => panic!("{other:?}"), } assert!(started.elapsed() < NEVER_LONGER); - let stalled: Vec = std::fs::read_to_string(shim.join("stalled")) - .unwrap_or_default() - .lines() - .filter_map(|l| l.trim().parse().ok()) - .collect(); - for pid in &stalled { - assert!(!alive(*pid), "git {pid} still runs"); - } + // The close's own backup made the last head whole; before it the stopped + // one had left the folder at `kept`, which it was proven to be above. + assert!(proven_head(&home, &disk, "after").0 >= kept.0); let records = access_of(&home, A); let mine = records .iter() @@ -3130,6 +2800,7 @@ impl Jobs { replace: false, confirmed: false, expect_head: None, + passphrase: None, }) { Response::RestorePreview(p) => p.head, other => panic!("{other:?}"), @@ -3172,6 +2843,7 @@ impl Jobs { replace, confirmed: true, expect_head: Some(self.restore_head.clone()), + passphrase: None, } } } @@ -3424,7 +3096,7 @@ fn finished(what: &str, thread: std::thread::JoinHandle) -> T { /// phase, by the server's test knob; they make books one at a time, so the /// second and third wait for their turn, not yet held, until the one before /// is let go), and `acme` is closed and opened again while each is: its -/// close is made slow (its backup's git stalls), and during it another book +/// close is made slow (its backup's copy stalls), and during it another book /// (`cedar`) is opened and closed and answers at once, while the close of /// `acme` is still not answered. All three jobs finish correctly, none /// stopped, none told of any error. @@ -3432,23 +3104,17 @@ fn finished(what: &str, thread: std::thread::JoinHandle) -> T { #[test] fn closing_and_opening_one_book_never_stops_waits_for_or_refuses_another_books_jobs() { let home = Home::new("close-spares-other-jobs"); - let shim = shim_git(&home); let mut args = JOB_ARGS.to_vec(); - args.extend(["--close-backup", "120000"]); - let server = server_with_shim(&home, &shim, &args); + args.extend(["--close-backup", "120000", "--slow-steps", "600000"]); + let server = Server::start_with(&home, &args); let jobs = Jobs::new(&home); home.create(B, "USD"); let run = home.run(); - let stalled = || { - std::fs::read_to_string(shim.join("stalled")) - .unwrap_or_default() - .lines() - .count() - }; + let stalled = || reached(&home, A); // One close and reopening of `acme`, while the jobs are held. let cycle = |why: &str| { let before = stalled(); - std::fs::write(shim.join("stall"), b"").unwrap(); + std::fs::write(stall_file(&home, A), b"").unwrap(); let closing = admin_in_thread(&home, Request::CloseBook { id: A.into() }); wait_for( &format!("{why}: the close of {A} is in its backup"), @@ -3487,7 +3153,7 @@ fn closing_and_opening_one_book_never_stops_waits_for_or_refuses_another_books_j "{why}" ); assert!(!closing.is_finished(), "{why}: the close was answered"); - std::fs::remove_file(shim.join("stall")).unwrap(); + std::fs::remove_file(stall_file(&home, A)).unwrap(); assert_eq!( finished(&format!("{why}: the close of {A}"), closing), Response::CloseBook { @@ -3599,177 +3265,6 @@ fn job_server_again(home: &Home) -> Server { Server::start_with(home, &args) } -/// A git that can't end on SIGTERM (its group frozen here, so the signal -/// stays pending) is killed once the grace has run out, and the lock it -/// leaves in a backup FOLDER is the owner's: the server never removes it. It -/// is recorded with its whole path, the target's backup is marked failed with -/// words naming the file and saying when it may be removed, the close says -/// its last backup wasn't whole, and the status (`books.backup`) says the -/// same after the book is opened again. The next backup, meeting the lock, -/// fails by git's own words and leaves the file; once the owner removes it -/// the backup goes on, and both repositories pass `git fsck`. -#[cfg(unix)] -#[test] -fn a_lock_a_kill_leaves_in_the_backup_folder_is_reported_and_never_removed_by_the_server() { - let home = Home::new("close-lock-left"); - let shim = slow_real_git(&home); - // A bound long enough that the test freezes git before the close's own - // bound runs out: the freeze is made on the condition that git is - // inside the push, not on a guess at how long that takes. - let server = server_with_shim( - &home, - &shim, - &[ - "--close-backup", - "8000", - "--backup-quiet", - "3600000", - "--timers", - "20", - ], - ); - home.create(A, "USD"); - let disk = home.dir.path().join("disk"); - std::fs::create_dir_all(&disk).unwrap(); - let mut w = Wire::new(&home, A); - w.initialize("owner"); - set_backup_folder(&mut w, &disk); - draft(&mut w, "the first backup"); - match home.admin(Request::BackUpNow { - id: A.into(), - new_disk: false, - }) { - Response::BackedUp { targets, .. } => { - assert!(targets.iter().all(|t| t.problem.is_none()), "{targets:?}"); - } - other => panic!("{other:?}"), - } - draft(&mut w, "to be pushed inside a push"); - let target = disk.join(format!("{A}.git")); - let lock = target.join("refs").join("heads").join("main.lock"); - // Another writer's lock, there before our push: never touched, never - // named. - let another = target.join("refs").join("heads").join("another.lock"); - std::fs::write(&another, b"").unwrap(); - std::fs::write(shim.join("deaf"), b"").unwrap(); - std::fs::write(shim.join("slow-push"), b"").unwrap(); - let closing = std::thread::spawn({ - let admin = home.run().join("admin.sock"); - move || ledger_mcp::admin::call(&admin, Request::CloseBook { id: A.into() }).unwrap() - }); - wait_for("git is inside the push", Duration::from_secs(60), || { - shim.join("hooked").exists() && lock.exists() - }); - let hooked: u32 = std::fs::read_to_string(shim.join("hooked")) - .unwrap() - .lines() - .next() - .unwrap() - .trim() - .parse() - .unwrap(); - freeze_group_of(hooked); - let outcome = match closing.join().unwrap() { - Response::CloseBook { outcome, .. } => outcome, - other => panic!("{other:?}"), - }; - let why = match outcome { - CloseOutcome::ClosedBackupIncomplete(why) => why, - other => panic!("a backup that left a lock was answered as {other:?}"), - }; - let lock_text = lock.display().to_string(); - // Every lock git left in the folder, the HEAD lock beside the branch's - // own (git locks HEAD as well when it moves the branch HEAD names; a - // newer git goes on past a stale one, an older one refuses the push - // with "cannot lock ref 'HEAD'", as on macOS): each is named in the - // words, and the owner removes those, as the words say, and no other. - let left: Vec = locks_under(&target) - .into_iter() - .filter(|l| l != "refs/heads/another.lock") - .map(|l| target.join(l)) - .collect(); - assert!(left.contains(&lock), "{left:?}"); - for file in &left { - assert!( - why.contains(&file.display().to_string()), - "{} isn't named in: {why}", - file.display() - ); - } - assert!(why.contains(&lock_text), "{why}"); - assert!( - why.contains("nothing else is using the backup folder"), - "{why}" - ); - assert!(!why.contains("another.lock"), "{why}"); - assert!(!why.contains(&home.root().display().to_string()), "{why}"); - // Left where it was: the server deleted nothing in the owner's folder. - assert!(lock.exists(), "a file in the owner's folder was deleted"); - assert!(another.exists()); - let record = backup_record_of(&home, A); - assert!( - record - .iter() - .any(|r| r.get("kind") == Some(&json!("lock_left")) - && r.get("repo") == Some(&json!("folder")) - && r.get("path") == Some(&json!(lock_text))), - "{record:?}" - ); - assert!( - !record - .iter() - .any(|r| r.get("kind") == Some(&json!("lock_removed")) - && r.get("repo") == Some(&json!("folder"))), - "{record:?}" - ); - // Opened again, the status says it, in words that name the file. - std::fs::remove_file(shim.join("slow-push")).unwrap(); - assert_eq!(open_book(&home, A), OpenOutcome::Opened); - let mut w = Wire::new(&home, A); - w.initialize("owner"); - let status = w.call("books.backup", json!({})); - let shown = status["result"]["structuredContent"]["targets"][0]["last_error"] - .as_str() - .unwrap_or_else(|| panic!("the status names no failure: {status}")) - .to_string(); - assert!(shown.contains(&lock_text), "{shown}"); - assert!( - shown.contains("nothing else is using the backup folder"), - "{shown}" - ); - // With the lock still there the next backup fails (git's own words) and - // the file stays; once the owner removes it, it goes on. - match home.admin(Request::BackUpNow { - id: A.into(), - new_disk: false, - }) { - Response::BackedUp { targets, .. } => { - assert!(targets.iter().any(|t| t.problem.is_some()), "{targets:?}"); - } - other => panic!("{other:?}"), - } - assert!( - left.iter().all(|f| f.exists()), - "a later backup removed one of {left:?}" - ); - for file in &left { - std::fs::remove_file(file).unwrap(); - } - match home.admin(Request::BackUpNow { - id: A.into(), - new_disk: false, - }) { - Response::BackedUp { targets, .. } => { - assert!(targets.iter().all(|t| t.problem.is_none()), "{targets:?}"); - } - other => panic!("{other:?}"), - } - assert!(another.exists()); - fsck_of(&home.book_dir(A).join("archive.git")); - fsck_of(&target); - assert!(server.close().success()); -} - /// Whether `thread` finished within `within`, never hanging the test. #[cfg(unix)] fn finishes_within(thread: &std::thread::JoinHandle, within: Duration) -> bool { @@ -3801,6 +3296,7 @@ fn a_close_is_answered_while_a_restore_preview_of_its_book_is_still_running() { replace: false, confirmed: false, expect_head: None, + passphrase: None, }; let previewing = job_held_in(&home, "restore:fetch", &preview, "restore:fetch"); let closing = admin_in_thread(&home, Request::CloseBook { id: A.to_string() }); diff --git a/crates/ledger-gui/src/owner.rs b/crates/ledger-gui/src/owner.rs index 0f459d62..edb204c6 100644 --- a/crates/ledger-gui/src/owner.rs +++ b/crates/ledger-gui/src/owner.rs @@ -130,11 +130,30 @@ pub enum AgentStart { Missing(Installer), } +/// A passphrase typed into the window: never shown by `Debug`, wiped from +/// memory when dropped. +#[derive(Clone, Default, PartialEq, Eq)] +pub struct Secret(pub String); + +impl std::fmt::Debug for Secret { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Secret(…)") + } +} + +impl Drop for Secret { + fn drop(&mut self) { + zeroize::Zeroize::zeroize(&mut self.0); + } +} + /// A restore previewed: what it would do, and what it is of (INVARIANT 3). #[derive(Clone, Debug, PartialEq, Eq)] pub struct RestorePlan { - /// The backup, as the server is told it. + /// The backup, as the server is told it: a folder or a file. pub source: String, + /// Its passphrase when it has one: never shown, wiped when dropped. + pub passphrase: Option, /// The books' id it comes back as. pub id: String, /// Whether it replaces the books of that id (kept in legacy/). @@ -441,6 +460,7 @@ pub trait Owner: Send + Sync { source: &str, id: Option, replace: bool, + passphrase: Option, ) -> Result; /// Restore as `plan` previewed it. fn restore(&self, plan: &RestorePlan) -> Result, String>; @@ -632,6 +652,9 @@ struct RestoreForm { source: String, id: String, replace: bool, + /// The backup's passphrase, if it has one (wiped when the form is + /// dropped). + passphrase: String, /// A check under way, and what it was asked (a result for anything /// since edited is dropped). planning: Option, @@ -639,6 +662,13 @@ struct RestoreForm { problem: Option, } +impl Drop for RestoreForm { + /// What was typed and not handed over is wiped from memory. + fn drop(&mut self) { + zeroize::Zeroize::zeroize(&mut self.passphrase); + } +} + /// The menu's state: a dialog, the job under way, and the last outcome. #[derive(Default)] pub struct OwnerMenu { @@ -1114,7 +1144,7 @@ impl OwnerMenu { egui::Modal::new(self.scope.unwrap_or(egui::Id::NULL).with("owner-restore")).show(ctx, |ui| { ui.set_max_width(520.0); ui.heading("Restore books"); - ui.label("The backup: its repository's address, or its folder (the books' .git folder in your backup folder)."); + ui.label("The backup: your backup folder, the folder of one set of books in it, or a backup file (.wbbackup)."); // Not changed while it is being checked. let open = form.planning.is_none(); let edited = ui @@ -1122,9 +1152,21 @@ impl OwnerMenu { open, egui::TextEdit::singleline(&mut form.source) .desired_width(f32::INFINITY) - .hint_text("/media/backup/acme.git, or git@host:you/books.git"), + .hint_text("/media/backup, or /home/you/acme.wbbackup"), ) .changed(); + ui.horizontal(|ui| { + ui.label("Passphrase, if the backup has one"); + if ui + .add_enabled( + open, + egui::TextEdit::singleline(&mut form.passphrase).password(true), + ) + .changed() + { + form.plan = None; + } + }); ui.horizontal(|ui| { ui.label("As the books"); let id_edited = ui @@ -1164,6 +1206,8 @@ impl OwnerMenu { if ui.add_enabled(ready, egui::Button::new("Check it")).clicked() { let (tx, rx) = channel(); let (o, s, r) = (owner.clone(), form.source.clone(), form.replace); + let pass = Some(Secret(form.passphrase.clone())) + .filter(|p| !p.0.is_empty()); let id = Some(form.id.trim().to_string()).filter(|i| !i.is_empty()); let ctx = ui.ctx().clone(); // Only reads the backup: stopped with its tab. @@ -1174,7 +1218,7 @@ impl OwnerMenu { if stop.requested() { return; } - let _ = tx.send(o.plan_restore(&s, id, r)); + let _ = tx.send(o.plan_restore(&s, id, r, pass)); ctx.request_repaint(); }, ); diff --git a/crates/ledger-gui/tests/assistants.rs b/crates/ledger-gui/tests/assistants.rs index 24afcf64..2f16c5bb 100644 --- a/crates/ledger-gui/tests/assistants.rs +++ b/crates/ledger-gui/tests/assistants.rs @@ -264,7 +264,13 @@ impl Owner for Fake { fn back_up_now(&self, _: &str) -> Result, String> { Err("not here".into()) } - fn plan_restore(&self, _: &str, _: Option, _: bool) -> Result { + fn plan_restore( + &self, + _: &str, + _: Option, + _: bool, + _: Option, + ) -> Result { Err("not here".into()) } fn restore(&self, _: &RestorePlan) -> Result, String> { diff --git a/crates/ledger-gui/tests/dock.rs b/crates/ledger-gui/tests/dock.rs index c9b7f842..f844fb08 100644 --- a/crates/ledger-gui/tests/dock.rs +++ b/crates/ledger-gui/tests/dock.rs @@ -34,7 +34,13 @@ impl Owner for Fake { fn back_up_now(&self, _: &str) -> Result, String> { Err("not here".into()) } - fn plan_restore(&self, _: &str, _: Option, _: bool) -> Result { + fn plan_restore( + &self, + _: &str, + _: Option, + _: bool, + _: Option, + ) -> Result { Err("not here".into()) } fn restore(&self, _: &RestorePlan) -> Result, String> { diff --git a/crates/ledger-gui/tests/format_upgrade.rs b/crates/ledger-gui/tests/format_upgrade.rs index 5d8738f0..858b02f0 100644 --- a/crates/ledger-gui/tests/format_upgrade.rs +++ b/crates/ledger-gui/tests/format_upgrade.rs @@ -91,6 +91,7 @@ impl Owner for Fake { _source: &str, _id: Option, _replace: bool, + _passphrase: Option, ) -> Result { Err("not in these tests".into()) } diff --git a/crates/ledger-gui/tests/host_holds.rs b/crates/ledger-gui/tests/host_holds.rs index cdf44c94..bec45ba6 100644 --- a/crates/ledger-gui/tests/host_holds.rs +++ b/crates/ledger-gui/tests/host_holds.rs @@ -80,7 +80,13 @@ impl Owner for Held { fn back_up_now(&self, _: &str) -> Result, String> { Err("not here".into()) } - fn plan_restore(&self, _: &str, _: Option, _: bool) -> Result { + fn plan_restore( + &self, + _: &str, + _: Option, + _: bool, + _: Option, + ) -> Result { Err("not here".into()) } fn restore(&self, _: &RestorePlan) -> Result, String> { diff --git a/crates/ledger-gui/tests/owner_menu.rs b/crates/ledger-gui/tests/owner_menu.rs index ad83141e..eea4fdb6 100644 --- a/crates/ledger-gui/tests/owner_menu.rs +++ b/crates/ledger-gui/tests/owner_menu.rs @@ -48,11 +48,13 @@ impl Owner for Fake { source: &str, id: Option, replace: bool, + passphrase: Option, ) -> Result { std::thread::sleep(std::time::Duration::from_millis(300)); self.said(format!("plan {source} {id:?} {replace}")); Ok(RestorePlan { source: source.to_string(), + passphrase, id: id.unwrap_or_else(|| "acme".into()), replace, head: (7, "ab".repeat(32)), @@ -220,7 +222,7 @@ fn the_books_menu_hands_each_action_to_the_owner_and_writes_nothing() { h.get_all_by_role(egui::accesskit::Role::TextInput) .nth(page_fields) .unwrap() - .type_text("/media/disk/acme.git"); + .type_text("/media/disk/backups"); h.run_steps(2); assert!( h.query_by_label("Restore it").is_none(), @@ -230,7 +232,7 @@ fn the_books_menu_hands_each_action_to_the_owner_and_writes_nothing() { settle(&mut h, &f, start + 3); assert_eq!( f.asked.lock().unwrap()[start + 2], - "plan /media/disk/acme.git None false" + "plan /media/disk/backups None false" ); assert!( h.query_by_label_contains("is whole: through event 7") @@ -240,7 +242,7 @@ fn the_books_menu_hands_each_action_to_the_owner_and_writes_nothing() { settle(&mut h, &f, start + 4); assert_eq!( f.asked.lock().unwrap()[start + 3], - "restore /media/disk/acme.git acme 7" + "restore /media/disk/backups acme 7" ); // There is no "Close the books": a company's tab, or the window, closes @@ -307,7 +309,7 @@ fn nothing_is_changed_while_it_is_at_work() { h.get_all_by_role(egui::accesskit::Role::TextInput) .nth(page_fields) .unwrap() - .type_text("/media/disk/acme.git"); + .type_text("/media/disk/backups"); h.run_steps(2); h.get_by_label("Check it").click(); h.run_steps(2); @@ -390,7 +392,7 @@ fn screenshots() { h.get_all_by_role(egui::accesskit::Role::TextInput) .nth(page_fields) .unwrap() - .type_text("/media/disk/acme.git"); + .type_text("/media/disk/backups"); shot(&mut h, "restore-ask"); h.get_by_label("Check it").click(); let n = f.asked.lock().unwrap().len(); diff --git a/crates/ledger-gui/tests/serving.rs b/crates/ledger-gui/tests/serving.rs index 00762696..fbd0b638 100644 --- a/crates/ledger-gui/tests/serving.rs +++ b/crates/ledger-gui/tests/serving.rs @@ -179,7 +179,13 @@ impl Owner for Fake { fn back_up_now(&self, _: &str) -> Result, String> { Err("not here".into()) } - fn plan_restore(&self, _: &str, _: Option, _: bool) -> Result { + fn plan_restore( + &self, + _: &str, + _: Option, + _: bool, + _: Option, + ) -> Result { Err("not here".into()) } fn restore(&self, _: &RestorePlan) -> Result, String> { @@ -464,7 +470,13 @@ fn a_window_with_no_server_asks_nothing_of_any() { fn back_up_now(&self, _: &str) -> Result, String> { Err("not here".into()) } - fn plan_restore(&self, _: &str, _: Option, _: bool) -> Result { + fn plan_restore( + &self, + _: &str, + _: Option, + _: bool, + _: Option, + ) -> Result { Err("not here".into()) } fn restore(&self, _: &RestorePlan) -> Result, String> { diff --git a/crates/ledger-gui/tests/sidenav.rs b/crates/ledger-gui/tests/sidenav.rs index 4c78b799..1060d4b8 100644 --- a/crates/ledger-gui/tests/sidenav.rs +++ b/crates/ledger-gui/tests/sidenav.rs @@ -42,7 +42,13 @@ impl Owner for Quiet { fn back_up_now(&self, _: &str) -> Result, String> { Err("not here".into()) } - fn plan_restore(&self, _: &str, _: Option, _: bool) -> Result { + fn plan_restore( + &self, + _: &str, + _: Option, + _: bool, + _: Option, + ) -> Result { Err("not here".into()) } fn restore(&self, _: &RestorePlan) -> Result, String> { diff --git a/crates/ledger-gui/tests/tabs.rs b/crates/ledger-gui/tests/tabs.rs index f598bca3..9dee83fe 100644 --- a/crates/ledger-gui/tests/tabs.rs +++ b/crates/ledger-gui/tests/tabs.rs @@ -585,7 +585,13 @@ impl Owner for Agentic { fn back_up_now(&self, _: &str) -> Result, String> { Err("not here".into()) } - fn plan_restore(&self, _: &str, _: Option, _: bool) -> Result { + fn plan_restore( + &self, + _: &str, + _: Option, + _: bool, + _: Option, + ) -> Result { Err("not here".into()) } fn restore(&self, _: &RestorePlan) -> Result, String> { @@ -2105,9 +2111,11 @@ impl Owner for Gated { source: &str, id: Option, replace: bool, + passphrase: Option, ) -> Result { Ok(RestorePlan { source: source.to_string(), + passphrase, id: id.unwrap_or_else(|| "alpha".into()), replace, head: (7, "ab".repeat(32)), diff --git a/crates/ledger-gui/tests/update_notice.rs b/crates/ledger-gui/tests/update_notice.rs index 8375bd14..5ff4cca3 100644 --- a/crates/ledger-gui/tests/update_notice.rs +++ b/crates/ledger-gui/tests/update_notice.rs @@ -40,7 +40,13 @@ impl Owner for Fake { fn back_up_now(&self, _: &str) -> Result, String> { Err("not in these tests".into()) } - fn plan_restore(&self, _: &str, _: Option, _: bool) -> Result { + fn plan_restore( + &self, + _: &str, + _: Option, + _: bool, + _: Option, + ) -> Result { Err("not in these tests".into()) } fn restore(&self, _: &RestorePlan) -> Result, String> { diff --git a/crates/ledger-gui/tests/web_connect.rs b/crates/ledger-gui/tests/web_connect.rs index 2c85d74c..11016bc8 100644 --- a/crates/ledger-gui/tests/web_connect.rs +++ b/crates/ledger-gui/tests/web_connect.rs @@ -183,6 +183,7 @@ impl Owner for Web { _source: &str, _id: Option, _replace: bool, + _passphrase: Option, ) -> Result { Err("not here".into()) } diff --git a/crates/ledger-gui/tests/welcome.rs b/crates/ledger-gui/tests/welcome.rs index b8fcc736..d5682dd0 100644 --- a/crates/ledger-gui/tests/welcome.rs +++ b/crates/ledger-gui/tests/welcome.rs @@ -47,7 +47,13 @@ impl Owner for Fake { fn back_up_now(&self, _: &str) -> Result, String> { Err("not here".into()) } - fn plan_restore(&self, _: &str, _: Option, _: bool) -> Result { + fn plan_restore( + &self, + _: &str, + _: Option, + _: bool, + _: Option, + ) -> Result { Err("not here".into()) } fn restore(&self, _: &RestorePlan) -> Result, String> { diff --git a/crates/ledger-host/src/commands.rs b/crates/ledger-host/src/commands.rs index be17a3d0..dc8cb62f 100644 --- a/crates/ledger-host/src/commands.rs +++ b/crates/ledger-host/src/commands.rs @@ -2493,14 +2493,17 @@ fn make_token( Ok(info) } -/// The id a backup is restored as when none is given: its repository's -/// name (`acme.git` → `acme`). +/// The id a backup is restored as when none is given and the backup does +/// not say whose it is: the name of its folder or file (`acme` or +/// `acme.wbbackup` → `acme`). fn restore_id(source: &str) -> Option { let last = source - .trim_end_matches('/') - .rsplit(['/', ':']) - .next()? - .trim_end_matches(".git"); + .trim_end_matches(['/', '\\']) + .rsplit(['/', '\\']) + .next()?; + let last = last + .strip_suffix(&format!(".{}", ledger_store::backup::FILE_EXTENSION)) + .unwrap_or(last); ledger_store::root::BookId::parse(last) .ok() .map(|id| id.to_string()) @@ -2524,6 +2527,9 @@ fn confirmed(question: &str, yes: bool) -> Result { Ok(matches!(answer.trim(), "y" | "Y" | "yes" | "Yes")) } +/// What the server says of a backup that needs its passphrase. +const NEEDS_PASSPHRASE: &str = "needs the passphrase it was made with"; + /// `wanderbooks books restore` (INVARIANT 3). fn restore( common: &Common, @@ -2536,7 +2542,20 @@ fn restore( eprintln!("error: {why}"); Err(exit(1)) }; - let plan = match plan_restore(common, source, id, replace, true) { + let mut plan = plan_restore(common, source, id.clone(), replace, true, None); + // A backup protected by a passphrase (D-92): asked for at a terminal, + // unechoed, once; never taken from the command line, where a shell + // would keep it. + if matches!(&plan, Err(why) if why.contains(NEEDS_PASSPHRASE)) { + match rpassword::prompt_password("This backup is protected by a passphrase. Passphrase: ") { + Ok(typed) if !typed.is_empty() => { + let typed = ledger_mcp::admin::Passphrase(typed); + plan = plan_restore(common, source, id, replace, true, Some(typed)); + } + _ => return fail("the backup needs its passphrase: nothing was restored".into()), + } + } + let plan = match plan { Ok(plan) => plan, Err(why) => return fail(why), }; @@ -2566,8 +2585,11 @@ fn restore( /// what it would do, a line each (INVARIANT 3: shown before it is done). #[derive(Clone, Debug, PartialEq, Eq)] pub struct RestorePlan { - /// The backup, as the server is told it (a folder by its full path). + /// The backup, as the server is told it (a folder or a file by its + /// full path). pub source: String, + /// Its passphrase, if it has one (never shown, wiped when dropped). + pub passphrase: Option, /// The books' id it comes back as. pub id: String, /// Whether it replaces the books of that id (kept in legacy/). @@ -2590,15 +2612,16 @@ pub fn plan_restore( id: Option, replace: bool, flags: bool, + passphrase: Option, ) -> Result { - // A folder is named to the server by its full path (the server's - // working folder isn't this one); anything else is an address. - let source = match Path::new(source) { + // A folder or a file is named to the server by its full path (the + // server's working folder isn't this one). + let source = match Path::new(source.trim()) { p if p.exists() => std::path::absolute(p) .unwrap_or_else(|_| p.to_path_buf()) .display() .to_string(), - _ => source.trim().to_string(), + _ => return Err(format!("there is no backup at {}", source.trim())), }; // One preview (under the id given, or any: it only reports), then the // id. @@ -2614,6 +2637,7 @@ pub fn plan_restore( replace, confirmed: false, expect_head: None, + passphrase: passphrase.clone(), }, )? { Response::RestorePreview(p) => p, @@ -2662,6 +2686,18 @@ pub fn plan_restore( preview.blobs, preview.vault_files )]; + if preview.passed_over > 0 { + lines.push(format!( + "{} newer backup(s) in it were damaged and passed over: this is the newest that is whole.", + preview.passed_over + )); + } + if preview.sealed { + lines.push( + "It is protected by a passphrase: the restored books keep backing up protected by it, from this computer." + .into(), + ); + } if let Some(origin) = &preview.origin { lines.push(format!("It is a backup of the books \"{origin}\".")); } @@ -2672,19 +2708,16 @@ pub fn plan_restore( } else { format!("It comes back as new books \"{id}\", beside any others.") }); - match preview.origin.as_deref() { - Some(o) if o == id => {} - Some(o) => lines.push(format!( - "Under a name other than its books' (\"{o}\"), they won't back up to the private repository those books back up to (that would stop theirs): if these are those books, restore them as \"{o}\"{}; else name a repository of their own.", - flag(&format!("--id {o}")) - )), - None => lines.push( - "It doesn't say whose books it holds: they won't back up to the private repository their settings name until one of their own is named." - .into(), - ), + if let Some(o) = preview.origin.as_deref() + && o != id + { + lines.push(format!( + "They were backed up as \"{o}\"; they come back as \"{id}\" and back up to their own folder in the backup folder." + )); } Ok(RestorePlan { source, + passphrase, id, replace, head: preview.head, @@ -2702,6 +2735,7 @@ pub fn carry_out_restore(common: &Common, plan: &RestorePlan) -> Result { @@ -4109,15 +4143,14 @@ mod tests { } #[test] - fn a_backup_is_restored_under_its_repository_name() { + fn a_backup_is_restored_under_its_folders_or_files_name() { for (source, want) in [ - ("/media/disk/backups/acme.git", Some("acme")), - ("/media/disk/backups/acme.git/", Some("acme")), - ("git@host:owner/acme-books.git", Some("acme-books")), - ("ssh://host/owner/acme", Some("acme")), - ("https://host/owner/acme.git", Some("acme")), - ("acme.git", Some("acme")), - ("/media/disk/Backups/Acme.git", None), + ("/media/disk/backups/acme", Some("acme")), + ("/media/disk/backups/acme/", Some("acme")), + ("/media/disk/acme-books.wbbackup", Some("acme-books")), + (r"C:\Backups\acme.wbbackup", Some("acme")), + ("acme", Some("acme")), + ("/media/disk/Backups/Acme", None), ("/", None), ("", None), ] { diff --git a/crates/ledger-mcp/src/admin.rs b/crates/ledger-mcp/src/admin.rs index 6b403d30..a480c3f5 100644 --- a/crates/ledger-mcp/src/admin.rs +++ b/crates/ledger-mcp/src/admin.rs @@ -121,8 +121,8 @@ pub enum Request { Restore { /// The books' id. id: String, - /// The backup: a git repository's address, or its folder - /// (`.git` in the backup folder). + /// The backup: a backup folder, the folder of one set of books in + /// it, or a backup file (`.wbbackup`), by its full path. source: String, /// Replace the books called `id`. #[serde(default)] @@ -133,8 +133,12 @@ pub enum Request { /// The head the preview read: restored only if still so. #[serde(default)] expect_head: Option<(u64, String)>, + /// The backup's passphrase, when it is protected by one (D-92): + /// never shown, never kept. + #[serde(default, skip_serializing_if = "Option::is_none")] + passphrase: Option, }, - /// Back books up now (plan 3.7): to every target their settings name. + /// Back books up now (plan 3.7): to the folder their settings name. BackUpNow { /// The books. id: String, @@ -660,6 +664,12 @@ pub struct RestorePreview { /// The id of the books it holds, as they were backed up. #[serde(default, skip_serializing_if = "Option::is_none")] pub origin: Option, + /// Whether it is protected by a passphrase. + #[serde(default)] + pub sealed: bool, + /// Newer backups in it that were not whole and were passed over. + #[serde(default)] + pub passed_over: u64, } /// What a restore did. @@ -687,7 +697,7 @@ pub struct Restored { /// How one backup target took a backup now. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct BackedUpTarget { - /// "repository" or "folder". + /// "folder". pub target: String, /// Where (no path in the data root). pub at: String, @@ -988,17 +998,18 @@ mod tests { #[test] fn a_restore_request_is_a_preview_unless_confirmed() { let r: Envelope = serde_json::from_value( - json!({"proto": 1, "op": "restore", "id": "acme", "source": "/backups/acme.git"}), + json!({"proto": 1, "op": "restore", "id": "acme", "source": "/backups/acme"}), ) .unwrap(); assert_eq!( r.request, Request::Restore { id: "acme".into(), - source: "/backups/acme.git".into(), + source: "/backups/acme".into(), replace: false, confirmed: false, expect_head: None, + passphrase: None, } ); } @@ -1075,6 +1086,8 @@ mod tests { vault_files: 1, exists: true, origin: Some("acme".into()), + sealed: false, + passed_over: 0, }), Response::Restored(Restored { id: "acme".into(), diff --git a/crates/ledger-mcp/src/backup.rs b/crates/ledger-mcp/src/backup.rs index fa529c03..0a949139 100644 --- a/crates/ledger-mcp/src/backup.rs +++ b/crates/ledger-mcp/src/backup.rs @@ -1,114 +1,95 @@ -//! The server's backups of a book (plan 3.7, D-30, D-31): made a while +//! The server's backups of a book (plan 3.7, D-30, D-91): made a while //! after the books are written (when the writing stops), when they open, -//! before they close, and when asked; each pushed to the targets the +//! before they close, and when asked; written to the backup folder the //! book's settings name; each recorded in the book's `ops/backup.jsonl`; -//! each target's backup drilled weekly. +//! the folder's backup proven weekly. //! //! ```text -//! GOAL: every write reaches the owner's backups soon after it is made, -//! and the owner (and agent) can see that it did, or why not. +//! GOAL: every write reaches the owner's backup soon after it is made, and +//! the owner (and agent) can see that it did, or why not. //! SOURCE: plan 3.7 (triggers, "ops/backup.jsonl", books.backup, Needs -//! attention for a target more than 24 h behind, drills), D-30 (a -//! git repository and a folder), D-31 (plain git), 3.9 and D-39 -//! (a verified local backup with the keys before a format -//! upgrade). +//! attention for a backup more than 24 h behind, drills), D-91 +//! (a plain folder, no git), D-92 (a passphrase), 3.9 and D-39 (a +//! proven local backup with the keys before a format upgrade), +//! WB-backup-1. //! INVARIANTS: -//! 1. A backup is committed under the store's lock (ledger_store::backup -//! INVARIANT 1; its stored files staged before, outside it) and -//! pushed outside it: the books are never held while the network is -//! slow. One run or drill at a time. -//! 2. Every commit, push and drill is a record of `ops/backup.jsonl` (a +//! 1. A backup is taken under the store's lock as a cut of the books +//! (ledger_store::backup::Cut: the journal's length and head, the +//! vault and keys) and written outside it: the books are never held +//! while a disk or a network share is slow. One run or drill at a +//! time. +//! 2. Every cut, write and drill is a record of `ops/backup.jsonl` (a //! chain log, not the journal: a backup never moves the books' head), -//! each target's outcome a record of its own, keyed by the target -//! itself (a new folder or address starts with no standing). -//! 3. A target is stale when it lacks the books' head and the first try -//! to back up what it lacks (the first commit or failure since its -//! last good push, or since its first try if it never had one, or -//! since the failed commits that kept it from any) is more than -//! STALE_AFTER old; its last error is its last push's, or a -//! later failed commit's. +//! the destination's outcome a record of its own, keyed by the +//! destination itself (its folder, and the passphrase's fingerprint: a +//! new folder, or a changed passphrase, starts with no standing). +//! 3. A backup is stale when it lacks the books' head and the first try +//! to back up what it lacks (the first cut or failure since its last +//! good write, or since its first try if it never had one, or since the +//! failed cuts that kept it from any) is more than STALE_AFTER old; its +//! last error is its last write's, or a later failed cut's. //! 4. Nothing here names a path of the data root to an agent. -//! 5. Every target that holds a backup is drilled (ledger_store::backup:: -//! drill: cloned, proven whole, its journal the live one's beginning) -//! once DRILL_EVERY has passed since its last good drill, or +//! 5. A backup that holds a backup is drilled (ledger_store::backup:: +//! drill: its books built and proven whole, its journal the live one's +//! beginning) once DRILL_EVERY has passed since its last good drill, or //! RETRY_AFTER since a failed one (at the server's next look for //! drills); a failed drill is said in the standing until one passes. -//! 6. A target whose push failed lately (RETRY_AFTER) is left out of a -//! backup after a write, and only that one; a folder target's -//! repository is made only while the target never took a backup of -//! these books (one gone since is a disk not connected), restored -//! books counting the backups of the books they were. -//! 7. Books restored beside the books they were (under another id) never -//! push to the repository those books back up to (it would stop -//! theirs): it is paused for them, and said, until another is named. -//! 8. A damaged backup record never keeps the books shut: it is set +//! 6. A destination whose write failed lately (RETRY_AFTER) is left out of +//! a backup after a write; a destination's backup is begun only while +//! it never took one of these books (one gone since is a disk not +//! connected), restored books counting the backups of the books they +//! were. +//! 7. A damaged backup record never keeps the books shut: it is set //! aside and a new one begun. -//! 9. A format upgrade (plan 3.9, D-39) is made only after the books are -//! committed to their archive and the archive proven to hold them -//! exactly as they are (journal, stored files, vault and keys), all +//! 8. A format upgrade (plan 3.9, D-39) is made only after the books are +//! written to their local backup (`local-backup/` in the book's folder, +//! the same form) and that backup proven to hold them exactly as they +//! are (journal, vault and keys; every stored file re-hashed), all //! under the store's lock, so nothing is written in between; a backup //! that can't be made or proven upgrades nothing. Both are records. -//! 10. These backups can be shut (`shut`), once, for good: git is stopped -//! (every command running, with all it started) and none starts; the -//! call waits for every step that was under way to END (each step's -//! count rides in its own blocking task, so it is not lost when the -//! future that began it is dropped, as a close's 60 s bound drops -//! one), and for the run or drill holding the books' turn; then the -//! backup record is closed under its own lock. After `shut` returns, -//! this holder (a timer's, a request's, any clone from before) runs -//! nothing, spawns no process, and writes nothing, whatever the books -//! are doing: not in this process's later opening of the same books, -//! whose own backups are another object with another record handle. -//! 11. A close is not held by a step it doesn't wait for. When a close +//! 9. These backups can be shut (`shut`), once, for good: the file copy in +//! progress stops at its next piece and none starts; the call waits for +//! every step that was under way to END (each step's count rides in its +//! own blocking task, so it is not lost when the future that began it +//! is dropped, as a close's 60 s bound drops one), and for the run or +//! drill holding the books' turn; then the backup record is closed +//! under its own lock. After `shut` returns, this holder (a timer's, a +//! request's, any clone from before) runs nothing, and writes nothing, +//! whatever the books are doing. +//! 10. A close is not held by a step it doesn't wait for. When a close //! begins (`hurry`, before its last backup), these stop at their next //! look: a drill, a format upgrade that has not yet reached its final //! look, and a backup a call or a timer asked for (`run_with` for any -//! `why` but `close`), looking between git commands and phases, once -//! per journal line, file or 64 KiB chunk (ledger_store::backup -//! INVARIANT 6), and between targets. A drill's scratch clone is -//! removed and nothing is said of its target (neither a pass nor a -//! failure: it is due again when the books next open). A run stopped -//! this way records `stopped` (what it was doing: `commit` or `push`) -//! and no result of its own for the step it didn't finish: a commit it -//! had made stands in the archive and is recorded as made, a target it -//! hadn't pushed to is said nothing of, and its caller is told it was -//! stopped because the books are closing (tools/backup.rs, which marks -//! the call's access record `stopped_by_close`). The one thing a stop is -//! a failure for is a lock git left in the owner's folder (INVARIANT 12). -//! An upgrade is reported not done, the books unchanged, and its backup -//! (a commit it made on the way) recorded, if the close's stop reaches -//! it before its final look, which is made once everything it needs is -//! proven and just before the `journal.format_set` line is appended: a -//! stop is honoured up to that look. One that arrives between it and the -//! append does not undo the upgrade: the line is appended, the database's -//! row is written and the upgrade is recorded as made (safe: the books -//! are in this version's format and proven backed up, and the close that -//! asked for the stop is waiting for the books lock). The last backup of -//! the close, and the stop `shut` makes of what is left of it, are not -//! hurried: only `shut` stops them. The close's whole bound is the sum -//! written in the books server's INVARIANT 10 (local.rs). -//! 12. A lock file a stopped git left is dealt with by the step that -//! stopped it (ledger_store::backup INVARIANT 5) and recorded: a -//! record `lock_removed` (the archive's own, made by the git just -//! stopped) or `lock_left`, with `repo` (`archive`, `folder` or -//! `repository`), `lock` (a path in that repository), `why`, and for a -//! lock left in the owner's folder, `path`, its whole path. Git is sent -//! SIGTERM first and removes its own locks, so these records are the -//! rare case. A lock left in the owner's folder is never removed by -//! this program: it marks that target's backup failed, in a `push` -//! record whose error names the files and says to remove them only when -//! nothing else is using the backup folder; that error is the target's -//! `last_error` in `books.backup` and in the server's backup status, and -//! what a close that couldn't finish its last backup says. (A run whose -//! future was dropped at its bound has that record written by `shut`.) -//! The archive's locks found when the books open are dealt with the -//! same way (the store is open, and its lock is ours): only those older -//! than ten minutes are removed. A close is not answered before these -//! are recorded, the backup record being closed after them. +//! `why` but `close`), looking between pieces (ledger_store::backups +//! INVARIANT 8) and between destinations. A drill's scratch folder is +//! removed and nothing is said of its destination (it is due again +//! when the books next open). A run stopped this way records +//! `stopped` (what it was doing: `cut` or `write`) and no result of its +//! own for the step it didn't finish: what it had written stands, and +//! the destination proves whole at its previous manifest (the one in +//! place before the run); its caller is told it was stopped because +//! the books are closing (tools/backup.rs, which marks the call's +//! access record `stopped_by_close`). An upgrade is reported not done, +//! the books unchanged, if the close's stop reaches it before its final +//! look, which is made once everything it needs is proven and just +//! before the `journal.format_set` line is appended: a stop is +//! honoured up to that look. One that arrives between it and the append +//! does not undo the upgrade. The last backup of the close, and the +//! stop `shut` makes of what is left of it, are not hurried: only +//! `shut` stops them. The close's whole bound is the sum written in the +//! books server's INVARIANT 10 (local.rs). +//! 11. The passphrase's key is read from the book's `local/` folder at each +//! run: with one there, every write is sealed; one that is there and +//! can't be read stops the write (never a plain one). The key never +//! reaches a record, an error or a status. +//! 12. Old forms are left alone and said once: a private repository named +//! by the books' old setting is no longer used, and the old backup +//! history in the book's folder is neither read, written nor removed; +//! the status says so until a backup has been made in the new form. //! ``` use crate::server::SharedStore; -use ledger_store::backup::{self, BackupError, Git, LockNotes, Target}; +use ledger_store::backup::{self as backup, BackupError, BackupKey, Ctx, Cut, Destination}; use ledger_store::chain::ChainLog; use serde::Serialize; use serde_json::{Map, Value, json}; @@ -116,10 +97,10 @@ use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; -/// What a call is told when these backups were shut (INVARIANT 10). +/// What a call is told when these backups were shut (INVARIANT 9). pub const SHUT: &str = "the books were closed: nothing was backed up"; -/// Blocking steps of the backups under way (INVARIANT 10). +/// Blocking steps of the backups under way (INVARIANT 9). #[derive(Default)] struct Busy { steps: AtomicUsize, @@ -138,13 +119,20 @@ impl Drop for Step { } } +/// The test knob's file in a book's `ops/`: while it is there, a backup +/// waits at each phase ([`Backups::slow_steps`]). +pub const SLOW_BACKUP: &str = "slow-backup"; +/// The file beside it that gets a line each time a backup reaches a phase +/// and waits. +pub const SLOW_BACKUP_REACHED: &str = "slow-backup-reached"; + /// The book's backup record, in its `ops/`. pub const LOG_FILE: &str = "backup.jsonl"; /// The record's genesis text. const GENESIS: &str = "wanderbooks-backup-v1"; -/// How long a target may lack the books' head before it is stale. +/// How long a destination may lack the books' head before it is stale. pub const STALE_AFTER: chrono::Duration = chrono::Duration::hours(24); -/// How often each target's backup is drilled (plan 3.7: weekly). +/// How often each destination's backup is drilled (plan 3.7: weekly). pub const DRILL_EVERY: chrono::Duration = chrono::Duration::days(7); /// How long after a failed run (or drill) the next is tried. pub const RETRY_AFTER: std::time::Duration = std::time::Duration::from_secs(15 * 60); @@ -162,20 +150,17 @@ pub struct Backups { log: Mutex, /// One run at a time. running: tokio::sync::Mutex<()>, - /// Set by `shut` (INVARIANT 10): git stops, nothing starts. + /// Set by `shut` (INVARIANT 9): copying stops, nothing starts. shut: Arc, /// The blocking steps under way. busy: Arc, - /// Set when a close begins, before its last backup (INVARIANT 11): the + /// Set when a close begins, before its last backup (INVARIANT 10): the /// steps a close doesn't wait for (a drill, a format upgrade not yet /// journaled, a backup a call or a timer asked for) stop, and `shut` /// sets it too. It is the book's store's flag (`SharedStore::hurry`), so /// the book's calls that can run long see it too. The close's own last /// backup is stopped by `shut` alone, so it can run. hurry: Arc, - /// The lock files a stopped git left, as they were dealt with - /// (ledger_store::backup INVARIANT 5), until they are recorded. - locks: LockNotes, /// A test knob (`--slow-steps`): how long a drill or a format upgrade /// waits, in milliseconds, at each phase, giving up when hurried. slow_ms: AtomicU64, @@ -203,10 +188,10 @@ pub struct Upgraded { /// The backup a format upgrade made first: the books as they were. #[derive(Debug, Clone, PartialEq, Eq)] pub struct UpgradeBackup { - /// Whether it was committed now (false: the last backup already held + /// Whether it was written now (false: the local backup already held /// the books as they were). pub made: bool, - /// Its commit in the books' archive. + /// Its number in the local backup. pub commit: String, /// The head it holds: the books before the upgrade. pub head: (u64, String), @@ -214,8 +199,8 @@ pub struct UpgradeBackup { /// Why a format upgrade wasn't made: nothing was upgraded. struct UpgradeFailed { - /// The backup committed on the way, if one was. - made: Option, + /// The backup written on the way, if one was. + made: Option, /// Why, in words. why: String, } @@ -232,7 +217,7 @@ impl UpgradeFailed { } /// The backup `made` (now, or earlier) didn't prove whole. - fn proof(made: Option, e: BackupError) -> Self { + fn proof(made: Option, e: BackupError) -> Self { Self { made, why: format!( @@ -242,7 +227,7 @@ impl UpgradeFailed { } /// Proven, and the books refused the upgrade. - fn store(made: Option, e: ledger_store::StoreError) -> Self { + fn store(made: Option, e: ledger_store::StoreError) -> Self { Self { made, why: format!("{e}: nothing was upgraded"), @@ -258,14 +243,14 @@ impl UpgradeFailed { } } -/// One target's standing (INVARIANT 3). +/// One destination's standing (INVARIANT 3). #[derive(Debug, Clone, Serialize, PartialEq, Eq)] pub struct TargetStatus { - /// "repository" or "folder". + /// "folder". pub target: String, - /// Where (the repository's address, or "the backup folder"). + /// Where (a name, never a path of the data root). pub at: String, - /// When it last took a push, if ever (UTC). + /// When it last took a backup (UTC), if ever. pub last_ok_at: Option, /// The journal seq it holds, if any. pub through_seq: Option, @@ -277,8 +262,10 @@ pub struct TargetStatus { pub last_drill_at: Option, /// Why its last drill failed, if it did. pub drill_error: Option, - /// Paused for books restored as a copy of others (INVARIANT 7). - pub paused: bool, + /// Protected by a passphrase. + pub sealed: bool, + /// Its disk isn't connected (its last try found no folder). + pub disconnected: bool, } /// The books' backup standing. @@ -286,47 +273,70 @@ pub struct TargetStatus { pub struct Status { /// The books' head now. pub head_seq: u64, - /// Each target the settings name. + /// Each destination the settings name. pub targets: Vec, - /// None set up: what to do. + /// None set up, or an old form left alone: what to know and do. pub note: Option, } -/// A target the settings name. +/// A destination the settings name. #[derive(Debug, Clone)] struct Named { - target: Target, + /// Where, and sealed or not; Err when its key can't be read. + dest: Result, /// Where, as an agent is told it. at: String, - /// The target itself, as its records name it (INVARIANT 2): a digest - /// of where it is (never a path an agent is shown). + /// The destination itself, as its records name it (INVARIANT 2): a + /// digest of where it is and which passphrase (never a path an agent + /// is shown). key: String, + sealed: bool, } -/// The targets the book's settings name (D-30). -fn targets(store: &ledger_store::Store, book: &str) -> Vec { +/// What a person is told when no backup folder is set. +pub const NONE_SET: &str = "no backup is set up: choose a backup folder (a folder on another disk, or one that Dropbox, iCloud, OneDrive or Google Drive keeps in sync) with books.set_setting backup.folder, or in the window"; + +/// What books that still name a private repository are told. +pub const OLD_REMOTE: &str = "These books' settings still name a private repository for backups. That kind of backup is no longer made and the repository is left alone: choose a backup folder instead."; + +/// What books that still carry an old backup history are told. +pub const OLD_ARCHIVE: &str = "An older backup folder from an earlier version is still in the books' folder. It is no longer written or read, and nothing was deleted: you may delete it yourself once the new backup is whole."; + +/// The destination the book's settings name (D-91). +fn targets(store: &ledger_store::Store, book: &str, dir: &Path) -> Vec { use sha2::{Digest, Sha256}; - let s = store.ledger().settings(); - let mut out = Vec::new(); - if let Some(url) = s.backup_git_remote() { - out.push((Target::Remote(url.to_string()), url.to_string())); + let Some(folder) = store.ledger().settings().backup_folder() else { + return Vec::new(); + }; + let loaded = BackupKey::load(dir); + let (key, sealed, fp) = match &loaded { + Ok(Some(k)) => (Ok(Some(k.clone())), true, k.fingerprint()), + Ok(None) => (Ok(None), false, String::new()), + Err(e) => (Err(e.to_string()), true, "unreadable".to_string()), + }; + let digest: String = Sha256::digest(format!("{folder}\0{book}\0{fp}").as_bytes())[..8] + .iter() + .map(|b| format!("{b:02x}")) + .collect(); + vec![Named { + dest: key.map(|key| Destination { + folder: PathBuf::from(folder), + key, + }), + at: "the backup folder".to_string(), + key: digest, + sealed, + }] +} + +/// What an error of a write is, for the record: tells a disk not connected. +fn error_kind(e: &BackupError) -> &'static str { + match e { + BackupError::NoFolder => "no_folder", + BackupError::NoBackupThere => "no_backup_there", + BackupError::Elsewhere | BackupError::Ahead(..) => "elsewhere", + _ => "other", } - if let Some(folder) = s.backup_folder() { - out.push(( - Target::Folder(PathBuf::from(folder)), - "the backup folder".to_string(), - )); - } - out.into_iter() - .map(|(target, at)| Named { - key: Sha256::digest(target.source(book).as_bytes())[..8] - .iter() - .map(|b| format!("{b:02x}")) - .collect(), - target, - at, - }) - .collect() } impl Backups { @@ -337,8 +347,8 @@ impl Backups { let path = ledger_store::ops::ops_dir(dir).join(LOG_FILE); let (log, carried) = match ChainLog::open(&path, GENESIS) { Ok((log, _)) => (log, Vec::new()), - // INVARIANT 8: set aside, begun again, what it knew of whose - // backups the targets hold carried into the new one. + // INVARIANT 7: set aside, begun again, what it knew of whose + // backups the destinations hold carried into the new one. Err(ledger_store::chain::ChainError::Damaged { .. }) => { let known = known_before_damage(&path); let aside = path.with_extension(format!( @@ -367,7 +377,6 @@ impl Backups { shut: Arc::default(), busy: Arc::default(), hurry, - locks: LockNotes::default(), slow_ms: AtomicU64::new(0), paused: Arc::default(), hold: Mutex::new(None), @@ -375,20 +384,19 @@ impl Backups { for fields in carried { me.record(fields); } - // The store is open, so its lock is ours: no other wanderbooks - // process runs git on this archive, and none of this process's does - // yet. A lock in it older than ten minutes is a dead git's; a - // younger one is left (store INVARIANT 5a). - for note in backup::clear_archive_locks(dir) { - me.record_lock(¬e); + // An old backup history in the book's folder is left alone, and + // noted once (INVARIANT 12). + if dir.join(OLD_ARCHIVE_DIR).exists() && !me.records().iter().any(|r| is(r, "old_archive")) + { + me.record(json!({"kind": "old_archive"})); } - // Books just restored: whose they were (INVARIANTS 6, 7). + // Books just restored: whose they were (INVARIANT 6). let marker = ledger_store::ops::ops_dir(dir).join(ledger_store::root::RESTORED_FROM); if let Ok(origin) = std::fs::read_to_string(&marker) { let origin = Some(origin.trim()).filter(|o| !o.is_empty()); let named = me .store - .try_with_store(|s| targets(s, book)) + .try_with_store(|s| targets(s, book, dir)) .ok_or("its backups can't be read yet: the books are busy")?; me.restored(origin, &named); std::fs::remove_file(&marker) @@ -401,7 +409,7 @@ impl Backups { let Value::Object(mut map) = fields else { return; }; - // INVARIANT 4: a git or store message may quote a path in the root. + // INVARIANT 4: a store message may quote a path in the root. if let Some(Value::String(e)) = map.get_mut("error") { *e = hide(e, &self.dir); } @@ -414,14 +422,14 @@ impl Backups { } } - /// Whether these backups were shut (INVARIANT 10). + /// Whether these backups were shut (INVARIANT 9). fn is_shut(&self) -> bool { self.shut.load(Ordering::SeqCst) } /// A step begins: counted before the shut flag is looked at, and /// `shut` sets the flag before it looks at the count, so a step either - /// sees them shut or is waited for, never neither (INVARIANT 10). + /// sees them shut or is waited for, never neither (INVARIANT 9). fn begin(&self) -> Result { self.busy.steps.fetch_add(1, Ordering::SeqCst); let step = Step(self.busy.clone()); @@ -431,40 +439,57 @@ impl Backups { Ok(step) } - /// git, stopped by `shut`: the close's own last backup (INVARIANT 10). - fn git(&self) -> Result { - Ok(Git::find()? - .with_cancel(self.shut.clone()) - .with_lock_notes(self.locks.clone())) - } - - /// git for a backup a call or a timer asked for: stopped as soon as a - /// close begins (INVARIANT 11), so it can't hold the close. - fn git_for(&self, why: &str) -> Result { - if why == "close" { - self.git() + /// The stop for the close's own last backup (INVARIANT 9), or, for a + /// backup a call or a timer asked for, the one a close begins + /// (INVARIANT 10), so it can't hold the close. + fn ctx_for(&self, why: &str) -> Ctx { + let flag = if why == "close" { + self.shut.clone() } else { - Ok(Git::find()? - .with_cancel(self.hurry.clone()) - .with_lock_notes(self.locks.clone())) + self.hurry.clone() + }; + let ctx = Ctx::new().with_stop(flag.clone()); + // The test knob: a backup waits at each phase while + // `ops/slow-backup` is there (and `--slow-steps` was given), until + // the stop it runs under is asked for, as a slow disk would hold it. + if self.slow_ms.load(Ordering::SeqCst) == 0 { + return ctx; } + let marker = ledger_store::ops::ops_dir(&self.dir).join(SLOW_BACKUP); + let paused = self.paused.clone(); + ctx.with_phase_watch(Arc::new(move |_phase: &str| { + if !marker.exists() { + return; + } + paused.fetch_add(1, Ordering::SeqCst); + // Said to the test: a backup has reached a phase and waits. + if let Ok(mut f) = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(marker.with_file_name(SLOW_BACKUP_REACHED)) + { + use std::io::Write; + let _ = f.write_all(b"x\n"); + } + while marker.exists() && !flag.load(Ordering::SeqCst) { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + })) } - /// git for a step a close hurries (a drill, a format upgrade): stopped - /// as soon as the close begins (INVARIANT 11). - fn hurried_git(&self) -> Result { - let git = Git::find()? - .with_cancel(self.hurry.clone()) - .with_lock_notes(self.locks.clone()); + /// The stop for a step a close hurries (a drill, a format upgrade), with + /// the test knob's wait at each phase. + fn hurried_ctx(&self) -> Ctx { + let ctx = Ctx::new().with_stop(self.hurry.clone()); let ms = self.slow_ms.load(Ordering::SeqCst); if ms == 0 { - return Ok(git); + return ctx; } let (hurry, paused) = (self.hurry.clone(), self.paused.clone()); - Ok(git.with_phase_watch(Arc::new(move |phase: &str| { - // From the second phase on (the first is the clone, before + ctx.with_phase_watch(Arc::new(move |phase: &str| { + // From the second phase on (the first is the fetch, before // there is anything of the step's own to see). - if phase == "clone" { + if phase == "fetch" { return; } paused.fetch_add(1, Ordering::SeqCst); @@ -472,7 +497,7 @@ impl Backups { while std::time::Instant::now() < by && !hurry.load(Ordering::SeqCst) { std::thread::sleep(std::time::Duration::from_millis(10)); } - }))) + })) } /// Make each phase of a drill or format upgrade wait `by` (a test @@ -500,7 +525,7 @@ impl Backups { self.paused.load(Ordering::SeqCst) } - /// A close begins (INVARIANT 11): the steps it doesn't wait for stop at + /// A close begins (INVARIANT 10): the steps it doesn't wait for stop at /// their next look. The close's last backup, and what `shut` stops, are /// not affected until `shut`. pub fn hurry(&self) { @@ -511,37 +536,14 @@ impl Backups { self.hurry.load(Ordering::SeqCst) } - /// A lock a stopped git left, as it was dealt with: a record of the - /// backup (INVARIANT 12). - fn record_lock(&self, note: &backup::LockNote) { - let mut fields = json!({ - "kind": if note.removed { "lock_removed" } else { "lock_left" }, - "repo": note.repo, "lock": note.lock, "why": note.why, - }); - // A lock left in the owner's folder is named by its whole path. - if let (Some(path), Value::Object(map)) = (¬e.path, &mut fields) { - map.insert("path".into(), json!(path)); - } - self.record(fields); - } - - /// Record the locks dealt with since the last look; the notes. - fn note_locks(&self) -> Vec { - let notes = self.locks.take(); - for note in ¬es { - self.record_lock(note); - } - notes - } - - /// Shut these backups for good (INVARIANT 10): git stopped, every step - /// ended, the record closed. Call it after the last backup the books - /// will have, and before the books' store is let go. - pub async fn shut(&self) -> Vec { + /// Shut these backups for good (INVARIANT 9): copying stopped, every + /// step ended, the record closed. Call it after the last backup the + /// books will have, and before the books' store is let go. + pub async fn shut(&self) { self.shut.store(true, Ordering::SeqCst); self.hurry.store(true, Ordering::SeqCst); - // The run or drill holding the books' turn ends (its git was just - // stopped), and none begins after. + // The run or drill holding the books' turn ends (its copying was + // just stopped), and none begins after. let _turn = self.running.lock().await; loop { let ended = self.busy.ended.notified(); @@ -550,36 +552,7 @@ impl Backups { } ended.await; } - let notes = self.note_locks(); - // A run whose future was dropped at its bound (a close's last - // backup) never recorded its push: a lock its stopped git left in the - // owner's folder is that target's failure all the same, named, in the - // standing the owner reads (ledger_store::backup INVARIANT 5b). Locks - // a run took in hand itself were recorded by it, and aren't here. - let left: Vec<&backup::LockNote> = notes - .iter() - .filter(|n| !n.removed && n.path.is_some()) - .collect(); - let mut said = Vec::new(); - if !left.is_empty() { - for n in self.named().await { - let paths: Vec<&str> = left - .iter() - .filter(|l| l.repo == n.target.kind()) - .filter_map(|l| l.path.as_deref()) - .collect(); - if !paths.is_empty() { - let error = BackupError::LockLeft(paths.join(", ")).to_string(); - self.record( - json!({"kind": "push", "why": "close", "target": n.target.kind(), - "at": n.at, "key": n.key, "ok": false, "error": error}), - ); - said.push(error); - } - } - } self.log.lock().unwrap_or_else(|e| e.into_inner()).close(); - said } fn records(&self) -> Vec> { @@ -591,10 +564,10 @@ impl Backups { .unwrap_or_default() } - /// The targets the settings name now. + /// The destination the settings name now. async fn named(&self) -> Vec { - let (store, book) = (self.store.clone(), self.book.clone()); - tokio::task::spawn_blocking(move || store.with_store(|s| targets(s, &book)).ok()) + let (store, book, dir) = (self.store.clone(), self.book.clone(), self.dir.clone()); + tokio::task::spawn_blocking(move || store.with_store(|s| targets(s, &book, &dir)).ok()) .await .ok() .flatten() @@ -602,22 +575,15 @@ impl Backups { } /// Note that these books were just restored from a backup of the books - /// `origin` (INVARIANTS 6, 7), `named` the targets they name: the same - /// books (their targets took their backups), or others' (the - /// repository those back up to is paused for these). + /// `origin` (INVARIANT 6), `named` the destinations they name: the same + /// books (their destination took their backups), or others'. fn restored(&self, origin: Option<&str>, named: &[Named]) { let same = origin == Some(self.book.as_str()); - let keys = |remote: bool| -> Vec { - named - .iter() - .filter(|n| !remote || matches!(n.target, Target::Remote(_))) - .map(|n| n.key.clone()) - .collect() - }; + let keys: Vec = named.iter().map(|n| n.key.clone()).collect(); if same { - self.record(json!({"kind": "restored", "origin": origin, "held": keys(false)})); + self.record(json!({"kind": "restored", "origin": origin, "held": keys})); } else { - self.record(json!({"kind": "restored", "origin": origin, "paused": keys(true)})); + self.record(json!({"kind": "restored", "origin": origin})); } } @@ -636,12 +602,12 @@ impl Backups { self.run_with(why, false).await } - /// [`Self::run`]; with `new_disk`, a folder target that took these + /// [`Self::run`]; with `new_disk`, a destination that took these /// books' backups and holds none now is begun again there (the owner /// says it is a new disk). pub async fn run_with(&self, why: &str, new_disk: bool) -> Result { let _one = self.running.lock().await; - // Books let go of (closed, or replaced by a restore) push nothing + // Books let go of (closed, or replaced by a restore) write nothing // more, and leave no record of a run that never began. if self.is_shut() { return Err(SHUT.to_string()); @@ -650,156 +616,127 @@ impl Backups { return Err(crate::server::STOPPED.to_string()); } // A run a call or a timer asked for is stopped by a close - // (INVARIANT 11); the close's own last backup is not. + // (INVARIANT 10); the close's own last backup is not. let stoppable = why != "close"; if stoppable && self.hurried() { - return Err(self.stopped_words(None)); + return Err(self.stopped_words()); } if self.named().await.is_empty() { return Ok(self.status().await); } let step = self.begin()?; let (store, dir, book) = (self.store.clone(), self.dir.clone(), self.book.clone()); - let git = self.git_for(why); - let made = tokio::task::spawn_blocking(move || { + let cut = tokio::task::spawn_blocking(move || { let _step = step; - let git = git?; - // The stored files first, outside the lock: they never change. - // Only a head start (a file being written can trip it): the - // commit stages them all again. - let _ = backup::stage_blobs(&git, &dir); - // The commit, under it. + // The cut, under the lock. store .with_store(|s| -> Result<_, BackupError> { - let made = backup::commit(&git, &dir, &book, s.head())?; - Ok((made, targets(s, &book), s.head())) + Ok((Cut::take(&book, &dir, s.head())?, targets(s, &book, &dir))) }) .map_err(BackupError::Damaged) .and_then(|r| r) }) .await .unwrap_or(Err(BackupError::Damaged("the backup stopped".into()))); - let _ = self.note_locks(); - let (made, named, head) = match made { + let (cut, named) = match cut { Ok(m) => m, - // Stopped by a close: neither a success nor a failure of the - // backup, so nothing is said of any target (INVARIANT 11); what - // was committed before it stands in the archive, and the close - // makes its own last backup. - Err(BackupError::Cancelled(_)) if stoppable => { - self.record(json!({"kind": "stopped", "why": why, "during": "commit"})); - return Err(self.stopped_words(None)); - } Err(e) => { - let lock_left = matches!(e, BackupError::LockLeft(_)); let e = hide(&e.to_string(), &self.dir); self.record(json!({"kind": "commit", "why": why, "ok": false, "error": e})); - return Err(if stoppable && self.hurried() && lock_left { - self.stopped_words(Some(&e)) - } else { - e - }); + return Err(e); } }; - if let Some(m) = &made { - self.record( - json!({"kind": "commit", "why": why, "ok": true, "commit": m.commit, - "head": {"seq": m.head.0, "hash": m.head.1}}), - ); - } - // Each target, outside the lock; after a write, one that failed - // lately waits out RETRY_AFTER (the others don't wait for it). + let head = cut.head().clone(); + // The destination, outside the lock; after a write, one that + // failed lately waits out RETRY_AFTER. let records = self.records(); let now = chrono::Utc::now(); for n in named { - if paused(&n.key, &records) || (why == "write" && failed_lately(&n.key, &records, now)) - { + if why == "write" && failed_lately(&n.key, &records, now) { continue; } if stoppable && self.hurried() { - self.record(json!({"kind": "stopped", "why": why, "during": "push"})); - return Err(self.stopped_words(None)); + self.record(json!({"kind": "stopped", "why": why, "during": "write"})); + return Err(self.stopped_words()); } - // Its repository is made only where it never took a backup. + let dest = match &n.dest { + Ok(d) => d.clone(), + Err(e) => { + self.record( + json!({"kind": "push", "why": why, "target": "folder", "at": n.at, + "key": n.key, "ok": false, "error": e, "error_kind": "other"}), + ); + continue; + } + }; + // Its folder is begun only where it never took a backup. let may_create = new_disk || !held_before(&n.key, &records); let step = self.begin()?; - let git = self.git_for(why); - let (dir, book, t) = (self.dir.clone(), self.book.clone(), n.target.clone()); - let pushed = tokio::task::spawn_blocking(move || { + let ctx = self.ctx_for(why); + let cut = cut.clone(); + let written = tokio::task::spawn_blocking(move || { let _step = step; - backup::push(&git?, &dir, &book, &t, may_create) + backup::write_destination(&dest, &cut, may_create, &ctx) }) .await - .unwrap_or(Err(BackupError::Damaged("the push stopped".into()))); - let _ = self.note_locks(); - match pushed { - Ok(commit) => self.record( - json!({"kind": "push", "why": why, "target": n.target.kind(), - "at": n.at, "key": n.key, "ok": true, "commit": commit, + .unwrap_or(Err(BackupError::Damaged("the backup stopped".into()))); + match written { + Ok(w) => self.record( + json!({"kind": "push", "why": why, "target": "folder", "at": n.at, + "key": n.key, "ok": true, "number": w.number, "new": w.new, "head": {"seq": head.0, "hash": head.1}}), ), - // Stopped by a close: not a failure of the target, and not - // a success: said once, of the run (INVARIANT 11). + // Stopped by a close: not a failure of the destination, and + // not a success: said once, of the run (INVARIANT 10). Err(BackupError::Cancelled(_)) if stoppable => { - self.record(json!({"kind": "stopped", "why": why, "during": "push", - "target": n.target.kind(), "key": n.key})); - return Err(self.stopped_words(None)); - } - Err(e) => { - let lock_left = matches!(e, BackupError::LockLeft(_)); - self.record( - json!({"kind": "push", "why": why, "target": n.target.kind(), - "at": n.at, "key": n.key, "ok": false, "error": e.to_string()}), - ); - // A stop that left a lock is a failure the owner must - // hear of, and the call is told both. - if stoppable && self.hurried() && lock_left { - return Err(self.stopped_words(Some(&hide(&e.to_string(), &self.dir)))); - } + self.record(json!({"kind": "stopped", "why": why, "during": "write", + "key": n.key})); + return Err(self.stopped_words()); } + Err(e) => self.record( + json!({"kind": "push", "why": why, "target": "folder", "at": n.at, + "key": n.key, "ok": false, "error": e.to_string(), + "error_kind": error_kind(&e)}), + ), } } Ok(self.status().await) } /// What a run a close stopped answers: that it was stopped because the - /// books are closing (the call's access record says so), and, if it left - /// a lock in the owner's folder, that too. - fn stopped_words(&self, also: Option<&str>) -> String { - match also { - None => crate::server::STOPPED_BY_CLOSE_WORDS.to_string(), - Some(more) => format!("{} Also: {more}", crate::server::STOPPED_BY_CLOSE_WORDS), - } + /// books are closing (the call's access record says so). + fn stopped_words(&self) -> String { + crate::server::STOPPED_BY_CLOSE_WORDS.to_string() } /// The format upgrade, after a verified local backup with the keys - /// (plan/served.md 3.9, D-39; INVARIANT 9). The caller has the owner's + /// (plan/served.md 3.9, D-39; INVARIANT 8). The caller has the owner's /// go-ahead (the passphrase, checked by the server). /// /// Under the store's lock, so nothing is written between the backup - /// and the upgrade: the books committed to their archive (made - /// whatever targets the settings name, or none), the archive cloned - /// and proven to hold the books exactly as they are, journal, stored - /// files, vault and keys ([`backup::prove_archive`]); only then this - /// version's journal format declared (ledger_store - /// `Store::upgrade_format`). Books already in it: nothing is done. - /// Both the backup and the upgrade are records of `ops/backup.jsonl`; - /// the targets take them at the next backup, the books having moved. + /// and the upgrade: the books written to their local backup (whatever + /// destination the settings name, or none), that backup proven to hold + /// the books exactly as they are, journal, stored files, vault and keys + /// ([`backup::prove_local`]); only then this version's journal format + /// declared (ledger_store `Store::upgrade_format`). Books already in it: + /// nothing is done. Both the backup and the upgrade are records of + /// `ops/backup.jsonl`; the destination takes them at the next backup, + /// the books having moved. pub async fn upgrade_format(&self) -> Result { let _one = self.running.lock().await; // Books let go of, between the request's start and now, upgrade // nothing and leave no record (a failure written through this // handle would land in the book's record after it was opened - // again): INVARIANT 10. + // again): INVARIANT 9. let step = self.begin()?; let (store, dir, book) = (self.store.clone(), self.dir.clone(), self.book.clone()); - let git_for_upgrade = self.hurried_git(); + let ctx = self.hurried_ctx(); let cancel = self.hurry.clone(); let done = tokio::task::spawn_blocking(move || { let _step = step; // Books that wait for nothing are left as they are: not even - // their archive is made or staged (asked again under the lock - // below; only an upgrade moves the format, one at a time). + // their local backup is made (asked again under the lock below; + // only an upgrade moves the format, one at a time). match store.with_store(|s| (s.journal_format().upgrade().is_none(), s.head())) { Ok((true, head)) => { return Ok(Upgraded { @@ -811,11 +748,6 @@ impl Backups { Ok((false, _)) => {} Err(why) => return Err(UpgradeFailed::stopped(why)), } - // Stored files staged ahead, outside the lock (as a backup's). - let git = git_for_upgrade; - if let Ok(git) = &git { - let _ = backup::stage_blobs(git, &dir); - } store .with_store_mut(|s| -> Result { let head = s.head(); @@ -826,28 +758,21 @@ impl Backups { head, }); }; - let git = git.map_err(UpgradeFailed::backup)?; - let made = backup::commit(&git, &dir, &book, head.clone()) - .map_err(UpgradeFailed::backup)?; + let cut = + Cut::take(&book, &dir, head.clone()).map_err(UpgradeFailed::backup)?; + let made = + backup::write_local(&dir, &cut, &ctx).map_err(UpgradeFailed::backup)?; let scratch = ledger_store::ops::ops_dir(&dir).join("upgrade-check"); let _ = std::fs::remove_dir_all(&scratch); - let proven = backup::prove_archive(&git, &dir, &head, &scratch) - .and_then(|p| match &made { - // The commit proven is the one just made. - Some(m) if m.commit != p.commit => Err(BackupError::Damaged( - "the backup it proved isn't the one it made".into(), - )), - _ => Ok(p), - }) - .map_err(|e| UpgradeFailed::proof(made.clone(), e))?; - let commit = proven.commit; - // The last look for a close (INVARIANT 11): once the + backup::prove_local(&dir, &book, &head, &scratch, &ctx) + .map_err(|e| UpgradeFailed::proof(Some(made.clone()), e))?; + // The last look for a close (INVARIANT 10): once the // `journal.format_set` line is appended the upgrade // finishes, which is quick; before it, it is stopped, // the books unchanged. if cancel.load(Ordering::SeqCst) { return Err(UpgradeFailed { - made: made.clone(), + made: Some(made.clone()), why: "the books are closing: nothing was upgraded".into(), }); } @@ -865,13 +790,13 @@ impl Backups { ); Some(waiting) } - Err(e) => return Err(UpgradeFailed::store(made.clone(), e)), + Err(e) => return Err(UpgradeFailed::store(Some(made.clone()), e)), }; Ok(Upgraded { upgrade, backup: Some(UpgradeBackup { - made: made.is_some(), - commit, + made: made.new, + commit: format!("local backup {}", made.number), head, }), head: s.head(), @@ -882,7 +807,6 @@ impl Backups { }) .await .unwrap_or_else(|_| Err(UpgradeFailed::stopped("the upgrade stopped".into()))); - let _ = self.note_locks(); match done { Ok(u) => { if let (Some(b), Some(up)) = (&u.backup, &u.upgrade) { @@ -904,7 +828,8 @@ impl Backups { if let Some(m) = &failed.made { self.record( json!({"kind": "commit", "why": "format_upgrade", "ok": true, - "commit": m.commit, "head": {"seq": m.head.0, "hash": m.head.1}}), + "commit": format!("local backup {}", m.number), + "head": {"seq": m.head.0, "hash": m.head.1}}), ); } let why = hide(&failed.why, &self.dir); @@ -916,8 +841,8 @@ impl Backups { /// Whether a drill is due (INVARIANT 5). pub async fn drill_due(&self) -> bool { - // Through the store first: books let go name no target, and their - // record isn't read for a timer. + // Through the store first: books let go name no destination, and + // their record isn't read for a timer. let named = self.named().await; if named.is_empty() || self.is_shut() { return false; @@ -927,7 +852,8 @@ impl Backups { named.iter().any(|n| drill_due(&n.key, &records, now)) } - /// Drill each target whose drill is due (INVARIANT 5), each recorded. + /// Drill each destination whose drill is due (INVARIANT 5), each + /// recorded. pub async fn drill(&self) { let _one = self.running.lock().await; if self.is_shut() || self.store.is_stopped() { @@ -936,43 +862,44 @@ impl Backups { let records = self.records(); let now = chrono::Utc::now(); for n in self.named().await { - if paused(&n.key, &records) || !drill_due(&n.key, &records, now) { + if !drill_due(&n.key, &records, now) { continue; } if self.hurried() { return; } + let Ok(dest) = n.dest.clone() else { + continue; + }; let Ok(step) = self.begin() else { return; }; - let git = self.hurried_git(); - let (dir, book, t) = (self.dir.clone(), self.book.clone(), n.target.clone()); + let ctx = self.hurried_ctx(); + let (dir, book) = (self.dir.clone(), self.book.clone()); let drilled = tokio::task::spawn_blocking(move || { let _step = step; - let scratch = ledger_store::ops::ops_dir(&dir).join(format!("drill-{}", t.kind())); + let scratch = ledger_store::ops::ops_dir(&dir).join("drill-folder"); let _ = std::fs::remove_dir_all(&scratch); - let git = git?; backup::drill( - &git, - &t, + &dest, &book, &dir.join(ledger_store::JOURNAL_FILE), &scratch, + &ctx, ) }) .await .unwrap_or(Err(BackupError::Damaged("the drill stopped".into()))); - let _ = self.note_locks(); match drilled { - // Stopped by a close (INVARIANT 11): neither a pass nor a - // failure, so nothing is said of the target; the drill is - // due again when the books next open. + // Stopped by a close (INVARIANT 10): neither a pass nor a + // failure, so nothing is said of the destination; the drill + // is due again when the books next open. Err(BackupError::Cancelled(_)) => {} Ok(head) => { - self.record(json!({"kind": "drill", "target": n.target.kind(), + self.record(json!({"kind": "drill", "target": "folder", "at": n.at, "key": n.key, "ok": true, "head": {"seq": head.0, "hash": head.1}})) } - Err(e) => self.record(json!({"kind": "drill", "target": n.target.kind(), + Err(e) => self.record(json!({"kind": "drill", "target": "folder", "at": n.at, "key": n.key, "ok": false, "error": e.to_string()})), } } @@ -986,7 +913,7 @@ impl Backups { .await .ok() .flatten() - .unwrap_or_else(|| standing_of(&[], &[], 0, chrono::Utc::now())) + .unwrap_or_else(|| standing_of(&[], &[], 0, chrono::Utc::now(), None)) } /// The standing, read from `store` (held by the caller: books.start). @@ -995,16 +922,21 @@ impl Backups { } } +/// The old backup history's folder in a book's folder: left alone. +const OLD_ARCHIVE_DIR: &str = "archive.git"; + fn standing(store: &ledger_store::Store, book: &str, dir: &Path) -> Status { let records = ledger_store::chain::read(&ledger_store::ops::ops_dir(dir).join(LOG_FILE), GENESIS) .map(|r| r.records) .unwrap_or_default(); + let old_remote = store.ledger().settings().backup_git_remote().is_some(); standing_of( - &targets(store, book), + &targets(store, book, dir), &records, store.head().0, chrono::Utc::now(), + Some(old_remote), ) } @@ -1013,22 +945,38 @@ fn standing_of( records: &[Map], head_seq: u64, now: chrono::DateTime, + old_remote: Option, ) -> Status { + let targets: Vec = named + .iter() + .map(|n| status_of("folder", &n.at, &n.key, n.sealed, records, head_seq, now)) + .collect(); + // The old forms, said until a backup has been made in the new one + // (INVARIANT 12). + let mut notes: Vec<&str> = Vec::new(); + if named.is_empty() { + notes.push(NONE_SET); + } + if old_remote == Some(true) { + notes.push(OLD_REMOTE); + } + let new_form_made = records.iter().any(|r| is(r, "push") && ok(r)); + let old_archive_at = records.iter().rposition(|r| is(r, "old_archive")); + if old_archive_at.is_some_and(|i| !records[i..].iter().any(|r| is(r, "push") && ok(r))) + && !new_form_made + { + notes.push(OLD_ARCHIVE); + } Status { head_seq, - note: named.is_empty().then(|| { - "no backups are set up: set backup.git_remote (a private repository) and backup.folder (a folder on another disk) with books.set_setting".to_string() - }), - targets: named - .iter() - .map(|n| status_of(n.target.kind(), &n.at, &n.key, records, head_seq, now)) - .collect(), + note: (!notes.is_empty()).then(|| notes.join(" ")), + targets, } } impl Status { - /// Whether the human should hear of it: none set up, or one stale, - /// failing, or failing its drill. + /// Whether the human should hear of it: none set up, an old form to + /// act on, or one stale, failing, or failing its drill. pub fn needs_attention(&self) -> bool { self.note.is_some() || self @@ -1112,17 +1060,6 @@ fn text_field(r: &Map, field: &str) -> Option { r.get(field).and_then(Value::as_str).map(str::to_string) } -/// Whether the target `key` is paused for books restored beside others -/// (INVARIANT 7). -fn paused(key: &str, records: &[Map]) -> bool { - records.iter().any(|r| { - is(r, "restored") - && r.get("paused") - .and_then(Value::as_array) - .is_some_and(|keys| keys.iter().any(|k| k.as_str() == Some(key))) - }) -} - /// Whether the target `key` took a backup of these books (INVARIANT 6). fn held_before(key: &str, records: &[Map]) -> bool { records.iter().any(|r| { @@ -1134,10 +1071,6 @@ fn held_before(key: &str, records: &[Map]) -> bool { }) } -/// What books restored beside others are told of the repository paused -/// for them. -pub const PAUSED: &str = "not backed up here: these books were restored as a copy of the books this repository keeps, and backing up here would stop theirs; name a repository of their own (backup.git_remote)"; - /// Whether the target `key`'s last push failed less than RETRY_AFTER ago. fn failed_lately( key: &str, @@ -1182,6 +1115,7 @@ fn status_of( kind: &str, at: &str, key: &str, + sealed: bool, records: &[Map], head_seq: u64, now: chrono::DateTime, @@ -1221,21 +1155,23 @@ fn status_of( .filter(|r| !ok(r)) .and_then(|r| text(r, "error")); let drill = records.iter().rfind(|r| is(r, "drill") && of(r, key)); - let paused = paused(key, records); + let disconnected = records + .iter() + .rfind(|r| is(r, "push") && of(r, key)) + .is_some_and(|r| { + !ok(r) && r.get("error_kind").and_then(Value::as_str) == Some("no_folder") + }); TargetStatus { target: kind.to_string(), at: at.to_string(), last_ok_at: last_ok.and_then(|i| text(&records[i], "ts")), through_seq, - stale: behind && old && head_seq > 0 && !paused, - last_error: if paused { - Some(PAUSED.to_string()) - } else { - last_error - }, + stale: behind && old && head_seq > 0, + last_error, last_drill_at: drill.and_then(|r| text(r, "ts")), drill_error: drill.filter(|r| !ok(r)).and_then(|r| text(r, "error")), - paused, + sealed, + disconnected, } } @@ -1248,11 +1184,11 @@ mod tests { let dir = Path::new("/home/u/.local/share/wanderbooks/books/acme"); assert_eq!( hide( - "fatal: '/home/u/.local/share/wanderbooks/books/acme/archive.git' and /home/u/.local/share/wanderbooks/run", + "cannot write '/home/u/.local/share/wanderbooks/books/acme/journal.jsonl' and /home/u/.local/share/wanderbooks/run", dir ), format!( - "fatal: 'the book's folder/archive.git' and {}/run", + "cannot write 'the book's folder/journal.jsonl' and {}/run", ledger_store::root::THE_ROOT ) ); @@ -1288,7 +1224,7 @@ mod tests { let now = chrono::Utc::now(); let r = |kind, ok, seq, ago| rec(now, kind, "k", ok, seq, ago); let st = |records: &[Map], head| { - status_of("folder", "f", "k", records, head, now) + status_of("folder", "f", "k", false, records, head, now) }; let day = chrono::Duration::hours(24); let hour = chrono::Duration::hours(1); @@ -1376,16 +1312,16 @@ mod tests { let now = chrono::Utc::now(); let day = chrono::Duration::hours(24); let hour = chrono::Duration::hours(1); - // git missing (say) from the first run on: never a push of its own. + // The books unreadable (say) from the first run on: never a write of its own. let failing = [ rec(now, "commit", "", false, 0, day + hour), rec(now, "commit", "", false, 0, hour), ]; - let t = status_of("folder", "f", "k", &failing, 3, now); + let t = status_of("folder", "f", "k", false, &failing, 3, now); assert_eq!(t.last_error.as_deref(), Some("commit failed")); assert!(t.stale, "{t:?}"); // Failing an hour only: said, not yet stale. - let t = status_of("folder", "f", "k", &failing[1..], 3, now); + let t = status_of("folder", "f", "k", false, &failing[1..], 3, now); assert_eq!( (t.last_error.as_deref(), t.stale), (Some("commit failed"), false) @@ -1397,7 +1333,7 @@ mod tests { ] .concat(); assert_eq!( - status_of("folder", "f", "k", &mended, 3, now).last_error, + status_of("folder", "f", "k", false, &mended, 3, now).last_error, None ); } @@ -1416,15 +1352,9 @@ mod tests { let same = [restored("held", &["k"])]; assert!(held_before("k", &same)); assert!(!held_before("new", &same)); - assert!(!paused("k", &same)); - // Others' (restored beside them): their repository is paused, said. - let beside = [restored("paused", &["r"])]; - assert!(paused("r", &beside)); - assert!(!paused("k", &beside)); + // Others' (restored under another id): no backup of theirs is held. + let beside = [restored("origin", &["other"])]; assert!(!held_before("r", &beside)); - let t = status_of("repository", "x", "r", &beside, 9, now); - assert_eq!(t.last_error.as_deref(), Some(PAUSED)); - assert!(!t.stale && t.paused); // A push of its own counts as held, too. assert!(held_before( "k", @@ -1448,7 +1378,7 @@ mod tests { rec(now, "commit", "", true, 3, day * 2), rec(now, "push", "k", false, 0, hour), ]; - let t = status_of("folder", "f", "k", &records, 3, now); + let t = status_of("folder", "f", "k", false, &records, 3, now); assert!(!t.stale, "{t:?}"); assert_eq!(t.last_error.as_deref(), Some("push failed")); // Holding the head: never stale; one behind since long: stale. @@ -1456,8 +1386,8 @@ mod tests { rec(now, "push", "k", true, 3, day * 3), rec(now, "push", "k", false, 0, day * 2), ]; - assert!(!status_of("folder", "f", "k", &held, 3, now).stale); - assert!(status_of("folder", "f", "k", &held, 4, now).stale); + assert!(!status_of("folder", "f", "k", false, &held, 3, now).stale); + assert!(status_of("folder", "f", "k", false, &held, 4, now).stale); } #[test] @@ -1515,6 +1445,7 @@ mod tests { "folder", "f", "k", + false, &[pushed.clone(), r("drill", false, hour)], 3, now, @@ -1525,6 +1456,7 @@ mod tests { "folder", "f", "k", + false, &[pushed, r("drill", false, hour), r("drill", true, hour)], 3, now, @@ -1543,7 +1475,8 @@ mod tests { last_error: None, last_drill_at: None, drill_error: None, - paused: false, + sealed: false, + disconnected: false, }; let status = |t: TargetStatus| Status { head_seq: 3, diff --git a/crates/ledger-mcp/src/local.rs b/crates/ledger-mcp/src/local.rs index 80b4e826..5df519dd 100644 --- a/crates/ledger-mcp/src/local.rs +++ b/crates/ledger-mcp/src/local.rs @@ -1585,7 +1585,8 @@ impl Books { replace, confirmed, expect_head, - } => self.restore(id, source, replace, confirmed, expect_head), + passphrase, + } => self.restore(id, source, replace, confirmed, expect_head, passphrase), Request::UpgradeFormat { id, passphrase } => self.upgrade_format(id, &passphrase), Request::OpenBook { id } => self.open_one(id), Request::CloseBook { id } => self.close_one(id), @@ -2092,19 +2093,11 @@ impl Books { }; // A run still going is stopped, and waited for: nothing of the // backups runs once this returns. - let left = backups.shut().await; + backups.shut().await; access.close(); uploads.close(); exports.close(); store.let_go().await; - // A git stopped at its bound that left locks in the owner's folder: - // said with the file, as the standing says it (ledger_store backup - // INVARIANT 5b), not only that the backup took too long. - let problem = match (problem, left.is_empty()) { - (problem, true) => problem, - (None, false) => Some(left.join("; ")), - (Some(why), false) => Some(format!("{why}; {}", left.join("; "))), - }; problem.map(|why| self.hide(why)) } @@ -2203,8 +2196,9 @@ impl Books { replace: bool, confirmed: bool, expect_head: Option<(u64, String)>, + passphrase: Option, ) -> Response { - // admin INVARIANT 3: never the root, nor the address given. + // admin INVARIANT 3: never the root, nor the place given. let said = |text: String| { let text = if source.chars().count() > 1 { text.replace(&source, "the backup given") @@ -2217,26 +2211,23 @@ impl Books { Ok(id) => id, Err(e) => return said(e.to_string()), }; - let git = match ledger_store::backup::Git::find() { - Ok(git) => git, - Err(e) => return said(e.to_string()), - }; + let from = std::path::PathBuf::from(&source); + let pass = passphrase.as_ref().map(|p| p.0.as_str()); // A preview only reports (whether books of that id exist among // what it says), so it changes nothing and takes no book's turn: a // close of this id never waits behind its clone and its queue for // the books lock (INVARIANT 10). Only the server's close stops it. if !confirmed { let stop = self.job("restore", &self.server_stop); - return match self - .root - .restore_preview_stoppable(&git, &source, &id, &stop) - { + return match self.root.restore_preview_stoppable(&from, pass, &id, &stop) { Ok(p) => Response::RestorePreview(admin::RestorePreview { head: p.head, blobs: p.blobs, vault_files: p.vault_files, exists: p.exists, origin: p.origin, + sealed: p.sealed, + passed_over: p.passed_over, }), Err(e) => said(e.to_string()), }; @@ -2291,7 +2282,7 @@ impl Books { } match self .root - .restore_stoppable(&git, &source, &id, &expect_head, replace, &stop) + .restore_stoppable(&from, pass, &id, &expect_head, replace, &stop) { Ok(r) => { // Restored: kept whether or not it opens; its backups told @@ -4319,24 +4310,19 @@ fn backup_due( after(s.target_failed_at).then_some("retry") } -/// Whether a run's every target holds the books: a target paused for -/// these books (restored as a copy of others) is no failure to try again. +/// Whether a run's every target holds the books: none failed, so none is +/// to be tried again. fn every_target_held(status: &crate::backup::Status) -> bool { - status - .targets - .iter() - .all(|t| t.paused || t.last_error.is_none()) + status.targets.iter().all(|t| t.last_error.is_none()) } /// Why the last backup at a close wasn't whole, if it wasn't: a target -/// that failed, or lacks the books' head (a target paused for books -/// restored as a copy of others is no failure). None when there is -/// nothing to say, or no target. +/// that failed, or lacks the books' head. None when there is nothing to +/// say, or no target. fn backup_incomplete(status: &crate::backup::Status) -> Option { let lacking: Vec = status .targets .iter() - .filter(|t| !t.paused) .filter_map(|t| match (&t.last_error, t.through_seq) { (Some(why), _) => Some(format!("{} failed: {why}", t.at)), (None, through) if through != Some(status.head_seq) => { @@ -4510,9 +4496,9 @@ mod tests { w.backed = Some(5); assert_eq!(backup_due(Some(&w), 5, at(9 + retry - 1), quiet), None); assert_eq!(backup_due(Some(&w), 5, at(9 + retry), quiet), Some("retry")); - // A paused target is no failure; another's error is. - let target = |paused: bool, error: Option<&str>| crate::backup::TargetStatus { - target: "repository".into(), + // A target's error is a failure to try again. + let target = |error: Option<&str>| crate::backup::TargetStatus { + target: "folder".into(), at: "x".into(), last_ok_at: None, through_seq: None, @@ -4520,20 +4506,18 @@ mod tests { last_error: error.map(str::to_string), last_drill_at: None, drill_error: None, - paused, + sealed: false, + disconnected: false, }; let status = |targets| crate::backup::Status { head_seq: 5, targets, note: None, }; - assert!(every_target_held(&status(vec![ - target(true, Some("paused")), - target(false, None) - ]))); + assert!(every_target_held(&status(vec![target(None), target(None)]))); assert!(!every_target_held(&status(vec![ - target(false, Some("no")), - target(false, None) + target(Some("no")), + target(None) ]))); assert!(every_target_held(&status(vec![]))); w.ran(5, Some(true), at(9 + retry)); @@ -5193,19 +5177,15 @@ mod tests { .unwrap() } - /// git, on the books' own archive: what it said. - fn archive_git(dir: &Path, args: &[&str]) -> String { - let out = std::process::Command::new("git") - .arg(format!( - "--git-dir={}", - // A canonical path on Windows carries `\\?\`, which git refuses. - ledger_store::root::plain_path(&dir.join("archive.git")).display() - )) - .args(args) - .output() - .unwrap(); - assert!(out.status.success(), "{out:?}"); - String::from_utf8(out.stdout).unwrap() + /// The books' own local backup, proven whole and built in a scratch + /// folder: the books as they were backed up. + fn local_backup(dir: &Path, tag: &str) -> ledger_store::backup::Verified { + let scratch = dir.join(format!("scratch-{tag}")); + let ctx = ledger_store::backup::Ctx::new(); + let found = + ledger_store::backup::find(&dir.join(ledger_store::backup::LOCAL_DIR), None, &ctx) + .expect("a local backup is there"); + ledger_store::backup::verify_found(&found, &scratch, true, &ctx).expect("it proves whole") } /// plan/served.md 3.9's `format_upgrade_waits_for_consent`, the @@ -5258,7 +5238,7 @@ mod tests { } assert_eq!(journal(), before); assert!( - !dir.join("archive.git").exists(), + !dir.join(ledger_store::backup::LOCAL_DIR).exists(), "no backup before consent" ); assert!(listed(&books, "acme").format_upgrade.is_some()); @@ -5296,20 +5276,15 @@ mod tests { ); assert_eq!(done.head.0, backup.head.0 + 1); // The backup: the books as they were, keys and all, the latest - // commit of their archive. + // of their local backup. + assert_eq!(backup.commit, "local backup 1"); + let kept = local_backup(&dir, "kept"); assert_eq!( - archive_git(&dir, &["rev-parse", "HEAD"]).trim(), - backup.commit - ); - assert_eq!( - archive_git(&dir, &["show", &format!("{}:journal.jsonl", backup.commit)]).as_bytes(), + std::fs::read(kept.tree.join(ledger_store::JOURNAL_FILE)).unwrap(), before.as_slice() ); assert_eq!( - archive_git( - &dir, - &["show", &format!("{}:keys/legacy.key", backup.commit)] - ), + std::fs::read_to_string(kept.tree.join("keys").join("legacy.key")).unwrap(), "ab".repeat(32) ); // Both on the backup record. @@ -5333,7 +5308,7 @@ mod tests { } assert_eq!(journal(), after); // Books this version made wait for nothing, and asking for their - // upgrade changes nothing of them: not even a backup repository. + // upgrade changes nothing of them: not even a local backup. create(&books, "beta"); assert_eq!(listed(&books, "beta").format_upgrade, None); let beta = books.root.book_dir(&BookId::parse("beta").unwrap()); @@ -5343,18 +5318,18 @@ mod tests { } other => panic!("{other:?}"), } - assert!(!beta.join("archive.git").exists(), "nothing was changed"); + assert!( + !beta.join(ledger_store::backup::LOCAL_DIR).exists(), + "nothing was changed" + ); } - /// The backup is trusted only once proven, and only the one just made: - /// an archive whose head names a branch other than the one a backup's - /// clone takes (a damaged archive) takes the new commit where no - /// clone finds it, so what is proven isn't what was made: nothing is - /// upgraded, and it is recorded. Once the archive is right, its latest - /// commit (which already holds the books) is proven and the upgrade - /// made. + /// The backup is trusted only once proven: a local backup that was + /// written and then damaged proves nothing whole, so nothing is + /// upgraded, and it is recorded. Once it is right, its latest (which + /// already holds the books) is proven and the upgrade made. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn no_upgrade_unless_the_backup_just_made_is_proven() { + async fn no_upgrade_unless_the_backup_is_proven() { let home = tempfile::tempdir().unwrap(); let books = books_in(home.path()); let dir = old_books(&books, "acme"); @@ -5366,17 +5341,27 @@ mod tests { }; let (d, s) = (dir.clone(), store.clone()); let first = tokio::task::spawn_blocking(move || { - let git = ledger_store::backup::Git::find().unwrap(); let head = s.with_store(|s| s.head()).unwrap(); - ledger_store::backup::commit(&git, &d, "acme", head).unwrap() + let cut = ledger_store::backup::Cut::take("acme", &d, head).unwrap(); + ledger_store::backup::write_local(&d, &cut, &ledger_store::backup::Ctx::new()).unwrap() }) .await + .unwrap(); + // Its journal piece is damaged, one byte. + let piece = std::fs::read_dir( + dir.join(ledger_store::backup::LOCAL_DIR) + .join("acme") + .join("journal"), + ) .unwrap() - .expect("a first backup"); - archive_git(&dir, &["symbolic-ref", "HEAD", "refs/heads/elsewhere"]); - // A second later: the commit made now, of the same files, isn't - // byte for byte the first (git dates commits to the second). - tokio::time::sleep(std::time::Duration::from_millis(1100)).await; + .next() + .unwrap() + .unwrap() + .path(); + let good = std::fs::read(&piece).unwrap(); + let mut bad = good.clone(); + bad[3] ^= 1; + std::fs::write(&piece, &bad).unwrap(); let before = std::fs::read(dir.join(ledger_store::JOURNAL_FILE)).unwrap(); match upgrade(&books, "acme", PASS).await { Response::Refused(why) => { @@ -5394,18 +5379,13 @@ mod tests { std::fs::read_to_string(ledger_store::ops::ops_dir(&dir).join(crate::backup::LOG_FILE)) .unwrap() }; - assert!( - record().contains(r#""why":"format_upgrade""#), - "the commit made: {}", - record() - ); assert!(record().contains(r#""ok":false"#), "{}", record()); - // The archive put right: its latest commit holds the books. - archive_git(&dir, &["symbolic-ref", "HEAD", "refs/heads/main"]); + // The piece put right: the backup proves, and the upgrade is made. + std::fs::write(&piece, &good).unwrap(); match upgrade(&books, "acme", PASS).await { Response::FormatUpgraded(u) => { let b = u.backup.clone().expect("proven"); - assert_eq!(b.commit, first.commit, "{u:?}"); + assert_eq!(b.commit, format!("local backup {}", first.number), "{u:?}"); assert_eq!(b.head, first.head); assert_eq!(u.head.0, first.head.0 + 1); } @@ -5422,8 +5402,9 @@ mod tests { let books = books_in(home.path()); let dir = old_books(&books, "acme"); ledger_store::passphrase::set(&books.root.auth_dir().unwrap(), PASS, None).unwrap(); - // A file no book keeps: the backup refuses it. - std::fs::write(dir.join(".gitattributes"), "* -text\n").unwrap(); + // A file where the local backup's folder goes: the backup can't be + // made. + std::fs::write(dir.join(ledger_store::backup::LOCAL_DIR), "x").unwrap(); let before = std::fs::read(dir.join(ledger_store::JOURNAL_FILE)).unwrap(); match upgrade(&books, "acme", PASS).await { Response::Refused(why) => { diff --git a/crates/ledger-mcp/src/tools/backup.rs b/crates/ledger-mcp/src/tools/backup.rs index 28a6b2f5..16dbbebf 100644 --- a/crates/ledger-mcp/src/tools/backup.rs +++ b/crates/ledger-mcp/src/tools/backup.rs @@ -1,11 +1,11 @@ -//! `books.backup` and `books.back_up_now` (plan 3.7, D-30): the books' +//! `books.backup` and `books.back_up_now` (plan 3.7, D-91): the books' //! backups as they stand, and one made now. //! //! ```text //! GOAL: the agent can tell the human whether the books are backed up, //! and back them up now when asked. //! SOURCE: plan 3.7 ("books.backup {status|run} reports it": two tools, -//! one read-only), D-30. +//! one read-only), D-91. //! INVARIANTS: //! 1. A status reads the backup record only; a run makes and pushes a //! backup (backup.rs) and answers the status after it. @@ -29,7 +29,7 @@ pub struct BackUpNowParams { #[derive(Debug, Serialize, JsonSchema)] pub struct TargetOut { - /// "repository" (the private repository) or "folder". + /// "folder". pub target: String, /// Where it is. pub at: String, @@ -42,12 +42,14 @@ pub struct TargetOut { /// Why its last backup failed, if it did. pub last_error: Option, /// When its backup was last proven restorable (UTC), if ever: each - /// is cloned and checked weekly. + /// is rebuilt and checked weekly. pub last_drill_at: Option, /// Why that check failed, if it did: tell the human. pub drill_error: Option, - /// Not backed up there: these books were restored as a copy of others. - pub paused: bool, + /// Protected by a passphrase. + pub sealed: bool, + /// Its disk isn't connected: tell the human to connect it. + pub disconnected: bool, } #[derive(Debug, Serialize, JsonSchema)] @@ -77,7 +79,8 @@ impl From for BackupOut { last_error: t.last_error, last_drill_at: t.last_drill_at, drill_error: t.drill_error, - paused: t.paused, + sealed: t.sealed, + disconnected: t.disconnected, }) .collect(), } @@ -89,7 +92,7 @@ impl BooksServer { #[tool( name = "books.backup", title = "Backups", - description = "Whether the books are backed up: each backup target the settings name (backup.git_remote, a private repository; backup.folder, a folder on another disk), when it last took the books, through which journal seq, and why it failed if it did. stale: it lacks the latest, and the first try to back that up was more than a day ago: tell the human. The books back themselves up a little after each change, when they open and before they close; books.back_up_now makes one now.", + description = "Whether the books are backed up: the backup folder the settings name (backup.folder: a folder on another disk, or one a sync service keeps), when it last took the books, through which journal seq, when it was last proven restorable, and why it failed if it did. stale: it lacks the latest, and the first try to back that up was more than a day ago: tell the human. disconnected: its disk isn't there. The books back themselves up a little after each change, when they open and before they close; books.back_up_now makes one now.", annotations(read_only_hint = true, open_world_hint = false) )] async fn backup(&self, _params: Parameters) -> Result, String> { @@ -99,7 +102,7 @@ impl BooksServer { #[tool( name = "books.back_up_now", title = "Back up now", - description = "Back the books up now to every target the settings name, and answer how each went (as books.backup). new_disk: true only when the human says the backup folder's disk is new: the books' backup is then begun there again. Needs books:admin.", + description = "Back the books up now to the backup folder the settings name, and answer how it went (as books.backup). new_disk: true only when the human says the backup folder's disk is new: the books' backup is then begun there again. Needs books:admin.", annotations( read_only_hint = false, destructive_hint = false, diff --git a/crates/ledger-store/src/backup.rs b/crates/ledger-store/src/backup.rs deleted file mode 100644 index 90977be2..00000000 --- a/crates/ledger-store/src/backup.rs +++ /dev/null @@ -1,3932 +0,0 @@ -//! Backups (plan 3.7, D-30, D-31): the book as it is, in git. Each book -//! keeps a bare repository, `archive.git`, whose commits are its journal, -//! its stored files, its vault and keys, and its access log as they were; -//! it is pushed to the owner's private repository and to a repository in -//! the owner's folder. Not encrypted (D-31): the destinations keep it -//! private. -//! -//! ```text -//! GOAL: a book's every write survives the loss of this computer, and a -//! backup is proven whole before it is trusted or restored. -//! SOURCE: plan 3.7 ("Each run: verifies the chain; commits the new -//! journal lines and blobs to archive.git; pushes to the -//! targets"; "Proven before use"; drills), D-30 (both targets), -//! D-31 (no encryption). The chain isn't verified at each run: the -//! server verifies it when it opens the books, every write after -//! goes through the store, and drills prove what reached each -//! target. -//! INVARIANTS: -//! 1. A commit holds exactly the files under the backed-up paths -//! (BACKED_UP) of the book's folder as they are at that moment: every -//! one, by name (checked against the folder after staging; no ignore -//! rule applies), and byte for byte (no attributes rule can reach it: -//! none of the owner's or the system's is read, the archive's own is -//! taken out, and a `.gitattributes` in the book's folder refuses the -//! backup). The caller holds the store's lock, so the journal is whole -//! lines and the vault matches it. A commit with nothing changed is -//! not made. -//! 2. A push only moves a target forward (fast-forward): one that has -//! diverged is reported, never forced. -//! 3. A backup is trusted only after it is cloned, its tree found to be -//! plain files under BACKED_UP only (no link, no submodule, nothing -//! else) before any of it is written out, its journal's chain -//! replayed, every stored file re-hashed, every TIN record the books -//! name present with the vault's key file, and its head found -//! equal to the one its commit records (`verify`); a drill also -//! checks its journal is a byte prefix of the live one. -//! 4. git runs with its configuration pinned where it matters: no system -//! config or attributes; no hooks, here or in a repository on this -//! computer it pushes to; no prompts, signing, ignore or attributes -//! files, file watchers or command-running transports; our own -//! identity, the files ref format. A repository on this computer is -//! pushed to or read only if plain: a bare repository at that very -//! path, nothing in it sending git elsewhere (a `.git`, `commondir`, -//! `gitdir`, objects borrowed from elsewhere, a link where it or its -//! own parts are, something beside it git would take instead), its configuration only -//! what `git init --bare` writes and where a copy of one came from; -//! and it is read as a far one is. A git -//! that says nothing for GIT_TIMEOUT is stopped with all it started. -//! What git said of itself is kept in whole lines; callers hide the -//! paths in it before an agent sees it (ledger-mcp backup.rs, -//! root.rs). None of ours starts another git to go on after it ends -//! (`gc.auto=0`, `maintenance.auto=false`): when a git of ours has -//! ended, nothing it began is still working. -//! 5. A git that is stopped (cancelled, or silent for GIT_TIMEOUT) is -//! stopped gently: SIGTERM to its whole process group first (git -//! removes the lock files it holds when it is sent one, and a push's -//! receiving end the objects it had not yet kept), up to TERM_GRACE -//! (5 s: git's handler takes milliseconds, so the grace is only for a -//! machine too loaded to schedule it) for the group to end, and only -//! then SIGKILL. So a lock left behind is the rare case, and there is -//! nothing to clean up in the usual one. (Windows has no signal to -//! send a group: the nearest thing the code has, `taskkill /T /F`, -//! ends the tree at once, and the rules below cover what is left.) -//! Once the stopped command is reaped AND every process it started is -//! gone (a killed process can still take a lock in its last -//! instructions, so the process group is waited for, GROUP_GONE_WAIT, -//! and nothing is looked at as left over while it isn't), the locks in -//! the repositories that command could write are dealt with, each -//! noted ([`LockNote`], for the caller's record). Each repository is -//! looked at as the command begins (its folder opened once, the locks -//! already there listed); "ours" is a lock that wasn't there then. -//! (A stopped `init` of the archive, or of a folder target's new -//! repository, is such a command too: its HEAD lock is dealt with -//! the same way.) -//! a. The book's own archive (`archive.git` in the book's folder, -//! private to this program): the locks of ours are removed once -//! the group is gone, each noted. Nothing else is removed from -//! it in a stop. At open (`clear_archive_locks`), and when a -//! backup begins, only a lock older than ARCHIVE_STALE (10 -//! minutes) is removed, each removal noted; a younger one is -//! left (the next backup tries again, and removes it once it is -//! old). Running git by hand inside the archive is unsupported: -//! only the store lock keeps another wanderbooks process out, and -//! what protects the archive from one that doesn't is that this -//! code never removes a lock younger than ARCHIVE_STALE except -//! one that its own stopped git made (a lock a person's git -//! holds that long is the person's to deal with). -//! b. A target on this computer (a folder, or a repository named by -//! a path): its git is our `receive-pack`, a child of the one -//! stopped. This program NEVER writes to, or deletes from, a -//! folder that is the owner's (an external disk, a synced folder -//! such as Syncthing's, shared with other computers and other -//! gits): only git itself does. A lock git left there when it -//! had to be killed, that wasn't there when the push began, is -//! left in place and reported with its whole path: a note -//! (`lock_left`), and [`BackupError::LockLeft`], which marks the -//! target's backup failed and names the files and what the owner -//! may do (remove them, only when nothing else is using the -//! backup folder). A lock that was there when the push began is -//! another's: untouched, and not named. A later backup that finds -//! the lock gone goes on normally. A repository far away (ssh, -//! https) is never looked at: its receiving end cleans up when -//! the connection ends. -//! c. No removal follows a path. A removal goes through the folder -//! handle opened and verified once, when the command began (it is -//! the archive in the book's folder, not a link; git_locks), never -//! follows a link, and removes only a regular file named as git -//! names its locks, in the places git puts them. -//! 6. A step that has to end when the books are let go (the caller's -//! cancel flag, [`Git::with_cancel`]) ends promptly, wherever it is, -//! and leaves nothing half-made: it looks for the flag between every -//! git command and phase of a verification (`clone`, `tree`, -//! `checkout`, `replay`, `verify`, `blobs`, `vault`, `prefix`), once -//! per file listed or hashed, once per chunk of the journal compared -//! and once per journal line replayed (cancel.rs); a git command -//! running is killed. A stopped drill or proof removes its scratch -//! clone (the one removal that is not itself stopped: it is as long -//! as the clone is big). The longest between two looks is one git -//! command's stop (SIGTERM and up to TERM_GRACE, then a kill, GROUP_GONE_WAIT), -//! one journal line, one file, or one 64 KiB chunk. -//! 7. What a git said is in hand as soon as it has ended and everything -//! it wrote has been read (drain.rs): to the end of its pipes, or, when -//! another process still holds a pipe open (Windows: a copy taken by a -//! process started at the same moment), to the point where the pipe -//! holds nothing; never for a fixed wait on a pipe that has no end -//! (10 s at most, as the last resort). With `WANDERBOOKS_GIT_TIMINGS` -//! set to a file, each command appends a line to it: how long it ran, -//! how long its pipes took to close, and how each ended. -//! ``` - -use std::path::{Path, PathBuf}; -use std::process::{Command, Stdio}; -use std::time::{Duration, Instant}; - -/// A book's backup repository, in its own folder. -pub const ARCHIVE_DIR: &str = "archive.git"; -/// What a backup holds, of a book's folder (INVARIANT 1). -pub const BACKED_UP: [&str; 5] = [ - crate::JOURNAL_FILE, - "blobs", - crate::root::VAULT_DIR, - crate::root::KEYS_DIR, - crate::access::ACCESS_FILE, -]; -/// The longest a git command may say nothing before it is stopped. -pub const GIT_TIMEOUT: Duration = Duration::from_secs(300); -/// How long a git that is to be stopped is given, after SIGTERM, to end -/// (and so remove its own lock files) before its whole process group is -/// killed (INVARIANT 5). Git's handler takes milliseconds; the grace is for -/// a machine so loaded that the handler is slow to be scheduled. It is -/// generous on purpose: a lock left in the owner's folder costs the owner a -/// step by hand, while a longer grace costs only a git that ignores SIGTERM. -pub const TERM_GRACE: Duration = Duration::from_secs(5); -/// How old a lock in the book's own archive must be, at open and when a -/// backup begins, before it is taken for a dead git's (INVARIANT 5a): a -/// younger one is left, and the next backup tries again. -pub const ARCHIVE_STALE: Duration = Duration::from_secs(600); - -/// How to get git on this system, in plain words (P15 C1, WB-pkg-4). The -/// program does not carry a git of its own: git is a separate program under -/// the GPL, and shipping one is the owner's decision (`docs/install.md`). -/// Until a person installs it, backups are off and the books work as ever. -pub fn how_to_get_git() -> &'static str { - if cfg!(windows) { - "Install Git for Windows from https://git-scm.com/download/win (or, in a terminal, run: winget install --id Git.Git -e), then try again." - } else if cfg!(target_os = "macos") { - "Open Terminal and run: xcode-select --install (a window asks to install Apple's command line tools, which include git; or run: brew install git), then try again." - } else { - "Install git with your system's package manager (for example: sudo apt install git, or sudo dnf install git, or sudo pacman -S git), then try again." - } -} - -/// Where Apple's developer tools keep a real git on a Mac: the command -/// line tools' folder and Xcode's. -const MAC_DEVELOPER_DIRS: [&str; 2] = [ - "/Library/Developer/CommandLineTools", - "/Applications/Xcode.app/Contents/Developer", -]; - -/// Whether `exe` is the stub macOS ships at `/usr/bin/git`: with no -/// developer tools installed (none of `developer_dirs` holds a -/// `usr/bin/git`) it is not git but a program that opens Apple's installer -/// dialog and fails, so it is not a git to run (a backup would otherwise -/// pop that dialog and report a failure with a stranger's words). -fn macos_git_stub(exe: &Path, developer_dirs: &[&Path]) -> bool { - exe == Path::new("/usr/bin/git") - && !developer_dirs - .iter() - .any(|dir| dir.join("usr/bin/git").is_file()) -} - -/// Why a backup couldn't be made, pushed or trusted. Never names a path of -/// the data root (INVARIANT 4). -#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] -pub enum BackupError { - /// git isn't installed. - #[error( - "git isn't installed, so backups are off until it is. {}", - how_to_get_git() - )] - NoGit, - /// A git command failed; what it said, in whole lines (paths in it are - /// the caller's to hide, INVARIANT 4). - #[error("git {0}: {1}")] - Git(String, String), - /// A git command ran past its time limit. - #[error("git {0} took too long and was stopped")] - TimedOut(String), - /// A git command stopped because the books it served were let go - /// ([`Git::with_cancel`]). - #[error("git {0} was stopped: the books are closing")] - Cancelled(String), - /// A git of ours was stopped while it was writing a backup folder (or a - /// repository on this computer), and left lock files there (every one - /// named, whole paths, separated by `, `), which this program never - /// removes from a place that is the owner's (INVARIANT 5b). - #[error( - "git was stopped while it was writing the backup, and left lock files in your backup folder: {0}. This program doesn't remove files from your backup folder. Remove those files (only those), and only when nothing else is using the backup folder (another computer, a sync program, git run by hand); the next backup then goes on" - )] - LockLeft(String), - /// A folder target that isn't there (an external disk not mounted). - #[error("the backup folder isn't there (is its disk connected?)")] - NoFolder, - /// A folder target 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 target moved on without us: never forced (INVARIANT 2). - #[error("the backup at {0} has changes this computer doesn't: it was not overwritten")] - Diverged(String), - /// A backup that isn't whole. - #[error("that backup can't be trusted: {0}")] - Damaged(String), - /// 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 { - BackupError::Io(e.kind()) - } -} - -/// A lock file a git left, as it was dealt with (INVARIANT 5): for the -/// caller's own record of the backup (never names a path of the data root: -/// the repository is `archive`, or the target's kind, and the lock is -/// named from the repository's own folder). -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct LockNote { - /// `archive`, `folder` or `repository`. - pub repo: &'static str, - /// The lock, as a path in the repository (`index.lock`, - /// `refs/heads/main.lock`). - pub lock: String, - /// Removed (the archive's, made by the git just stopped), or left. - pub removed: bool, - /// Why: what ended the git that made it, or why it was left. - pub why: &'static str, - /// For a lock left in a folder that is the owner's: its whole path, the - /// file the owner is told to remove (INVARIANT 5b). - pub path: Option, -} - -/// A watcher of a verification's phases ([`Git::with_phase_watch`]). -pub type PhaseWatch = std::sync::Arc; - -/// What a caller may watch of a git's work, and look at after it (tests, -/// and the server's record of a backup). -#[derive(Clone, Default)] -struct Watch { - /// Told the name of each phase of a verification as it begins. - phase: Option, - /// The lock files dealt with since the caller last took them. - notes: std::sync::Arc>>, -} - -impl std::fmt::Debug for Watch { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("Watch") - } -} - -/// Git for Windows' per-user install (no administrator needed): under the -/// account's local application data. -fn per_user_git_dirs() -> Vec { - if cfg!(windows) - && let Some(local) = std::env::var_os("LOCALAPPDATA") - { - return vec![Path::new(&local).join(r"Programs\Git\cmd")]; - } - Vec::new() -} - -/// The git program, found once. -#[derive(Debug, Clone)] -pub struct Git { - exe: PathBuf, - /// How long it may say nothing before it is stopped (GIT_TIMEOUT). - quiet: Duration, - /// Set by whoever serves the books when they are let go: a git - /// command running is stopped, with what it started, and none starts. - cancel: Option>, - /// How long a git that is to be stopped has to end after SIGTERM - /// before it is killed (TERM_GRACE). - term_grace: Duration, - watch: Watch, -} - -impl Git { - /// git, from the usual places (never the working directory). - pub fn find() -> Result { - let dirs = std::env::var_os("PATH") - .map(|p| std::env::split_paths(&p).collect::>()) - .unwrap_or_default(); - dirs.iter() - .chain( - [ - "/usr/bin", - "/bin", - "/usr/local/bin", - "/opt/homebrew/bin", - // Git for Windows' own folders (a host started clean - // has a short PATH). - r"C:\Program Files\Git\cmd", - r"C:\Program Files\Git\bin", - ] - .iter() - .map(PathBuf::from) - .collect::>() - .iter(), - ) - .chain(per_user_git_dirs().iter()) - .filter(|d| d.is_absolute()) - .map(|d| d.join(if cfg!(windows) { "git.exe" } else { "git" })) - .find(|p| { - p.is_file() - && !(cfg!(target_os = "macos") - && macos_git_stub(p, &MAC_DEVELOPER_DIRS.map(Path::new))) - }) - .map(|exe| Git { - exe, - quiet: GIT_TIMEOUT, - cancel: None, - term_grace: TERM_GRACE, - watch: Watch::default(), - }) - .ok_or(BackupError::NoGit) - } - - /// This git, given `grace` (not TERM_GRACE) to end after SIGTERM before - /// it is killed (a seam for tests). - #[must_use] - pub fn with_term_grace(mut self, grace: Duration) -> Self { - self.term_grace = grace; - self - } - - /// This git, stopped (every command running, and any that would - /// start) once `cancel` is set: how the server's close ends a backup - /// that is still going, instead of leaving it to run against books it - /// reported closed. - #[must_use] - pub fn with_cancel(mut self, cancel: std::sync::Arc) -> Self { - self.cancel = Some(cancel); - self - } - - fn cancelled(&self) -> bool { - self.cancel - .as_ref() - .is_some_and(|c| c.load(std::sync::atomic::Ordering::SeqCst)) - } - - /// Ok, or `Cancelled(what)` once this git was cancelled: looked at - /// between a step's phases and inside its loops over files, so a step - /// that is not running a git command ends as promptly as one that is - /// (INVARIANT 6). - fn check(&self, what: &str) -> Result<(), BackupError> { - if self.cancelled() { - Err(BackupError::Cancelled(what.to_string())) - } else { - Ok(()) - } - } - - /// This git, telling `watch` the name of each phase of a verification - /// as it begins (a seam for tests and for the server's own test knob - /// that makes a drill slow: `watch` may wait, but must give up when - /// the cancel flag is set). - #[must_use] - pub fn with_phase_watch(mut self, watch: PhaseWatch) -> Self { - self.watch.phase = Some(watch); - self - } - - /// This git, sharing `sink` for the lock files it deals with - /// (INVARIANT 5), which the caller takes with [`Self::take_lock_notes`]: - /// every git made from the same sink reports into it. - #[must_use] - pub fn with_lock_notes(mut self, sink: LockNotes) -> Self { - self.watch.notes = sink.0; - self - } - - /// The lock files dealt with since this was last called. - pub fn take_lock_notes(&self) -> Vec { - std::mem::take(&mut *self.watch.notes.lock().unwrap_or_else(|e| e.into_inner())) - } - - fn note(&self, note: LockNote) { - self.watch - .notes - .lock() - .unwrap_or_else(|e| e.into_inner()) - .push(note); - } - - fn phase(&self, name: &str) { - if let Some(watch) = &self.watch.phase { - watch(name); - } - } - - /// A git command with a clean configuration (INVARIANT 4). - fn command(&self) -> Command { - let mut c = Command::new(&self.exe); - c.env("GIT_CONFIG_NOSYSTEM", "1") - .env("GIT_ATTR_NOSYSTEM", "1") - .env("GIT_TERMINAL_PROMPT", "0") - .env("GIT_ASKPASS", "true") - .env_remove("GIT_DIR") - .env_remove("GIT_WORK_TREE") - .env_remove("GIT_INDEX_FILE") - .args([ - "-c", - "core.hooksPath=/dev/null", - "-c", - "commit.gpgsign=false", - "-c", - "user.name=wanderbooks", - "-c", - "user.email=backup@wanderbooks.invalid", - "-c", - "init.defaultBranch=main", - "-c", - "core.autocrlf=false", - // The owner's own ignore and attributes files never leave a - // file out of a backup or change its bytes; nothing runs - // to watch the files. - "-c", - "core.excludesFile=/dev/null", - "-c", - "core.attributesFile=/dev/null", - "-c", - "core.fsmonitor=false", - "-c", - "init.templateDir=", - "-c", - "init.defaultRefFormat=files", - "-c", - "init.defaultObjectFormat=sha1", - "-c", - "log.showSignature=false", - "-c", - "push.gpgSign=false", - // No git of ours starts another to go on after it ends - // (a detached `gc` would outlive a stopped backup and hold - // locks: INVARIANT 5). - "-c", - "gc.auto=0", - "-c", - "maintenance.auto=false", - // A link is never made from a backup's tree (verify - // refuses one before checkout, too). - "-c", - "core.symlinks=false", - // Only these ways of reaching a repository: never one that - // runs a command (ext::, fd::), whatever the owner's own - // configuration allows. - "-c", - "protocol.allow=never", - "-c", - "protocol.ext.allow=never", - "-c", - "protocol.fd.allow=never", - "-c", - "protocol.file.allow=always", - "-c", - "protocol.ssh.allow=always", - "-c", - "protocol.https.allow=always", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()); - c - } - - /// Run `args` (named `what` in errors): its output. Stopped, with every - /// process it started, once it has said nothing for GIT_TIMEOUT - /// (a push or a clone reports its progress as it goes). - fn run(&self, what: &str, args: &[&std::ffi::OsStr]) -> Result { - self.run_killed(what, args).0 - } - - /// [`Self::run`], and whether the command had to be killed (cancelled - /// or gone quiet) and what became of everything it started. - fn run_killed( - &self, - what: &str, - args: &[&std::ffi::OsStr], - ) -> (Result, Killed) { - let killed = std::cell::Cell::new(Killed::No); - let result = self.run_with(what, args, &killed); - (result, killed.get()) - } - - /// [`Self::run`] where every repository the command may write (its - /// `guards`) is looked at as the command begins, and has the locks it - /// left dealt with if the command was stopped, once all it started is - /// gone (INVARIANT 5). A stop that left a lock in the owner's folder is - /// said so: [`BackupError::LockLeft`]. - fn run_in( - &self, - what: &str, - args: &[&std::ffi::OsStr], - guards: &[&Watched], - ) -> Result { - let snaps: Vec = guards.iter().map(|g| g.snapshot()).collect(); - let (result, killed) = self.run_killed(what, args); - if killed != Killed::No { - let mut left = Vec::new(); - for (guard, snap) in guards.iter().zip(&snaps) { - left.extend(guard.after_kill(self, snap, killed == Killed::Gone)); - } - if matches!( - result, - Err(BackupError::Cancelled(_) | BackupError::TimedOut(_)) - ) && !left.is_empty() - { - return Err(BackupError::LockLeft(left.join(", "))); - } - } - result - } - - fn run_with( - &self, - what: &str, - args: &[&std::ffi::OsStr], - killed: &std::cell::Cell, - ) -> Result { - use std::sync::atomic::{AtomicU64, Ordering}; - if self.cancelled() { - return Err(BackupError::Cancelled(what.to_string())); - } - let mut c = self.command(); - // A path made canonical on Windows carries `\\?\`, which git refuses. - c.args(args.iter().map(|a| match a.to_str() { - Some(text) if text.contains(r"\\?\") => { - std::ffi::OsString::from(crate::root::without_extended_prefix(text)) - } - _ => (*a).to_os_string(), - })); - #[cfg(unix)] - { - use std::os::unix::process::CommandExt; - c.process_group(0); - } - let asked = Instant::now(); - let running = Running::begin(); - let mut child = crate::lock::spawn(&mut c).map_err(|e| match e.kind() { - std::io::ErrorKind::NotFound => BackupError::NoGit, - kind => BackupError::Io(kind), - })?; - let started = Instant::now(); - let spawn_took = started.duration_since(asked); - // Milliseconds since `started` when git last said anything. - let heard = std::sync::Arc::new(AtomicU64::new(0)); - // What it answers is kept whole (a listing of every file); what it - // says of itself, in part. - let stdout = - crate::drain::Drain::start(child.stdout.take(), usize::MAX, started, heard.clone()); - let stderr = - crate::drain::Drain::start(child.stderr.take(), OUTPUT_MAX, started, heard.clone()); - // Once git has ended normally, what it started is stopped (Unix: - // its group; Windows has no group to signal, and nothing is looked - // for: a process spawned per git call would cost more than the - // leftovers it could find). - #[cfg(unix)] - let kill_leftovers = |pid: u32| { - // SAFETY: kill has no preconditions; the group is git's own - // (process_group(0) above). - unsafe { - libc::kill(-(pid as libc::pid_t), libc::SIGKILL); - } - }; - #[cfg(windows)] - let kill_leftovers = |_: u32| {}; - let status = loop { - if let Some(status) = child.try_wait()? { - break status; - } - let quiet_for = started - .elapsed() - .saturating_sub(Duration::from_millis(heard.load(Ordering::Relaxed))); - if self.cancelled() { - killed.set(self.stop(&mut child)); - git_stopped(what, "cancelled", running.0, started.elapsed()); - return Err(BackupError::Cancelled(what.to_string())); - } - if quiet_for > self.quiet { - killed.set(self.stop(&mut child)); - git_stopped(what, "quiet", running.0, started.elapsed()); - return Err(BackupError::TimedOut(what.to_string())); - } - std::thread::sleep(Duration::from_millis(20)); - }; - let ran = started.elapsed(); - // What it started may still hold its pipes: not waited for. Once - // git has ended, what it wrote is in its pipes already; it is read - // to the pipes' end, or, when something else still holds them open - // (a copy a process started at the same moment took, on Windows), - // until nothing is left in them (drain.rs), never for the 10 s - // limit that stays only as the last resort. - kill_leftovers(child.id()); - let ended = Instant::now(); - let [(stdout, out_how), (stderr, err_how)] = - crate::drain::finish([&stdout, &stderr], ended, Duration::from_secs(10)); - git_timing(&GitTiming { - what, - first: args.first().map(|a| a.to_string_lossy().into_owned()), - exit: status - .code() - .map_or_else(|| "signal".to_string(), |c| c.to_string()), - running: running.0, - spawn_took, - ran, - pipes_took: ended.elapsed(), - out: (out_how, stdout.len()), - err: (err_how, stderr.len()), - }); - if status.success() { - Ok(String::from_utf8_lossy(&stdout).trim().to_string()) - } else { - let cut = stderr.len() >= OUTPUT_MAX; - Err(BackupError::Git(what.to_string(), said(&stderr, cut))) - } - } -} - -impl Git { - /// Stop a git that is running, and everything it started (INVARIANT 5): - /// SIGTERM to its process group first (git removes the lock files it - /// holds when it is sent one, and a push's receiving end the objects it - /// had not yet kept), then up to `term_grace` for the group to end, and - /// only then SIGKILL. The leader is reaped as the group is waited for - /// (a zombie is still in its group). What became of the group. - /// - /// Windows has no signal to send a group: the nearest thing the code has - /// is `taskkill /T /F`, which ends the tree at once, so there is no - /// grace there, and no reliance on git's own clean-up: the lock rules - /// (INVARIANT 5) cover what is left. - fn stop(&self, child: &mut std::process::Child) -> Killed { - #[cfg(unix)] - { - let pid = child.id(); - // SAFETY: kill has no preconditions; the group is git's own - // (process_group(0) when it was started). - unsafe { - libc::kill(-(pid as libc::pid_t), libc::SIGTERM); - } - let by = Instant::now() + self.term_grace; - loop { - let _ = child.try_wait(); - if group_empty(pid) { - return Killed::Gone; - } - if Instant::now() >= by { - break; - } - std::thread::sleep(Duration::from_millis(5)); - } - // SAFETY: as above. - unsafe { - libc::kill(-(pid as libc::pid_t), libc::SIGKILL); - } - let _ = child.kill(); - let _ = child.wait(); - group_gone(pid) - } - #[cfg(windows)] - { - let _ = crate::lock::spawn( - std::process::Command::new("taskkill") - .args(["/T", "/F", "/PID", &child.id().to_string()]) - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(Stdio::null()), - ) - .and_then(|mut k| k.wait()); - let _ = child.kill(); - let _ = child.wait(); - Killed::Gone - } - } -} - -/// Git commands of this process running now, for [`git_timing`]. -static RUNNING: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - -/// One running git command, counted from the moment it is asked for; `.0` -/// is how many (itself included) there were then. -struct Running(usize); - -impl Running { - fn begin() -> Running { - Running(RUNNING.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1) - } -} - -impl Drop for Running { - fn drop(&mut self) { - RUNNING.fetch_sub(1, std::sync::atomic::Ordering::SeqCst); - } -} - -/// What one git command did (see [`git_timing`]). -struct GitTiming<'a> { - what: &'a str, - first: Option, - exit: String, - running: usize, - spawn_took: Duration, - ran: Duration, - pipes_took: Duration, - out: (crate::drain::Closed, usize), - err: (crate::drain::Closed, usize), -} - -/// The file `WANDERBOOKS_GIT_TIMINGS` names, if it is set: every git -/// command of this process appends a line to it as it ends (a diagnostic -/// for the tests that run the server on a machine nobody can look at: how -/// long each command ran, and how long its pipes took to close after it -/// ended). Never set by the program itself. -fn timings_file() -> Option<&'static Path> { - static FILE: std::sync::OnceLock> = std::sync::OnceLock::new(); - FILE.get_or_init(|| { - std::env::var_os("WANDERBOOKS_GIT_TIMINGS") - .filter(|v| !v.is_empty()) - .map(PathBuf::from) - }) - .as_deref() -} - -fn timings_line(line: &str) { - use std::io::Write; - static BEGAN: std::sync::OnceLock = std::sync::OnceLock::new(); - let Some(file) = timings_file() else { - return; - }; - let at = BEGAN.get_or_init(Instant::now).elapsed().as_millis(); - if let Ok(mut f) = std::fs::OpenOptions::new() - .create(true) - .append(true) - .open(file) - { - let _ = writeln!(f, "+{at}ms {line}"); - } -} - -fn git_timing(t: &GitTiming<'_>) { - if timings_file().is_none() { - return; - } - timings_line(&format!( - "git {} {} exit={} running={} spawn={}ms ran={}ms pipes={}ms stdout={}:{}B stderr={}:{}B", - t.what, - t.first.as_deref().unwrap_or(""), - t.exit, - t.running, - t.spawn_took.as_millis(), - t.ran.as_millis(), - t.pipes_took.as_millis(), - t.out.0.word(), - t.out.1, - t.err.0.word(), - t.err.1, - )); -} - -fn git_stopped(what: &str, why: &str, running: usize, ran: Duration) { - timings_line(&format!( - "git {what} stopped={why} running={running} ran={}ms", - ran.as_millis() - )); -} - -/// The most kept of what a git says of itself. -const OUTPUT_MAX: usize = 1 << 20; - -/// What became of a git command that was killed. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Killed { - /// It ended by itself. - No, - /// Killed, and it and everything it started is gone. - Gone, - /// Killed, but something it started was still there when we stopped - /// looking (GROUP_GONE_WAIT). - Lingering, -} - -/// How long, after a git was killed, to wait for everything it started to -/// be gone. -pub const GROUP_GONE_WAIT: Duration = Duration::from_secs(2); - -/// Whether the process group `pid` led has no process left. -#[cfg(unix)] -fn group_empty(pid: u32) -> bool { - // SAFETY: signal 0 only asks whether a process is in the group. - let found = unsafe { libc::kill(-(pid as libc::pid_t), 0) }; - found != 0 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH) -} - -/// Wait until the process group `pid` led has no process left, for -/// GROUP_GONE_WAIT at most: a killed process can run a few more -/// instructions before the kernel takes it, and could take a lock in them. -fn group_gone(pid: u32) -> Killed { - #[cfg(unix)] - { - let by = Instant::now() + GROUP_GONE_WAIT; - loop { - if group_empty(pid) { - return Killed::Gone; - } - if Instant::now() >= by { - return Killed::Lingering; - } - std::thread::sleep(Duration::from_millis(5)); - } - } - #[cfg(windows)] - { - // taskkill /T /F ended the tree before it returned. - let _ = pid; - Killed::Gone - } -} - -/// A shared place for the lock files dealt with (see -/// [`Git::with_lock_notes`]). -#[derive(Clone, Default)] -pub struct LockNotes(std::sync::Arc>>); - -impl LockNotes { - /// What was dealt with since this was last called. - pub fn take(&self) -> Vec { - std::mem::take(&mut *self.0.lock().unwrap_or_else(|e| e.into_inner())) - } -} - -/// A repository a git command may leave locks in when it is stopped. -pub struct Watched { - dir: PathBuf, - /// `archive`, `folder` or `repository`. - kind: &'static str, -} - -/// A repository as it was when a command began: its folder opened once -/// (never again by its path: INVARIANT 5), and the locks already in it. -struct Snapshot { - handle: Option, - before: std::collections::BTreeSet, -} - -impl Watched { - /// The book's own archive, `dir` (`/archive.git`): private to - /// this program, one git of ours at a time. - fn archive(dir: &Path) -> Self { - Self { - dir: dir.to_path_buf(), - kind: "archive", - } - } - - /// A target repository on this computer, the owner's. - fn target(dir: &Path, kind: &'static str) -> Self { - Self { - dir: dir.to_path_buf(), - kind, - } - } - - fn is_archive(&self) -> bool { - self.kind == "archive" - } - - fn open(&self) -> std::io::Result { - if self.is_archive() { - match ( - self.dir.parent(), - self.dir.file_name().and_then(|n| n.to_str()), - ) { - (Some(book), Some(name)) => crate::git_locks::RepoDir::open_in(book, name), - _ => Err(std::io::ErrorKind::InvalidInput.into()), - } - } else { - crate::git_locks::RepoDir::open(&self.dir) - } - } - - /// Looked at as a command begins. - fn snapshot(&self) -> Snapshot { - let handle = self.open().ok(); - let before = handle - .as_ref() - .map(|h| h.locks().into_iter().map(|f| f.lock).collect()) - .unwrap_or_default(); - Snapshot { handle, before } - } - - /// The command was stopped. Once all it started is `gone`, deal with - /// the locks it left (INVARIANT 5): in the archive, remove those that - /// were not there when the command began; in the owner's folder remove - /// nothing, and say so. The whole paths of the locks left there. - fn after_kill(&self, git: &Git, snap: &Snapshot, gone: bool) -> Vec { - // A repository that didn't exist when the command began (a new - // target's, made by an `init` that was stopped) is looked at, never - // changed. The archive is only ever touched through the handle - // opened before the command. - let fresh; - let handle = match (&snap.handle, self.is_archive()) { - (Some(h), _) => h, - (None, true) => return Vec::new(), - (None, false) => match self.open() { - Ok(h) => { - fresh = h; - &fresh - } - Err(_) => return Vec::new(), - }, - }; - let mut left = Vec::new(); - for found in handle.locks() { - if snap.before.contains(&found.lock) { - continue; - } - let lock = found.lock; - if self.is_archive() { - if !gone { - git.note(LockNote { - repo: self.kind, - lock, - removed: false, - why: "what git started was still running", - path: None, - }); - } else if handle.remove(&lock).unwrap_or(false) { - git.note(LockNote { - repo: self.kind, - lock, - removed: true, - why: "git was stopped", - path: None, - }); - } - } else { - let path = handle.path().join(&lock).display().to_string(); - git.note(LockNote { - repo: self.kind, - lock, - removed: false, - why: if gone { - "git was stopped while it held it: the owner's folder is never changed by this program" - } else { - "what git started was still running" - }, - path: Some(path.clone()), - }); - left.push(path); - } - } - left - } -} - -/// The locks of the book's archive in `book_dir` that are older than -/// ARCHIVE_STALE, removed, each noted in `notes`; and, when `say_young`, -/// each younger one noted as left. The archive is opened once and only -/// regular files named as git names its locks are touched (INVARIANT 5a). -fn clear_stale_archive_locks( - book_dir: &Path, - removed_why: &'static str, - young: Option<&'static str>, - notes: &mut Vec, -) { - let Ok(handle) = crate::git_locks::RepoDir::open_in(book_dir, ARCHIVE_DIR) else { - return; - }; - let now = std::time::SystemTime::now(); - for found in handle.locks() { - let old = found - .modified - .and_then(|t| now.duration_since(t).ok()) - .is_some_and(|age| age >= ARCHIVE_STALE); - if old { - if handle.remove(&found.lock).unwrap_or(false) { - notes.push(LockNote { - repo: "archive", - lock: found.lock, - removed: true, - why: removed_why, - path: None, - }); - } - } else if let Some(why) = young { - notes.push(LockNote { - repo: "archive", - lock: found.lock, - removed: false, - why, - path: None, - }); - } - } -} - -/// The locks a git of ours left in the book's archive at an earlier time -/// (killed with the server, a power cut), for the caller to say it removed -/// them: those older than ARCHIVE_STALE are removed, younger ones are left -/// and noted as left (the next backup tries again, and removes them once -/// they are old). Call it while this process holds the book's store lock: -/// no other wanderbooks process runs git on the archive (INVARIANT 5a). -pub fn clear_archive_locks(book_dir: &Path) -> Vec { - let mut notes = Vec::new(); - clear_stale_archive_locks( - book_dir, - "found when the books opened, older than ten minutes", - Some("younger than ten minutes when the books opened: left, the next backup tries again"), - &mut notes, - ); - notes -} - -/// What git said when it failed: its messages without its progress, the -/// last whole lines of it (never a line cut part way, which could hide a -/// path from those who hide paths, INVARIANT 4); `cut` when only the last -/// of what it said was kept (its first line may be part of one). -fn said(stderr: &[u8], cut: bool) -> String { - let text = String::from_utf8_lossy(stderr); - let text = match (cut, text.find(['\r', '\n'])) { - (true, Some(at)) => &text[at + 1..], - (true, None) => "", - (false, _) => &text[..], - }; - let lines: Vec<&str> = text - .split(['\r', '\n']) - .map(str::trim) - .filter(|l| !l.is_empty() && !l.contains("% (") && !l.ends_with(", done.")) - .collect(); - let mut kept: Vec<&str> = Vec::new(); - let mut size = 0; - for line in lines.iter().rev() { - if line.len() > 1000 || size + line.len() > 1000 { - break; - } - size += line.len() + 1; - kept.push(line); - } - kept.reverse(); - kept.join("\n") -} - -/// One backup made: its commit and the journal head it holds. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Made { - /// The commit's id. - pub commit: String, - /// The journal's head it holds: seq and hash. - pub head: (u64, String), -} - -fn os(s: &str) -> &std::ffi::OsStr { - std::ffi::OsStr::new(s) -} - -/// The archive of the book in `book_dir`, made (bare, private) if missing. -/// No attributes rule of its own (which could change the bytes it keeps) -/// is ever left in it. -fn archive(git: &Git, book_dir: &Path) -> Result { - let dir = book_dir.join(ARCHIVE_DIR); - if !dir.join("HEAD").is_file() { - crate::root::private_book_folder(book_dir, ARCHIVE_DIR) - .map_err(|e| BackupError::Damaged(e.to_string()))?; - // A git killed in the middle of making it leaves HEAD's lock, which - // would stop every later `init` (INVARIANT 5). - git.run_in( - "init", - &[os("init"), os("--bare"), os("-q"), dir.as_os_str()], - &[&Watched::archive(&dir)], - )?; - } - let _ = std::fs::remove_file(dir.join("info").join("attributes")); - // Nor one in the book's folder: refused, never followed. - if book_dir.join(".gitattributes").exists() { - return Err(BackupError::Damaged( - "the book's folder holds a file (.gitattributes) no book keeps".into(), - )); - } - Ok(dir) -} - -/// Commit the book in `book_dir`, whose journal's head is `head`, to its -/// archive (INVARIANT 1): the commit, or None when nothing changed since -/// the last. The caller holds the store's lock while this runs. -pub fn commit( - git: &Git, - book_dir: &Path, - book: &str, - head: (u64, String), -) -> Result, BackupError> { - let archive = archive(git, book_dir)?; - clear_old_locks(git, book_dir); - let guard = Watched::archive(&archive); - let git_dir = format!("--git-dir={}", archive.display()); - let work_tree = format!("--work-tree={}", book_dir.display()); - let paths: Vec<&str> = BACKED_UP - .iter() - .copied() - .filter(|p| book_dir.join(p).exists()) - .collect(); - if !paths.is_empty() { - let mut add = vec![ - os(&git_dir), - os(&work_tree), - os("add"), - os("-A"), - os("-f"), - os("--"), - ]; - add.extend(paths.iter().map(|p| os(p))); - git.run_in("add", &add, &[&guard])?; - } - // What was backed up and is now gone altogether (a vault purged to - // nothing) goes from the next commit too. - let gone: Vec<&str> = BACKED_UP - .iter() - .copied() - .filter(|p| !book_dir.join(p).exists()) - .collect(); - if !gone.is_empty() { - let mut rm = vec![ - os(&git_dir), - os(&work_tree), - os("rm"), - os("-r"), - os("-q"), - os("--cached"), - os("--ignore-unmatch"), - os("--"), - ]; - rm.extend(gone.iter().map(|p| os(p))); - git.run_in("rm", &rm, &[&guard])?; - } - // Every file there is in it, nothing else (INVARIANT 1). - let listed = git.run( - "ls-files", - &[os(&git_dir), os(&work_tree), os("ls-files"), os("-z")], - )?; - let mut indexed: Vec = listed - .split('\0') - .filter(|p| !p.is_empty()) - .map(str::to_string) - .collect(); - indexed.sort(); - let mut on_disk = Vec::new(); - for p in &paths { - files_under(git, book_dir, Path::new(p), &mut on_disk)?; - } - on_disk.sort(); - if on_disk - .iter() - .any(|p| p.rsplit('/').next() == Some(".gitattributes")) - { - return Err(BackupError::Damaged( - "the book's folder holds a file (.gitattributes) no book keeps".into(), - )); - } - if indexed != on_disk { - return Err(BackupError::Damaged( - "the backup wouldn't hold the books exactly as they are".into(), - )); - } - let unchanged = git - .run( - "diff", - &[ - os(&git_dir), - os(&work_tree), - os("diff"), - os("--cached"), - os("--quiet"), - ], - ) - .is_ok(); - let has_commits = git - .run( - "rev-parse", - &[ - os(&git_dir), - os("rev-parse"), - os("-q"), - os("--verify"), - os("HEAD"), - ], - ) - .is_ok(); - if unchanged && has_commits { - return Ok(None); - } - // The books it holds by name too (a restore tells their own from - // others'). - let message = format!("seq {} head {}\n\nbook {book}", head.0, head.1); - git.run_in( - "commit", - &[ - os(&git_dir), - os(&work_tree), - os("commit"), - os("-q"), - os("--no-verify"), - os("--allow-empty"), - os("-m"), - os(&message), - ], - &[&guard], - )?; - let commit = git.run("rev-parse", &[os(&git_dir), os("rev-parse"), os("HEAD")])?; - Ok(Some(Made { commit, head })) -} - -/// Stage the book's stored files in its archive ahead of a commit, outside -/// the store's lock: they never change once written (named by their -/// hash), so the commit under the lock has only the new ones to read. -pub fn stage_blobs(git: &Git, book_dir: &Path) -> Result<(), BackupError> { - let blobs = crate::store::BLOBS_DIR; - if !book_dir.join(blobs).is_dir() { - return Ok(()); - } - let archive = archive(git, book_dir)?; - clear_old_locks(git, book_dir); - let guard = Watched::archive(&archive); - let git_dir = format!("--git-dir={}", archive.display()); - let work_tree = format!("--work-tree={}", book_dir.display()); - git.run_in( - "add", - &[ - os(&git_dir), - os(&work_tree), - os("add"), - os("-A"), - os("-f"), - os("--"), - os(blobs), - ], - &[&guard], - )?; - Ok(()) -} - -/// The locks a git left behind (the server killed, a power cut) would -/// refuse every later backup: those older than ARCHIVE_STALE are removed, -/// each noted, so none a git still at work holds is touched (INVARIANT 5a). -fn clear_old_locks(git: &Git, book_dir: &Path) { - let mut notes = Vec::new(); - clear_stale_archive_locks( - book_dir, - "older than ten minutes when a backup began", - None, - &mut notes, - ); - for note in notes { - git.note(note); - } -} - -/// Every file under `rel` in `base` (or `rel` itself), as paths relative to -/// `base` with `/` between their parts. -fn files_under( - git: &Git, - base: &Path, - rel: &Path, - out: &mut Vec, -) -> Result<(), BackupError> { - // Looked at once per entry: a folder of any size is left promptly - // (INVARIANT 6). - git.check("listing the files")?; - let full = base.join(rel); - let meta = std::fs::symlink_metadata(&full)?; - if meta.is_dir() { - for entry in std::fs::read_dir(&full)? { - files_under(git, base, &rel.join(entry?.file_name()), out)?; - } - } else { - let parts: Vec = rel - .components() - .map(|c| c.as_os_str().to_string_lossy().into_owned()) - .collect(); - out.push(parts.join("/")); - } - Ok(()) -} - -/// What `git init --bare` writes in a repository's configuration, and -/// nothing else a backup's repository may hold: a setting of its own (a -/// command to run, objects borrowed from elsewhere, a work tree to write) -/// could make a push or a clone do more than move the books. -const PLAIN_SETTINGS: [&str; 9] = [ - "core.repositoryformatversion", - "core.filemode", - "core.bare", - "core.logallrefupdates", - "core.ignorecase", - "core.precomposeunicode", - "core.symlinks", - "extensions.objectformat", - "extensions.refstorage", -]; - -/// Refuse the repository on this computer at `address` unless it is plain: -/// its configuration only what `git init --bare` writes, no objects of -/// another's. -fn plain_repository(git: &Git, address: &str) -> Result<(), BackupError> { - let dir = PathBuf::from(address.strip_prefix("file://").unwrap_or(address)); - let not_plain = || { - BackupError::Damaged( - "its repository holds settings of its own: back up to one made only for these books" - .into(), - ) - }; - // A bare repository right there, as git will find it: nothing that - // sends git somewhere else first (a .git in it, another repository's - // files named in it), and not a name git would look beside. - // git takes it as a repository (and so looks no further, beside it) - // only when it holds objects, refs and a HEAD naming one. - let head = std::fs::read_to_string(dir.join("HEAD")).unwrap_or_default(); - let head = head.trim(); - let names_one = head.strip_prefix("ref: refs/").is_some() - || (head.len() >= 40 && head.bytes().all(|b| b.is_ascii_hexdigit())); - if !names_one - || !dir.join("config").is_file() - || !dir.join("objects").is_dir() - || !dir.join("refs").is_dir() - { - return Err(BackupError::Damaged( - "that isn't a backup's repository: name the repository itself".into(), - )); - } - for elsewhere in [".git", "commondir", "gitdir"] { - if std::fs::symlink_metadata(dir.join(elsewhere)).is_ok() { - return Err(not_plain()); - } - } - // Nor a link where its own parts are (which would send what is - // written there elsewhere); the folder holding it may be one. - let trimmed = PathBuf::from( - address - .strip_prefix("file://") - .unwrap_or(address) - .trim_end_matches('/'), - ); - for part in [ - trimmed.clone(), - dir.join("HEAD"), - dir.join("config"), - dir.join("objects"), - dir.join("refs"), - ] { - if std::fs::symlink_metadata(&part).is_ok_and(|m| m.file_type().is_symlink()) { - return Err(not_plain()); - } - } - // Nor anything git would take in its place, beside it. - let bare = address - .strip_prefix("file://") - .unwrap_or(address) - .trim_end_matches('/'); - for beside in [".git", ".bundle"] { - if std::fs::symlink_metadata(format!("{bare}{beside}")).is_ok() { - return Err(not_plain()); - } - } - if dir.join("objects").join("info").join("alternates").exists() { - return Err(not_plain()); - } - let config = dir.join("config"); - let file = format!("--file={}", config.display()); - let names = git.run( - "config", - &[os("config"), os(&file), os("--list"), os("--name-only")], - )?; - // A copy made with `git clone --bare` also names where it came from: - // only that. - let plain = |name: &str| { - let name = name.trim().to_ascii_lowercase(); - let tail = |section: &str, keys: &[&str]| { - name.strip_prefix(section) - .and_then(|rest| rest.rsplit_once('.')) - .is_some_and(|(_, key)| keys.contains(&key)) - }; - PLAIN_SETTINGS.contains(&name.as_str()) - || tail("remote.", &["url", "fetch", "mirror"]) - || tail("branch.", &["remote", "merge"]) - // Made with `git init --bare --shared`: harmless. - || name == "core.sharedrepository" - || name == "receive.denynonfastforwards" - }; - if names.lines().any(|n| !plain(n)) { - return Err(not_plain()); - } - Ok(()) -} - -/// Whether git reads `address` as a repository on this computer (a path, -/// or `file://`), not one it reaches over the network (`ssh://`, -/// `https://`, or `host:path`). -pub fn is_local(address: &str) -> bool { - if let Some((scheme, _)) = address.split_once("://") { - return scheme == "file"; - } - match address.split_once(':') { - // host:path, where the host part holds no slash. - Some((host, _)) => host.contains('/'), - None => true, - } -} - -/// Where a backup goes (D-30). -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum Target { - /// The owner's private repository, as git names it. - Remote(String), - /// The owner's folder: a repository in it named `.git`. - Folder(PathBuf), -} - -impl Target { - /// Where the backup of the book `book` is, as git reads it. - pub fn source(&self, book: &str) -> String { - match self { - Target::Remote(url) => url.clone(), - Target::Folder(folder) => folder.join(format!("{book}.git")).display().to_string(), - } - } - - /// What it is called in records: "repository" or "folder". - pub fn kind(&self) -> &'static str { - match self { - Target::Remote(_) => "repository", - Target::Folder(_) => "folder", - } - } -} - -/// Push the archive of the book `book` in `book_dir` to `target` -/// (INVARIANT 2): the commit it now holds. -/// -/// A folder target's repository is made only when `may_create` (it never -/// took a backup): one that took backups and is gone is a disk not -/// connected (a mount point with nothing mounted on it), never made again -/// where the disk should be. -pub fn push( - git: &Git, - book_dir: &Path, - book: &str, - target: &Target, - may_create: bool, -) -> Result { - let archive = archive(git, book_dir)?; - let git_dir = format!("--git-dir={}", archive.display()); - let to = match target { - // Never read as an option, never a command (protocols, above). - Target::Remote(url) if url.starts_with('-') || url.trim().is_empty() => { - return Err(BackupError::Damaged( - "that isn't a repository address git takes".into(), - )); - } - Target::Remote(url) => url.clone(), - Target::Folder(folder) => { - if !folder.is_dir() { - return Err(BackupError::NoFolder); - } - let repo = folder.join(format!("{book}.git")); - if !repo.join("HEAD").is_file() { - if !may_create { - return Err(BackupError::NoBackupThere); - } - // The repository is new: any lock in it is ours, by the - // same rules as a push's (INVARIANT 5b). - git.run_in( - "init", - &[os("init"), os("--bare"), os("-q"), repo.as_os_str()], - &[&Watched::target(&repo, target.kind())], - )?; - } - repo.display().to_string() - } - }; - if matches!(target, Target::Folder(_)) || is_local(&to) { - plain_repository(git, &to)?; - } - // A repository on this computer is updated by a git we start, which - // doesn't get our configuration: told, in its own words, to run no - // hooks (a folder others can write could hold some). - let exe = git.exe.display().to_string(); - let receive = format!("--receive-pack='{exe}' -c core.hooksPath=/dev/null receive-pack"); - // Its progress keeps it from counting as stalled (Git::run). - let mut args = vec![ - os(&git_dir), - os("push"), - os("--progress"), - os("--no-verify"), - ]; - if matches!(target, Target::Folder(_)) || is_local(&to) { - if exe.contains('\'') { - return Err(BackupError::Damaged( - "git is installed where its hooks can't be turned off (a quote in its path)".into(), - )); - } - args.push(os(&receive)); - } - args.extend([os(&to), os("HEAD:refs/heads/main")]); - // The repositories this push may leave a lock in if it is killed: the - // archive, and the target if it is on this computer (one far away - // cleans up after its own connection's end, and isn't ours to touch). - let mine = Watched::archive(&archive); - let theirs = (matches!(target, Target::Folder(_)) || is_local(&to)).then(|| { - Watched::target( - Path::new(to.strip_prefix("file://").unwrap_or(&to)), - target.kind(), - ) - }); - let mut guards = vec![&mine]; - guards.extend(theirs.as_ref()); - match git.run_in("push", &args, &guards) { - Ok(_) => {} - Err(BackupError::Git(_, said)) - if said.contains("non-fast-forward") - || said.contains("[rejected]") - || said.contains("fetch first") => - { - return Err(BackupError::Diverged(match target { - Target::Remote(url) => url.clone(), - Target::Folder(_) => "the backup folder".to_string(), - })); - } - Err(e) => return Err(e), - } - git.run("rev-parse", &[os(&git_dir), os("rev-parse"), os("HEAD")]) -} - -/// A backup proven whole (INVARIANT 3). -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Verified { - /// Its journal's head: seq and hash. - pub head: (u64, String), - /// Stored files re-hashed. - pub blobs: u64, - /// Where it was cloned (the caller's scratch folder), its working tree - /// the book as it was. - pub tree: PathBuf, - /// The id of the books it holds, as their last backup named them. - pub book: Option, -} - -/// Clone the backup at `source` (a repository's address, or its folder: -/// `.git` in a backup folder) -/// into `scratch` (a new folder) and prove it whole (INVARIANT 3). -pub fn verify(git: &Git, source: &str, scratch: &Path) -> Result { - if scratch.exists() { - return Err(BackupError::Damaged("its scratch folder is in use".into())); - } - // One on this computer is read as one far away would be (so it reports - // its progress), once it is known to run nothing of its own. - if is_local(source) { - plain_repository(git, source)?; - } - // Stops at its next step once the books are let go (cancel.rs); what - // it had cloned is the caller's scratch folder, removed by the caller. - let _stoppable = git.cancel.clone().map(crate::cancel::scope); - let store_err = |e: crate::StoreError| match e { - crate::StoreError::Cancelled => BackupError::Cancelled("verifying".into()), - e => BackupError::Damaged(e.to_string()), - }; - git.phase("clone"); - git.check("clone")?; - git.run( - "clone", - &[ - os("clone"), - os("--progress"), - os("--no-local"), - os("--no-checkout"), - os("--branch"), - os("main"), - os("--"), - os(source), - scratch.as_os_str(), - ], - )?; - git.phase("tree"); - let git_dir = format!("--git-dir={}", scratch.join(".git").display()); - // Its tree before any of it is written out: plain files, only where a - // book keeps what is backed up. A link or a submodule (which could - // point the checkout, or the store opened on it, anywhere) or anything - // else is refused. - let listed = git.run( - "ls-tree", - &[ - os(&git_dir), - os("ls-tree"), - os("-r"), - os("-z"), - os("--full-tree"), - os("HEAD"), - ], - )?; - for entry in listed.split('\0').filter(|e| !e.is_empty()) { - git.check("reading its tree")?; - let (meta, path) = entry.split_once('\t').unwrap_or((entry, "")); - let mode = meta.split(' ').next().unwrap_or(""); - let top = path.split('/').next().unwrap_or(""); - if !["100644", "100755"].contains(&mode) || !BACKED_UP.contains(&top) { - return Err(BackupError::Damaged(format!( - "it holds {path:?}, which no book keeps" - ))); - } - } - git.phase("checkout"); - let work_tree = format!("--work-tree={}", scratch.display()); - git.run( - "checkout", - &[ - os(&git_dir), - os(&work_tree), - os("checkout"), - os("-q"), - os("-f"), - os("main"), - ], - )?; - git.phase("replay"); - let mut store = crate::Store::open(scratch).map_err(store_err)?; - git.phase("verify"); - store.verify_and_heal().map_err(store_err)?; - git.phase("blobs"); - let blobs = store.verify_blobs().map_err(store_err)?; - let head = store.head(); - // Every TIN record the books name is there, and the key that opens - // them. - let named: 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); - git.phase("vault"); - if !named.is_empty() { - use sha2::{Digest, Sha256}; - let vault = scratch.join(crate::root::VAULT_DIR); - let mut held = std::collections::BTreeSet::new(); - if vault.is_dir() { - for f in std::fs::read_dir(&vault)? { - git.check("reading its vault")?; - held.insert(hex::encode(Sha256::digest(std::fs::read(f?.path())?))); - } - } - if let Some(missing) = named.iter().find(|h| !held.contains(*h)) { - return Err(BackupError::Damaged(format!( - "a TIN record the books name isn't in it ({})", - &missing[..12.min(missing.len())] - ))); - } - let key = scratch - .join(crate::root::KEYS_DIR) - .join(crate::root::LEGACY_KEY_FILE); - if !key.is_file() { - return Err(BackupError::Damaged( - "its TIN records are in it, but not the key that opens them".into(), - )); - } - } - // The head the backup records: its commit says "seq N head H". - let recorded = git.run( - "log", - &[os(&git_dir), os("log"), os("-1"), os("--format=%s")], - )?; - if recorded.trim() != format!("seq {} head {}", head.0, head.1) { - return Err(BackupError::Damaged(format!( - "its journal ends at event {}, but the backup records another head", - head.0 - ))); - } - let body = git.run( - "log", - &[os(&git_dir), os("log"), os("-1"), os("--format=%b")], - )?; - let book = body - .lines() - .find_map(|l| l.trim().strip_prefix("book ")) - .map(str::to_string); - Ok(Verified { - head, - blobs, - tree: scratch.to_path_buf(), - book, - }) -} - -/// A restore drill (INVARIANT 3): the backup of the book `book` at -/// `target` cloned into `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( - git: &Git, - target: &Target, - book: &str, - live: &Path, - scratch: &Path, -) -> Result<(u64, String), BackupError> { - if let Target::Folder(folder) = target - && !folder.is_dir() - { - return Err(BackupError::NoFolder); - } - let checked = verify(git, &target.source(book), scratch).and_then(|v| { - git.phase("prefix"); - match is_prefix_with(live, &v.tree.join(crate::JOURNAL_FILE), || { - git.check("comparing journals") - }) { - 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 archive holds the book in `book_dir` exactly as it -/// is now, its journal's head `head` (INVARIANT 3, and more): the archive -/// cloned into `scratch` (a new folder, removed after) and proven whole as -/// a restore proves a backup, its head `head`, its journal the book's byte -/// for byte, and its TIN 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_archive( - git: &Git, - book_dir: &Path, - head: &(u64, String), - scratch: &Path, -) -> Result { - let archive = book_dir.join(ARCHIVE_DIR); - let source = archive.display().to_string(); - let proven = verify(git, &source, scratch).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 - ))); - } - if std::fs::read(book_dir.join(crate::JOURNAL_FILE))? - != std::fs::read(v.tree.join(crate::JOURNAL_FILE))? - { - return Err(BackupError::Damaged( - "its journal isn't the books' own, byte for byte".into(), - )); - } - git.phase("compare"); - git.check("comparing")?; - for kept in [crate::root::VAULT_DIR, crate::root::KEYS_DIR] { - if held_files(git, book_dir, kept)? != held_files(git, &v.tree, 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" - } - ))); - } - } - let git_dir = format!("--git-dir={}", v.tree.join(".git").display()); - let commit = git.run("rev-parse", &[os(&git_dir), os("rev-parse"), os("HEAD")])?; - Ok(Proven { - head: v.head, - blobs: v.blobs, - commit, - }) - }); - let _ = std::fs::remove_dir_all(scratch); - proven -} - -/// The book's archive proven to hold the book as it is ([`prove_archive`]). -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Proven { - /// The journal's head it holds: the book's. - pub head: (u64, String), - /// Stored files re-hashed. - pub blobs: u64, - /// The commit proven: the archive's latest. - pub commit: String, -} - -/// Every file under `rel` in `base`, by its path there, with its bytes -/// (none when `rel` isn't there). -fn held_files(git: &Git, base: &Path, rel: &str) -> Result)>, BackupError> { - if std::fs::symlink_metadata(base.join(rel)).is_err() { - return Ok(Vec::new()); - } - let mut names = Vec::new(); - files_under(git, base, Path::new(rel), &mut names)?; - names.sort(); - names - .into_iter() - .map(|n| { - git.check("reading the files")?; - let bytes = std::fs::read(base.join(&n))?; - Ok((n, bytes)) - }) - .collect() -} - -/// 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) -> std::io::Result { - is_prefix_with(live, backup, || Ok(())).map_err(|e| match e { - BackupError::Io(kind) => std::io::Error::from(kind), - other => std::io::Error::other(other.to_string()), - }) -} - -/// [`is_prefix`], asking `each` before every chunk read (a step that has -/// to stop looks for its stop there, INVARIANT 6). -fn is_prefix_with( - live: &Path, - backup: &Path, - mut each: impl FnMut() -> Result<(), BackupError>, -) -> Result { - use std::io::Read; - 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 { - each()?; - 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); - } - } -} - -#[cfg(all(test, unix))] -mod tests { - use super::*; - use crate::Store; - use ledger_core::{AccountType, Currency, Money, Side}; - - fn usd(s: &str) -> Money { - Money::new(s.parse().unwrap(), Currency::USD) - } - - /// WB-pkg-4: with no git a backup says how to get one, in words for - /// this system, and names no path of the data root. - #[test] - fn a_missing_git_says_how_to_get_it() { - let said = BackupError::NoGit.to_string(); - assert!(said.contains("git isn't installed"), "{said}"); - assert!(said.contains("backups are off until it is"), "{said}"); - assert!(said.ends_with(how_to_get_git()), "{said}"); - let how = how_to_get_git(); - if cfg!(windows) { - assert!( - how.contains("git-scm.com") && how.contains("winget"), - "{how}" - ); - } else if cfg!(target_os = "macos") { - assert!(how.contains("xcode-select --install"), "{how}"); - } else { - assert!(how.contains("package manager"), "{how}"); - } - assert!(how.ends_with("try again."), "{how}"); - } - - /// macOS's `/usr/bin/git` is a stub until the developer tools are - /// installed: it is no git, and nothing else is taken for one. - #[test] - fn the_mac_stub_is_not_a_git_until_the_developer_tools_are_there() { - let dir = tempfile::tempdir().unwrap(); - let tools = dir.path().join("CommandLineTools"); - let stub = Path::new("/usr/bin/git"); - assert!(macos_git_stub(stub, &[tools.as_path()]), "no tools yet"); - std::fs::create_dir_all(tools.join("usr/bin")).unwrap(); - std::fs::write(tools.join("usr/bin/git"), b"").unwrap(); - assert!(!macos_git_stub(stub, &[tools.as_path()]), "tools installed"); - // Any other git is never the stub. - assert!(!macos_git_stub( - Path::new("/opt/homebrew/bin/git"), - &[dir.path()] - )); - } - - /// 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 - } - - #[test] - fn a_backup_is_the_book_and_proves_whole() { - let git = Git::find().expect("git is installed"); - let dir = tempfile::tempdir().unwrap(); - let b = dir.path().join("book"); - let mut s = book(&b); - let made = commit(&git, &b, "acme", s.head()) - .unwrap() - .expect("a first backup"); - assert_eq!(made.head, s.head()); - // Nothing new: no commit. - assert_eq!(commit(&git, &b, "acme", s.head()).unwrap(), None); - // To a folder, then proven from it. - let folder = dir.path().join("disk"); - std::fs::create_dir(&folder).unwrap(); - let target = Target::Folder(folder.clone()); - assert_eq!(push(&git, &b, "acme", &target, true).unwrap(), made.commit); - let v = verify( - &git, - folder.join("acme.git").to_str().unwrap(), - &dir.path().join("v1"), - ) - .unwrap(); - assert_eq!(v.head, s.head()); - assert_eq!(v.blobs, 1); - assert!( - is_prefix( - &b.join(crate::JOURNAL_FILE), - &v.tree.join(crate::JOURNAL_FILE) - ) - .unwrap() - ); - // More writes: a new commit, pushed forward. - s.add_account("6000", "Supplies", AccountType::Expense, None, false) - .unwrap(); - let next = commit(&git, &b, "acme", s.head()).unwrap().unwrap(); - assert_ne!(next.commit, made.commit); - push(&git, &b, "acme", &target, true).unwrap(); - let v2 = verify( - &git, - folder.join("acme.git").to_str().unwrap(), - &dir.path().join("v2"), - ) - .unwrap(); - assert_eq!(v2.head, s.head()); - // The older backup is a prefix of the live journal; the live one is - // not a prefix of the older. - assert!( - is_prefix( - &b.join(crate::JOURNAL_FILE), - &v.tree.join(crate::JOURNAL_FILE) - ) - .unwrap() - ); - assert!( - !is_prefix( - &v.tree.join(crate::JOURNAL_FILE), - &b.join(crate::JOURNAL_FILE) - ) - .unwrap() - ); - // The database, its lock and the side channels aren't backed up. - let listed = git - .run( - "ls-tree", - &[ - os(&format!("--git-dir={}", b.join(ARCHIVE_DIR).display())), - os("ls-tree"), - os("--name-only"), - os("HEAD"), - ], - ) - .unwrap(); - let mut names: Vec<&str> = listed.lines().collect(); - names.sort(); - assert_eq!(names, ["blobs", crate::JOURNAL_FILE]); - } - - #[test] - fn a_folder_targets_hooks_never_run() { - use std::os::unix::fs::PermissionsExt; - let git = Git::find().expect("git is installed"); - let dir = tempfile::tempdir().unwrap(); - let b = dir.path().join("book"); - let s = book(&b); - commit(&git, &b, "acme", s.head()).unwrap(); - let folder = dir.path().join("disk"); - let repo = folder.join("acme.git"); - std::fs::create_dir(&folder).unwrap(); - git.run( - "init", - &[os("init"), os("--bare"), os("-q"), repo.as_os_str()], - ) - .unwrap(); - let ran = dir.path().join("ran"); - std::fs::create_dir_all(repo.join("hooks")).unwrap(); - for hook in ["pre-receive", "update", "post-receive", "post-update"] { - let h = repo.join("hooks").join(hook); - std::fs::write( - &h, - format!("#!/bin/sh\necho {hook} >> '{}'\n", ran.display()), - ) - .unwrap(); - std::fs::set_permissions(&h, std::fs::Permissions::from_mode(0o755)).unwrap(); - } - // As a folder, and named as a repository by its path. - push(&git, &b, "acme", &Target::Folder(folder.clone()), true).unwrap(); - push( - &git, - &b, - "acme", - &Target::Remote(repo.display().to_string()), - true, - ) - .unwrap(); - assert!( - !ran.exists(), - "a hook ran: {:?}", - std::fs::read_to_string(&ran) - ); - let v = verify(&git, repo.to_str().unwrap(), &dir.path().join("v")).unwrap(); - assert_eq!(v.head, s.head()); - } - - #[test] - fn a_target_that_moved_on_is_never_overwritten() { - let git = Git::find().expect("git is installed"); - let dir = tempfile::tempdir().unwrap(); - let folder = dir.path().join("disk"); - std::fs::create_dir(&folder).unwrap(); - let target = Target::Folder(folder.clone()); - // Two books of the same id push to one folder: the second has its - // own history, which isn't the first's. - let one = dir.path().join("one"); - let s = book(&one); - commit(&git, &one, "acme", s.head()).unwrap(); - push(&git, &one, "acme", &target, true).unwrap(); - let two = dir.path().join("two"); - let mut s2 = book(&two); - s2.add_account("6000", "Supplies", AccountType::Expense, None, false) - .unwrap(); - commit(&git, &two, "acme", s2.head()).unwrap(); - let e = push(&git, &two, "acme", &target, true).unwrap_err(); - assert!(matches!(e, BackupError::Diverged(_)), "{e}"); - // The folder still holds the first's. - let v = verify( - &git, - folder.join("acme.git").to_str().unwrap(), - &dir.path().join("v"), - ) - .unwrap(); - assert_eq!(v.head, s.head()); - } - - #[test] - fn a_missing_folder_or_a_strange_address_is_said_plainly() { - let git = Git::find().expect("git is installed"); - let dir = tempfile::tempdir().unwrap(); - let b = dir.path().join("book"); - let s = book(&b); - commit(&git, &b, "acme", s.head()).unwrap(); - let e = push( - &git, - &b, - "acme", - &Target::Folder(dir.path().join("unplugged")), - true, - ) - .unwrap_err(); - assert_eq!(e, BackupError::NoFolder); - // Never read as an option, never empty: refused before git runs. - for url in ["--upload-pack=touch /x", "-x", "", " "] { - let e = push(&git, &b, "acme", &Target::Remote(url.into()), true).unwrap_err(); - assert!(matches!(e, BackupError::Damaged(_)), "{url}: {e}"); - } - // Never a command. - assert!( - push( - &git, - &b, - "acme", - &Target::Remote("ext::sh -c 'touch x'".into()), - true - ) - .is_err() - ); - assert!(!Path::new("x").exists()); - // A source that isn't a backup can't be trusted. - let e = verify( - &git, - dir.path().join("nothing").to_str().unwrap(), - &dir.path().join("v"), - ) - .unwrap_err(); - assert!(e.to_string().contains("name the repository itself"), "{e}"); - let e = verify( - &git, - "ssh://nowhere.invalid/books.git", - &dir.path().join("v"), - ) - .unwrap_err(); - assert!(matches!(e, BackupError::Git(..)), "{e}"); - let text = e.to_string(); - assert!(!text.contains(&b.display().to_string()), "{text}"); - } - - #[test] - fn no_ignore_rule_leaves_a_file_out() { - let git = Git::find().expect("git is installed"); - let dir = tempfile::tempdir().unwrap(); - let b = dir.path().join("book"); - let s = book(&b); - for (d, f) in [ - (crate::root::VAULT_DIR, "tin-1.bin"), - (crate::root::KEYS_DIR, "legacy.key"), - ] { - std::fs::create_dir(b.join(d)).unwrap(); - std::fs::write(b.join(d).join(f), b"x").unwrap(); - } - commit(&git, &b, "acme", s.head()).unwrap(); - // Ignore rules where git looks for them, as a template or a hand - // might leave them. - std::fs::create_dir_all(b.join(ARCHIVE_DIR).join("info")).unwrap(); - std::fs::write( - b.join(ARCHIVE_DIR).join("info").join("exclude"), - "*.key\n*.bin\nblobs/\n", - ) - .unwrap(); - std::fs::write(b.join(crate::root::VAULT_DIR).join("tin-2.bin"), b"y").unwrap(); - commit(&git, &b, "acme", s.head()) - .unwrap() - .expect("the new record is a change"); - let listed = git - .run( - "ls-tree", - &[ - os(&format!("--git-dir={}", b.join(ARCHIVE_DIR).display())), - os("ls-tree"), - os("-r"), - os("--name-only"), - os("HEAD"), - ], - ) - .unwrap(); - for want in [ - "keys/legacy.key", - "vault/tin-1.bin", - "vault/tin-2.bin", - crate::JOURNAL_FILE, - ] { - assert!(listed.lines().any(|l| l == want), "{want}: {listed}"); - } - assert!(listed.lines().any(|l| l.starts_with("blobs/")), "{listed}"); - } - - #[test] - fn what_git_said_keeps_whole_lines_and_drops_its_progress() { - let text = b"Counting objects: 100% (3/3), done.\rWriting objects: 50% (1/2)\r\nfatal: '/root/books/acme' is not a repository\n"; - assert_eq!( - said(text, false), - "fatal: '/root/books/acme' is not a repository" - ); - // A line too long to keep whole is left out, never cut. - let long = format!("fatal: {}\nerror: short\n", "x".repeat(2000)); - assert_eq!(said(long.as_bytes(), false), "error: short"); - // A long line last: nothing before it is reached past it. - let last = format!("error: first\nfatal: {}\n", "x".repeat(2000)); - assert_eq!(said(last.as_bytes(), false), ""); - assert_eq!( - said( - b"remote: Enumerating objects: 5, done.\nfatal: gone\n", - false - ), - "fatal: gone" - ); - } - - #[test] - fn a_purged_vault_leaves_the_next_backup() { - let git = Git::find().expect("git is installed"); - let dir = tempfile::tempdir().unwrap(); - let b = dir.path().join("book"); - let s = book(&b); - std::fs::create_dir(b.join(crate::root::VAULT_DIR)).unwrap(); - std::fs::write(b.join(crate::root::VAULT_DIR).join("tin-1.bin"), b"sealed").unwrap(); - commit(&git, &b, "acme", s.head()).unwrap().unwrap(); - std::fs::remove_dir_all(b.join(crate::root::VAULT_DIR)).unwrap(); - commit(&git, &b, "acme", s.head()) - .unwrap() - .expect("the purge is a change"); - let folder = dir.path().join("disk"); - std::fs::create_dir(&folder).unwrap(); - push(&git, &b, "acme", &Target::Folder(folder.clone()), true).unwrap(); - let v = verify( - &git, - folder.join("acme.git").to_str().unwrap(), - &dir.path().join("v"), - ) - .unwrap(); - assert!(!v.tree.join(crate::root::VAULT_DIR).exists()); - } - - #[test] - fn a_lock_left_behind_never_stops_the_next_backup() { - let git = Git::find().expect("git is installed"); - let dir = tempfile::tempdir().unwrap(); - let b = dir.path().join("book"); - let mut s = book(&b); - commit(&git, &b, "acme", s.head()).unwrap().unwrap(); - // A git stopped part way leaves its locks: while one might still be - // at work they stay (the backup waits), once older they go. - let locks = ["index.lock", "HEAD.lock", "refs/heads/main.lock"]; - for lock in locks { - std::fs::write(b.join(ARCHIVE_DIR).join(lock), b"").unwrap(); - } - s.add_account("6000", "Supplies", AccountType::Expense, None, false) - .unwrap(); - assert!(commit(&git, &b, "acme", s.head()).is_err()); - let then = std::time::SystemTime::now() - ARCHIVE_STALE - Duration::from_secs(1); - for lock in locks { - std::fs::File::options() - .write(true) - .open(b.join(ARCHIVE_DIR).join(lock)) - .unwrap() - .set_modified(then) - .unwrap(); - } - let made = commit(&git, &b, "acme", s.head()) - .unwrap() - .expect("backed up"); - assert_eq!(made.head, s.head()); - for lock in locks { - assert!(!b.join(ARCHIVE_DIR).join(lock).exists(), "{lock}"); - } - } - - #[test] - fn a_backup_with_a_changed_stored_file_or_a_busy_scratch_is_refused() { - let git = Git::find().expect("git is installed"); - let dir = tempfile::tempdir().unwrap(); - let b = dir.path().join("book"); - let s = book(&b); - commit(&git, &b, "acme", s.head()).unwrap(); - let folder = dir.path().join("disk"); - std::fs::create_dir(&folder).unwrap(); - push(&git, &b, "acme", &Target::Folder(folder.clone()), true).unwrap(); - let source = folder.join("acme.git").display().to_string(); - // A scratch folder in use is never written into. - let busy = dir.path().join("busy"); - std::fs::create_dir(&busy).unwrap(); - let e = verify(&git, &source, &busy).unwrap_err(); - assert!(matches!(e, BackupError::Damaged(_)), "{e}"); - assert_eq!(std::fs::read_dir(&busy).unwrap().count(), 0); - // One stored file's bytes changed, its name kept. - let work = dir.path().join("work"); - git.run( - "clone", - &[os("clone"), os("-q"), os(&source), work.as_os_str()], - ) - .unwrap(); - let mut blob = None; - for f in walk(&work.join("blobs")) { - blob = Some(f); - } - let blob = blob.expect("a stored file"); - std::fs::write(&blob, b"not the receipt").unwrap(); - let w = format!("--git-dir={}", work.join(".git").display()); - let t = format!("--work-tree={}", work.display()); - git.run( - "commit", - &[ - os(&w), - os(&t), - os("commit"), - os("-qam"), - os(&format!("seq {} head {}", s.head().0, s.head().1)), - ], - ) - .unwrap(); - let bad = dir.path().join("bad.git"); - git.run( - "clone", - &[ - os("clone"), - os("-q"), - os("--bare"), - work.as_os_str(), - bad.as_os_str(), - ], - ) - .unwrap(); - let e = verify(&git, bad.to_str().unwrap(), &dir.path().join("v")).unwrap_err(); - assert!(matches!(e, BackupError::Damaged(_)), "{e}"); - } - - #[test] - fn a_drill_proves_this_books_history_only() { - let git = Git::find().expect("git is installed"); - let dir = tempfile::tempdir().unwrap(); - let folder = dir.path().join("disk"); - std::fs::create_dir(&folder).unwrap(); - let target = Target::Folder(folder.clone()); - let one = dir.path().join("one"); - let s = book(&one); - commit(&git, &one, "acme", s.head()).unwrap(); - push(&git, &one, "acme", &target, true).unwrap(); - let journal = one.join(crate::JOURNAL_FILE); - let scratch = dir.path().join("drill"); - assert_eq!( - drill(&git, &target, "acme", &journal, &scratch).unwrap(), - s.head() - ); - assert!(!scratch.exists(), "the scratch folder is removed"); - // Another book's backup, whole in itself, isn't this book's. - // (Another currency: its journal differs from its first line.) - let two = dir.path().join("two"); - let mut s2 = Store::create(&two, Currency::new("EUR").unwrap()).unwrap(); - s2.add_account("6000", "Supplies", AccountType::Expense, None, false) - .unwrap(); - let e = drill( - &git, - &target, - "acme", - &two.join(crate::JOURNAL_FILE), - &scratch, - ) - .unwrap_err(); - assert!(e.to_string().contains("isn't this book's history"), "{e}"); - assert!(!scratch.exists()); - // A folder that isn't there. - let gone = Target::Folder(dir.path().join("unplugged")); - assert_eq!( - drill(&git, &gone, "acme", &journal, &scratch).unwrap_err(), - BackupError::NoFolder - ); - // Where each target's backup is. - assert_eq!( - target.source("acme"), - folder.join("acme.git").display().to_string() - ); - assert_eq!( - Target::Remote("ssh://h/b".into()).source("acme"), - "ssh://h/b" - ); - } - - /// The backup a format upgrade makes first (plan 3.9): the archive - /// proves to hold the book exactly as it is, its keys and vault file - /// for file; a key, a vault record or the journal that differs from - /// the archive's latest, or a head it doesn't hold, is refused; and - /// the scratch folder goes either way. - #[test] - fn the_archive_proves_to_hold_the_book_as_it_is_keys_and_all() { - let git = Git::find().expect("git is installed"); - let dir = tempfile::tempdir().unwrap(); - let b = dir.path().join("book"); - let mut s = book(&b); - let keys = b.join(crate::root::KEYS_DIR); - std::fs::create_dir(&keys).unwrap(); - std::fs::write(keys.join(crate::root::LEGACY_KEY_FILE), b"ab".repeat(32)).unwrap(); - let vault = b.join(crate::root::VAULT_DIR); - std::fs::create_dir(&vault).unwrap(); - std::fs::write(vault.join("tin-1.bin"), b"sealed").unwrap(); - let made = commit(&git, &b, "acme", s.head()).unwrap().unwrap(); - let scratch = dir.path().join("check"); - let proven = prove_archive(&git, &b, &s.head(), &scratch).unwrap(); - assert_eq!(proven.head, s.head()); - assert_eq!(proven.commit, made.commit); - assert_eq!(proven.blobs, 1); - assert!(!scratch.exists(), "the scratch folder is removed"); - let refused = |b: &Path, head: &(u64, String)| { - let e = prove_archive(&git, b, head, &scratch).unwrap_err(); - assert!(!scratch.exists()); - e.to_string() - }; - // A key that isn't the one backed up. - std::fs::write(keys.join(crate::root::LEGACY_KEY_FILE), b"cd".repeat(32)).unwrap(); - assert!(refused(&b, &s.head()).contains("keys folder")); - std::fs::write(keys.join(crate::root::LEGACY_KEY_FILE), b"ab".repeat(32)).unwrap(); - // A key the backup lacks. - std::fs::write(keys.join("other.key"), b"x").unwrap(); - assert!(refused(&b, &s.head()).contains("keys folder")); - std::fs::remove_file(keys.join("other.key")).unwrap(); - // A vault record that isn't the one backed up. - std::fs::write(vault.join("tin-1.bin"), b"sealed again").unwrap(); - assert!(refused(&b, &s.head()).contains("TIN vault")); - std::fs::write(vault.join("tin-1.bin"), b"sealed").unwrap(); - assert!(prove_archive(&git, &b, &s.head(), &scratch).is_ok()); - // The books moved on since the backup. - s.add_account("6000", "Fees", AccountType::Expense, None, false) - .unwrap(); - let e = refused(&b, &s.head()); - assert!(e.contains("they are at event"), "{e}"); - // The head it holds, but the journal on disk changed under it. - let old_head = made.head.clone(); - let e = refused(&b, &old_head); - assert!(e.contains("byte for byte"), "{e}"); - } - - #[test] - fn a_backup_holding_a_link_or_a_stranger_is_refused_before_checkout() { - let git = Git::find().expect("git is installed"); - let dir = tempfile::tempdir().unwrap(); - let b = dir.path().join("book"); - let s = book(&b); - commit(&git, &b, "acme", s.head()).unwrap(); - let folder = dir.path().join("disk"); - std::fs::create_dir(&folder).unwrap(); - push(&git, &b, "acme", &Target::Folder(folder.clone()), true).unwrap(); - let subject = format!("seq {} head {}", s.head().0, s.head().1); - let planted = dir.path().join("planted.db"); - type Spoil = fn(&Path, &Path); - let spoils: [(&str, Spoil); 4] = [ - ("db-link", |w, planted| { - std::os::unix::fs::symlink(planted, w.join("wanderbooks.db")).unwrap(); - }), - ("vault-link", |w, _| { - std::os::unix::fs::symlink("/etc", w.join(crate::root::VAULT_DIR)).unwrap(); - }), - ("journal-link", |w, _| { - let j = w.join(crate::JOURNAL_FILE); - let real = w.join("elsewhere.jsonl"); - std::fs::rename(&j, &real).unwrap(); - std::os::unix::fs::symlink(&real, &j).unwrap(); - }), - ("stranger", |w, _| { - std::fs::write(w.join("README"), b"hello").unwrap(); - }), - ]; - for (tag, spoil) in spoils { - let work = dir.path().join(format!("work-{tag}")); - let source = folder.join("acme.git"); - let out = Command::new("git") - .args(["clone", "-q"]) - .arg(&source) - .arg(&work) - .output() - .unwrap(); - assert!(out.status.success(), "{out:?}"); - spoil(&work, &planted); - let out = Command::new("git") - .arg("-C") - .arg(&work) - .args(["-c", "user.name=t", "-c", "user.email=t@t.invalid"]) - .args(["add", "-A", "."]) - .output() - .unwrap(); - assert!(out.status.success(), "{out:?}"); - let out = Command::new("git") - .arg("-C") - .arg(&work) - .args([ - "-c", - "user.name=t", - "-c", - "user.email=t@t.invalid", - "-c", - "commit.gpgsign=false", - ]) - .args(["commit", "-qm", &subject]) - .output() - .unwrap(); - assert!(out.status.success(), "{tag}: {out:?}"); - let bad = dir.path().join(format!("{tag}.git")); - let out = Command::new("git") - .args(["clone", "-q", "--bare"]) - .arg(&work) - .arg(&bad) - .output() - .unwrap(); - assert!(out.status.success(), "{out:?}"); - let scratch = dir.path().join(format!("v-{tag}")); - let e = verify(&git, bad.to_str().unwrap(), &scratch).unwrap_err(); - assert!(matches!(e, BackupError::Damaged(_)), "{tag}: {e}"); - assert!(!planted.exists(), "{tag}: wrote outside its folder"); - assert!( - !scratch.join(crate::JOURNAL_FILE).exists(), - "{tag}: checked out" - ); - } - } - - #[test] - fn local_addresses_are_told_from_networked_ones() { - for (address, local) in [ - ("/srv/books.git", true), - ("file:///srv/books.git", true), - ("acme.git", true), - ("backups/acme.git", true), - ("./x:y", true), - ("ssh://host/books.git", false), - ("https://host/owner/books", false), - ("git@host:owner/books.git", false), - ("host:books.git", false), - ] { - assert_eq!(is_local(address), local, "{address}"); - } - } - - #[test] - fn a_file_git_wont_take_fails_the_backup() { - let git = Git::find().expect("git is installed"); - let dir = tempfile::tempdir().unwrap(); - let b = dir.path().join("book"); - let s = book(&b); - std::fs::create_dir(b.join(crate::root::VAULT_DIR)).unwrap(); - // git leaves out a file named .git without a word. - std::fs::write(b.join(crate::root::VAULT_DIR).join(".git"), b"x").unwrap(); - let e = commit(&git, &b, "acme", s.head()).unwrap_err(); - assert!(matches!(e, BackupError::Damaged(_)), "{e}"); - } - - #[test] - fn no_attributes_rule_changes_a_byte() { - let git = Git::find().expect("git is installed"); - let dir = tempfile::tempdir().unwrap(); - let b = dir.path().join("book"); - let s = book(&b); - std::fs::create_dir(b.join(crate::root::VAULT_DIR)).unwrap(); - let bytes = b"$Id: kept$\r\nline two\r\n"; - std::fs::write(b.join(crate::root::VAULT_DIR).join("tin-1.bin"), bytes).unwrap(); - commit(&git, &b, "acme", s.head()).unwrap(); - // The archive's own rules are taken out before each backup. - let info = b.join(ARCHIVE_DIR).join("info"); - std::fs::create_dir_all(&info).unwrap(); - std::fs::write(info.join("attributes"), "* ident text eol=lf\n").unwrap(); - std::fs::write(b.join(crate::root::VAULT_DIR).join("tin-2.bin"), bytes).unwrap(); - commit(&git, &b, "acme", s.head()).unwrap().unwrap(); - assert!(!info.join("attributes").exists()); - let gd = format!("--git-dir={}", b.join(ARCHIVE_DIR).display()); - for f in ["vault/tin-1.bin", "vault/tin-2.bin"] { - let out = Command::new(&git.exe) - .args([&gd, "cat-file", "-p", &format!("HEAD:{f}")]) - .output() - .unwrap(); - assert_eq!(out.stdout, bytes, "{f}"); - } - // A rules file in the book's folder, or in what is backed up: - // refused. - for at in [ - b.join(".gitattributes"), - b.join(crate::root::VAULT_DIR).join(".gitattributes"), - ] { - std::fs::write(&at, "* ident\n").unwrap(); - let e = commit(&git, &b, "acme", s.head()).unwrap_err(); - assert!(e.to_string().contains(".gitattributes"), "{e}"); - std::fs::remove_file(&at).unwrap(); - } - } - - #[test] - fn the_archives_own_hooks_never_run() { - use std::os::unix::fs::PermissionsExt; - let git = Git::find().expect("git is installed"); - let dir = tempfile::tempdir().unwrap(); - let b = dir.path().join("book"); - let mut s = book(&b); - commit(&git, &b, "acme", s.head()).unwrap(); - let ran = dir.path().join("ran"); - let hooks = b.join(ARCHIVE_DIR).join("hooks"); - std::fs::create_dir_all(&hooks).unwrap(); - for hook in [ - "pre-commit", - "post-commit", - "reference-transaction", - "pre-push", - "post-index-change", - ] { - let h = hooks.join(hook); - std::fs::write( - &h, - format!("#!/bin/sh\necho {hook} >> '{}'\n", ran.display()), - ) - .unwrap(); - std::fs::set_permissions(&h, std::fs::Permissions::from_mode(0o755)).unwrap(); - } - s.add_account("6000", "Supplies", AccountType::Expense, None, false) - .unwrap(); - commit(&git, &b, "acme", s.head()).unwrap().unwrap(); - let folder = dir.path().join("disk"); - std::fs::create_dir(&folder).unwrap(); - push(&git, &b, "acme", &Target::Folder(folder), true).unwrap(); - assert!( - !ran.exists(), - "a hook ran: {:?}", - std::fs::read_to_string(&ran) - ); - } - - /// A git that runs the real one with the owner's own configuration set - /// to everything that could spoil a backup. - fn hostile_git(dir: &Path, real: &Git) -> Git { - use std::os::unix::fs::PermissionsExt; - let home = dir.join("hostile-home"); - let hooks = home.join("hooks"); - std::fs::create_dir_all(&hooks).unwrap(); - let marker = dir.join("marker"); - for hook in [ - "post-commit", - "pre-push", - "post-receive", - "reference-transaction", - ] { - let h = hooks.join(hook); - std::fs::write( - &h, - format!("#!/bin/sh\necho {hook} >> '{}'\n", marker.display()), - ) - .unwrap(); - std::fs::set_permissions(&h, std::fs::Permissions::from_mode(0o755)).unwrap(); - } - std::fs::write(home.join("ignore"), "*.bin\n*.key\nblobs/\n").unwrap(); - std::fs::write(home.join("attributes"), "* text=auto eol=lf ident\n").unwrap(); - std::fs::write( - home.join(".gitconfig"), - format!( - "[core]\n\tautocrlf = true\n\texcludesFile = {h}/ignore\n\tattributesFile = {h}/attributes\n\thooksPath = {h}/hooks\n\tfsmonitor = touch '{m}.fsmonitor'\n\tsymlinks = true\n[commit]\n\tgpgsign = true\n[push]\n\tgpgSign = true\n[gpg]\n\tprogram = false\n[init]\n\tdefaultRefFormat = reftable\n\ttemplateDir = {h}/template\n[protocol \"ext\"]\n\tallow = always\n[log]\n\tshowSignature = true\n", - h = home.display(), - m = marker.display() - ), - ) - .unwrap(); - let wrapper = dir.join("git"); - std::fs::write( - &wrapper, - format!( - "#!/bin/sh\nexport HOME='{}'\nexport XDG_CONFIG_HOME='{}'\nexec '{}' \"$@\"\n", - home.display(), - home.display(), - real.exe.display() - ), - ) - .unwrap(); - std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap(); - Git { - exe: wrapper, - quiet: GIT_TIMEOUT, - cancel: None, - term_grace: TERM_GRACE, - watch: Watch::default(), - } - } - - #[test] - fn the_owners_git_configuration_never_spoils_a_backup() { - let real = Git::find().expect("git is installed"); - let dir = tempfile::tempdir().unwrap(); - let git = hostile_git(dir.path(), &real); - let b = dir.path().join("book"); - let s = book(&b); - std::fs::create_dir(b.join(crate::root::VAULT_DIR)).unwrap(); - let crlf = b"$Id: x$\r\nline\r\n"; - std::fs::write(b.join(crate::root::VAULT_DIR).join("tin-1.bin"), crlf).unwrap(); - std::fs::create_dir(b.join(crate::root::KEYS_DIR)).unwrap(); - std::fs::write(b.join(crate::root::KEYS_DIR).join("legacy.key"), b"k").unwrap(); - commit(&git, &b, "acme", s.head()).unwrap().unwrap(); - let folder = dir.path().join("disk"); - std::fs::create_dir(&folder).unwrap(); - push(&git, &b, "acme", &Target::Folder(folder.clone()), true).unwrap(); - let v = verify( - &git, - folder.join("acme.git").to_str().unwrap(), - &dir.path().join("v"), - ) - .unwrap(); - assert_eq!(v.head, s.head()); - assert_eq!(std::fs::read(v.tree.join("vault/tin-1.bin")).unwrap(), crlf); - assert!(v.tree.join("keys/legacy.key").is_file()); - assert!(!dir.path().join("marker").exists(), "a hook ran"); - assert!( - !dir.path().join("marker.fsmonitor").exists(), - "a watcher ran" - ); - assert!( - push( - &git, - &b, - "acme", - &Target::Remote("ext::sh -c 'touch x'".into()), - true - ) - .is_err() - ); - } - - /// A git that is the real one with the hooks folder of its own: each - /// `core.hooksPath=/dev/null` it is given (in its own arguments, and in - /// the `--receive-pack` command a push to this computer runs) names - /// `hooks` instead, where a `reference-transaction` hook waits, while - /// `hooks/slow` exists, at the point where git holds its ref locks (and - /// a commit its index lock): how a real git is made slow enough to be - /// killed inside the work. `hooks/hooked` has a line per hook that waited. - /// While `hooks/deaf` exists when a git begins, that git (and all it - /// starts) has SIGTERM blocked, as a mask every child inherits: the - /// signal stays pending, git's handler never runs, and only the kill - /// ends it ([`deaf`]). - fn slow_git(dir: &Path, real: &Git) -> (Git, PathBuf) { - use std::os::unix::fs::PermissionsExt; - let hooks = dir.join("slow-hooks"); - std::fs::create_dir_all(&hooks).unwrap(); - let hook = hooks.join("reference-transaction"); - std::fs::write( - &hook, - "#!/bin/sh\ncat >/dev/null\n[ \"$1\" = prepared ] || exit 0\nd=\"$(dirname \"$0\")\"\nif [ -e \"$d/slow\" ]; then\n echo $$ >> \"$d/hooked\"\n while [ -e \"$d/slow\" ]; do sleep 0.05; done\nfi\nexit 0\n", - ) - .unwrap(); - std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap(); - // The receiving end's `pre-receive`: waits while `slow-pack` exists, - // after the pack has been received into the quarantine. - let pre = hooks.join("pre-receive"); - std::fs::write( - &pre, - "#!/bin/sh\ncat >/dev/null\nd=\"$(dirname \"$0\")\"\nif [ -e \"$d/slow-pack\" ]; then\n echo $$ >> \"$d/hooked-pack\"\n while [ -e \"$d/slow-pack\" ]; do sleep 0.05; done\nfi\nexit 0\n", - ) - .unwrap(); - std::fs::set_permissions(&pre, std::fs::Permissions::from_mode(0o755)).unwrap(); - let wrapper = dir.join("slow-git"); - std::fs::write( - &wrapper, - format!( - "#!/bin/sh\nn=$#\nwhile [ $n -gt 0 ]; do\n a=\"$1\"; shift\n case \"$a\" in\n *core.hooksPath=/dev/null*) a=$(printf '%s' \"$a\" | sed 's|core.hooksPath=/dev/null|core.hooksPath={}|g') ;;\n esac\n set -- \"$@\" \"$a\"\n n=$((n-1))\ndone\nif [ -e '{}/deaf' ]; then exec perl -MPOSIX -e 'sigprocmask(SIG_BLOCK, POSIX::SigSet->new(SIGTERM)) or die; exec @ARGV or die' '{}' \"$@\"; fi\nexec '{}' \"$@\"\n", - hooks.display(), - hooks.display(), - real.exe.display(), - real.exe.display() - ), - ) - .unwrap(); - std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap(); - ( - Git { - exe: wrapper, - quiet: GIT_TIMEOUT, - cancel: None, - term_grace: TERM_GRACE, - watch: Watch::default(), - }, - hooks, - ) - } - - /// Wait until a hook of `slow_git` is waiting. - fn wait_hooked(hooks: &Path) { - let by = Instant::now() + Duration::from_secs(30); - while !hooks.join("hooked").exists() { - assert!(Instant::now() < by, "git never reached its ref update"); - std::thread::sleep(Duration::from_millis(10)); - } - } - - fn fsck(git: &Git, repo: &Path) { - git.run( - "fsck", - &[ - os(&format!("--git-dir={}", repo.display())), - os("fsck"), - os("--strict"), - ], - ) - .unwrap_or_else(|e| panic!("the repository isn't whole: {e}")); - } - - /// The locks in `repo`, as paths in it. - fn locks_in(repo: &Path) -> Vec { - crate::git_locks::RepoDir::open(repo) - .unwrap() - .locks() - .into_iter() - .map(|f| f.lock) - .collect() - } - - /// Make the gits `slow_git` starts from now on unable to end on - /// SIGTERM (a blocked signal stays pending on every system). A stopped - /// process is not enough: macOS acts on a SIGTERM sent to a process - /// that was stopped (the git ended inside its grace, and removed its - /// own locks), where Linux holds the signal until it is continued. - fn deaf(hooks: &Path) { - std::fs::write(hooks.join("deaf"), b"").unwrap(); - } - - /// Hold every process of the group `pid` leads still (SIGSTOP), so that - /// none goes on while the stop is being asked for. A git that can't end - /// on SIGTERM, with the locks it holds, is made on purpose by [`deaf`]; - /// this only keeps it from finishing meanwhile. - fn freeze_group_of(pid: u32) { - let out = std::process::Command::new("ps") - .args(["-o", "pgid=", "-p", &pid.to_string()]) - .output() - .unwrap(); - let group: i32 = String::from_utf8_lossy(&out.stdout) - .trim() - .parse() - .expect("ps names the group"); - // SAFETY: stopping the group this test's own git started. - assert_eq!(unsafe { libc::kill(-group, libc::SIGSTOP) }, 0); - } - - /// The pid of the first hook of `slow_git` that waited, in `file`. - fn hooked_pid(hooks: &Path, file: &str) -> u32 { - std::fs::read_to_string(hooks.join(file)) - .unwrap() - .lines() - .next() - .unwrap() - .trim() - .parse() - .unwrap() - } - - /// INVARIANT 5, the archive, told to stop: a real git in the middle of a - /// commit, holding the ref locks, ends on SIGTERM and removes them - /// itself. Nothing is left, and nothing was cleaned up here (no note): - /// the grace is long, so a git that needed the kill would show. - #[test] - fn a_git_stopped_by_sigterm_mid_commit_leaves_no_lock_and_needs_no_cleanup() { - let real = Git::find().expect("git is installed"); - let dir = tempfile::tempdir().unwrap(); - let (slow, hooks) = slow_git(dir.path(), &real); - let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - let cancelled = slow - .clone() - .with_cancel(flag.clone()) - .with_term_grace(Duration::from_secs(120)); - let b = dir.path().join("book"); - let mut s = book(&b); - commit(&slow, &b, "acme", s.head()).unwrap().unwrap(); - s.add_account("6000", "Supplies", AccountType::Expense, None, false) - .unwrap(); - let archive = b.join(ARCHIVE_DIR); - std::fs::write(hooks.join("slow"), b"").unwrap(); - let running = { - let (git, b, head) = (cancelled.clone(), b.clone(), s.head()); - std::thread::spawn(move || commit(&git, &b, "acme", head)) - }; - wait_hooked(&hooks); - // Inside the commit's ref update it holds the ref locks. - let held = locks_in(&archive); - assert!(held.contains(&"HEAD.lock".to_string()), "{held:?}"); - assert!( - held.contains(&"refs/heads/main.lock".to_string()), - "{held:?}" - ); - flag.store(true, std::sync::atomic::Ordering::SeqCst); - assert_eq!( - running.join().unwrap().unwrap_err(), - BackupError::Cancelled("commit".into()) - ); - assert_eq!(locks_in(&archive), Vec::::new()); - assert_eq!( - cancelled.take_lock_notes(), - Vec::new(), - "git removed its own locks: there was nothing for this program to clean up" - ); - // The next backup, with no one to remove anything by hand. - std::fs::remove_file(hooks.join("slow")).unwrap(); - let made = commit(&slow, &b, "acme", s.head()) - .unwrap() - .expect("the next backup is made"); - assert_eq!(made.head, s.head()); - fsck(&real, &archive); - } - - /// INVARIANT 5, the archive, a git that can't end on SIGTERM: killed - /// only after the grace; once its group is gone the locks it left, none - /// of which was there when the command began, are removed through the - /// archive's own handle, each noted; the next backup needs no hand. - #[test] - fn a_git_that_cannot_end_on_sigterm_is_killed_after_the_grace_and_its_archive_locks_go() { - let real = Git::find().expect("git is installed"); - let dir = tempfile::tempdir().unwrap(); - let (slow, hooks) = slow_git(dir.path(), &real); - let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - let grace = Duration::from_millis(400); - let cancelled = slow - .clone() - .with_cancel(flag.clone()) - .with_term_grace(grace); - let b = dir.path().join("book"); - let mut s = book(&b); - commit(&slow, &b, "acme", s.head()).unwrap().unwrap(); - s.add_account("6000", "Supplies", AccountType::Expense, None, false) - .unwrap(); - let archive = b.join(ARCHIVE_DIR); - deaf(&hooks); - std::fs::write(hooks.join("slow"), b"").unwrap(); - let running = { - let (git, b, head) = (cancelled.clone(), b.clone(), s.head()); - std::thread::spawn(move || commit(&git, &b, "acme", head)) - }; - wait_hooked(&hooks); - let held = locks_in(&archive); - assert!(!held.is_empty(), "git held no lock inside its ref update"); - freeze_group_of(hooked_pid(&hooks, "hooked")); - let stopped = Instant::now(); - flag.store(true, std::sync::atomic::Ordering::SeqCst); - assert_eq!( - running.join().unwrap().unwrap_err(), - BackupError::Cancelled("commit".into()) - ); - assert!( - stopped.elapsed() >= grace, - "killed before the grace had run out" - ); - assert_eq!(locks_in(&archive), Vec::::new()); - let notes = cancelled.take_lock_notes(); - for lock in &held { - assert!( - notes.iter().any(|n| n.repo == "archive" - && &n.lock == lock - && n.removed - && n.why == "git was stopped" - && n.path.is_none()), - "{lock} wasn't noted: {notes:?}" - ); - } - std::fs::remove_file(hooks.join("slow")).unwrap(); - let made = commit(&slow, &b, "acme", s.head()) - .unwrap() - .expect("the next backup is made"); - assert_eq!(made.head, s.head()); - fsck(&real, &archive); - } - - /// INVARIANT 5, the index lock: a real git stopped inside `add` (here - /// hashing a very large, empty, stored file) holds the index lock, and - /// removes it itself on SIGTERM; the next backup needs no hand. - #[test] - fn a_git_stopped_mid_add_leaves_no_index_lock() { - let real = Git::find().expect("git is installed"); - let dir = tempfile::tempdir().unwrap(); - let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - let git = real - .clone() - .with_cancel(flag.clone()) - .with_term_grace(Duration::from_secs(120)); - let b = dir.path().join("book"); - let s = book(&b); - commit(&real, &b, "acme", s.head()).unwrap().unwrap(); - let big = b.join("blobs").join("big-and-empty"); - std::fs::File::create(&big) - .unwrap() - .set_len(64 << 30) - .unwrap(); - let archive = b.join(ARCHIVE_DIR); - let running = { - let (git, b) = (git.clone(), b.clone()); - std::thread::spawn(move || stage_blobs(&git, &b)) - }; - // The lock is taken as `add` begins and held until it ends, which - // for a file this size is minutes: seeing it is being inside. - let by = Instant::now() + Duration::from_secs(60); - while !archive.join("index.lock").exists() { - assert!(Instant::now() < by, "git never took the index lock"); - std::thread::sleep(Duration::from_millis(5)); - } - flag.store(true, std::sync::atomic::Ordering::SeqCst); - assert_eq!( - running.join().unwrap().unwrap_err(), - BackupError::Cancelled("add".into()) - ); - assert_eq!(locks_in(&archive), Vec::::new()); - assert_eq!(git.take_lock_notes(), Vec::new()); - std::fs::remove_file(&big).unwrap(); - stage_blobs(&real, &b).unwrap(); - fsck(&real, &archive); - } - - /// A book backed up once to a folder target, then changed and - /// committed again, ready for a push: (git, hooks, book folder, target - /// repository, the target, the store). - fn ready_to_push( - dir: &Path, - real: &Git, - ) -> (Git, PathBuf, PathBuf, PathBuf, Target, crate::Store) { - let (slow, hooks) = slow_git(dir, real); - let b = dir.join("book"); - let mut s = book(&b); - commit(&slow, &b, "acme", s.head()).unwrap().unwrap(); - let folder = dir.join("disk"); - std::fs::create_dir(&folder).unwrap(); - let target = Target::Folder(folder.clone()); - push(&slow, &b, "acme", &target, true).unwrap(); - s.add_account("6000", "Supplies", AccountType::Expense, None, false) - .unwrap(); - commit(&slow, &b, "acme", s.head()).unwrap().unwrap(); - (slow, hooks, b, folder.join("acme.git"), target, s) - } - - fn main_of(real: &Git, repo: &Path) -> String { - real.run( - "rev-parse", - &[ - os(&format!("--git-dir={}", repo.display())), - os("rev-parse"), - os("refs/heads/main"), - ], - ) - .unwrap() - } - - /// INVARIANT 5b, told to stop: a real git in the middle of a push (its - /// receive-pack holding the target's ref lock) ends on SIGTERM and its - /// receiving end removes the lock itself. Nothing was removed here, a - /// lock that was there before the push is untouched, the next push - /// succeeds, and both repositories pass git's check. - #[test] - fn a_push_stopped_by_sigterm_leaves_no_lock_in_the_target_and_removes_nothing_there() { - let real = Git::find().expect("git is installed"); - let dir = tempfile::tempdir().unwrap(); - let (slow, hooks, b, repo, target, _s) = ready_to_push(dir.path(), &real); - // Another writer's lock, held before our push begins. - std::fs::write(repo.join("refs/heads/another.lock"), b"").unwrap(); - let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - let cancelled = slow - .clone() - .with_cancel(flag.clone()) - .with_term_grace(Duration::from_secs(120)); - std::fs::write(hooks.join("slow"), b"").unwrap(); - let running = { - let (git, b, target) = (cancelled.clone(), b.clone(), target.clone()); - std::thread::spawn(move || push(&git, &b, "acme", &target, true)) - }; - wait_hooked(&hooks); - assert!(repo.join("refs/heads/main.lock").exists()); - flag.store(true, std::sync::atomic::Ordering::SeqCst); - assert_eq!( - running.join().unwrap().unwrap_err(), - BackupError::Cancelled("push".into()) - ); - assert!(!repo.join("refs/heads/main.lock").exists()); - assert!( - repo.join("refs/heads/another.lock").exists(), - "a lock that was there before the push was removed" - ); - assert_eq!(cancelled.take_lock_notes(), Vec::new()); - // The next push, nobody's hand in it. - std::fs::remove_file(hooks.join("slow")).unwrap(); - std::fs::remove_file(hooks.join("hooked")).unwrap(); - let commit_id = push(&slow, &b, "acme", &target, true).unwrap(); - assert_eq!(main_of(&real, &repo), commit_id); - fsck(&real, &repo); - fsck(&real, &b.join(ARCHIVE_DIR)); - } - - /// INVARIANT 5b, a git that can't end on SIGTERM: killed after the - /// grace, it leaves the target's ref lock, and nothing in the owner's - /// folder is deleted by us, whatever the lock's age. The push is - /// reported as failed, naming the file and what the owner may do. A - /// lock that was there before the push began is not named, and is - /// untouched. Once the owner (here, the test) removes the file the next - /// push succeeds, and both repositories pass git's check. - #[test] - fn a_lock_left_in_a_folder_target_by_a_kill_is_never_removed_but_reported() { - let real = Git::find().expect("git is installed"); - let dir = tempfile::tempdir().unwrap(); - let (slow, hooks, b, repo, target, _s) = ready_to_push(dir.path(), &real); - std::fs::write(repo.join("refs/heads/another.lock"), b"").unwrap(); - let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - let grace = Duration::from_millis(400); - let cancelled = slow - .clone() - .with_cancel(flag.clone()) - .with_term_grace(grace); - deaf(&hooks); - std::fs::write(hooks.join("slow"), b"").unwrap(); - let running = { - let (git, b, target) = (cancelled.clone(), b.clone(), target.clone()); - std::thread::spawn(move || push(&git, &b, "acme", &target, true)) - }; - wait_hooked(&hooks); - let lock = repo.join("refs/heads/main.lock"); - assert!(lock.exists()); - freeze_group_of(hooked_pid(&hooks, "hooked")); - let stopped = Instant::now(); - flag.store(true, std::sync::atomic::Ordering::SeqCst); - let said = running.join().unwrap().unwrap_err(); - assert!(stopped.elapsed() >= grace); - let BackupError::LockLeft(named) = &said else { - panic!("{said:?}"); - }; - assert!( - named.split(", ").any(|p| p == lock.display().to_string()), - "{said}" - ); - // Every lock it left is named, by its whole path, and each is there. - for path in named.split(", ") { - assert!(Path::new(path).exists(), "{path}"); - } - let words = said.to_string(); - assert!( - words.contains("nothing else is using the backup folder"), - "{words}" - ); - assert!(!words.contains("another.lock"), "{words}"); - // Left where it was, and the one before our push untouched. - assert!(lock.exists(), "a file in the owner's folder was deleted"); - assert!(repo.join("refs/heads/another.lock").exists()); - let notes = cancelled.take_lock_notes(); - assert!( - notes.iter().all(|n| n.repo == "folder" - && !n.removed - && n.path.as_deref() == Some(repo.join(&n.lock).display().to_string().as_str())), - "{notes:?}" - ); - assert!( - notes.iter().any(|n| n.lock == "refs/heads/main.lock"), - "{notes:?}" - ); - assert!( - !notes.iter().any(|n| n.lock.contains("another")), - "{notes:?}" - ); - // Still there, a later push fails by git's own words, and the file - // stays. - std::fs::remove_file(hooks.join("slow")).unwrap(); - assert!(push(&slow, &b, "acme", &target, true).is_err()); - assert!(lock.exists(), "a later push removed it"); - // The owner removes it; the next backup goes on. - std::fs::remove_file(&lock).unwrap(); - let commit_id = push(&slow, &b, "acme", &target, true).unwrap(); - assert_eq!(main_of(&real, &repo), commit_id); - fsck(&real, &repo); - fsck(&real, &b.join(ARCHIVE_DIR)); - } - - /// A book whose next push carries a large object (about 48 MiB that - /// doesn't compress), with a `pre-receive` hook on the receiving side - /// that waits while `slow-pack` exists: the pack has been received into - /// the target's quarantine by then, and the push is held inside the - /// transfer's receiving end. - fn large_push_ready(dir: &Path, real: &Git) -> (Git, PathBuf, PathBuf, PathBuf, Target) { - let (slow, hooks, b, repo, target, _s) = ready_to_push(dir, real); - let mut bytes = vec![0u8; 48 << 20]; - let mut x: u64 = 0x9E37_79B9_7F4A_7C15; - for chunk in bytes.chunks_mut(8) { - x ^= x << 13; - x ^= x >> 7; - x ^= x << 17; - chunk.copy_from_slice(&x.to_le_bytes()[..chunk.len()]); - } - std::fs::write(b.join("blobs").join("large-and-random"), &bytes).unwrap(); - commit(&slow, &b, "acme", (1, "x".into())) - .map(|_| ()) - .unwrap(); - (slow, hooks, b, repo, target) - } - - /// INVARIANT 5, 6: a push stopped while its pack is being received (a - /// large object, the receiving end held up by a hook) leaves both - /// repositories whole, however it was ended: git's own check is run on - /// both at once, with nothing cleaned up between. - #[test] - fn a_push_stopped_during_the_pack_transfer_leaves_both_repositories_whole() { - let real = Git::find().expect("git is installed"); - for (name, frozen) in [("by SIGTERM", false), ("by the kill after the grace", true)] { - let dir = tempfile::tempdir().unwrap(); - let (slow, hooks, b, repo, target) = large_push_ready(dir.path(), &real); - let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - let cancelled = slow - .clone() - .with_cancel(flag.clone()) - .with_term_grace(Duration::from_millis(if frozen { 400 } else { 120_000 })); - if frozen { - deaf(&hooks); - } - std::fs::write(hooks.join("slow-pack"), b"").unwrap(); - let running = { - let (git, b, target) = (cancelled.clone(), b.clone(), target.clone()); - std::thread::spawn(move || push(&git, &b, "acme", &target, true)) - }; - let by = Instant::now() + Duration::from_secs(300); - while !hooks.join("hooked-pack").exists() { - assert!( - Instant::now() < by, - "{name}: the push never reached the receiving end's hook" - ); - std::thread::sleep(Duration::from_millis(10)); - } - // The pack is in the target's quarantine: a stop is in the - // transfer's receiving end. - let incoming = std::fs::read_dir(repo.join("objects")) - .unwrap() - .flatten() - .filter(|e| e.file_name().to_string_lossy().contains("incoming-")) - .count(); - assert!(incoming > 0, "{name}: nothing was being received"); - if frozen { - freeze_group_of(hooked_pid(&hooks, "hooked-pack")); - } - flag.store(true, std::sync::atomic::Ordering::SeqCst); - let said = running.join().unwrap().unwrap_err(); - assert!( - matches!(said, BackupError::Cancelled(_) | BackupError::LockLeft(_)), - "{name}: {said:?}" - ); - // At once: nothing cleaned up, nothing waited for. - fsck(&real, &repo); - fsck(&real, &b.join(ARCHIVE_DIR)); - // And the target still takes the next push, after the owner's - // own removal of a lock a kill left (none, when SIGTERM ended - // git). - std::fs::remove_file(hooks.join("slow-pack")).unwrap(); - std::fs::remove_file(hooks.join("hooked-pack")).unwrap(); - if let BackupError::LockLeft(path) = said { - assert!(frozen, "{name}: SIGTERM left a lock"); - std::fs::remove_file(path).unwrap(); - } - let commit_id = push(&slow, &b, "acme", &target, true).unwrap(); - assert_eq!(main_of(&real, &repo), commit_id, "{name}"); - fsck(&real, &repo); - } - } - - /// INVARIANT 5a: at open, a lock in the archive is removed only if it - /// is older than ARCHIVE_STALE, each removal noted; a younger one is - /// left (and said so), nothing that isn't a lock's name is touched, and - /// the next backup removes a lock once it has grown old. - #[test] - fn the_archives_age_rule_at_open() { - let git = Git::find().expect("git is installed"); - let dir = tempfile::tempdir().unwrap(); - let b = dir.path().join("book"); - let mut s = book(&b); - commit(&git, &b, "acme", s.head()).unwrap().unwrap(); - let archive = b.join(ARCHIVE_DIR); - let old_enough = std::time::SystemTime::now() - ARCHIVE_STALE - Duration::from_secs(5); - let age = |path: &Path, to: std::time::SystemTime| { - std::fs::File::options() - .write(true) - .open(path) - .unwrap() - .set_modified(to) - .unwrap(); - }; - let old = ["index.lock", "refs/heads/main.lock"]; - let young = ["HEAD.lock", "packed-refs.lock"]; - for lock in old.iter().chain(&young) { - std::fs::write(archive.join(lock), b"").unwrap(); - } - for lock in old { - age(&archive.join(lock), old_enough); - } - // Not locks, however old: a file of git's own, a folder named like - // one, and a link. - std::fs::write(archive.join("description.lock-not"), b"").unwrap(); - age(&archive.join("description.lock-not"), old_enough); - std::fs::create_dir(archive.join("shallow.lock")).unwrap(); - let notes = clear_archive_locks(&b); - let removed: Vec<&str> = notes - .iter() - .filter(|n| n.removed) - .map(|n| n.lock.as_str()) - .collect(); - let mut removed_sorted = removed.clone(); - removed_sorted.sort(); - assert_eq!(removed_sorted, ["index.lock", "refs/heads/main.lock"]); - let mut left: Vec<&str> = notes - .iter() - .filter(|n| !n.removed) - .map(|n| n.lock.as_str()) - .collect(); - left.sort(); - assert_eq!(left, ["HEAD.lock", "packed-refs.lock"]); - assert!(notes.iter().all(|n| n.repo == "archive")); - assert_eq!(locks_in(&archive), ["HEAD.lock", "packed-refs.lock"]); - assert!(archive.join("description.lock-not").exists()); - assert!(archive.join("shallow.lock").is_dir()); - // The next backup meets a young lock: it fails by git's words, and - // the lock stays. Once old it is removed, noted, and the backup goes. - s.add_account("6000", "Supplies", AccountType::Expense, None, false) - .unwrap(); - assert!(commit(&git, &b, "acme", s.head()).is_err()); - assert!(archive.join("HEAD.lock").exists()); - for lock in young { - age(&archive.join(lock), old_enough); - } - let git = git.with_lock_notes(LockNotes::default()); - let made = commit(&git, &b, "acme", s.head()) - .unwrap() - .expect("backed up"); - assert_eq!(made.head, s.head()); - let notes = git.take_lock_notes(); - let mut removed: Vec<&str> = notes.iter().map(|n| n.lock.as_str()).collect(); - removed.sort(); - assert_eq!(removed, ["HEAD.lock", "packed-refs.lock"]); - assert!(notes.iter().all(|n| n.removed && n.repo == "archive")); - assert_eq!(locks_in(&archive), Vec::::new()); - } - - /// INVARIANT 5a and git_locks INVARIANT 1: what is removed after a stop - /// is removed through the archive's folder as it was opened when the - /// command began. A `refs` folder swapped for a link, or the archive's - /// own path swapped for one, in the meantime, touches nothing outside. - #[test] - fn removal_after_a_stop_goes_through_the_handle_opened_before_the_command() { - let git = Git::find().expect("git is installed"); - let dir = tempfile::tempdir().unwrap(); - let outside = dir.path().join("outside"); - std::fs::create_dir_all(outside.join("refs/heads")).unwrap(); - for lock in ["index.lock", "HEAD.lock", "refs/heads/main.lock"] { - std::fs::write(outside.join(lock), b"theirs").unwrap(); - } - let untouched = |what: &str| { - for lock in ["index.lock", "HEAD.lock", "refs/heads/main.lock"] { - assert_eq!( - std::fs::read(outside.join(lock)).unwrap(), - b"theirs", - "{what}: {lock} outside was touched" - ); - } - }; - // 1. `refs` swapped for a link. - let b = dir.path().join("book"); - let s = book(&b); - commit(&git, &b, "acme", s.head()).unwrap().unwrap(); - let archive = b.join(ARCHIVE_DIR); - let watched = Watched::archive(&archive); - let snap = watched.snapshot(); - std::fs::write(archive.join("index.lock"), b"ours").unwrap(); - std::fs::write(archive.join("refs/heads/main.lock"), b"ours").unwrap(); - std::fs::rename(archive.join("refs"), dir.path().join("refs-moved")).unwrap(); - std::os::unix::fs::symlink(outside.join("refs"), archive.join("refs")).unwrap(); - let left = watched.after_kill(&git, &snap, true); - assert!(left.is_empty()); - assert!(!archive.join("index.lock").exists(), "its own lock stays"); - assert!( - dir.path().join("refs-moved/heads/main.lock").exists(), - "the folder moved aside was reached through the link" - ); - untouched("refs swapped"); - let notes = git.take_lock_notes(); - assert_eq!( - notes.iter().map(|n| n.lock.as_str()).collect::>(), - ["index.lock"] - ); - // 2. The archive's own path swapped for a link. - std::fs::remove_file(archive.join("refs")).unwrap(); - std::fs::rename(dir.path().join("refs-moved"), archive.join("refs")).unwrap(); - std::fs::remove_file(archive.join("refs/heads/main.lock")).unwrap(); - let snap = watched.snapshot(); - std::fs::write(archive.join("index.lock"), b"ours").unwrap(); - let moved = b.join("archive-moved.git"); - std::fs::rename(&archive, &moved).unwrap(); - std::os::unix::fs::symlink(&outside, &archive).unwrap(); - let left = watched.after_kill(&git, &snap, true); - assert!(left.is_empty()); - assert!(!moved.join("index.lock").exists()); - untouched("archive path swapped"); - // 3. A command that began when the archive path was already a link - // has no handle, and nothing is removed anywhere. - std::fs::write(outside.join("new.lock"), b"theirs").unwrap(); - let snap = watched.snapshot(); - assert!(snap.handle.is_none()); - std::fs::write(outside.join("index.lock"), b"theirs").unwrap(); - assert!(watched.after_kill(&git, &snap, true).is_empty()); - untouched("path a link from the start"); - } - - /// INVARIANT 6: a drill stops inside whichever phase it is told to stop - /// in, never going on to the next, and leaves nothing (its scratch - /// folder is removed). The stop is set as the phase begins; each case - /// fails when the stop is no longer looked at inside that phase. - #[test] - fn a_drill_stops_inside_the_phase_it_is_told_to_stop_in() { - let real = Git::find().expect("git is installed"); - let dir = tempfile::tempdir().unwrap(); - let b = dir.path().join("book"); - let s = book(&b); - commit(&real, &b, "acme", s.head()).unwrap().unwrap(); - let folder = dir.path().join("disk"); - std::fs::create_dir(&folder).unwrap(); - let target = Target::Folder(folder); - push(&real, &b, "acme", &target, true).unwrap(); - let order = [ - "clone", "tree", "checkout", "replay", "verify", "blobs", "vault", "prefix", - ]; - for stop_in in ["clone", "replay", "verify", "blobs", "prefix"] { - let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); - let git = real.clone().with_cancel(flag.clone()).with_phase_watch({ - let (flag, seen) = (flag.clone(), seen.clone()); - std::sync::Arc::new(move |phase: &str| { - seen.lock().unwrap().push(phase.to_string()); - if phase == stop_in { - flag.store(true, std::sync::atomic::Ordering::SeqCst); - } - }) - }); - let scratch = dir.path().join(format!("scratch-{stop_in}")); - let drilled = drill( - &git, - &target, - "acme", - &b.join(crate::JOURNAL_FILE), - &scratch, - ); - assert!( - matches!(drilled, Err(BackupError::Cancelled(_))), - "{stop_in}: {drilled:?}" - ); - let seen = seen.lock().unwrap().clone(); - let last = order - .iter() - .position(|p| *p == seen.last().unwrap()) - .unwrap(); - let at = order.iter().position(|p| *p == stop_in).unwrap(); - assert_eq!(last, at, "{stop_in}: went on to {seen:?}"); - assert!(!scratch.exists(), "{stop_in}: its scratch folder was left"); - } - // Not stopped, it goes through every phase. - let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); - let git = real.clone().with_phase_watch({ - let seen = seen.clone(); - std::sync::Arc::new(move |phase: &str| seen.lock().unwrap().push(phase.to_string())) - }); - drill( - &git, - &target, - "acme", - &b.join(crate::JOURNAL_FILE), - &dir.path().join("whole"), - ) - .unwrap(); - assert_eq!(*seen.lock().unwrap(), order.map(String::from)); - } - - /// A stand-in for git: a script. - fn fake_git(dir: &Path, script: &str, quiet: Duration) -> Git { - use std::os::unix::fs::PermissionsExt; - let exe = dir.join("fake-git"); - std::fs::write(&exe, format!("#!/bin/sh\n{script}\n")).unwrap(); - std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap(); - Git { - exe, - quiet, - cancel: None, - term_grace: TERM_GRACE, - watch: Watch::default(), - } - } - - /// Cancelled, a git that is running is stopped at once, with all it - /// started, and one that would start doesn't (the server's close ends - /// a backup instead of leaving it to run against closed books). - #[test] - fn a_cancelled_git_stops_what_runs_and_starts_nothing() { - let dir = tempfile::tempdir().unwrap(); - let pid = dir.path().join("pid"); - let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - let slow = fake_git( - dir.path(), - &format!("sleep 30 & echo $! > '{}'; sleep 30", pid.display()), - Duration::from_secs(60), - ) - .with_cancel(cancel.clone()); - let running = { - let slow = slow.clone(); - std::thread::spawn(move || slow.run("slow", &[])) - }; - // It is running (it wrote its child's pid) before it is cancelled. - let by = Instant::now() + Duration::from_secs(10); - while !pid.exists() { - assert!(Instant::now() < by, "the fake git never started"); - std::thread::sleep(Duration::from_millis(10)); - } - let cancelled_at = Instant::now(); - cancel.store(true, std::sync::atomic::Ordering::SeqCst); - assert_eq!( - running.join().unwrap().unwrap_err(), - BackupError::Cancelled("slow".into()) - ); - assert!(cancelled_at.elapsed() < Duration::from_secs(5)); - let child: i32 = std::fs::read_to_string(&pid) - .unwrap() - .trim() - .parse() - .unwrap(); - // `run` returned: the group was waited for, so what it started is - // gone now, not at some later moment. - // SAFETY: signal 0 only asks whether the process is there. - assert_ne!(unsafe { libc::kill(child, 0) }, 0, "what it started ran on"); - // And none starts now. - std::fs::remove_file(&pid).unwrap(); - assert_eq!( - slow.run("again", &[]).unwrap_err(), - BackupError::Cancelled("again".into()) - ); - assert!(!pid.exists(), "a cancelled git started anyway"); - } - - /// INVARIANT 5: a git is told to end (SIGTERM, to its whole group) - /// before it is killed, and killed only once the grace has run out: one - /// that ignores the signal (a trap, as a hook may set) is waited for the - /// whole grace, then killed with all it started. - #[test] - fn a_git_that_ignores_sigterm_is_killed_after_the_grace_with_all_it_started() { - let dir = tempfile::tempdir().unwrap(); - let (started, termed) = (dir.path().join("started"), dir.path().join("termed")); - let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - let grace = Duration::from_millis(500); - let stubborn = fake_git( - dir.path(), - &format!( - "trap 'echo term >> \"{}\"' TERM\necho $$ > '{}'\nwhile :; do sleep 0.05; done", - termed.display(), - started.display() - ), - Duration::from_secs(60), - ) - .with_cancel(cancel.clone()) - .with_term_grace(grace); - let running = { - let stubborn = stubborn.clone(); - std::thread::spawn(move || stubborn.run("stubborn", &[])) - }; - let by = Instant::now() + Duration::from_secs(30); - while !started.exists() { - assert!(Instant::now() < by, "the fake git never started"); - std::thread::sleep(Duration::from_millis(10)); - } - let stopped = Instant::now(); - cancel.store(true, std::sync::atomic::Ordering::SeqCst); - assert_eq!( - running.join().unwrap().unwrap_err(), - BackupError::Cancelled("stubborn".into()) - ); - assert!( - stopped.elapsed() >= grace, - "killed before the grace had run out" - ); - assert!(termed.exists(), "it was never sent SIGTERM first"); - let shell: i32 = std::fs::read_to_string(&started) - .unwrap() - .trim() - .parse() - .unwrap(); - // SAFETY: signal 0 only asks whether the process is there. - assert_ne!(unsafe { libc::kill(shell, 0) }, 0, "it ran on"); - } - - #[test] - fn a_git_is_stopped_only_once_it_falls_quiet_and_with_all_it_started() { - let dir = tempfile::tempdir().unwrap(); - let limit = Duration::from_millis(500); - // Talking all along, for longer than the limit: let run. - let talking = fake_git( - dir.path(), - "for i in 1 2 3 4 5 6 7; do echo $i >&2; sleep 0.2; done; echo done", - limit, - ); - assert_eq!(talking.run("talk", &[]).unwrap(), "done"); - // Quiet: stopped, and what it started too. - let pid = dir.path().join("pid"); - let quiet = fake_git( - dir.path(), - &format!("sleep 30 & echo $! > '{}'; sleep 30", pid.display()), - Duration::from_millis(300), - ); - let started = Instant::now(); - assert_eq!( - quiet.run("wait", &[]).unwrap_err(), - BackupError::TimedOut("wait".into()) - ); - assert!(started.elapsed() < Duration::from_secs(10)); - let child: i32 = std::fs::read_to_string(&pid) - .unwrap() - .trim() - .parse() - .unwrap(); - std::thread::sleep(Duration::from_millis(200)); - // SAFETY: signal 0 only asks whether the process is there. - assert_ne!( - unsafe { libc::kill(child, 0) }, - 0, - "what it started still runs" - ); - // Done, leaving something holding its output: not waited for. - let lingering = fake_git(dir.path(), "(sleep 30 &) ; echo ok", GIT_TIMEOUT); - let started = Instant::now(); - assert_eq!(lingering.run("linger", &[]).unwrap(), "ok"); - assert!(started.elapsed() < Duration::from_secs(5)); - // Failing: what it said, in whole lines. - let failing = fake_git(dir.path(), "echo 'fatal: no' >&2; exit 1", GIT_TIMEOUT); - assert_eq!( - failing.run("fail", &[]).unwrap_err(), - BackupError::Git("fail".into(), "fatal: no".into()) - ); - // Said at length, then failing: the end of it is kept (where the - // error is), from a whole line on. - let chatty = fake_git( - dir.path(), - "i=0; while [ $i -lt 30000 ]; do echo \"remote: line $i of a long story that goes on\" >&2; i=$((i+1)); done; echo 'fatal: the end' >&2; exit 1", - GIT_TIMEOUT, - ); - match chatty.run("chat", &[]).unwrap_err() { - BackupError::Git(_, said) => { - assert!(said.ends_with("fatal: the end"), "{said}"); - assert!( - said.lines() - .all(|l| l.starts_with("remote: line ") || l == "fatal: the end"), - "{said}" - ); - } - other => panic!("{other:?}"), - } - // Where its path holds a quote, a push to this computer's own - // repository is refused (its hooks couldn't be turned off). - let quoted = dir.path().join("it's"); - std::fs::create_dir("ed).unwrap(); - let real = Git::find().expect("git is installed"); - std::os::unix::fs::symlink(&real.exe, quoted.join("git")).unwrap(); - let odd = Git { - exe: quoted.join("git"), - quiet: GIT_TIMEOUT, - cancel: None, - term_grace: TERM_GRACE, - watch: Watch::default(), - }; - let b = dir.path().join("book"); - let s = book(&b); - commit(&real, &b, "acme", s.head()).unwrap(); - let disk = dir.path().join("disk"); - std::fs::create_dir(&disk).unwrap(); - let e = push(&odd, &b, "acme", &Target::Folder(disk), true).unwrap_err(); - assert!(e.to_string().contains("quote"), "{e}"); - // A long answer is kept whole (only what it says of itself is cut). - let long = fake_git( - dir.path(), - "i=0; while [ $i -lt 40000 ]; do echo blobs/ab/cd/0123456789012345678901234567890123456789; i=$((i+1)); done", - GIT_TIMEOUT, - ); - assert_eq!(long.run("list", &[]).unwrap().lines().count(), 40000); - } - - #[test] - fn a_repository_with_settings_of_its_own_is_never_pushed_to_or_read() { - let git = Git::find().expect("git is installed"); - let dir = tempfile::tempdir().unwrap(); - let b = dir.path().join("book"); - let s = book(&b); - commit(&git, &b, "acme", s.head()).unwrap(); - let folder = dir.path().join("disk"); - std::fs::create_dir(&folder).unwrap(); - let target = Target::Folder(folder.clone()); - push(&git, &b, "acme", &target, true).unwrap(); - let repo = folder.join("acme.git"); - let marker = dir.path().join("ran"); - let config = std::fs::read_to_string(repo.join("config")).unwrap(); - // A command to run on a push; then objects borrowed from elsewhere. - std::fs::write( - repo.join("config"), - format!( - "{config}[core]\n\talternateRefsCommand = touch '{}'\n", - marker.display() - ), - ) - .unwrap(); - for e in [ - push(&git, &b, "acme", &target, true).unwrap_err(), - push( - &git, - &b, - "acme", - &Target::Remote(repo.display().to_string()), - true, - ) - .unwrap_err(), - verify(&git, repo.to_str().unwrap(), &dir.path().join("v1")).unwrap_err(), - ] { - assert!(e.to_string().contains("settings of its own"), "{e}"); - } - // Where a copy came from is no setting of its own; a command to - // run on its way in is. - std::fs::write( - repo.join("config"), - format!("{config}[remote \"origin\"]\n\turl = /x\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n[branch \"main\"]\n\tremote = origin\n\tmerge = refs/heads/main\n"), - ) - .unwrap(); - push(&git, &b, "acme", &target, true).unwrap(); - std::fs::write( - repo.join("config"), - format!( - "{config}[remote \"origin\"]\n\tuploadpack = touch '{}'\n", - marker.display() - ), - ) - .unwrap(); - assert!(push(&git, &b, "acme", &target, true).is_err()); - std::fs::write(repo.join("config"), &config).unwrap(); - std::fs::write(repo.join("objects/info/alternates"), "/elsewhere/objects\n").unwrap(); - let e = verify(&git, repo.to_str().unwrap(), &dir.path().join("v2")).unwrap_err(); - assert!(e.to_string().contains("settings of its own"), "{e}"); - assert!(!marker.exists()); - // Plain again: fine. - std::fs::remove_file(repo.join("objects/info/alternates")).unwrap(); - push(&git, &b, "acme", &target, true).unwrap(); - // Something in it that sends git to another repository first: a - // .git in it, or another's files named in it. - let other = dir.path().join("other.git"); - git.run( - "init", - &[os("init"), os("--bare"), os("-q"), other.as_os_str()], - ) - .unwrap(); - for (name, text) in [ - (".git", format!("gitdir: {}\n", other.display())), - ("commondir", format!("{}\n", other.display())), - ("gitdir", format!("{}\n", other.display())), - ] { - std::fs::write(repo.join(name), text).unwrap(); - let e = push(&git, &b, "acme", &target, true).unwrap_err(); - assert!(e.to_string().contains("settings of its own"), "{name}: {e}"); - let e = verify( - &git, - repo.to_str().unwrap(), - &dir.path().join(format!("v-{name}")), - ) - .unwrap_err(); - assert!(e.to_string().contains("settings of its own"), "{name}: {e}"); - std::fs::remove_file(repo.join(name)).unwrap(); - } - // Something beside it git would take in its place: a repository - // named the same with .git after it, or a bundle. - let decoy = folder.join("acme.git.git"); - git.run( - "init", - &[os("init"), os("--bare"), os("-q"), decoy.as_os_str()], - ) - .unwrap(); - let e = push(&git, &b, "acme", &target, true).unwrap_err(); - assert!(e.to_string().contains("settings of its own"), "{e}"); - std::fs::remove_dir_all(&decoy).unwrap(); - std::fs::write(folder.join("acme.git.bundle"), b"x").unwrap(); - let e = verify(&git, repo.to_str().unwrap(), &dir.path().join("v-bundle")).unwrap_err(); - assert!(e.to_string().contains("settings of its own"), "{e}"); - std::fs::remove_file(folder.join("acme.git.bundle")).unwrap(); - // A HEAD and a config but no objects or refs: not a repository git - // stops at (it would look beside it). - let hollow = dir.path().join("hollow.git"); - std::fs::create_dir(&hollow).unwrap(); - std::fs::write(hollow.join("HEAD"), "ref: refs/heads/main\n").unwrap(); - std::fs::write(hollow.join("config"), "[core]\n\tbare = true\n").unwrap(); - let e = push( - &git, - &b, - "acme", - &Target::Remote(hollow.display().to_string()), - true, - ) - .unwrap_err(); - assert!(e.to_string().contains("name the repository itself"), "{e}"); - // Its parts, or itself, a link elsewhere: refused (what is written - // there would land elsewhere). - let elsewhere = dir.path().join("elsewhere-objects"); - std::fs::rename(repo.join("objects"), &elsewhere).unwrap(); - std::os::unix::fs::symlink(&elsewhere, repo.join("objects")).unwrap(); - let e = push(&git, &b, "acme", &target, true).unwrap_err(); - assert!(e.to_string().contains("settings of its own"), "{e}"); - std::fs::remove_file(repo.join("objects")).unwrap(); - std::fs::rename(&elsewhere, repo.join("objects")).unwrap(); - let moved = dir.path().join("moved.git"); - std::fs::rename(&repo, &moved).unwrap(); - std::os::unix::fs::symlink(&moved, &repo).unwrap(); - let e = push(&git, &b, "acme", &target, true).unwrap_err(); - assert!(e.to_string().contains("settings of its own"), "{e}"); - std::fs::remove_file(&repo).unwrap(); - std::fs::rename(&moved, &repo).unwrap(); - push(&git, &b, "acme", &target, true).unwrap(); - // The folder holding it a link (to a disk's mount, say): fine. - let linked = dir.path().join("linked-disk"); - std::os::unix::fs::symlink(&folder, &linked).unwrap(); - push(&git, &b, "acme", &Target::Folder(linked), true).unwrap(); - // Shared, a copy's origin, a newer ref store: all plain. - let shared = dir.path().join("shared.git"); - git.run( - "init", - &[ - os("init"), - os("--bare"), - os("-q"), - os("--shared"), - shared.as_os_str(), - ], - ) - .unwrap(); - let plain = std::fs::read_to_string(shared.join("config")).unwrap(); - std::fs::write( - shared.join("config"), - format!( - "{plain}[remote \"origin\"]\n\tmirror = true\n[extensions]\n\trefStorage = files\n" - ), - ) - .unwrap(); - plain_repository(&git, shared.to_str().unwrap()).unwrap(); - // Not the repository itself (git would look beside it, or in it). - for address in [ - folder.join("acme"), - folder.clone(), - dir.path().join("nothing-here"), - ] { - let e = push( - &git, - &b, - "acme", - &Target::Remote(address.display().to_string()), - true, - ) - .unwrap_err(); - assert!( - e.to_string().contains("name the repository itself"), - "{address:?}: {e}" - ); - } - assert!(!marker.exists()); - } - - #[test] - fn a_backup_folder_gone_from_a_connected_disk_is_never_made_again() { - let git = Git::find().expect("git is installed"); - let dir = tempfile::tempdir().unwrap(); - let b = dir.path().join("book"); - let s = book(&b); - commit(&git, &b, "acme", s.head()).unwrap(); - // A mount point with nothing mounted: there, but not the backup. - let mount = dir.path().join("mnt"); - std::fs::create_dir(&mount).unwrap(); - let target = Target::Folder(mount.clone()); - assert_eq!( - push(&git, &b, "acme", &target, false).unwrap_err(), - BackupError::NoBackupThere - ); - // A folder that isn't there at all: not connected. - let gone = Target::Folder(dir.path().join("gone")); - assert_eq!( - push(&git, &b, "acme", &gone, false).unwrap_err(), - BackupError::NoFolder - ); - assert!(!mount.join("acme.git").exists()); - // Never backed up there yet: made. - push(&git, &b, "acme", &target, true).unwrap(); - assert!(mount.join("acme.git").join("HEAD").is_file()); - } - - #[test] - fn what_git_said_cut_short_ends_at_its_last_whole_line() { - assert_eq!( - said(b"ot/books/acme'\nfatal: one\nfatal: two", true), - "fatal: one\nfatal: two" - ); - assert_eq!(said(b"ot/books/acme' is not", true), ""); - assert_eq!( - said(b"fatal: one\nfatal: two", false), - "fatal: one\nfatal: two" - ); - } - - /// Every file under `dir`. - fn walk(dir: &Path) -> Vec { - let mut out = Vec::new(); - for e in std::fs::read_dir(dir).unwrap() { - let p = e.unwrap().path(); - if p.is_dir() { - out.extend(walk(&p)); - } else { - out.push(p); - } - } - out - } -} diff --git a/crates/ledger-store/src/backups/cut.rs b/crates/ledger-store/src/backup/cut.rs similarity index 100% rename from crates/ledger-store/src/backups/cut.rs rename to crates/ledger-store/src/backup/cut.rs diff --git a/crates/ledger-store/src/backups/form.rs b/crates/ledger-store/src/backup/form.rs similarity index 100% rename from crates/ledger-store/src/backups/form.rs rename to crates/ledger-store/src/backup/form.rs diff --git a/crates/ledger-store/src/backups/io.rs b/crates/ledger-store/src/backup/io.rs similarity index 99% rename from crates/ledger-store/src/backups/io.rs rename to crates/ledger-store/src/backup/io.rs index 2de10e1f..a8213369 100644 --- a/crates/ledger-store/src/backups/io.rs +++ b/crates/ledger-store/src/backup/io.rs @@ -1,5 +1,5 @@ //! Where a backup's files live, behind one seam: a folder on a disk -//! ([`DirSet`]), or the one-file form ([`crate::backups::single`]). +//! ([`DirSet`]), or the one-file form ([`crate::backup::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 diff --git a/crates/ledger-store/src/backups/mod.rs b/crates/ledger-store/src/backup/mod.rs similarity index 100% rename from crates/ledger-store/src/backups/mod.rs rename to crates/ledger-store/src/backup/mod.rs diff --git a/crates/ledger-store/src/backups/read.rs b/crates/ledger-store/src/backup/read.rs similarity index 100% rename from crates/ledger-store/src/backups/read.rs rename to crates/ledger-store/src/backup/read.rs diff --git a/crates/ledger-store/src/backups/seal.rs b/crates/ledger-store/src/backup/seal.rs similarity index 98% rename from crates/ledger-store/src/backups/seal.rs rename to crates/ledger-store/src/backup/seal.rs index 4e23d170..0bfbf03c 100644 --- a/crates/ledger-store/src/backups/seal.rs +++ b/crates/ledger-store/src/backup/seal.rs @@ -137,6 +137,13 @@ impl BackupKey { self.kdf.salt == other.kdf.salt && bool::from(self.master.ct_eq(&*other.master)) } + /// A short, public name for this key: what the salt it was derived + /// with hashes to. Said in a record to tell one passphrase's backups + /// from another's; it opens nothing. + pub fn fingerprint(&self) -> String { + sha_hex(self.kdf.salt.as_bytes())[..12].to_string() + } + /// 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) diff --git a/crates/ledger-store/src/backups/single.rs b/crates/ledger-store/src/backup/single.rs similarity index 100% rename from crates/ledger-store/src/backups/single.rs rename to crates/ledger-store/src/backup/single.rs diff --git a/crates/ledger-store/src/backups/write.rs b/crates/ledger-store/src/backup/write.rs similarity index 100% rename from crates/ledger-store/src/backups/write.rs rename to crates/ledger-store/src/backup/write.rs diff --git a/crates/ledger-store/src/drain.rs b/crates/ledger-store/src/drain.rs deleted file mode 100644 index eda2bc92..00000000 --- a/crates/ledger-store/src/drain.rs +++ /dev/null @@ -1,370 +0,0 @@ -//! Reading what a child process says, without waiting on a pipe it doesn't -//! hold (P11c, found on Windows in the open/close hammer). -//! -//! ```text -//! GOAL: the output of a child that has ended is in hand once everything -//! it wrote has been read, however long some other process keeps the -//! other end of its pipe open. -//! SOURCE: the standard library's `Command` (Windows: `CreateProcessW` with -//! `bInheritHandles`, the child's end of each pipe inheritable from -//! the moment it is made until the parent closes it, so a process -//! started by another thread in that moment holds a copy and the -//! pipe has no end-of-file until that process ends too); found by -//! the open/close hammer on Windows (plan/p15-app-and-relay.md -//! 3.1, D-77). -//! INVARIANTS: -//! 1. Nothing a child wrote is lost: bytes already in the pipe when the -//! child ended are read before the reader is let go (the pipe is asked -//! what it holds; the reader is let go only when it is blocked in its -//! read with nothing in the pipe, for QUIET together). -//! 2. The reader is let go when the pipe reaches its end (every writer -//! gone), or when it is idle as in 1, or after `limit`, whichever is -//! first; which one is reported ([`Closed`]). -//! 3. A reader let go while still blocked ends by itself when the last -//! holder of the pipe's other end lets go; it holds nothing else. -//! ``` - -use std::io::Read; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::sync::{Arc, Mutex}; -use std::time::{Duration, Instant}; - -/// How long a reader must be seen blocked in its read, with nothing in the -/// pipe, before it is let go (INVARIANT 1): longer than any thread waits to -/// run after it has been handed a byte. -pub(crate) const QUIET: Duration = Duration::from_millis(100); - -/// How long a reader in its read, with no read returning, is waited for when -/// the pipe can't say whether it holds anything. -const BLIND: Duration = Duration::from_millis(1500); - -/// How the wait for a pipe ended. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum Closed { - /// The pipe reached its end: every writer was gone. - Eof, - /// Something else still held the pipe's other end, and nothing was left - /// in it to read. - Idle, - /// The limit passed first; what had been read is what is returned. - Limit, -} - -impl Closed { - pub(crate) fn word(self) -> &'static str { - match self { - Closed::Eof => "eof", - Closed::Idle => "held-open", - Closed::Limit => "limit", - } - } -} - -/// A pipe being read on its own thread. -pub(crate) struct Drain { - bytes: Arc>>, - /// True while the pipe is open (its reader hasn't ended): guards the - /// raw descriptor or handle asked about below. - open: Arc>, - /// True from just before the reader calls `read` until it returns. - reading: Arc, - /// How many reads have returned. - reads: Arc, - raw: usize, - cap: usize, -} - -/// The raw descriptor (Unix) or handle (Windows) of a pipe, as a number. -pub(crate) trait Raw { - fn raw(&self) -> usize; -} - -#[cfg(unix)] -impl Raw for T { - fn raw(&self) -> usize { - self.as_raw_fd() as usize - } -} - -#[cfg(windows)] -impl Raw for T { - fn raw(&self) -> usize { - self.as_raw_handle() as usize - } -} - -/// How many bytes `pipe` holds now, if that can be asked: `None` when it -/// can't (the pipe is at its end, or the question failed), which is never -/// taken as "nothing". -fn pending(raw: usize) -> Option { - #[cfg(unix)] - { - let mut fd = libc::pollfd { - fd: raw as libc::c_int, - events: libc::POLLIN, - revents: 0, - }; - // SAFETY: one valid pollfd, and no wait. - let ready = unsafe { libc::poll(&mut fd, 1, 0) }; - // Anything else is readable, or hung up (end of file), or failed: - // never "nothing". - if ready == 0 { Some(0) } else { None } - } - #[cfg(windows)] - { - use windows_sys::Win32::System::Pipes::PeekNamedPipe; - let mut available: u32 = 0; - // SAFETY: `raw` is a pipe handle that stays open while `open` is - // held (the reader closes it only under that lock); no buffer is - // asked for, only the count. - let ok = unsafe { - PeekNamedPipe( - raw as *mut core::ffi::c_void, - std::ptr::null_mut(), - 0, - std::ptr::null_mut(), - &mut available, - std::ptr::null_mut(), - ) - }; - if ok == 0 { - None - } else { - Some(available as usize) - } - } -} - -impl Drain { - /// Start reading `pipe` (if any) on a thread of its own, keeping the - /// last `cap` bytes; `heard` is set to the milliseconds since `started` - /// whenever a byte arrives. - pub(crate) fn start

( - pipe: Option

, - cap: usize, - started: Instant, - heard: Arc, - ) -> Drain - where - P: Read + Raw + Send + 'static, - { - let bytes = Arc::new(Mutex::new(Vec::new())); - let open = Arc::new(Mutex::new(pipe.is_some())); - let reading = Arc::new(AtomicBool::new(false)); - let reads = Arc::new(AtomicU64::new(0)); - let raw = pipe.as_ref().map_or(0, Raw::raw); - let (b, o, r, n_reads) = (bytes.clone(), open.clone(), reading.clone(), reads.clone()); - if let Some(mut p) = pipe { - std::thread::spawn(move || { - let mut buf = [0u8; 8192]; - loop { - r.store(true, Ordering::SeqCst); - let got = p.read(&mut buf); - r.store(false, Ordering::SeqCst); - n_reads.fetch_add(1, Ordering::SeqCst); - match got { - Ok(0) => break, - Ok(n) => { - heard.store(started.elapsed().as_millis() as u64, Ordering::Relaxed); - // Bounded: a git that says this much is kept - // only in part, its last part (where its - // errors are). - let mut bytes = b.lock().unwrap_or_else(|e| e.into_inner()); - bytes.extend_from_slice(&buf[..n]); - if bytes.len() > cap.saturating_mul(2) { - let cut = bytes.len() - cap; - bytes.drain(..cut); - } - } - Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} - Err(_) => break, - } - } - // Closed under the lock the question above is asked under, - // so a descriptor that is gone is never asked about. - let mut open = o.lock().unwrap_or_else(|e| e.into_inner()); - *open = false; - drop(p); - }); - } - Drain { - bytes, - open, - reading, - reads, - raw, - cap, - } - } - - /// Whether the pipe has reached its end. - fn ended(&self) -> bool { - !*self.open.lock().unwrap_or_else(|e| e.into_inner()) - } - - /// Whether the reader is blocked in its read with nothing in the pipe; - /// when the pipe can't say what it holds, whether the reader is in its - /// read (`None` is returned for the caller to weigh against time). - fn idle(&self) -> Option { - let open = self.open.lock().unwrap_or_else(|e| e.into_inner()); - if !*open || !self.reading.load(Ordering::SeqCst) { - return Some(false); - } - pending(self.raw).map(|n| n == 0) - } - - /// What has been read, in whole (the last `cap` bytes of it). - fn taken(&self) -> Vec { - let mut bytes = self.bytes.lock().unwrap_or_else(|e| e.into_inner()); - if bytes.len() > self.cap { - let cut = bytes.len() - self.cap; - bytes.drain(..cut); - } - std::mem::take(&mut *bytes) - } -} - -/// Wait, until `limit` after `since`, for every one of `drains` to reach -/// its end or to be idle (INVARIANT 1 and 2), then take what each read: the -/// bytes, and how its wait ended. -pub(crate) fn finish( - drains: [&Drain; N], - since: Instant, - limit: Duration, -) -> [(Vec, Closed); N] { - // When each reader was first seen blocked in its read (with nothing in - // the pipe, or the pipe unable to say), and the reads it had made then. - let mut idle_since: [Option; N] = [None; N]; - let mut blind_since: [Option<(Instant, u64)>; N] = [None; N]; - let mut how: [Option; N] = [None; N]; - loop { - let now = Instant::now(); - for (i, d) in drains.iter().enumerate() { - if how[i].is_some() { - continue; - } - if d.ended() { - how[i] = Some(Closed::Eof); - } else { - match d.idle() { - Some(true) => { - let since = *idle_since[i].get_or_insert(now); - if now.duration_since(since) >= QUIET { - how[i] = Some(Closed::Idle); - } - } - Some(false) => { - idle_since[i] = None; - blind_since[i] = None; - } - // The pipe can't say what it holds: the reader in its - // read, with no read returning for BLIND, is idle (a - // reader is never kept from a byte for that long). - None => { - let reads = d.reads.load(Ordering::SeqCst); - let (since, was) = *blind_since[i].get_or_insert((now, reads)); - if was != reads { - blind_since[i] = Some((now, reads)); - } else if now.duration_since(since) >= BLIND { - how[i] = Some(Closed::Idle); - } - } - } - } - } - if how.iter().all(Option::is_some) { - break; - } - if now.duration_since(since) >= limit { - break; - } - std::thread::sleep(Duration::from_millis(2)); - } - // An end reached in the instant before this is read: its last bytes - // are in, the reader having stored them before it ended. - std::array::from_fn(|i| (drains[i].taken(), how[i].unwrap_or(Closed::Limit))) -} - -#[cfg(all(test, unix))] -mod tests { - use super::*; - use std::process::{Command, Stdio}; - - fn drained(child: &mut std::process::Child) -> (Drain, Drain) { - let heard = Arc::new(AtomicU64::new(0)); - let now = Instant::now(); - ( - Drain::start(child.stdout.take(), usize::MAX, now, heard.clone()), - Drain::start(child.stderr.take(), 1 << 20, now, heard), - ) - } - - /// INVARIANT 1 and 2. A child that ends, leaving a grandchild that - /// still holds its pipes (the Windows leak, made by hand), has its - /// whole output read, and the wait ends in far less than the limit. - #[test] - fn a_pipe_another_process_still_holds_is_read_in_whole_without_waiting_for_it() { - let mut child = Command::new("sh") - .arg("-c") - .arg("echo out-one; echo err-one >&2; (sleep 5 .lock`, `packed-refs.lock`, `shallow.lock`, -//! `config.lock`). -//! INVARIANTS: -//! 1. A repository is opened once (`RepoDir::open`, `open_in`): a -//! directory that is not a link, the folder it was found in kept as -//! the book's own. Every look and every removal after that goes -//! through that handle: the folders below it (`refs/`, and those -//! under it) are each opened from the one above with links refused, -//! so a folder swapped for a link, or the repository's own path swapped -//! for one, after the handle was opened, sends nothing anywhere: the -//! handle still names the folder that was opened. -//! 2. Only a regular file is ever removed (never a link, never a folder, -//! never a file whose type changed), and only one named as git names -//! its locks, in the places git puts them (`is_lock`). A name that -//! isn't one is refused. -//! 3. Where there is no directory handle to be had (not Unix) each step -//! looks at the path itself and refuses a link: the same rules, -//! without the guarantee against a swap in between. Nothing else -//! about the platform's behaviour is designed here. -//! ``` - -use std::io; -use std::path::{Path, PathBuf}; -use std::time::SystemTime; - -/// Locks git makes in a repository's own folder. -const TOP: [&str; 5] = [ - "HEAD.lock", - "index.lock", - "config.lock", - "packed-refs.lock", - "shallow.lock", -]; -/// Locks git makes below it, outside `refs/`. -const BELOW: [&str; 2] = [ - "objects/info/commit-graph.lock", - "objects/pack/multi-pack-index.lock", -]; -/// How deep under `refs/` a lock is looked for. -const REFS_DEPTH: usize = 12; - -/// Whether `rel` (a path in a repository, with `/` between its parts) is -/// named as git names a lock, in a place git puts one (INVARIANT 2). -pub fn is_lock(rel: &str) -> bool { - if TOP.contains(&rel) || BELOW.contains(&rel) { - return true; - } - let Some(under) = rel.strip_prefix("refs/") else { - return false; - }; - let parts: Vec<&str> = under.split('/').collect(); - parts.len() <= REFS_DEPTH - && parts - .iter() - .all(|p| !p.is_empty() && *p != "." && *p != "..") - && parts - .last() - .is_some_and(|name| name.len() > ".lock".len() && name.ends_with(".lock")) -} - -/// A lock found: its path in the repository, and when it was last written. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Found { - /// `index.lock`, `refs/heads/main.lock`. - pub lock: String, - /// Its modification time, when the system said. - pub modified: Option, -} - -/// A repository's folder, opened once (INVARIANT 1). -#[derive(Debug)] -pub struct RepoDir { - path: PathBuf, - inner: imp::Dir, -} - -impl RepoDir { - /// The folder at `path`, which must not itself be a link. - pub fn open(path: &Path) -> io::Result { - Ok(RepoDir { - path: path.to_path_buf(), - inner: imp::open(path)?, - }) - } - - /// The folder `name` inside the folder `parent` (the book's own folder - /// holding its archive): `name` must not be a link. - pub fn open_in(parent: &Path, name: &str) -> io::Result { - Ok(RepoDir { - path: parent.join(name), - inner: imp::open_in(parent, name)?, - }) - } - - /// The path it was opened by (for words, never for an operation). - pub fn path(&self) -> &Path { - &self.path - } - - /// The locks in it, sorted: regular files named as git names its locks. - pub fn locks(&self) -> Vec { - let mut out = Vec::new(); - for rel in TOP.iter().chain(BELOW.iter()) { - if let Some(modified) = self.inner.regular(rel) { - out.push(Found { - lock: (*rel).to_string(), - modified, - }); - } - } - self.inner.refs(&mut out, REFS_DEPTH); - out.sort_by(|a, b| a.lock.cmp(&b.lock)); - out - } - - /// Remove the lock `rel` (INVARIANTS 1, 2): Ok(true) if a regular file - /// of that name was removed, Ok(false) if there was none (or it was - /// not a regular file: nothing was done), Err if the name isn't a - /// lock's or the system refused. - pub fn remove(&self, rel: &str) -> io::Result { - if !is_lock(rel) { - return Err(io::Error::new( - io::ErrorKind::InvalidInput, - "not a name git gives a lock", - )); - } - self.inner.remove(rel) - } -} - -#[cfg(unix)] -mod imp { - use super::{Found, SystemTime}; - use std::ffi::{CStr, CString, OsStr}; - use std::io; - use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd}; - use std::os::unix::ffi::OsStrExt; - use std::path::Path; - - #[derive(Debug)] - pub struct Dir(OwnedFd); - - const FLAGS: libc::c_int = libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC; - - fn c(text: &OsStr) -> io::Result { - CString::new(text.as_bytes()) - .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "a name with a NUL")) - } - - fn owned(fd: libc::c_int) -> io::Result { - if fd < 0 { - Err(io::Error::last_os_error()) - } else { - // SAFETY: a file descriptor just returned by the system, owned - // by no one else. - Ok(unsafe { OwnedFd::from_raw_fd(fd) }) - } - } - - pub fn open(path: &Path) -> io::Result

{ - let path = c(path.as_os_str())?; - // SAFETY: a NUL-ended path; the flags refuse a link at its end. - owned(unsafe { libc::open(path.as_ptr(), FLAGS | libc::O_NOFOLLOW) }).map(Dir) - } - - pub fn open_in(parent: &Path, name: &str) -> io::Result { - let parent = c(parent.as_os_str())?; - // SAFETY: as in `open`; the parent may be reached through links (it - // is the book's own folder), only `name` may not be one. - let parent = owned(unsafe { libc::open(parent.as_ptr(), FLAGS) })?; - sub(parent.as_raw_fd(), name).map(Dir) - } - - /// The folder `name` of `dir`, a link refused. - fn sub(dir: RawFd, name: &str) -> io::Result { - let name = c(OsStr::new(name))?; - // SAFETY: `dir` is open for the call; the name is NUL-ended. - owned(unsafe { libc::openat(dir, name.as_ptr(), FLAGS | libc::O_NOFOLLOW) }) - } - - /// `name` in `dir` as it is (a link is not followed): its stat. - fn stat(dir: RawFd, name: &str) -> io::Result { - let name = c(OsStr::new(name))?; - // SAFETY: zeroed stat is a valid out-parameter; `dir` is open. - let mut st: libc::stat = unsafe { std::mem::zeroed() }; - let found = - unsafe { libc::fstatat(dir, name.as_ptr(), &mut st, libc::AT_SYMLINK_NOFOLLOW) }; - if found == 0 { - Ok(st) - } else { - Err(io::Error::last_os_error()) - } - } - - fn is_regular(st: &libc::stat) -> bool { - (st.st_mode & libc::S_IFMT) == libc::S_IFREG - } - - fn is_dir(st: &libc::stat) -> bool { - (st.st_mode & libc::S_IFMT) == libc::S_IFDIR - } - - fn modified(st: &libc::stat) -> Option { - let secs = u64::try_from(st.st_mtime).ok()?; - let nanos = u32::try_from(st.st_mtime_nsec).ok()?; - Some(SystemTime::UNIX_EPOCH + std::time::Duration::new(secs, nanos)) - } - - /// The names in the folder `dir` (a fresh look each time). - fn names(dir: RawFd) -> Vec { - // SAFETY: a duplicate of an open descriptor, handed to fdopendir, - // which owns it from then on (closedir closes it). - let copy = unsafe { libc::dup(dir) }; - if copy < 0 { - return Vec::new(); - } - let stream = unsafe { libc::fdopendir(copy) }; - if stream.is_null() { - // SAFETY: fdopendir didn't take it. - unsafe { libc::close(copy) }; - return Vec::new(); - } - let mut out = Vec::new(); - // SAFETY: `stream` is a live directory stream until closedir; each - // entry's name is a NUL-ended string valid until the next readdir. - unsafe { - libc::rewinddir(stream); - loop { - let entry = libc::readdir(stream); - if entry.is_null() { - break; - } - let name = CStr::from_ptr((*entry).d_name.as_ptr()); - if let Ok(name) = name.to_str() - && name != "." - && name != ".." - { - out.push(name.to_string()); - } - } - libc::closedir(stream); - } - out - } - - impl Dir { - /// The folder holding `rel`, opened step by step from this one - /// with a link refused at each, and `rel`'s last part. - fn parent_of<'a>(&self, rel: &'a str) -> io::Result<(OwnedFd, &'a str)> { - let mut parts: Vec<&str> = rel.split('/').collect(); - let last = parts.pop().ok_or(io::ErrorKind::InvalidInput)?; - // SAFETY: a duplicate of the open descriptor, owned here. - let mut here = owned(unsafe { libc::dup(self.0.as_raw_fd()) })?; - for part in parts { - here = sub(here.as_raw_fd(), part)?; - } - Ok((here, last)) - } - - /// A regular file at `rel`: its modification time (when known). - pub fn regular(&self, rel: &str) -> Option> { - let (parent, name) = self.parent_of(rel).ok()?; - let st = stat(parent.as_raw_fd(), name).ok()?; - is_regular(&st).then(|| modified(&st)) - } - - /// The locks under `refs/`, in `out`. - pub fn refs(&self, out: &mut Vec, depth: usize) { - let Ok(refs) = sub(self.0.as_raw_fd(), "refs") else { - return; - }; - fn walk(dir: RawFd, prefix: &str, depth: usize, out: &mut Vec) { - for name in names(dir) { - let Ok(st) = stat(dir, &name) else { continue }; - let rel = format!("{prefix}{name}"); - if is_regular(&st) { - if super::is_lock(&rel) { - out.push(Found { - lock: rel, - modified: modified(&st), - }); - } - } else if is_dir(&st) - && depth > 0 - && let Ok(inner) = sub(dir, &name) - { - walk(inner.as_raw_fd(), &format!("{rel}/"), depth - 1, out); - } - } - } - walk(refs.as_raw_fd(), "refs/", depth, out); - } - - pub fn remove(&self, rel: &str) -> io::Result { - let (parent, name) = match self.parent_of(rel) { - Ok(found) => found, - // A folder that isn't there (or is a link): nothing to remove. - Err(_) => return Ok(false), - }; - match stat(parent.as_raw_fd(), name) { - Ok(st) if is_regular(&st) => {} - _ => return Ok(false), - } - let name = c(OsStr::new(name))?; - // SAFETY: the parent is open; the name is NUL-ended and relative - // to it, and names a regular file just looked at. - let removed = unsafe { libc::unlinkat(parent.as_raw_fd(), name.as_ptr(), 0) }; - if removed == 0 { - Ok(true) - } else { - let e = io::Error::last_os_error(); - if e.kind() == io::ErrorKind::NotFound { - Ok(false) - } else { - Err(e) - } - } - } - } -} - -#[cfg(not(unix))] -mod imp { - use super::{Found, SystemTime}; - use std::io; - use std::path::{Path, PathBuf}; - - #[derive(Debug)] - pub struct Dir(PathBuf); - - fn plain(path: &Path) -> io::Result<()> { - let meta = std::fs::symlink_metadata(path)?; - if meta.file_type().is_symlink() || !meta.is_dir() { - return Err(io::Error::new( - io::ErrorKind::InvalidInput, - "not a plain folder", - )); - } - Ok(()) - } - - pub fn open(path: &Path) -> io::Result { - plain(path)?; - Ok(Dir(path.to_path_buf())) - } - - pub fn open_in(parent: &Path, name: &str) -> io::Result { - open(&parent.join(name)) - } - - impl Dir { - fn at(&self, rel: &str) -> io::Result { - let mut path = self.0.clone(); - let mut parts: Vec<&str> = rel.split('/').collect(); - let last = parts.pop().ok_or(io::ErrorKind::InvalidInput)?; - for part in parts { - path.push(part); - plain(&path)?; - } - path.push(last); - Ok(path) - } - - pub fn regular(&self, rel: &str) -> Option> { - let path = self.at(rel).ok()?; - let meta = std::fs::symlink_metadata(path).ok()?; - meta.file_type().is_file().then(|| meta.modified().ok()) - } - - pub fn refs(&self, out: &mut Vec, depth: usize) { - fn walk(dir: &Path, prefix: &str, depth: usize, out: &mut Vec) { - let Ok(entries) = std::fs::read_dir(dir) else { - return; - }; - for e in entries.flatten() { - let Ok(meta) = std::fs::symlink_metadata(e.path()) else { - continue; - }; - let rel = format!("{prefix}{}", e.file_name().to_string_lossy()); - if meta.file_type().is_file() { - if super::is_lock(&rel) { - out.push(Found { - lock: rel, - modified: meta.modified().ok(), - }); - } - } else if meta.is_dir() && !meta.file_type().is_symlink() && depth > 0 { - walk(&e.path(), &format!("{rel}/"), depth - 1, out); - } - } - } - let refs = self.0.join("refs"); - if plain(&refs).is_ok() { - walk(&refs, "refs/", depth, out); - } - } - - pub fn remove(&self, rel: &str) -> io::Result { - let Ok(path) = self.at(rel) else { - return Ok(false); - }; - match std::fs::symlink_metadata(&path) { - Ok(meta) if meta.file_type().is_file() => std::fs::remove_file(path).map(|()| true), - _ => Ok(false), - } - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn repo(dir: &Path) -> PathBuf { - let repo = dir.join("repo.git"); - std::fs::create_dir_all(repo.join("refs/heads")).unwrap(); - std::fs::create_dir_all(repo.join("objects/pack")).unwrap(); - std::fs::create_dir_all(repo.join("objects/info")).unwrap(); - repo - } - - #[test] - fn only_the_names_git_gives_its_locks_are_locks() { - for yes in [ - "HEAD.lock", - "index.lock", - "config.lock", - "packed-refs.lock", - "shallow.lock", - "refs/heads/main.lock", - "refs/heads/feature/x.lock", - "refs/tags/v1.lock", - "objects/info/commit-graph.lock", - "objects/pack/multi-pack-index.lock", - ] { - assert!(is_lock(yes), "{yes}"); - } - for no in [ - "", - ".lock", - "refs/.lock", - "refs/heads/", - "refs/heads/main", - "refs/heads/../../x.lock", - "refs//x.lock", - "refs/heads/./x.lock", - "other.lock", - "objects/pack/pack-1.pack", - "objects/other.lock", - "../index.lock", - "/etc/x.lock", - "hooks/pre-commit.lock", - "refs", - ] { - assert!(!is_lock(no), "{no:?}"); - } - } - - #[test] - fn locks_are_found_and_only_regular_files_are_removed() { - let dir = tempfile::tempdir().unwrap(); - let repo = repo(dir.path()); - std::fs::write(repo.join("index.lock"), b"").unwrap(); - std::fs::write(repo.join("refs/heads/main.lock"), b"").unwrap(); - // Named like locks, but not files: neither is listed nor removed. - std::fs::create_dir(repo.join("HEAD.lock")).unwrap(); - std::fs::write(dir.path().join("elsewhere"), b"").unwrap(); - #[cfg(unix)] - std::os::unix::fs::symlink(dir.path().join("elsewhere"), repo.join("config.lock")).unwrap(); - // Not a lock's name. - std::fs::write(repo.join("refs/heads/main"), b"").unwrap(); - let handle = RepoDir::open(&repo).unwrap(); - let found: Vec = handle.locks().into_iter().map(|f| f.lock).collect(); - assert_eq!(found, ["index.lock", "refs/heads/main.lock"]); - assert!(handle.locks().iter().all(|f| f.modified.is_some())); - assert!(handle.remove("index.lock").unwrap()); - assert!(!handle.remove("index.lock").unwrap(), "already gone"); - assert!(!handle.remove("HEAD.lock").unwrap(), "a folder stays"); - assert!(repo.join("HEAD.lock").is_dir()); - #[cfg(unix)] - { - assert!(!handle.remove("config.lock").unwrap(), "a link stays"); - assert!(repo.join("config.lock").is_symlink()); - assert!(dir.path().join("elsewhere").exists()); - } - assert!(handle.remove("refs/heads/main").is_err(), "not a lock"); - assert!(repo.join("refs/heads/main").exists()); - assert!(handle.remove("../elsewhere.lock").is_err()); - } - - /// INVARIANT 1: a folder (or the repository's own path) swapped for a - /// link after the handle was opened sends nothing anywhere. - #[cfg(unix)] - #[test] - fn a_folder_swapped_for_a_link_after_the_handle_was_opened_touches_nothing_outside() { - let dir = tempfile::tempdir().unwrap(); - let outside = dir.path().join("outside"); - std::fs::create_dir_all(outside.join("refs/heads")).unwrap(); - for lock in ["index.lock", "HEAD.lock", "refs/heads/main.lock"] { - std::fs::write(outside.join(lock), b"theirs").unwrap(); - } - // `refs` swapped for a link to a folder holding a lock of that name. - let repo_path = repo(dir.path()); - std::fs::write(repo_path.join("refs/heads/main.lock"), b"ours").unwrap(); - let handle = RepoDir::open(&repo_path).unwrap(); - std::fs::rename(repo_path.join("refs"), dir.path().join("refs-moved")).unwrap(); - std::os::unix::fs::symlink(outside.join("refs"), repo_path.join("refs")).unwrap(); - assert!(!handle.remove("refs/heads/main.lock").unwrap()); - assert!(handle.locks().is_empty(), "a link is not looked through"); - assert_eq!( - std::fs::read(outside.join("refs/heads/main.lock")).unwrap(), - b"theirs" - ); - assert_eq!( - std::fs::read(dir.path().join("refs-moved/heads/main.lock")).unwrap(), - b"ours", - "nor was the folder it moved to touched through the link" - ); - // The repository's own path swapped for a link: the handle still - // names the folder it opened (moved aside), and the link's target - // is never touched. - let second = dir.path().join("second.git"); - std::fs::create_dir_all(second.join("refs")).unwrap(); - std::fs::write(second.join("index.lock"), b"ours").unwrap(); - let handle = RepoDir::open(&second).unwrap(); - std::fs::rename(&second, dir.path().join("second-moved.git")).unwrap(); - std::os::unix::fs::symlink(&outside, &second).unwrap(); - assert!(handle.remove("index.lock").unwrap()); - assert!(!dir.path().join("second-moved.git/index.lock").exists()); - assert_eq!( - std::fs::read(outside.join("index.lock")).unwrap(), - b"theirs", - "the link's target was touched" - ); - assert_eq!(std::fs::read(outside.join("HEAD.lock")).unwrap(), b"theirs"); - // And a repository that is a link when the handle is opened is - // refused, with the archive's own `open_in` too. - assert!(RepoDir::open(&second).is_err()); - assert!(RepoDir::open_in(dir.path(), "second.git").is_err()); - assert!(RepoDir::open_in(dir.path(), "second-moved.git").is_ok()); - } -} diff --git a/crates/ledger-store/src/lib.rs b/crates/ledger-store/src/lib.rs index eb6eb6ef..8afad193 100644 --- a/crates/ledger-store/src/lib.rs +++ b/crates/ledger-store/src/lib.rs @@ -21,17 +21,14 @@ pub mod access; pub mod auth; pub mod backup; -pub mod backups; pub mod blob; pub mod cancel; pub mod chain; pub mod describe; -mod drain; pub mod error; pub mod exports; pub mod form1099; pub mod format; -pub mod git_locks; pub mod journal; pub mod lock; pub mod meta; diff --git a/crates/ledger-store/src/root.rs b/crates/ledger-store/src/root.rs index 8c0bc6cb..ddb9abfe 100644 --- a/crates/ledger-store/src/root.rs +++ b/crates/ledger-store/src/root.rs @@ -1146,6 +1146,10 @@ pub struct RestorePreview { pub exists: bool, /// The id of the books it holds, as they were backed up. pub origin: Option, + /// Whether it is protected by a passphrase. + pub sealed: bool, + /// Newer backups in it that were not whole and were passed over. + pub passed_over: u64, } /// What [`Root::restore`] did. @@ -1166,21 +1170,22 @@ pub struct RestoreReport { } impl Root { - /// Clone the backup at `source` (a git repository's address, or its - /// folder: `.git` in a backup folder) into a scratch folder in `books/` and prove it - /// whole (backup.rs INVARIANT 3); the caller holds the books lock and - /// removes the folder. + /// Find the backup at `source` (a destination folder, one set's own + /// folder, or a backup file), prove it whole (backup INVARIANT 3), and + /// build its books in a scratch folder in `books/`, with every stored + /// file when `with_files`; the caller holds the books lock and removes + /// the folder. fn fetch_backup( &self, - git: &crate::backup::Git, - source: &str, + source: &Path, + passphrase: Option<&str>, books: &Path, id: &BookId, stop: &JobStop, + with_files: bool, ) -> Result<(PathBuf, crate::backup::Verified), RootError> { stop.at("fetch", "restored")?; - // git, and the verification's own phases and loops, look at the stop. - let git = git.clone().with_cancel(stop.flag()); + let ctx = crate::backup::Ctx::new().with_stop(stop.flag()); // Anything left from one that never finished goes first: none is // in progress (each holds the books lock). for entry in std::fs::read_dir(books)? { @@ -1194,7 +1199,9 @@ impl Root { } } let scratch = books.join(format!("{RESTORE_PREFIX}{id}-{}", std::process::id())); - match crate::backup::verify(&git, source, &scratch) { + let proven = crate::backup::find(source, passphrase, &ctx) + .and_then(|found| crate::backup::verify_found(&found, &scratch, with_files, &ctx)); + match proven { Ok(v) => Ok((scratch, v)), Err(e) => { // What the verification wrote goes with it (a stop leaves the @@ -1214,19 +1221,19 @@ impl Root { /// proven as [`Self::restore`] proves it, adding nothing to the root. pub fn restore_preview( &self, - git: &crate::backup::Git, - source: &str, + source: &Path, + passphrase: Option<&str>, id: &BookId, ) -> Result { - self.restore_preview_stoppable(git, source, id, &JobStop::never()) + self.restore_preview_stoppable(source, passphrase, id, &JobStop::never()) } /// [`Self::restore_preview`], stopped if `stop` asks: the clone is /// removed and nothing is left. pub fn restore_preview_stoppable( &self, - git: &crate::backup::Git, - source: &str, + source: &Path, + passphrase: Option<&str>, id: &BookId, stop: &JobStop, ) -> Result { @@ -1234,7 +1241,7 @@ impl Root { (|| { let _lock = self.books_lock(stop, "restored")?; let (books, _) = self.private_subdir(BOOKS_DIR, false)?; - let (scratch, v) = self.fetch_backup(git, source, &books, id, stop)?; + let (scratch, v) = self.fetch_backup(source, passphrase, &books, id, stop, false)?; let vault = scratch.join(VAULT_DIR); let vault_files = if vault.is_dir() { std::fs::read_dir(&vault) @@ -1250,6 +1257,8 @@ impl Root { vault_files, exists: std::fs::symlink_metadata(books.join(id.as_str())).is_ok(), origin: v.book, + sealed: v.key.is_some(), + passed_over: v.passed_over as u64, }) })() .map_err(|e| self.hide(e)) @@ -1264,13 +1273,20 @@ impl Root { /// first, kept whole; refused while anything holds them open. pub fn restore( &self, - git: &crate::backup::Git, - source: &str, + source: &Path, + passphrase: Option<&str>, id: &BookId, expect_head: &(u64, String), replace: bool, ) -> Result { - self.restore_stoppable(git, source, id, expect_head, replace, &JobStop::never()) + self.restore_stoppable( + source, + passphrase, + id, + expect_head, + replace, + &JobStop::never(), + ) } /// [`Self::restore`], stopped if `stop` asks at any phase before the @@ -1280,14 +1296,14 @@ impl Root { /// finishes: two renames and two directory syncs. pub fn restore_stoppable( &self, - git: &crate::backup::Git, - source: &str, + source: &Path, + passphrase: Option<&str>, id: &BookId, expect_head: &(u64, String), replace: bool, stop: &JobStop, ) -> Result { - self.restore_inner(git, source, id, expect_head, replace, stop) + self.restore_inner(source, passphrase, id, expect_head, replace, stop) .map_err(|e| match e { // The copy's checks are the adoption's: said as a restore. RootError::Adopt(text) => { @@ -1300,8 +1316,8 @@ impl Root { fn restore_inner( &self, - git: &crate::backup::Git, - source: &str, + source: &Path, + passphrase: Option<&str>, id: &BookId, expect_head: &(u64, String), replace: bool, @@ -1337,7 +1353,7 @@ impl Root { }; stop.at("start", "restored")?; let _scope = crate::cancel::scope(stop.flag()); - let (scratch, v) = self.fetch_backup(git, source, &books, id, stop)?; + let (scratch, v) = self.fetch_backup(source, passphrase, &books, id, stop, true)?; let staging = books.join(format!("{RESTORE_PREFIX}{id}-{}-book", std::process::id())); let built = (|| -> Result { stop.at("copy", "restored")?; @@ -1377,11 +1393,12 @@ impl Root { &std::fs::read(&access)?, )?; } - // Its backup history: the next backup carries on from it. - std::fs::rename( - scratch.join(".git"), - staging.join(crate::backup::ARCHIVE_DIR), - )?; + // A sealed backup keeps its key: the restored books carry on + // backing up sealed, to the same place, with no question asked. + if let Some(key) = &v.key { + key.store(&staging) + .map_err(|e| RootError::Adopt(format!("that backup can't be restored: {e}")))?; + } // Whose books they were, placed with them. crate::ops::prepare(&staging)?; write_private_file( diff --git a/crates/ledger-store/tests/backups.rs b/crates/ledger-store/tests/backup.rs similarity index 99% rename from crates/ledger-store/tests/backups.rs rename to crates/ledger-store/tests/backup.rs index a73a7038..35f3d289 100644 --- a/crates/ledger-store/tests/backups.rs +++ b/crates/ledger-store/tests/backup.rs @@ -7,7 +7,7 @@ use ledger_core::{AccountType, Currency, Money, Side}; use ledger_store::Store; -use ledger_store::backups::{ +use ledger_store::backup::{ BackupError, BackupKey, Ctx, Cut, Destination, find, save_file, verify_found, write_destination, }; use std::collections::BTreeMap; @@ -104,7 +104,7 @@ fn prove( pass: Option<&str>, root: &Path, name: &str, -) -> Result { +) -> Result { let found = find(source, pass, &Ctx::new())?; verify_found(&found, &root.join(name), true, &Ctx::new()) } diff --git a/crates/ledger-store/tests/root.rs b/crates/ledger-store/tests/root.rs index dc220c7f..3ddb5aaf 100644 --- a/crates/ledger-store/tests/root.rs +++ b/crates/ledger-store/tests/root.rs @@ -1338,34 +1338,39 @@ fn books_that_changed_since_the_preview_are_not_adopted() { assert_eq!(report.source_head, now); } -/// A backup of `store`'s books (in `dir`) in a folder target under -/// `home`: its address. -fn backed_up(home: &Path, dir: &Path, store: &Store) -> Option { - use ledger_store::backup::{self, Git, Target}; - let git = Git::find().ok()?; - backup::commit(&git, dir, "acme", store.head()).unwrap(); +/// A backup of `store`'s books (in `dir`) in a folder under `home`: the +/// folder. +fn backed_up(home: &Path, dir: &Path, store: &Store) -> std::path::PathBuf { + use ledger_store::backup::{Ctx, Cut, Destination, write_destination}; let folder = home.join("disk"); std::fs::create_dir_all(&folder).unwrap(); - let target = Target::Folder(folder); - backup::push(&git, dir, "acme", &target, true).unwrap(); - Some(target.source("acme")) + let cut = Cut::take("acme", dir, store.head()).unwrap(); + write_destination( + &Destination { + folder: folder.clone(), + key: None, + }, + &cut, + true, + &Ctx::new(), + ) + .unwrap(); + folder } #[test] fn a_restore_never_moves_books_something_holds() { - use ledger_store::backup::Git; let home = tmp("restore-held"); let (root, _) = Root::setup(home.path(), None, None).unwrap(); let acme = id("acme"); let held = root.create_book(&acme, Currency::USD).unwrap(); let dir = root.book_dir(&acme); - let source = backed_up(home.path(), &dir, &held).expect("git is installed"); - let git = Git::find().unwrap(); - let preview = root.restore_preview(&git, &source, &acme).unwrap(); + let source = backed_up(home.path(), &dir, &held); + let preview = root.restore_preview(&source, None, &acme).unwrap(); assert!(preview.exists); // Open (its writer lock held): refused, nothing moved. let e = root - .restore(&git, &source, &acme, &preview.head, true) + .restore(&source, None, &acme, &preview.head, true) .unwrap_err(); assert!(e.to_string().contains("are open"), "{e}"); assert!(dir.join(JOURNAL_FILE).is_file()); @@ -1378,17 +1383,17 @@ fn a_restore_never_moves_books_something_holds() { ); // Not over books without --replace; nothing to replace that isn't. let e = root - .restore(&git, &source, &acme, &preview.head, false) + .restore(&source, None, &acme, &preview.head, false) .unwrap_err(); assert!(matches!(e, RootError::Exists(_)), "{e}"); let e = root - .restore(&git, &source, &id("nobody"), &preview.head, true) + .restore(&source, None, &id("nobody"), &preview.head, true) .unwrap_err(); assert!(e.to_string().contains("no books called"), "{e}"); // Let go: replaced, the old kept whole. drop(held); let r = root - .restore(&git, &source, &acme, &preview.head, true) + .restore(&source, None, &acme, &preview.head, true) .unwrap(); let kept = root.path().join("legacy").join(r.replaced.unwrap()); assert!(kept.join(JOURNAL_FILE).is_file()); @@ -1831,17 +1836,16 @@ fn a_job_stopped_at_any_phase_before_its_point_of_no_return_leaves_the_root_as_i // restore, over books that exist: they stay as they are. let dir = root.book_dir(&id("adopted")); let store = Store::open(&dir).unwrap(); - let source = backed_up(home.path(), &dir, &store).expect("git is installed"); + let source = backed_up(home.path(), &dir, &store); drop(store); - let git = ledger_store::backup::Git::find().unwrap(); - let preview = root.restore_preview(&git, &source, &id("adopted")).unwrap(); + let preview = root.restore_preview(&source, None, &id("adopted")).unwrap(); let phases = ["start", "fetch", "copy", "file", "open", "verify", "place"]; for phase in phases { let before = root_files(&root); let (stop, seen) = stopping_at(phase); let e = refused(root.restore_stoppable( - &git, &source, + None, &id("adopted"), &preview.head, true, @@ -1858,7 +1862,7 @@ fn a_job_stopped_at_any_phase_before_its_point_of_no_return_leaves_the_root_as_i // The preview too: stopped, nothing left of its clone. let before = root_files(&root); let (stop, _) = stopping_at("fetch"); - let e = refused(root.restore_preview_stoppable(&git, &source, &id("adopted"), &stop)); + let e = refused(root.restore_preview_stoppable(&source, None, &id("adopted"), &stop)); assert!(matches!(e, RootError::Stopped(_)), "{e:?}"); assert_eq!(root_files(&root), before); // Never stopped, a restore asks `place` last and goes through. @@ -1868,7 +1872,7 @@ fn a_job_stopped_at_any_phase_before_its_point_of_no_return_leaves_the_root_as_i std::sync::Arc::new(move |p: &str| seen.lock().unwrap().push(p.to_string())) }); let r = root - .restore_stoppable(&git, &source, &id("adopted"), &preview.head, true, &stop) + .restore_stoppable(&source, None, &id("adopted"), &preview.head, true, &stop) .unwrap(); assert!(r.replaced.is_some()); assert_eq!( From 5d5f94e8dc577caa0ad7ef052def2cb907ced162 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 17:49:22 -0700 Subject: [PATCH 03/19] fix(store): a drill and a preview keep the stored files the store reads when it verifies the books The store's own verification reads the text an extraction recorded as a stored file, so a verification that left the stored files out would not prove books with extracted text. Every proof now builds the books with their stored files, as a restore does, and a test holds it. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-cli/tests/backups.rs | 4 +- crates/ledger-cli/tests/book_open_close.rs | 2 +- crates/ledger-mcp/src/local.rs | 2 +- crates/ledger-store/src/backup/read.rs | 72 ++++++++-------------- crates/ledger-store/src/root.rs | 7 +-- crates/ledger-store/tests/backup.rs | 38 +++++++++++- 6 files changed, 69 insertions(+), 56 deletions(-) diff --git a/crates/ledger-cli/tests/backups.rs b/crates/ledger-cli/tests/backups.rs index bc04aea7..b94215e4 100644 --- a/crates/ledger-cli/tests/backups.rs +++ b/crates/ledger-cli/tests/backups.rs @@ -364,7 +364,7 @@ async fn backed_up(c: &Client, within: Duration) -> Value { fn proven(home: &Home, source: &Path, tag: &str) -> (u64, String) { let scratch = home.outside(&format!("scratch-{tag}")); let found = find(source, None, &Ctx::new()).unwrap_or_else(|e| panic!("{tag}: {e}")); - verify_found(&found, &scratch, false, &Ctx::new()) + verify_found(&found, &scratch, &Ctx::new()) .unwrap_or_else(|e| panic!("{tag}: {e}")) .head } @@ -412,7 +412,7 @@ async fn a_book_backs_itself_up_to_its_folder_soon_after_a_write() { // Its journal is the live journal's beginning (a drill's check). let scratch = home.outside("scratch-prefix"); let found = find(&folder, None, &Ctx::new()).unwrap(); - let v = verify_found(&found, &scratch, false, &Ctx::new()).unwrap(); + let v = verify_found(&found, &scratch, &Ctx::new()).unwrap(); assert!( std::fs::read(home.book_dir("acme").join(ledger_store::JOURNAL_FILE)) .unwrap() diff --git a/crates/ledger-cli/tests/book_open_close.rs b/crates/ledger-cli/tests/book_open_close.rs index 076a1e91..089eb4e0 100644 --- a/crates/ledger-cli/tests/book_open_close.rs +++ b/crates/ledger-cli/tests/book_open_close.rs @@ -1159,7 +1159,7 @@ fn proven_head(home: &Home, disk: &std::path::Path, tag: &str) -> (u64, String) use ledger_store::backup::{Ctx, find, verify_found}; let scratch = home.dir.path().join(format!("scratch-{tag}")); let found = find(disk, None, &Ctx::new()).unwrap_or_else(|e| panic!("{tag}: {e}")); - verify_found(&found, &scratch, false, &Ctx::new()) + verify_found(&found, &scratch, &Ctx::new()) .unwrap_or_else(|e| panic!("{tag}: {e}")) .head } diff --git a/crates/ledger-mcp/src/local.rs b/crates/ledger-mcp/src/local.rs index 5df519dd..3642cb3f 100644 --- a/crates/ledger-mcp/src/local.rs +++ b/crates/ledger-mcp/src/local.rs @@ -5185,7 +5185,7 @@ mod tests { let found = ledger_store::backup::find(&dir.join(ledger_store::backup::LOCAL_DIR), None, &ctx) .expect("a local backup is there"); - ledger_store::backup::verify_found(&found, &scratch, true, &ctx).expect("it proves whole") + ledger_store::backup::verify_found(&found, &scratch, &ctx).expect("it proves whole") } /// plan/served.md 3.9's `format_upgrade_waits_for_consent`, the diff --git a/crates/ledger-store/src/backup/read.rs b/crates/ledger-store/src/backup/read.rs index 6b5a0a04..3c4bdaf3 100644 --- a/crates/ledger-store/src/backup/read.rs +++ b/crates/ledger-store/src/backup/read.rs @@ -478,16 +478,11 @@ fn put_scratch(dir: &Path, name: &str, bytes: &[u8]) -> std::io::Result<()> { } /// 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> { +/// access log, the vault, the keys and every stored file; every piece +/// proven as it is read. (The store reads some stored files itself when +/// it verifies the books, so a drill keeps them too, as a restore does.) +/// Returns the hashes of the stored files proven. +fn materialize(set: &Set, m: &Manifest, scratch: &Path) -> Result, BackupError> { let ctx = &set.ctx; std::fs::create_dir_all(scratch)?; for (series, kind, name) in [ @@ -524,23 +519,19 @@ fn materialize( 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(()))?; - } + 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()?; proven.insert(line.sha256); } Ok(proven) @@ -554,7 +545,6 @@ fn prove_books( m: &Manifest, scratch: &Path, proven_files: &BTreeSet, - with_files: bool, ctx: &Ctx, ) -> Result<(u64, (u64, String)), BackupError> { ctx.phase("replay"); @@ -570,11 +560,7 @@ fn prove_books( short(missing) ))); } - let blobs = if with_files { - store.verify_blobs()? - } else { - proven_files.len() as u64 - }; + let blobs = store.verify_blobs()?; let head = store.head(); let tins: Vec = store .ledger() @@ -618,15 +604,9 @@ fn prove_books( /// 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 { +/// passed over and said. Every stored file is re-hashed and kept in the +/// scratch folder (a restore moves them from it; a drill removes it). +pub fn verify_found(found: &Found, scratch: &Path, ctx: &Ctx) -> Result { if scratch.exists() { return Err(BackupError::Damaged("its scratch folder is in use".into())); } @@ -636,8 +616,8 @@ pub fn verify_found( 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)); + let attempt = + materialize(set, &m, scratch).and_then(|files| prove_books(&m, scratch, &files, ctx)); match attempt { Ok((blobs, head)) => { return Ok(Verified { @@ -712,7 +692,7 @@ pub fn drill( key: dest.key.clone(), set, }; - let checked = verify_found(&found, scratch, false, ctx).and_then(|v| { + let checked = verify_found(&found, scratch, ctx).and_then(|v| { ctx.phase("prefix"); if v.book.as_deref() != Some(book) { return Err(BackupError::Elsewhere); @@ -755,7 +735,7 @@ pub fn prove_local( key: None, set, }; - let proven = verify_found(&found, scratch, false, ctx).and_then(|v| { + let proven = verify_found(&found, scratch, ctx).and_then(|v| { if v.head != *head { return Err(BackupError::Damaged(format!( "it holds the books through event {}, and they are at event {}", diff --git a/crates/ledger-store/src/root.rs b/crates/ledger-store/src/root.rs index ddb9abfe..1a21944b 100644 --- a/crates/ledger-store/src/root.rs +++ b/crates/ledger-store/src/root.rs @@ -1182,7 +1182,6 @@ impl Root { books: &Path, id: &BookId, stop: &JobStop, - with_files: bool, ) -> Result<(PathBuf, crate::backup::Verified), RootError> { stop.at("fetch", "restored")?; let ctx = crate::backup::Ctx::new().with_stop(stop.flag()); @@ -1200,7 +1199,7 @@ impl Root { } let scratch = books.join(format!("{RESTORE_PREFIX}{id}-{}", std::process::id())); let proven = crate::backup::find(source, passphrase, &ctx) - .and_then(|found| crate::backup::verify_found(&found, &scratch, with_files, &ctx)); + .and_then(|found| crate::backup::verify_found(&found, &scratch, &ctx)); match proven { Ok(v) => Ok((scratch, v)), Err(e) => { @@ -1241,7 +1240,7 @@ impl Root { (|| { let _lock = self.books_lock(stop, "restored")?; let (books, _) = self.private_subdir(BOOKS_DIR, false)?; - let (scratch, v) = self.fetch_backup(source, passphrase, &books, id, stop, false)?; + let (scratch, v) = self.fetch_backup(source, passphrase, &books, id, stop)?; let vault = scratch.join(VAULT_DIR); let vault_files = if vault.is_dir() { std::fs::read_dir(&vault) @@ -1353,7 +1352,7 @@ impl Root { }; stop.at("start", "restored")?; let _scope = crate::cancel::scope(stop.flag()); - let (scratch, v) = self.fetch_backup(source, passphrase, &books, id, stop, true)?; + let (scratch, v) = self.fetch_backup(source, passphrase, &books, id, stop)?; let staging = books.join(format!("{RESTORE_PREFIX}{id}-{}-book", std::process::id())); let built = (|| -> Result { stop.at("copy", "restored")?; diff --git a/crates/ledger-store/tests/backup.rs b/crates/ledger-store/tests/backup.rs index 35f3d289..75303ca5 100644 --- a/crates/ledger-store/tests/backup.rs +++ b/crates/ledger-store/tests/backup.rs @@ -106,7 +106,7 @@ fn prove( name: &str, ) -> Result { let found = find(source, pass, &Ctx::new())?; - verify_found(&found, &root.join(name), true, &Ctx::new()) + verify_found(&found, &root.join(name), &Ctx::new()) } #[test] @@ -462,7 +462,7 @@ fn a_flipped_or_cut_piece_is_found_and_never_restored() { // 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()) + verify_found(&found, &root.join(name), &Ctx::new()) }; let set = std::fs::read_dir(&disk) .unwrap() @@ -687,3 +687,37 @@ fn a_loser_of_a_manifest_number_goes_on_from_the_winner() { ); prove(&disk, None, dir.path(), "v").unwrap(); } + +// --- what the store reads of a backup ----------------------------------- + +#[test] +fn the_text_read_from_a_stored_file_is_a_stored_file_too() { + // The store's own verification reads the text an extraction recorded as + // a stored file; a backup that left it out would not prove whole, so it + // is carried and proven with the rest. + let dir = tempfile::tempdir().unwrap(); + let b = dir.path().join("book"); + let mut s = book(&b); + let (attachment, _, _) = s + .attach_receipt(None, "words.txt", "text/plain", b"a receipt with words", None) + .unwrap(); + s.extract_attachment(attachment).unwrap(); + let text_sha = s + .extraction(attachment) + .unwrap() + .and_then(|x| x.text_sha256) + .expect("the text is a stored file"); + let disk = dir.path().join("disk"); + std::fs::create_dir(&disk).unwrap(); + write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap(); + let v = prove(&disk, None, dir.path(), "v").unwrap(); + assert!( + v.tree + .join("blobs") + .join(&text_sha[0..2]) + .join(&text_sha[2..4]) + .join(&text_sha) + .is_file() + ); + assert_eq!(v.head, s.head()); +} From 4313464bd7d0a7205b9ea431d60c48021015efc6 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 17:51:40 -0700 Subject: [PATCH 04/19] test(cli): the close tests stall a file copy where they stalled git Co-Authored-By: Claude Fable 5.2 --- crates/ledger-cli/tests/book_open_close.rs | 20 +++++++++++++++++--- crates/ledger-store/tests/backup.rs | 8 +++++++- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/crates/ledger-cli/tests/book_open_close.rs b/crates/ledger-cli/tests/book_open_close.rs index 089eb4e0..eb427989 100644 --- a/crates/ledger-cli/tests/book_open_close.rs +++ b/crates/ledger-cli/tests/book_open_close.rs @@ -1233,11 +1233,19 @@ fn a_close_is_not_answered_while_its_backup_still_runs() { Duration::from_millis(500), "after the close was answered", ); + // (The test's own stall file went with the lift.) + let changed = |before: &BTreeMap, + now: &BTreeMap| { + moved(before, now) + .into_iter() + .filter(|m| !m.contains("slow-backup")) + .collect::>() + }; assert_eq!( - moved(&at_close, &tree_of(&home.book_dir(A))), + changed(&at_close, &tree_of(&home.book_dir(A))), Vec::::new() ); - assert_eq!(moved(&in_folder, &tree_of(&disk)), Vec::::new()); + assert_eq!(changed(&in_folder, &tree_of(&disk)), Vec::::new()); // Opened again, the book's backup record is a whole chain, and it // backs up (nothing of the old backups is in its way). assert_eq!(open_book(&home, A), OpenOutcome::Opened); @@ -2523,8 +2531,14 @@ fn a_close_stops_a_running_backup_call_and_says_so() { && r.get("why") == Some(&json!("asked"))), "{record:?}" ); + // The run before the stall made its record; the stopped one made none + // of its own after its `stopped`. + let stopped_at = record + .iter() + .position(|r| r.get("kind") == Some(&json!("stopped"))) + .unwrap(); assert!( - !record + !record[stopped_at..] .iter() .any(|r| r.get("why") == Some(&json!("asked")) && r.get("kind") != Some(&json!("stopped"))), diff --git a/crates/ledger-store/tests/backup.rs b/crates/ledger-store/tests/backup.rs index 75303ca5..51130528 100644 --- a/crates/ledger-store/tests/backup.rs +++ b/crates/ledger-store/tests/backup.rs @@ -699,7 +699,13 @@ fn the_text_read_from_a_stored_file_is_a_stored_file_too() { let b = dir.path().join("book"); let mut s = book(&b); let (attachment, _, _) = s - .attach_receipt(None, "words.txt", "text/plain", b"a receipt with words", None) + .attach_receipt( + None, + "words.txt", + "text/plain", + b"a receipt with words", + None, + ) .unwrap(); s.extract_attachment(attachment).unwrap(); let text_sha = s From 91d88dcee7a23a92a3b4a2be2ae312ef594b5802 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 17:54:32 -0700 Subject: [PATCH 05/19] docs: packages need nothing for backups; handbook, tools and install words without git The Linux packages, the AUR recipe and the rpm metadata no longer depend on another program for backups (WB-pkg-4 is replaced); the Windows host's PATH no longer carries Git for Windows; the handbook an assistant reads, the tool descriptions, the install notes and the site say plain folders. A test adopts a clone of an old backup as the docs describe. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-cli/Cargo.toml | 2 - crates/ledger-cli/tests/backups.rs | 115 +++++++++++++++++ crates/ledger-cli/tests/packaging.rs | 36 +++--- crates/ledger-host/src/commands.rs | 4 +- crates/ledger-host/src/start.rs | 16 +-- crates/ledger-mcp/handbook/backups.md | 15 ++- crates/ledger-mcp/src/tools/kept.rs | 4 +- crates/ledger-mcp/src/tools/reports.rs | 2 +- crates/ledger-package/src/attention.rs | 2 +- deploy/README.md | 18 +-- deploy/packaging/aur/PKGBUILD | 2 +- deploy/packaging/macos/entitlements.plist | 8 +- deploy/packaging/packager.toml | 7 +- deploy/wanderbooks-server.service | 5 +- docs/architecture.md | 5 +- docs/install.md | 13 +- docs/mcp-interface.md | 149 +++++++++++----------- docs/packaging.md | 28 +--- docs/receipt-store.md | 27 ++-- docs/spec/claims/packaging.md | 23 ++-- site/index.html | 4 +- 21 files changed, 277 insertions(+), 208 deletions(-) diff --git a/crates/ledger-cli/Cargo.toml b/crates/ledger-cli/Cargo.toml index a992303d..ff19b180 100644 --- a/crates/ledger-cli/Cargo.toml +++ b/crates/ledger-cli/Cargo.toml @@ -75,8 +75,6 @@ workspace = true # program: `just package-linux`. Paths are relative to the workspace root. [package.metadata.generate-rpm] name = "wanderbooks" -# Backups run the system's git (WB-pkg-4): dnf fetches it. -requires = { git = "*" } summary = "Double-entry bookkeeping your agent keeps and you can read" license = "MIT OR Apache-2.0" url = "https://wanderbooks.ai" diff --git a/crates/ledger-cli/tests/backups.rs b/crates/ledger-cli/tests/backups.rs index b94215e4..5394e907 100644 --- a/crates/ledger-cli/tests/backups.rs +++ b/crates/ledger-cli/tests/backups.rs @@ -1236,3 +1236,118 @@ async fn old_settings_and_an_old_backup_history_are_left_alone_and_said() { drop(c); assert!(server.close().success()); } + +/// docs/backups.md, "A backup made with an older version": a person who +/// still has a backup made with git clones it themselves (git is their own +/// tool now) and adopts the plain folder. This makes such a backup the way +/// an older version did (a repository whose one commit is the books' +/// files), clones it as the docs say, and adopts the clone with its vault +/// and key as the docs say. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_clone_of_an_old_git_backup_is_adopted_as_a_plain_folder() { + let git = |dir: &Path, args: &[&str]| { + let out = Command::new("git") + .arg("-C") + .arg(dir) + .args(["-c", "user.name=t", "-c", "user.email=t@t.invalid"]) + .args(args) + .output(); + match out { + Ok(o) => { + assert!(o.status.success(), "{args:?}: {o:?}"); + true + } + // No git on this machine: the path is the person's own tool's. + Err(_) => false, + } + }; + let home = Home::new("old-backup"); + let server = Server::start(&home, Duration::from_secs(3600)); + home.create("acme"); + let c = connect(&home, "acme", home.token("acme", &ALL)).await; + call( + &c, + "books.add_party", + json!({"name": "Mo", "roles": ["member"]}), + ) + .await + .unwrap(); + call( + &c, + "books.set_tin", + json!({"party": "Mo", "tin": "12-3456789", "tin_type": "ein"}), + ) + .await + .unwrap(); + let (folder, want) = backed_up_acme(&home).await; + drop(c); + assert!(server.close().success()); + // The old backup: the books' files, committed, in a bare repository. + let book = home.book_dir("acme"); + let work = home.outside("old-work"); + std::fs::create_dir_all(&work).unwrap(); + for part in ["journal.jsonl", "blobs", "vault", "keys", "access.jsonl"] { + let from = book.join(part); + if from.is_dir() { + copy_dir(&from, &work.join(part)); + } else if from.is_file() { + std::fs::copy(&from, work.join(part)).unwrap(); + } + } + if !git(&work, &["init", "-q", "-b", "main"]) { + return; + } + git(&work, &["add", "-A", "-f"]); + git(&work, &["commit", "-q", "-m", "seq 1 head x\n\nbook acme"]); + let bare = home.outside("acme.git"); + let out = Command::new("git") + .args(["clone", "-q", "--bare"]) + .arg(&work) + .arg(&bare) + .output() + .unwrap(); + assert!(out.status.success(), "{out:?}"); + // The person's steps: clone it, then adopt the folder with its vault + // and key. + let clone = home.outside("acme-old"); + let out = Command::new("git") + .args(["clone", "-q"]) + .arg(&bare) + .arg(&clone) + .output() + .unwrap(); + assert!(out.status.success(), "{out:?}"); + let other = Home::new("old-backup-new"); + let server = Server::start(&other, Duration::from_secs(3600)); + let request = |confirmed: bool, expect_head: Option<(u64, String)>| Request::Adopt { + id: "acme".into(), + source: clone.clone(), + settings_toml: None, + config_json: None, + vault_dir: Some(clone.join("vault")), + vault_key: Some(clone.join("keys").join("legacy.key")), + confirmed, + expect_head, + skip_unknown: false, + }; + let preview = match other.admin(request(false, None)) { + Response::Preview(p) => p, + r => panic!("{r:?}"), + }; + match other.admin(request(true, Some(preview.source_head))) { + Response::Adopted(a) => { + assert!(a.problem.is_none(), "{a:?}"); + assert_eq!(a.head, live_head(&home, "acme")); + } + r => panic!("{r:?}"), + } + let c = connect(&other, "acme", other.token("acme", &["read"])).await; + assert_eq!(figures(&c).await, want); + let party = call(&c, "books.party", json!({"party": "Mo"})) + .await + .unwrap(); + assert_eq!(party["party"]["tin"]["in_vault"], true, "{party}"); + drop(c); + assert!(server.close().success()); + let _ = folder; +} diff --git a/crates/ledger-cli/tests/packaging.rs b/crates/ledger-cli/tests/packaging.rs index b54eaca4..d100d452 100644 --- a/crates/ledger-cli/tests/packaging.rs +++ b/crates/ledger-cli/tests/packaging.rs @@ -684,26 +684,30 @@ fn only_a_person_runs_the_workflow_that_publishes_the_repositories() { ); } -/// WB-pkg-4: on Linux git is a dependency of every package, so the package -/// manager fetches it; nothing carries a git of its own. +/// WB-pkg-4: a backup is plain files the program writes itself, so no +/// package depends on another program for it and none carries one. #[test] -fn the_linux_packages_depend_on_git_and_none_carries_one() { - let packager = read("deploy/packaging/packager.toml"); - assert_eq!( - packager.matches("\"git\"").count(), - 2, - "the deb and the pacman package depend on git" - ); - assert!(read("crates/ledger-cli/Cargo.toml").contains("requires = { git = \"*\" }")); - assert!(read("deploy/packaging/aur/PKGBUILD").contains("'git'")); +fn no_package_depends_on_another_program_for_backups() { + let word = |text: &str| { + text.to_lowercase() + .split(|c: char| !c.is_ascii_alphanumeric()) + .any(|w| w == "git") + }; for file in [ + "deploy/packaging/packager.toml", + "deploy/packaging/aur/PKGBUILD", + "crates/ledger-cli/Cargo.toml", "deploy/packaging/windows/wanderbooks.nsi", "deploy/packaging/macos/build-macos.sh", ] { - let text = read(file).to_lowercase(); - assert!( - !text.contains("mingit") && !text.contains("git.exe"), - "{file} bundles a git" - ); + let text = read(file); + // (Cargo.toml may name a git *dependency* of the build, never a + // package requirement.) + let checked: String = text + .lines() + .filter(|l| !l.contains("git =")) + .collect::>() + .join("\n"); + assert!(!word(&checked), "{file} depends on, or bundles, a git"); } } diff --git a/crates/ledger-host/src/commands.rs b/crates/ledger-host/src/commands.rs index dc8cb62f..fe687429 100644 --- a/crates/ledger-host/src/commands.rs +++ b/crates/ledger-host/src/commands.rs @@ -770,7 +770,7 @@ fn books_usage(prog: &str) { " back-up back the books up now to every backup their settings name (--new-disk: the backup folder's disk is new)" ); eprintln!( - " restore bring back a backup (a git repository's address, or BOOK.git in the backup folder), proven whole first: as new books, or replacing books (kept in legacy/)" + " restore bring back a backup (your backup folder, the folder of one set of books in it, or a backup file), proven whole first: as new books, or replacing books (kept in legacy/)" ); eprintln!( " upgrade give the go-ahead, with the owner passphrase, for books an older wanderbooks wrote to move to this version's journal format (a verified backup with the vault and keys first)" @@ -779,7 +779,7 @@ fn books_usage(prog: &str) { " extract read one attachment's text (a PDF, XLSX or text file) and journal it, one at a time; books an older version filed are read this way after an upgrade" ); eprintln!( - " put-aside move the old copies of adopted books (their data folder, their vault and its key, and other paths given: settings file, git history) whole into the legacy folder, once the books hold everything they do, byte for byte; nothing is deleted" + " put-aside move the old copies of adopted books (their data folder, their vault and its key, and other paths given: settings file, old history) whole into the legacy folder, once the books hold everything they do, byte for byte; nothing is deleted" ); } diff --git a/crates/ledger-host/src/start.rs b/crates/ledger-host/src/start.rs index 47690f43..8e10f8b9 100644 --- a/crates/ledger-host/src/start.rs +++ b/crates/ledger-host/src/start.rs @@ -12,7 +12,7 @@ //! and DBUS_SESSION_BUS_ADDRESS only when they point at this //! account's own private runtime folder, and SSH_AUTH_SOCK only when //! it names a socket this account owns (the owner's ssh agent, so the -//! server's backups reach a private git repository, D-30). Nothing +//! server's backups reach a folder on the network, D-91). Nothing //! else passes (a scope's own identifiers, such as INVOCATION_ID, are //! systemd's). Two more: APPIMAGE and APPDIR, only when they are //! this program's own (INVARIANT 6), so the host knows its own @@ -441,9 +441,9 @@ fn scope_made(child: &mut std::process::Child, log: &std::fs::File, from: u64) - /// The host's environment on Windows (INVARIANT 1's counterpart): the /// system's own variables, the account's profile, and a PATH fixed to the -/// system folders and Git for Windows (the backups run `git`). Nothing -/// else of the opener's passes. (CHOICE, P11c: no authority states a -/// Windows list; this is the least a Windows program and `git` need.) +/// system folders. Nothing else of the opener's passes. (CHOICE, P11c: no +/// authority states a Windows list; this is the least a Windows program +/// needs.) #[cfg(windows)] fn host_env(home: &Path) -> Vec<(String, std::ffi::OsString)> { let var = |name: &str| std::env::var_os(name); @@ -452,12 +452,8 @@ fn host_env(home: &Path) -> Vec<(String, std::ffi::OsString)> { .map_or_else(|| PathBuf::from(r"C:\Windows"), PathBuf::from); let program_files: PathBuf = var("ProgramFiles").map_or_else(|| PathBuf::from(r"C:\Program Files"), PathBuf::from); - let path = std::env::join_paths([ - system_root.join("System32"), - system_root.clone(), - program_files.join("Git").join("cmd"), - ]) - .unwrap_or_default(); + let path = std::env::join_paths([system_root.join("System32"), system_root.clone()]) + .unwrap_or_default(); let mut env: Vec<(String, std::ffi::OsString)> = vec![ ("PATH".into(), path), ("SystemRoot".into(), system_root.clone().into_os_string()), diff --git a/crates/ledger-mcp/handbook/backups.md b/crates/ledger-mcp/handbook/backups.md index b51c09c4..17b90a8f 100644 --- a/crates/ledger-mcp/handbook/backups.md +++ b/crates/ledger-mcp/handbook/backups.md @@ -1,9 +1,10 @@ # Backups -- The books back themselves up: a little after each change, when they open, before they close. Each backup goes to the targets the settings name: backup.git_remote, a private repository the human owns, and backup.folder, a folder on another disk. Both is best. The backups aren't encrypted: the human's repository host and disk keep them private. -- No targets set: books.start says so. Ask the human for the repository's address and the folder, then set them with books.set_setting (who decided, and when); choosing where backups go needs books:admin, as backing up does. -- books.backup says how each target stands: when it last took the books, through which journal seq, why the last try failed, and whether its weekly restore check passed. A target that is stale, failing, or failed its check: tell the human what it says, in plain words (a disk not connected, a repository that refused). -- books.back_up_now backs up at once, for instance before the human changes computers. A backup never changes the books. -- A backup folder that took these books' backups but holds none now is a disk not connected: ask the human to connect it. Only if they say the disk is new, back up now with new_disk: true to begin the books' backup there again. -- Books restored as a copy of other books (under another name) don't back up to those books' repository (that would stop theirs): books.backup says so; ask the human for one of their own. -- Restoring is the human's to do, outside these tools: a backup comes back as new books, or replacing these (the old books are kept, never deleted), and each is proven whole before it is restored. +- The books back themselves up: a little after each change, when they open, before they close. The backup goes to the backup folder the settings name (backup.folder): a folder on another disk, or one that Dropbox, iCloud, OneDrive or Google Drive keeps in sync. It holds one folder for these books, made only of files that are added and never changed or deleted, so a sync service never sees one change under it. +- No backup folder set: books.start says so. Ask the human which folder, then set it with books.set_setting (who decided, and when); choosing where backups go needs books:admin, as backing up does. The window has a folder chooser for the same. +- The human may protect the backups with a passphrase, set up in the window and off by default. Then every file in the folder is sealed and says no more than how many there are and how big. The passphrase is never in the books or in these tools, and a forgotten one can't be recovered: say so plainly if the human asks. books.backup says whether the backups are sealed. +- books.backup says how the folder stands: when it last took the books, through which journal seq, why the last try failed, and whether its weekly restore check passed. A folder that is stale, failing, or failed its check: tell the human what it says, in plain words (a disk not connected, another set of books in the folder). +- books.back_up_now backs up at once, for instance before the human changes computers. A backup never changes the books. The window's Save a backup... makes the same backup as one file to keep or carry. +- A backup folder that took these books' backups but holds none now is a disk not connected (disconnected: true): ask the human to connect it. Only if they say the disk is new, back up now with new_disk: true to begin the books' backup there again. +- Books that still name a private repository in their settings (an older kind of backup) are told it is no longer used: ask the human for a backup folder instead. Nothing older is deleted. +- Restoring is the human's to do, outside these tools: a backup comes back as new books, or replacing these (the old books are kept, never deleted), from the backup folder or a backup file, and each is proven whole before it is restored. diff --git a/crates/ledger-mcp/src/tools/kept.rs b/crates/ledger-mcp/src/tools/kept.rs index 99b59bc1..81c37088 100644 --- a/crates/ledger-mcp/src/tools/kept.rs +++ b/crates/ledger-mcp/src/tools/kept.rs @@ -1038,11 +1038,11 @@ impl BooksServer { // failing. { let st = self.backups.standing(store); - if st.note.is_some() { + if st.targets.is_empty() { next_steps.push(step( "books.backup", None, - "No backups are set up: ask the human for a private repository and a folder on another disk, then set backup.git_remote and backup.folder (books.set_setting).", + "No backups are set up: ask the human which folder to back up to (a folder on another disk, or one a sync service keeps), then set backup.folder (books.set_setting).", )); } else if st.needs_attention() { next_steps.push(step( diff --git a/crates/ledger-mcp/src/tools/reports.rs b/crates/ledger-mcp/src/tools/reports.rs index 2a3bb2f0..84b681b3 100644 --- a/crates/ledger-mcp/src/tools/reports.rs +++ b/crates/ledger-mcp/src/tools/reports.rs @@ -1124,7 +1124,7 @@ impl BooksServer { /// ```text /// GOAL: everything the CPA needs for the return in one zip, the K-1s' /// and 1099s' TINs included, without a full TIN ever landing in - /// the books (a git repository) or the conversation. + /// the books or the conversation. /// SOURCE: docs/mcp-interface.md; BS-partner-2; DECISION (owner, /// 2026-10-15): "it needs to be in the damn CPA package." /// INVARIANTS: diff --git a/crates/ledger-package/src/attention.rs b/crates/ledger-package/src/attention.rs index 97c1b72e..262cc0b7 100644 --- a/crates/ledger-package/src/attention.rs +++ b/crates/ledger-package/src/attention.rs @@ -1294,7 +1294,7 @@ pub fn find_with( count(ids.len(), "stored file is", "stored files are") ), detail: format!( - "Attachment {}: the bytes on disk don't match their recorded hash. Restore them from a backup (the books dir's git history).", + "Attachment {}: the bytes on disk don't match their recorded hash. Restore them from a backup.", ids.join(", ") ), target: Target::Documents, diff --git a/deploy/README.md b/deploy/README.md index 6d0630c8..af6f2642 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -104,17 +104,11 @@ and `IPAddressDeny=any` with `IPAddressAllow=localhost`, and no seccomp or Landlock lines (D-32, D-51). The loopback-only rule is deliberate: the server reaches nothing out. A -book whose backup target is a **remote** git repository needs that host -allowed, or its backups fail: - -```ini -# /etc/systemd/system/wanderbooks-server.service.d/backup.conf -[Service] -IPAddressAllow=203.0.113.10 -``` - -A backup to a folder on this machine needs nothing. The tunnel and Caddy -run as their own services and reach 127.0.0.1:7411, which the rule allows. +backup is a folder of plain files (docs/backups.md): a folder on this +machine's disks needs nothing, and nothing else is installed for it. (A +folder on a network share the machine mounts is a disk to the server, and +the mount, not the server, reaches the network.) The tunnel and Caddy run as +their own services and reach 127.0.0.1:7411, which the rule allows. ## 5. A token for each client @@ -221,7 +215,7 @@ a last backup and closes (3.9), so `TimeoutStopSec=600` is generous rather than needed. Backups still run on their own, from the books' settings, as on the -desktop (3.7, D-30, D-31); this machine runs git itself. +desktop (3.7, D-91): plain files in a folder, written by the server. ## 9. Prove the boundary (what CI runs) diff --git a/deploy/packaging/aur/PKGBUILD b/deploy/packaging/aur/PKGBUILD index 77d469f9..020b382c 100644 --- a/deploy/packaging/aur/PKGBUILD +++ b/deploy/packaging/aur/PKGBUILD @@ -9,7 +9,7 @@ pkgdesc="Double-entry bookkeeping your agent keeps and you can read" arch=('x86_64') url="https://wanderbooks.ai" license=('MIT' 'Apache-2.0') -depends=('gcc-libs' 'glibc' 'git') +depends=('gcc-libs' 'glibc') provides=('wanderbooks') conflicts=('wanderbooks') options=('!lto' '!strip') diff --git a/deploy/packaging/macos/entitlements.plist b/deploy/packaging/macos/entitlements.plist index 30dd36ee..5e3d36e5 100644 --- a/deploy/packaging/macos/entitlements.plist +++ b/deploy/packaging/macos/entitlements.plist @@ -5,13 +5,13 @@ The app is signed with the hardened runtime (codesign --options runtime), which Apple's notarization requires. It is NOT sandboxed (the App Sandbox would forbid what the product is: it starts a copy of - itself as the books server, runs the system's git for backups, and + itself as the books server, and reads and writes the person's data folder and the folders they pick for backups). Outside the sandbox, none of that needs an entitlement: - * starting itself as a child process and git as another: none; - * outgoing network connections (the relay, the update look, a git - remote): none (com.apple.security.network.client is a SANDBOX + * starting itself as a child process: none; + * outgoing network connections (the relay, the update look): none + (com.apple.security.network.client is a SANDBOX entitlement); * reading and writing its data folder, Application Support/wanderbooks: none (the Documents folder is a privacy prompt, answered by diff --git a/deploy/packaging/packager.toml b/deploy/packaging/packager.toml index 7a0b9791..8dbb5bf1 100644 --- a/deploy/packaging/packager.toml +++ b/deploy/packaging/packager.toml @@ -24,9 +24,8 @@ section = "utils" # A deb marks itself package-managed: `wanderbooks update` refuses on it # and says to use apt (plan 3.9). desktop-template = "deploy/packaging/wanderbooks.desktop" -# git: the backups run the system's git (WB-pkg-4); the package manager -# fetches it, so a Linux person never sees the missing-git words. -depends = ["libc6", "libgcc-s1", "git"] +# Backups need nothing installed (WB-pkg-4): they are plain files. +depends = ["libc6", "libgcc-s1"] [deb.files] "deploy/packaging/install-method-deb" = "usr/share/wanderbooks/install-method" @@ -42,7 +41,7 @@ depends = ["libc6", "libgcc-s1", "git"] "LICENSE-APACHE" = "usr/share/doc/wanderbooks/LICENSE-APACHE" [pacman] -depends = ["gcc-libs", "glibc", "git"] +depends = ["gcc-libs", "glibc"] [pacman.files] "deploy/packaging/install-method-aur" = "usr/share/wanderbooks/install-method" diff --git a/deploy/wanderbooks-server.service b/deploy/wanderbooks-server.service index 75ae263e..fbf376b7 100644 --- a/deploy/wanderbooks-server.service +++ b/deploy/wanderbooks-server.service @@ -50,9 +50,8 @@ ProtectHome=yes PrivateTmp=yes PrivateDevices=yes # No network but loopback: the tunnel reaches 127.0.0.1:7411, and the -# server reaches nothing out. A book whose backup target is a remote git -# repository needs that host allowed here (`IPAddressAllow=` its address) -# or its backups fail; see README.md. +# server reaches nothing out. Backups go to a folder on this machine's +# disks (see README.md), so they need no network. IPAddressDeny=any IPAddressAllow=localhost diff --git a/docs/architecture.md b/docs/architecture.md index c9cd1871..fca75099 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -487,9 +487,8 @@ already running with other flags keeps them; on a self-host machine `serve` is the unit's only holder. The unit sets `IPAddressDeny=any` and `IPAddressAllow=localhost`: the -server reaches nothing out. A book whose backup target is a remote git -repository therefore needs that host allowed in a drop-in (D-31 backups -still run on the server). The recipe, the head check for the move and the +server reaches nothing out. Backups go to a folder on the machine's own +disks and need no network (D-91). The recipe, the head check for the move and the two-account CI job are in `deploy/README.md`, `deploy/wanderbooks-server.service` and `.github/workflows/two-user.yml`; the checks are `crates/ledger-cli/tests/two_user.rs`. diff --git a/docs/install.md b/docs/install.md index 3fbf7944..c401de70 100644 --- a/docs/install.md +++ b/docs/install.md @@ -23,8 +23,8 @@ close the window: that quits Wanderbooks fully and closes your books. Where things are: the program is in `%LOCALAPPDATA%\Programs\Wanderbooks`; your books, keys and backups are in `%LOCALAPPDATA%\wanderbooks`. -Backups need Git for Windows (https://git-scm.com/download/win, or `winget -install --id Git.Git -e`); without it Wanderbooks works and says so. +Backups need nothing installed: choose a backup folder in Wanderbooks +(another disk, or a folder your cloud drive keeps in sync). ## macOS @@ -38,8 +38,9 @@ install --id Git.Git -e`); without it Wanderbooks works and says so. remove it, drag it to the Trash. Neither touches your books. Your books, keys and backups are in `~/Library/Application Support/wanderbooks`. -Backups need git: run `xcode-select --install` in Terminal (or `brew install -git`). +Backups need nothing installed: choose a backup folder in Wanderbooks +(another disk, or a folder iCloud, Dropbox, OneDrive or Google Drive keeps in +sync). ## Linux @@ -48,8 +49,8 @@ Ubuntu), the `.rpm` (Fedora), the Arch package, or the AppImage (one file: mark it executable, keep it where you put it, and run it). Open **Wanderbooks** from the menu. To update, install the newer package, or replace the AppImage. Your books are in `~/.local/share/wanderbooks` and are never touched by a package. -Backups need git (`sudo apt install git`, `sudo dnf install git`, -`sudo pacman -S git`). +Backups need nothing installed: choose a backup folder in Wanderbooks +(another disk, or a folder your sync program keeps). ## After it is installed diff --git a/docs/mcp-interface.md b/docs/mcp-interface.md index 41736caf..79c80df5 100644 --- a/docs/mcp-interface.md +++ b/docs/mcp-interface.md @@ -378,27 +378,21 @@ didn't open, with why). Protocol version 1: the requests are new, the (a drill, or a format upgrade not yet journaled, is stopped when the close begins, at its next look, so it never takes the last backup's turn; its scratch clone is removed and the books are unchanged): - a backup still running after that is stopped (git is sent SIGTERM, which - makes it remove its own lock files, and killed with all it started only - if it hasn't ended after 5 seconds) and waited for to end. The program - never writes to or deletes from a backup folder (it is the owner's, and - may be shared with other computers or a sync program): a lock git left - there when it had to be killed is left in place, recorded in - `ops/backup.jsonl` as `lock_left` with its whole path, and the target's - backup is marked failed with words naming the file and saying to remove - it only when nothing else is using the backup folder (`books.backup` - and the close's answer say the same; the next backup that finds the - lock gone goes on). In the book's own archive (`archive.git`, private to - the program; running git by hand inside it is unsupported) it removes - only the locks its own stopped git made, and, at open and when a backup - begins, locks older than ten minutes, each recorded `lock_removed`; + a backup still running after that is stopped (its copy of files + stops at the next piece, or the next 64 KiB of one) and waited for to + end. The program never rewrites or deletes anything in a backup folder + (it is the owner's, and may be shared with other computers or a sync + program): a backup stopped part way leaves pieces no manifest names and + the folder proves whole at its previous manifest, so there is nothing to + clean up and nothing to remove by hand. **What a close stops, and what it waits for.** At its start a close stops the calls and jobs that can do long I/O or loop over a book's whole journal or files, each at its next look: `books.back_up_now` and - a backup a timer asked for (git is stopped; the call answers that it was - stopped because the books are closing, its access record says + a backup a timer asked for (its copy is stopped; the call answers that it + was stopped because the books are closing, its access record says `refused: stopped_by_close`, and nothing it was doing is recorded as done; - a commit it had made stands), `books.verify` (once per journal line and + what it had written stands, and the folder still proves whole at its + previous manifest), `books.verify` (once per journal line and per stored file; a heal of a drifted database is begun only if no stop was asked before it, then finishes), `books.export_cpa_package` (once per stored file, unless it has journaled a decision, below), a drill, and a @@ -1329,75 +1323,74 @@ through the policy. ## Tools — backups -Books back themselves up (plan 3.7, D-30, -D-31): each keeps `archive.git`, a bare repository whose commits are its -journal, stored files, vault, keys and access log as they were (one -commit per backup, made under the store's lock, its message -`seq N head H` and, below, `book `), pushed fast-forward only to the targets the settings -name: `backup.git_remote` (the owner's private repository) and -`backup.folder` (a repository `.git` in a folder on another disk). -Not encrypted: the destinations keep it private. Backups run a little -after the books are last written (`--backup-quiet`, 30 s), when they -open, before they close, and on request; a failed one is retried after -15 minutes. Each target is drilled weekly: cloned, its chain replayed, -every stored file re-hashed, every TIN record the books name there with -its key, its head the one its commit records, its journal a byte prefix -of the live one (a failed drill is tried again at the server's next -hourly look, once 15 minutes have passed). A backup's tree is checked -before any of it is written out: plain files under the backed-up paths -only, never a link or a submodule. git runs with no hooks (in a -repository on this computer it pushes to as well), no ignore or -attributes rules of anyone's (a `.gitattributes` in a book's folder -refuses the backup) and no command-running transports; a repository on -this computer is used only if plain (a bare repository at that very -path, no settings of its own but where a copy came from, nothing sending -git elsewhere, no link where it or its parts are), and a backup folder that took backups and is gone is -reported as a disk not connected, never made again (restored books count -the backups of the books they were). Books restored beside the books they -were (under another id) don't push to those books' repository, which -would stop theirs: `books.backup` says it is paused for them until -another is named. A damaged backup record is set aside and begun again; -it never keeps the books shut. One book's drill holds the others' -backups until it ends (a backup at close waits at most a minute for -it). A target -whose push failed is left out of the backups after writes for 15 -minutes, then tried again, written to or not; the other targets don't -wait for it. Every -commit, push and drill is a record in the book's `ops/backup.jsonl` (a -chain log; a backup never moves the books' head), each target's records -keyed by the target itself. Setting `backup.*` (books.set_setting) needs -books:admin, as -backing up does: a backup is the whole book, its vault and key included. +Books back themselves up (plan 3.7, D-91, D-92): to the folder the settings +name, `backup.folder` (a folder on another disk, or one a sync service +keeps), as plain files written once (docs/backups.md): a folder for the +books holding a read-me, a `manifests/` folder, and the pieces the manifests +name, the journal and the access log as numbered segments, an index of the +stored files and the files themselves under their hash, the vault and keys +by content hash. The manifest is written last and makes a backup complete; +nothing in the folder is ever rewritten or deleted. Taking a backup holds +the store's lock only to cut the books (the journal's length and head, the +vault, the keys); the files are written after it. With a passphrase (D-92, +set up in the window; off by default) every file is sealed with +XChaCha20-Poly1305, the key derived with Argon2id (64 MiB, 3 passes, 1 +lane), names say no more than counts and sizes, and the key is kept on this +computer only. Backups run a little after the books are last written +(`--backup-quiet`, 30 s), when they open, before they close, and on request; +a failed one is retried after 15 minutes. The folder's backup is drilled +weekly: its books built and proven whole, every stored file re-hashed, every +TIN record the books name there with its key, its head the one its manifest +records, its journal a byte prefix of the live one (a failed drill is tried +again at the server's next hourly look, once 15 minutes have passed). A +backup is written only onto a folder whose newest whole manifest is a point +on the live journal; one holding other books, another history, or more than +these books have is said, and nothing is written. A backup folder that took +backups and is gone is reported as a disk not connected, never made again +(restored books count the backups of the books they were). Books restored +under another id back up to a folder of their own in the same place. A +damaged backup record is set aside and begun again; it never keeps the books +shut. A folder whose write failed is left out of the backups after writes +for 15 minutes, then tried again. Every cut, write and drill is a record in +the book's `ops/backup.jsonl` (a chain log; a backup never moves the books' +head), the folder's records keyed by the folder and the passphrase. Setting +`backup.*` (books.set_setting) needs books:admin, as backing up does: a +backup is the whole book, its vault and key included. Books that still name +a private repository (`backup.git_remote`, an older kind of backup) work as +ever; `books.backup`'s `note` says it is no longer used, and an older backup +history in the book's folder is left alone and said once. - `books.backup {}` (books:read) → `{ head_seq, targets: [{ target: - "repository" | "folder", at, last_ok_at, through_seq, stale, - last_error, last_drill_at, drill_error, paused }], note }`. `paused`: - not backed up there, these books being restored as a copy of others - (its `last_error` says so). `stale`: the target + "folder", at, last_ok_at, through_seq, stale, last_error, + last_drill_at, drill_error, sealed, disconnected }], note }`. + `sealed`: protected by a passphrase. `disconnected`: its disk isn't + there. `stale`: the target lacks the head, and the first try to back up what it lacks (since its last good backup, or ever) is more than a day old. `last_error`: its - last push's, or a later failed commit's. `note` - says what to set when no target is. `books.start` adds a next step when - none is set up, or one is stale, failing, paused or failed its drill. + last write's, or a later failed cut's. `note` + says what to set when no folder is, and what older settings or history are + no longer used. `books.start` adds a next step when none is set up, or the + folder is stale, failing or failed its drill. - `books.back_up_now { new_disk? }` (books:admin) → the same, after - backing up to every target now. `new_disk`: the backup folder's disk is + backing up to the folder now. `new_disk`: the backup folder's disk is new, so a folder that took these books' backups and holds none now is begun again (otherwise it is a disk not connected). The one tool whose - `openWorldHint` is true. A target paused for books restored as a copy - of others shows `paused` (and is no failure to retry). + `openWorldHint` is true. -Restoring is the owner's, from a terminal: `wanderbooks books restore -BACKUP [--id ID] [--replace] [--yes]` (the admin socket's `restore`, -previewed then confirmed against the previewed head; without `--id`, the -books keep the id of the books the backup holds, which the preview names, -else the repository's name; under another id they are a copy, and don't -push to those books' repository). The backup is -cloned into the root, proven whole as a drill proves it (but for the -live-journal check: there may be no live books), and built as an -adoption builds; it arrives as new books, or replaces books (`--replace`, -which are let go and moved whole into `legacy/-