steid

@jamesgill /

Rust36.1 KBCode·Blame·History·Raw
1//! Backup adapters: a consistent database snapshot, and the `tar.gz` it travels in.
2//!
3//! Two ports, one file, because they are two halves of one file format and reading them
4//! apart would mean reading the layout twice.
5//!
6//! **The archive work is blocking.** `tar` and `flate2` are synchronous, and gzipping a
7//! repository directory is real CPU rather than a wait, so every one of these runs
8//! inside `spawn_blocking` rather than pretending to be async on the runtime's threads.
9
10use std::{
11 fs::{self, File},
12 io::{self, Read, Write},
13 path::{Path, PathBuf},
14 sync::{Arc, Mutex},
15 time::{SystemTime, UNIX_EPOCH},
16};
17
18use flate2::{Compression, read::GzDecoder, write::GzEncoder};
19use sqlx::SqlitePool;
20
21use crate::application::{
22 backup::BackupManifest,
23 port::{
24 BACKUP_DATA_PREFIX, BACKUP_DATABASE, BACKUP_MANIFEST, BackupArchive, BackupError,
25 BackupPlan, DatabaseSnapshot, ExistingData, RestorePlan,
26 },
27};
28
29/// Where the live SQLite database file is, read out of a connection string.
30///
31/// `sqlite:steid.db?mode=rwc`, `sqlite://steid.db`, and a bare path all name a file;
32/// `sqlite::memory:` names nothing, which is `None` rather than an error — an in-memory
33/// instance genuinely has no file to snapshot, and saying so is more useful than
34/// inventing a path called `:memory:`.
35#[must_use]
36pub fn database_file(url: &str) -> Option<PathBuf> {
37 let rest = url
38 .strip_prefix("sqlite://")
39 .or_else(|| url.strip_prefix("sqlite:"))
40 .unwrap_or(url);
41
42 // Everything from the first `?` is sqlx's own options — `mode=rwc` and friends —
43 // and is not part of the filename.
44 let path = rest.split('?').next().unwrap_or_default();
45
46 (!path.is_empty() && path != ":memory:").then(|| PathBuf::from(path))
47}
48
49/// `VACUUM INTO`, which is SQLite's own answer to "copy this while it is in use".
50#[derive(Debug, Clone)]
51pub struct SqliteDatabaseSnapshot {
52 pool: SqlitePool,
53 /// The live file, for [`replace`](DatabaseSnapshot::replace). Never read when only
54 /// taking a snapshot — that goes through the pool, which is the point.
55 database: PathBuf,
56}
57
58impl SqliteDatabaseSnapshot {
59 pub fn new(pool: SqlitePool, database: impl Into<PathBuf>) -> Self {
60 Self {
61 pool,
62 database: database.into(),
63 }
64 }
65}
66
67impl DatabaseSnapshot for SqliteDatabaseSnapshot {
68 async fn snapshot(&self, workspace: &Path) -> Result<PathBuf, BackupError> {
69 let destination = workspace.join(format!("steid-snapshot-{}.db", uuid::Uuid::new_v4()));
70
71 let target = destination
72 .to_str()
73 .ok_or_else(|| BackupError::backend("the workspace path is not valid UTF-8"))?;
74
75 // Bound rather than interpolated: the path is ours, but a filename reaching a
76 // SQL statement by string concatenation is how the next one gets there too.
77 // `VACUUM INTO` refuses a destination that already exists, which is why the
78 // filename carries a fresh UUID rather than being a fixed name in a fresh
79 // directory — a workspace reused by mistake fails loudly instead of silently
80 // packing yesterday's database.
81 sqlx::query("vacuum into ?")
82 .bind(target)
83 .execute(&self.pool)
84 .await
85 .map_err(BackupError::backend)?;
86
87 Ok(destination)
88 }
89
90 async fn replace(&self, source: &Path) -> Result<(), BackupError> {
91 // Nothing may hold the file across the swap. Closing a clone closes the pool
92 // every other adapter in this process shares, which is the intent: after this
93 // line the process has no database, and the only thing it may do is finish
94 // restoring and exit.
95 self.pool.close().await;
96
97 let source = source.to_path_buf();
98 let database = self.database.clone();
99
100 blocking(move || {
101 // The journal siblings go first. A `-wal` left beside a replaced database
102 // belongs to the database that is no longer there, and SQLite would apply
103 // it — which is corruption, not staleness.
104 for suffix in ["-wal", "-shm"] {
105 let sibling = sibling(&database, suffix);
106 if sibling.exists() {
107 fs::remove_file(&sibling).map_err(BackupError::backend)?;
108 }
109 }
110
111 move_file(&source, &database)
112 })
113 .await
114 }
115}
116
117/// One backup as a gzipped tar.
118///
119/// The layout is the port's contract: `manifest.json`, `steid.db`, and the data
120/// directory under `data/`.
121#[derive(Debug, Clone, Copy, Default)]
122pub struct TarGzBackupArchive;
123
124impl TarGzBackupArchive {
125 #[must_use]
126 pub fn new() -> Self {
127 Self
128 }
129}
130
131impl BackupArchive for TarGzBackupArchive {
132 async fn pack(&self, plan: BackupPlan) -> Result<u64, BackupError> {
133 blocking(move || pack(&plan)).await
134 }
135
136 async fn manifest(&self, archive: &Path) -> Result<BackupManifest, BackupError> {
137 let archive = archive.to_path_buf();
138 blocking(move || read_manifest(&archive)).await
139 }
140
141 async fn unpack(&self, plan: RestorePlan) -> Result<(), BackupError> {
142 blocking(move || unpack(&plan)).await
143 }
144}
145
146/// Runs synchronous filesystem work off the runtime's threads.
147async fn blocking<T, F>(work: F) -> Result<T, BackupError>
148where
149 F: FnOnce() -> Result<T, BackupError> + Send + 'static,
150 T: Send + 'static,
151{
152 tokio::task::spawn_blocking(work)
153 .await
154 .map_err(BackupError::backend)?
155}
156
157/// `steid.db` → `steid.db-wal`.
158fn sibling(database: &Path, suffix: &str) -> PathBuf {
159 let mut name = database.as_os_str().to_os_string();
160 name.push(suffix);
161 PathBuf::from(name)
162}
163
164/// Moves a file, falling back to a copy when the two ends are on different filesystems.
165///
166/// A backup destination on a mounted volume is the ordinary case rather than the exotic
167/// one, and `rename` answers `EXDEV` there.
168fn move_file(source: &Path, destination: &Path) -> Result<(), BackupError> {
169 if let Some(parent) = destination.parent() {
170 fs::create_dir_all(parent).map_err(BackupError::backend)?;
171 }
172
173 match fs::rename(source, destination) {
174 Ok(()) => Ok(()),
175 Err(_) => {
176 fs::copy(source, destination).map_err(BackupError::backend)?;
177 // Best effort: the copy is what matters, and a scratch file left behind is
178 // the caller's workspace to clean up anyway.
179 let _ = fs::remove_file(source);
180 Ok(())
181 }
182 }
183}
184
185/// Writes the archive, and says how large it came out.
186///
187/// Built beside the destination as `<name>.partial` and renamed at the end, so an
188/// interrupted backup leaves something obviously unfinished rather than a truncated
189/// `.tar.gz` a later restore would trust.
190fn pack(plan: &BackupPlan) -> Result<u64, BackupError> {
191 if plan.destination.exists() {
192 return Err(BackupError::refused(format!(
193 "{} already exists",
194 plan.destination.display()
195 )));
196 }
197
198 if let Some(parent) = plan
199 .destination
200 .parent()
201 .filter(|parent| !parent.as_os_str().is_empty())
202 {
203 fs::create_dir_all(parent).map_err(BackupError::backend)?;
204 }
205
206 let partial = sibling(&plan.destination, ".partial");
207 let file = File::create(&partial).map_err(BackupError::backend)?;
208 let mut builder = tar::Builder::new(GzEncoder::new(file, Compression::default()));
209 // Never follow a symlink out of the data directory: with this off, a link is
210 // archived as a link, and `unpack` refuses one outright.
211 builder.follow_symlinks(false);
212
213 let manifest = serde_json::to_vec_pretty(&plan.manifest).map_err(BackupError::backend)?;
214 let mut header = tar::Header::new_gnu();
215 header.set_size(manifest.len() as u64);
216 header.set_mode(0o600);
217 header.set_mtime(epoch_seconds());
218 header.set_cksum();
219 builder
220 .append_data(&mut header, BACKUP_MANIFEST, manifest.as_slice())
221 .map_err(BackupError::backend)?;
222
223 builder
224 .append_path_with_name(&plan.database, BACKUP_DATABASE)
225 .map_err(BackupError::backend)?;
226
227 append_data_dir(&mut builder, &plan.data_dir)?;
228
229 let encoder = builder.into_inner().map_err(BackupError::backend)?;
230 let mut file = encoder.finish().map_err(BackupError::backend)?;
231 file.flush().map_err(BackupError::backend)?;
232 drop(file);
233
234 let bytes = fs::metadata(&partial).map_err(BackupError::backend)?.len();
235 fs::rename(&partial, &plan.destination).map_err(BackupError::backend)?;
236
237 Ok(bytes)
238}
239
240fn epoch_seconds() -> u64 {
241 SystemTime::now()
242 .duration_since(UNIX_EPOCH)
243 .map(|since| since.as_secs())
244 .unwrap_or_default()
245}
246
247/// Adds the whole data directory under `data/`.
248///
249/// Walked by hand rather than with `append_dir_all`, for three rules that walk cannot
250/// express:
251///
252/// - **Symlinks are skipped**, not followed and not stored. A link inside a bare
253/// repository is not something git puts there, and following one is the only way a
254/// path outside the data directory could get into the archive.
255/// - **Top-level dot-directories are skipped.** A handle is `[a-z0-9-]` and can never
256/// start with a dot, so nothing here is a repository — and the backup's own scratch
257/// directory lives at `<data_dir>/.backup`, which must not end up inside the archive
258/// it is being built in.
259/// - **Anything that is neither a file nor a directory is skipped**, with a line saying
260/// so, rather than failing the backup over a stray socket or device node.
261fn append_data_dir<W: Write>(
262 builder: &mut tar::Builder<W>,
263 data_dir: &Path,
264) -> Result<(), BackupError> {
265 // The root, always — a restore of an instance with no repositories must still make
266 // the directory.
267 let mut root = tar::Header::new_gnu();
268 root.set_entry_type(tar::EntryType::Directory);
269 root.set_size(0);
270 root.set_mode(0o750);
271 root.set_mtime(epoch_seconds());
272 root.set_cksum();
273 builder
274 .append_data(&mut root, format!("{BACKUP_DATA_PREFIX}/"), io::empty())
275 .map_err(BackupError::backend)?;
276
277 if !data_dir.is_dir() {
278 return Ok(());
279 }
280
281 walk(builder, data_dir, data_dir, true)
282}
283
284fn walk<W: Write>(
285 builder: &mut tar::Builder<W>,
286 data_dir: &Path,
287 dir: &Path,
288 top: bool,
289) -> Result<(), BackupError> {
290 let mut entries: Vec<PathBuf> = fs::read_dir(dir)
291 .map_err(BackupError::backend)?
292 .map(|entry| entry.map(|entry| entry.path()))
293 .collect::<Result<_, _>>()
294 .map_err(BackupError::backend)?;
295
296 // Directory order is filesystem order, which differs between machines. Sorting makes
297 // two backups of the same state produce the same entry order, which is what lets
298 // anyone compare them.
299 entries.sort();
300
301 for path in entries {
302 let name = path
303 .file_name()
304 .and_then(|name| name.to_str())
305 .ok_or_else(|| {
306 BackupError::backend(format!("{} is not a valid UTF-8 name", path.display()))
307 })?;
308
309 if top && name.starts_with('.') {
310 continue;
311 }
312
313 let metadata = fs::symlink_metadata(&path).map_err(BackupError::backend)?;
314
315 let relative = path.strip_prefix(data_dir).map_err(BackupError::backend)?;
316 let entry = format!("{BACKUP_DATA_PREFIX}/{}", relative.to_string_lossy());
317
318 if metadata.is_symlink() {
319 eprintln!("steid: backup skipped the symlink {}", path.display());
320 continue;
321 }
322
323 if metadata.is_dir() {
324 builder
325 .append_dir(format!("{entry}/"), &path)
326 .map_err(BackupError::backend)?;
327 walk(builder, data_dir, &path, false)?;
328 } else if metadata.is_file() {
329 let mut file = File::open(&path).map_err(BackupError::backend)?;
330 builder
331 .append_file(&entry, &mut file)
332 .map_err(BackupError::backend)?;
333 } else {
334 eprintln!(
335 "steid: backup skipped {}, which is not a file",
336 path.display()
337 );
338 }
339 }
340
341 Ok(())
342}
343
344/// The manifest, without extracting anything else.
345fn read_manifest(archive: &Path) -> Result<BackupManifest, BackupError> {
346 /// Enough for a manifest many times over, and not enough for a hostile archive to
347 /// make this allocate. It holds three numbers and two short strings.
348 const MAX: u64 = 64 * 1024;
349
350 for entry in open(archive)?.entries().map_err(BackupError::backend)? {
351 let mut entry = entry.map_err(BackupError::backend)?;
352 let path = entry.path().map_err(BackupError::backend)?.into_owned();
353
354 if path != Path::new(BACKUP_MANIFEST) {
355 continue;
356 }
357
358 let mut json = String::new();
359 entry
360 .by_ref()
361 .take(MAX)
362 .read_to_string(&mut json)
363 .map_err(|error| {
364 BackupError::malformed(format!("the manifest is unreadable: {error}"))
365 })?;
366
367 return serde_json::from_str(&json).map_err(|error| {
368 BackupError::malformed(format!("the manifest does not parse: {error}"))
369 });
370 }
371
372 Err(BackupError::malformed(
373 "there is no manifest.json in it, so it is not a Steid backup",
374 ))
375}
376
377fn open(archive: &Path) -> Result<tar::Archive<GzDecoder<File>>, BackupError> {
378 let file = File::open(archive).map_err(|error| {
379 BackupError::malformed(format!(
380 "{} could not be opened: {error}",
381 archive.display()
382 ))
383 })?;
384
385 Ok(tar::Archive::new(GzDecoder::new(file)))
386}
387
388/// Extracts an archive, refusing anything it did not write.
389///
390/// Every entry is checked before it is written, and the checks are the security of the
391/// whole feature: an archive is a file somebody hands the process, and `tar` has been a
392/// path-traversal primitive for forty years. An entry may only be a regular file or a
393/// directory, may only sit at `manifest.json`, `steid.db` or under `data/`, may not be
394/// absolute, and may not contain `..` — so no entry can name a path outside the two
395/// destinations, whatever the archive says.
396///
397/// Under [`ExistingData::Replace`] the `data/` entries land in `staging` instead, and
398/// [`swap`] moves them into place afterwards. The refuse-to-overwrite rule is unchanged
399/// by that and is what makes `staging` have to be a directory nothing has used before.
400fn unpack(plan: &RestorePlan) -> Result<(), BackupError> {
401 let mut database = false;
402
403 // Where the `data/` entries are written. Not the live directory when there is
404 // something in it to preserve — see the module note on unpacking beside.
405 let data_dir = match &plan.existing {
406 ExistingData::Refuse => plan.data_dir.clone(),
407 ExistingData::Replace { staging, .. } => {
408 if staging.exists() {
409 return Err(BackupError::refused(format!(
410 "{} already exists, and a restore stages into a fresh directory",
411 staging.display()
412 )));
413 }
414
415 staging.clone()
416 }
417 };
418
419 for entry in open(&plan.archive)?
420 .entries()
421 .map_err(BackupError::backend)?
422 {
423 let mut entry = entry.map_err(BackupError::backend)?;
424 let path = entry.path().map_err(BackupError::backend)?.into_owned();
425
426 let kind = entry.header().entry_type();
427 if !(kind.is_file() || kind.is_dir()) {
428 return Err(BackupError::malformed(format!(
429 "{} is a {kind:?}, and a backup holds only files and directories",
430 path.display()
431 )));
432 }
433
434 let Some(relative) = safe(&path) else {
435 return Err(BackupError::malformed(format!(
436 "{} is not a path a backup may contain",
437 path.display()
438 )));
439 };
440
441 let destination = if relative == Path::new(BACKUP_MANIFEST) {
442 // Already read, and not something the instance keeps.
443 continue;
444 } else if relative == Path::new(BACKUP_DATABASE) {
445 database = true;
446 plan.database.clone()
447 } else if let Ok(rest) = relative.strip_prefix(BACKUP_DATA_PREFIX) {
448 data_dir.join(rest)
449 } else {
450 return Err(BackupError::malformed(format!(
451 "{} is not part of a Steid backup",
452 path.display()
453 )));
454 };
455
456 if kind.is_dir() {
457 fs::create_dir_all(&destination).map_err(BackupError::backend)?;
458 continue;
459 }
460
461 // The use case established that the instance is empty; anything here means it
462 // was wrong, and overwriting is the one outcome a restore must never have.
463 if destination.exists() {
464 return Err(BackupError::refused(format!(
465 "{} already exists",
466 destination.display()
467 )));
468 }
469
470 if let Some(parent) = destination.parent() {
471 fs::create_dir_all(parent).map_err(BackupError::backend)?;
472 }
473
474 entry.unpack(&destination).map_err(BackupError::backend)?;
475 }
476
477 if !database {
478 return Err(BackupError::malformed(
479 "there is no steid.db in it, so it is not a Steid backup",
480 ));
481 }
482
483 // Only now: everything above could still fail, and until this line the live data
484 // directory has not been touched.
485 if let ExistingData::Replace { staging, aside } = &plan.existing {
486 swap(&plan.data_dir, staging, aside)?;
487 }
488
489 Ok(())
490}
491
492/// Moves what the data directory holds into `aside`, then the staged tree into its place.
493///
494/// Renames, so the two ends must share a filesystem — they do by construction, since the
495/// staging directory is inside the backup workspace which is inside the data directory.
496/// A rename is also the only move that cannot half-copy a bare repository.
497///
498/// **Top-level dot entries are left exactly where they are.** That is the backup
499/// workspace this is running out of, and any earlier `.replaced-…` — neither of which is
500/// state the archive is replacing, and moving the first would move the ground out from
501/// under the second loop.
502///
503/// Nothing is deleted. `aside` holds the previous instance until somebody removes it by
504/// hand.
505fn swap(data_dir: &Path, staging: &Path, aside: &Path) -> Result<(), BackupError> {
506 fs::create_dir_all(aside).map_err(BackupError::backend)?;
507
508 for path in entries(data_dir)? {
509 let name = file_name(&path)?;
510
511 if name.starts_with('.') {
512 continue;
513 }
514
515 fs::rename(&path, aside.join(name)).map_err(|error| {
516 BackupError::backend(format!(
517 "could not move {} aside to {}: {error}",
518 path.display(),
519 aside.display()
520 ))
521 })?;
522 }
523
524 for path in entries(staging)? {
525 let name = file_name(&path)?;
526
527 fs::rename(&path, data_dir.join(name)).map_err(|error| {
528 BackupError::backend(format!(
529 "could not move the restored {} into {}: {error}",
530 path.display(),
531 data_dir.display()
532 ))
533 })?;
534 }
535
536 // Empty by now. Best effort: the workspace is the caller's to remove anyway.
537 let _ = fs::remove_dir(staging);
538
539 Ok(())
540}
541
542/// One directory's entries, sorted, so a swap is the same operation twice running.
543fn entries(dir: &Path) -> Result<Vec<PathBuf>, BackupError> {
544 let mut found: Vec<PathBuf> = fs::read_dir(dir)
545 .map_err(|error| {
546 BackupError::backend(format!("could not read {}: {error}", dir.display()))
547 })?
548 .map(|entry| entry.map(|entry| entry.path()))
549 .collect::<Result<_, _>>()
550 .map_err(BackupError::backend)?;
551
552 found.sort();
553
554 Ok(found)
555}
556
557fn file_name(path: &Path) -> Result<&str, BackupError> {
558 path.file_name()
559 .and_then(|name| name.to_str())
560 .ok_or_else(|| {
561 BackupError::backend(format!("{} is not a valid UTF-8 name", path.display()))
562 })
563}
564
565/// An entry path, if it is one a backup may legally contain.
566///
567/// Relative, no `..`, no root, no Windows prefix, and no empty components. `None` means
568/// refuse — never "sanitise and carry on", because a path that needed sanitising was
569/// written by something that is not Steid.
570fn safe(path: &Path) -> Option<&Path> {
571 use std::path::Component;
572
573 let ordinary = path
574 .components()
575 .all(|component| matches!(component, Component::Normal(_)));
576
577 (ordinary && path.components().next().is_some()).then_some(path)
578}
579
580/// The in-memory [`DatabaseSnapshot`], for use-case tests.
581///
582/// Touches no disk: it hands back a path inside the workspace it was given and records
583/// what it was asked to do, which is all a use case's decisions can be checked against.
584#[derive(Debug, Default, Clone)]
585pub struct InMemoryDatabaseSnapshot {
586 taken: Arc<Mutex<u64>>,
587 installed: Arc<Mutex<Vec<PathBuf>>>,
588}
589
590impl InMemoryDatabaseSnapshot {
591 #[must_use]
592 pub fn new() -> Self {
593 Self::default()
594 }
595
596 /// How many snapshots were taken.
597 #[must_use]
598 pub fn taken(&self) -> u64 {
599 *self.taken.lock().expect("lock poisoned")
600 }
601
602 /// Every file that was installed as the live database, in order.
603 #[must_use]
604 pub fn installed(&self) -> Vec<PathBuf> {
605 self.installed.lock().expect("lock poisoned").clone()
606 }
607}
608
609impl DatabaseSnapshot for InMemoryDatabaseSnapshot {
610 async fn snapshot(&self, workspace: &Path) -> Result<PathBuf, BackupError> {
611 let mut taken = self.taken.lock().expect("lock poisoned");
612 *taken += 1;
613
614 Ok(workspace.join(format!("snapshot-{taken}.db")))
615 }
616
617 async fn replace(&self, source: &Path) -> Result<(), BackupError> {
618 self.installed
619 .lock()
620 .expect("lock poisoned")
621 .push(source.to_path_buf());
622
623 Ok(())
624 }
625}
626
627/// The in-memory [`BackupArchive`], for use-case tests.
628///
629/// Archives are entries in a map keyed by their path, so a backup taken through one
630/// handle can be restored through a clone of it — which is how a test copies an archive
631/// from one instance to another without a filesystem.
632#[derive(Debug, Default, Clone)]
633pub struct InMemoryBackupArchive {
634 manifests: Arc<Mutex<Vec<(PathBuf, BackupManifest)>>>,
635 packed: Arc<Mutex<Vec<BackupPlan>>>,
636 unpacked: Arc<Mutex<Vec<RestorePlan>>>,
637}
638
639impl InMemoryBackupArchive {
640 #[must_use]
641 pub fn new() -> Self {
642 Self::default()
643 }
644
645 /// Puts an archive there without going through [`pack`](BackupArchive::pack), for
646 /// testing what a restore does with a manifest it did not write.
647 pub fn plant(&self, path: impl Into<PathBuf>, manifest: BackupManifest) {
648 self.manifests
649 .lock()
650 .expect("lock poisoned")
651 .push((path.into(), manifest));
652 }
653
654 #[must_use]
655 pub fn packed(&self) -> Vec<BackupPlan> {
656 self.packed.lock().expect("lock poisoned").clone()
657 }
658
659 #[must_use]
660 pub fn unpacked(&self) -> Vec<RestorePlan> {
661 self.unpacked.lock().expect("lock poisoned").clone()
662 }
663}
664
665impl BackupArchive for InMemoryBackupArchive {
666 async fn pack(&self, plan: BackupPlan) -> Result<u64, BackupError> {
667 self.plant(plan.destination.clone(), plan.manifest.clone());
668 self.packed.lock().expect("lock poisoned").push(plan);
669
670 Ok(1024)
671 }
672
673 async fn manifest(&self, archive: &Path) -> Result<BackupManifest, BackupError> {
674 self.manifests
675 .lock()
676 .expect("lock poisoned")
677 .iter()
678 .find(|(path, _)| path == archive)
679 .map(|(_, manifest)| manifest.clone())
680 .ok_or_else(|| BackupError::malformed(format!("no archive at {}", archive.display())))
681 }
682
683 async fn unpack(&self, plan: RestorePlan) -> Result<(), BackupError> {
684 // Reads the manifest first, so a plan naming an archive that is not there fails
685 // here exactly as it would on disk.
686 self.manifest(&plan.archive).await?;
687 self.unpacked.lock().expect("lock poisoned").push(plan);
688
689 Ok(())
690 }
691}
692
693#[cfg(test)]
694mod tests {
695 use super::*;
696 use crate::application::backup::BackupCounts;
697
698 fn manifest() -> BackupManifest {
699 BackupManifest {
700 version: "0.4.0".to_owned(),
701 taken_at: "2026-09-08T14:25:30Z".to_owned(),
702 counts: BackupCounts {
703 users: 1,
704 organisations: 1,
705 repositories: 2,
706 },
707 }
708 }
709
710 /// A data directory with one bare-repository-shaped tree in it.
711 fn fixture(root: &Path) -> PathBuf {
712 let data = root.join("repos");
713 fs::create_dir_all(data.join("james/steid.git/refs/heads")).expect("mkdir");
714 fs::write(data.join("james/steid.git/HEAD"), b"ref: refs/heads/main\n").expect("write");
715 fs::write(data.join("james/steid.git/refs/heads/main"), b"abc123\n").expect("write");
716 data
717 }
718
719 fn plan(root: &Path, data: &Path) -> BackupPlan {
720 let database = root.join("snapshot.db");
721 fs::write(&database, b"SQLite format 3\0not really").expect("write");
722
723 BackupPlan {
724 destination: root.join("out.tar.gz"),
725 database,
726 data_dir: data.to_path_buf(),
727 manifest: manifest(),
728 }
729 }
730
731 #[test]
732 fn a_database_url_names_a_file() {
733 assert_eq!(
734 database_file("sqlite:/var/lib/steid/steid.db?mode=rwc"),
735 Some(PathBuf::from("/var/lib/steid/steid.db"))
736 );
737 assert_eq!(
738 database_file("sqlite://steid.db"),
739 Some(PathBuf::from("steid.db"))
740 );
741 assert_eq!(database_file("steid.db"), Some(PathBuf::from("steid.db")));
742 assert_eq!(database_file("sqlite::memory:"), None);
743 }
744
745 #[test]
746 fn an_archive_round_trips_the_database_and_every_repository() {
747 let root = tempfile::tempdir().expect("tempdir");
748 let data = fixture(root.path());
749 let plan = plan(root.path(), &data);
750
751 let bytes = pack(&plan).expect("should pack");
752 assert!(bytes > 0);
753 assert_eq!(
754 read_manifest(&plan.destination).expect("manifest"),
755 manifest()
756 );
757
758 let into = root.path().join("restored");
759 unpack(&RestorePlan {
760 archive: plan.destination.clone(),
761 database: into.join("steid.db"),
762 data_dir: into.join("repos"),
763 existing: ExistingData::Refuse,
764 })
765 .expect("should unpack");
766
767 assert_eq!(
768 fs::read(into.join("steid.db")).expect("read"),
769 b"SQLite format 3\0not really"
770 );
771 assert_eq!(
772 fs::read_to_string(into.join("repos/james/steid.git/HEAD")).expect("read"),
773 "ref: refs/heads/main\n"
774 );
775 assert!(into.join("repos/james/steid.git/refs/heads/main").is_file());
776 }
777
778 #[test]
779 fn a_replace_swaps_the_tree_in_and_leaves_the_old_one_beside_it() {
780 // The live data directory here is the one the archive is being poured over, and
781 // it holds the backup workspace the restore is running out of — which is why the
782 // swap has to leave top-level dot entries alone.
783 let root = tempfile::tempdir().expect("tempdir");
784 let plan = plan(root.path(), &fixture(root.path()));
785 pack(&plan).expect("should pack");
786
787 let live = root.path().join("live");
788 fs::create_dir_all(live.join("bob/notes.git")).expect("mkdir");
789 fs::write(live.join("bob/notes.git/HEAD"), b"mine\n").expect("write");
790 let workspace = live.join(".backup");
791 fs::create_dir_all(&workspace).expect("mkdir");
792 fs::write(workspace.join("keep-me"), b"scratch\n").expect("write");
793
794 let aside = live.join(".replaced-20260908T142530Z");
795 unpack(&RestorePlan {
796 archive: plan.destination.clone(),
797 database: workspace.join("steid.db"),
798 data_dir: live.clone(),
799 existing: ExistingData::Replace {
800 staging: workspace.join("incoming"),
801 aside: aside.clone(),
802 },
803 })
804 .expect("should unpack and swap");
805
806 assert_eq!(
807 fs::read_to_string(live.join("james/steid.git/HEAD")).expect("read"),
808 "ref: refs/heads/main\n",
809 "the archive's tree is not in place"
810 );
811 assert!(
812 !live.join("bob").exists(),
813 "the old tree is still where it was"
814 );
815 assert_eq!(
816 fs::read_to_string(aside.join("bob/notes.git/HEAD")).expect("read"),
817 "mine\n",
818 "the old tree was not moved aside intact"
819 );
820 assert!(
821 fs::read_to_string(workspace.join("keep-me")).expect("read") == "scratch\n",
822 "the swap moved the workspace it is running out of"
823 );
824 assert!(
825 !workspace.join("incoming").exists(),
826 "the staging directory survived the swap"
827 );
828 }
829
830 #[test]
831 fn a_failed_replace_leaves_the_live_directory_exactly_as_it_was() {
832 // Unpack beside, then swap: the extraction is where a corrupt archive fails, and
833 // it must fail before anything live has moved.
834 let root = tempfile::tempdir().expect("tempdir");
835 let truncated = root.path().join("half.tar.gz");
836 fs::write(&truncated, b"not a gzip at all").expect("write");
837
838 let live = root.path().join("live");
839 fs::create_dir_all(live.join("bob/notes.git")).expect("mkdir");
840 fs::write(live.join("bob/notes.git/HEAD"), b"mine\n").expect("write");
841 let workspace = live.join(".backup");
842 fs::create_dir_all(&workspace).expect("mkdir");
843
844 let refused = unpack(&RestorePlan {
845 archive: truncated,
846 database: workspace.join("steid.db"),
847 data_dir: live.clone(),
848 existing: ExistingData::Replace {
849 staging: workspace.join("incoming"),
850 aside: live.join(".replaced-20260908T142530Z"),
851 },
852 });
853
854 assert!(refused.is_err(), "a truncated archive is not a restore");
855 assert_eq!(
856 fs::read_to_string(live.join("bob/notes.git/HEAD")).expect("read"),
857 "mine\n",
858 "the instance lost its state to a failed restore"
859 );
860 assert!(
861 !live.join(".replaced-20260908T142530Z").exists(),
862 "nothing should have been moved aside"
863 );
864 }
865
866 #[test]
867 fn a_replace_refuses_to_stage_into_a_directory_that_already_exists() {
868 // The refuse-to-overwrite rule still applies inside the staging directory, so a
869 // staging directory somebody else is using would turn into a half-merge.
870 let root = tempfile::tempdir().expect("tempdir");
871 let plan = plan(root.path(), &fixture(root.path()));
872 pack(&plan).expect("should pack");
873
874 let live = root.path().join("live");
875 let workspace = live.join(".backup");
876 fs::create_dir_all(workspace.join("incoming")).expect("mkdir");
877
878 let refused = unpack(&RestorePlan {
879 archive: plan.destination.clone(),
880 database: workspace.join("steid.db"),
881 data_dir: live.clone(),
882 existing: ExistingData::Replace {
883 staging: workspace.join("incoming"),
884 aside: live.join(".replaced-20260908T142530Z"),
885 },
886 });
887
888 assert!(
889 matches!(refused, Err(BackupError::Refused(_))),
890 "{refused:?}"
891 );
892 }
893
894 #[test]
895 fn an_empty_data_directory_still_restores_as_a_directory() {
896 let root = tempfile::tempdir().expect("tempdir");
897 let data = root.path().join("repos");
898 fs::create_dir_all(&data).expect("mkdir");
899
900 let plan = plan(root.path(), &data);
901 pack(&plan).expect("should pack");
902
903 let into = root.path().join("restored");
904 unpack(&RestorePlan {
905 archive: plan.destination.clone(),
906 database: into.join("steid.db"),
907 data_dir: into.join("repos"),
908 existing: ExistingData::Refuse,
909 })
910 .expect("should unpack");
911
912 assert!(into.join("repos").is_dir());
913 }
914
915 #[test]
916 fn no_entry_names_a_path_outside_the_data_directory() {
917 let root = tempfile::tempdir().expect("tempdir");
918 let data = fixture(root.path());
919
920 // A secret next door, and a symlink from inside the data directory to it: the
921 // one way a walk could pull a path in from outside.
922 let secret = root.path().join("secret.txt");
923 fs::write(&secret, b"not yours").expect("write");
924 std::os::unix::fs::symlink(&secret, data.join("james/escape")).expect("symlink");
925 // And the backup's own scratch directory, which sits inside the data directory
926 // and must not end up inside the archive being built in it.
927 fs::create_dir_all(data.join(".backup/whatever")).expect("mkdir");
928 fs::write(data.join(".backup/whatever/big.db"), b"scratch").expect("write");
929
930 let plan = plan(root.path(), &data);
931 pack(&plan).expect("should pack");
932
933 let names = entry_names(&plan.destination);
934
935 for name in &names {
936 let path = Path::new(name);
937 assert!(
938 safe(path).is_some(),
939 "{name} is not a path a restore would accept"
940 );
941 assert!(
942 name == BACKUP_MANIFEST
943 || name == BACKUP_DATABASE
944 || name.starts_with(&format!("{BACKUP_DATA_PREFIX}/")),
945 "{name} is outside the archive's three destinations"
946 );
947 }
948
949 assert!(
950 !names.iter().any(|name| name.contains("escape")),
951 "the symlink was archived: {names:?}"
952 );
953 assert!(
954 !names.iter().any(|name| name.contains(".backup")),
955 "the scratch directory was archived: {names:?}"
956 );
957 }
958
959 #[test]
960 fn a_restore_refuses_an_entry_that_climbs_out() {
961 assert!(safe(Path::new("data/james/steid.git/HEAD")).is_some());
962 assert!(safe(Path::new("../etc/passwd")).is_none());
963 assert!(safe(Path::new("data/../../etc/passwd")).is_none());
964 assert!(safe(Path::new("/etc/passwd")).is_none());
965 assert!(safe(Path::new("")).is_none());
966 }
967
968 #[test]
969 fn a_restore_refuses_to_overwrite_what_is_already_there() {
970 let root = tempfile::tempdir().expect("tempdir");
971 let data = fixture(root.path());
972 let plan = plan(root.path(), &data);
973 pack(&plan).expect("should pack");
974
975 let into = root.path().join("restored");
976 fs::create_dir_all(into.join("repos/james/steid.git")).expect("mkdir");
977 fs::write(into.join("repos/james/steid.git/HEAD"), b"mine\n").expect("write");
978
979 let refused = unpack(&RestorePlan {
980 archive: plan.destination.clone(),
981 database: into.join("steid.db"),
982 data_dir: into.join("repos"),
983 existing: ExistingData::Refuse,
984 });
985
986 assert!(
987 matches!(refused, Err(BackupError::Refused(_))),
988 "{refused:?}"
989 );
990 assert_eq!(
991 fs::read_to_string(into.join("repos/james/steid.git/HEAD")).expect("read"),
992 "mine\n",
993 "the existing file was left alone"
994 );
995 }
996
997 #[test]
998 fn something_that_is_not_a_backup_is_said_to_be_one() {
999 let root = tempfile::tempdir().expect("tempdir");
1000 let not = root.path().join("holiday.tar.gz");
1001 fs::write(&not, b"not a gzip at all").expect("write");
1002
1003 assert!(matches!(
1004 read_manifest(&not),
1005 Err(BackupError::Malformed(_) | BackupError::Backend(_))
1006 ));
1007 }
1008
1009 #[test]
1010 fn packing_refuses_to_overwrite_an_existing_archive() {
1011 let root = tempfile::tempdir().expect("tempdir");
1012 let data = fixture(root.path());
1013 let plan = plan(root.path(), &data);
1014 fs::write(&plan.destination, b"someone else's").expect("write");
1015
1016 assert!(matches!(pack(&plan), Err(BackupError::Refused(_))));
1017 }
1018
1019 /// Every entry name in an archive, in order.
1020 fn entry_names(archive: &Path) -> Vec<String> {
1021 open(archive)
1022 .expect("open")
1023 .entries()
1024 .expect("entries")
1025 .map(|entry| {
1026 entry
1027 .expect("entry")
1028 .path()
1029 .expect("path")
1030 .to_string_lossy()
1031 .into_owned()
1032 })
1033 .collect()
1034 }
1035}