use crate::crypto::{content_id, pack_path, VaultKey}; use crate::index::ChunkIndex; use crate::restic::{self, Repository}; use anyhow::{anyhow, Context, Result}; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use std::fs::{self, File}; use std::io::{Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use tessera_core::decay::{ evaluate_decay, evaluate_gfs, DecayPolicy, RetentionPolicy, SnapshotRef, }; use tessera_core::manifest::SnapshotManifest; use uuid::Uuid; const RESTIC_CONFIG: &str = "{\n \"version\": 2,\n \"id\": \"tessera-restic-layout-v1\",\n \"tessera\": true\n}\n"; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct StoredSnapshot { pub id: Uuid, pub taken_at: DateTime, pub manifest: SnapshotManifest, pub size_bytes: u64, pub tree_root: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub stored_bytes: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub new_data_chunks: Option, } pub struct Vault { root: PathBuf, key: VaultKey, index: ChunkIndex, restic: Repository, } #[derive(Deserialize)] struct OutpostRepository { outpost_id: Uuid, password: String, } impl Vault { pub fn init(root: impl AsRef, passphrase: &str) -> Result { if passphrase == "dev-vault-key" { anyhow::bail!( "refusing to initialize a vault with the published dev passphrase; choose a private passphrase" ); } let root = root.as_ref().to_path_buf(); fs::create_dir_all(root.join("data"))?; fs::create_dir_all(root.join("snapshots"))?; fs::create_dir_all(root.join("index"))?; fs::create_dir_all(root.join("keys"))?; restrict_dir(&root.join("keys"))?; let config_path = root.join("config"); if !config_path.exists() { fs::write(&config_path, RESTIC_CONFIG)?; } let salt = root.join("keys/tessera.salt"); let key = VaultKey::derive_from_passphrase(passphrase, &salt)?; let index = ChunkIndex::default(); let v = Self { restic: Self::repository(&root, passphrase)?, root, key, index, }; v.save_index()?; Ok(v) } pub fn open(root: impl AsRef, passphrase: &str) -> Result { let root = root.as_ref().to_path_buf(); if !root.join("config").exists() { anyhow::bail!("vault not initialized"); } restrict_dir(&root.join("keys"))?; let salt = root.join("keys/tessera.salt"); let key = VaultKey::derive_from_passphrase(passphrase, &salt)?; let index = Self::load_index(&root)?; Ok(Self { restic: Self::repository(&root, passphrase)?, root, key, index, }) } fn repository(root: &Path, password: &str) -> Result { Ok(Repository { path: root.canonicalize()?.join("restic"), password: password.into(), }) } fn outpost_config_path(&self, orbit_id: Uuid) -> PathBuf { self.root .join("keys") .join(format!("outpost-{orbit_id}.json")) } pub fn outpost_repository_configured(&self, orbit_id: Uuid) -> Result { Ok(self.outpost_config_path(orbit_id).try_exists()?) } fn outpost_config(&self, orbit_id: Uuid) -> Result { Ok(serde_json::from_slice( &fs::read(self.outpost_config_path(orbit_id)) .context("outpost repository is not configured")?, )?) } fn outpost_repository(&self, orbit_id: Uuid, config: OutpostRepository) -> Repository { Repository { path: self .restic .path .with_file_name("outposts") .join(orbit_id.to_string()), password: config.password, } } pub fn register_outpost_snapshot( &mut self, mut manifest: SnapshotManifest, outpost_id: Uuid, restic_id: &str, ) -> Result> { restic::validate_id(restic_id)?; if !self.outpost_repository_configured(manifest.orbit_id)? { return Ok(None); } let config = self.outpost_config(manifest.orbit_id)?; if config.outpost_id != outpost_id { return Ok(None); } let id = Uuid::new_v5(&manifest.orbit_id, restic_id.as_bytes()); let dir = self.root.join("snapshots"); if dir.join(format!("{id}.json.enc")).try_exists()? || dir.join(format!("{id}.expired")).try_exists()? { return Ok(Some((id, false))); } let repo = self.outpost_repository(manifest.orbit_id, config); let summary = repo.snapshot_summary(restic_id, None, None)?; manifest.snapshot_id = id; manifest.restore_hints = serde_json::json!({ "format": "tar" }); self.write_snapshot( &StoredSnapshot { id, taken_at: Utc::now(), manifest, size_bytes: summary.total_bytes_processed, tree_root: format!("{}{restic_id}", restic::OUTPOST_PREFIX), stored_bytes: Some(summary.data_added_packed), new_data_chunks: Some(summary.data_blobs), }, false, )?; Ok(Some((id, true))) } pub fn prepare_outpost_capture( &self, manifest: SnapshotManifest, outpost_id: Uuid, restic_id: &str, ) -> Result { let config = self.outpost_config(manifest.orbit_id)?; anyhow::ensure!( config.outpost_id == outpost_id, "repository belongs to another outpost" ); let repo = self.outpost_repository(manifest.orbit_id, config); let id = manifest.snapshot_id; let expected_path = (manifest.provider != "filesystem").then_some(restic::PAYLOAD); let summary = repo.snapshot_summary(restic_id, Some(&restic::tessera_tag(id)), expected_path)?; Ok(StoredSnapshot { id, taken_at: Utc::now(), manifest, size_bytes: summary.total_bytes_processed, tree_root: format!("{}{restic_id}", restic::OUTPOST_PREFIX), stored_bytes: Some(summary.data_added_packed), new_data_chunks: Some(summary.data_blobs), }) } pub fn snapshot_files( &self, mut manifest: SnapshotManifest, max_file_bytes: Option, dry_run: bool, ) -> Result { let vault = self.root.canonicalize()?; anyhow::ensure!(!manifest.paths.is_empty(), "no filesystem paths to back up"); let paths = manifest .paths .iter() .map(|name| { let path = Path::new(name); let canonical = path .canonicalize() .with_context(|| format!("backup source {name}"))?; anyhow::ensure!( !canonical.starts_with(&vault), "backup source is inside the Tessera vault" ); if let Some(max) = max_file_bytes { let metadata = fs::metadata(path)?; anyhow::ensure!( !metadata.is_file() || metadata.len() <= max, "file exceeds max_file_bytes: {name}" ); } // Preserve a final symlink, while resolving aliases in its parent for vault exclusion. let path = if fs::symlink_metadata(path)?.is_symlink() { path.parent() .filter(|p| !p.as_os_str().is_empty()) .unwrap_or(Path::new(".")) .canonicalize()? .join(path.file_name().context("symlink name")?) } else { canonical }; Ok(path) }) .collect::>>()?; manifest.restore_hints = serde_json::json!({ "format": "tar" }); let exclude = restic::literal_pattern(&vault)?; self.restic_snapshot(manifest, dry_run, |cmd| { cmd.args(["--exclude", &exclude]); if let Some(max) = max_file_bytes { cmd.arg("--exclude-larger-than").arg(max.to_string()); } cmd.arg("--").args(paths); }) } pub fn snapshot_payload( &self, manifest: SnapshotManifest, payload: File, dry_run: bool, ) -> Result { let snap = self.prepare_payload(manifest, payload, dry_run)?; if !dry_run { self.publish_prepared(&snap)?; } Ok(snap) } pub fn prepare_payload( &self, manifest: SnapshotManifest, mut payload: File, dry_run: bool, ) -> Result { if payload.metadata()?.len() == 0 { // Restic rejects empty stdin. A relative filename keeps the same restore path. let temp = tempfile::tempdir()?; File::create(temp.path().join("payload"))?; return self.prepare_restic_snapshot(manifest, dry_run, |cmd| { cmd.current_dir(temp.path()) .args(["--force", "--", "payload"]); }); } payload.seek(SeekFrom::Start(0))?; self.prepare_restic_snapshot(manifest, dry_run, |cmd| { cmd.args(["--stdin", "--stdin-filename", restic::PAYLOAD]) .stdin(Stdio::from(payload)); }) } fn restic_snapshot( &self, manifest: SnapshotManifest, dry_run: bool, source: impl FnOnce(&mut Command), ) -> Result { let snap = self.prepare_restic_snapshot(manifest, dry_run, source)?; if !dry_run { self.publish_prepared(&snap)?; } Ok(snap) } fn prepare_restic_snapshot( &self, manifest: SnapshotManifest, dry_run: bool, source: impl FnOnce(&mut Command), ) -> Result { let taken_at = Utc::now(); let temp; let rehearsal; let repo = if dry_run && !self.restic.path.join("config").try_exists()? { temp = tempfile::tempdir()?; rehearsal = Repository { path: temp.path().join("repo"), password: self.restic.password.clone(), }; &rehearsal } else { &self.restic }; repo.init() .context("opening the deduplicated vault (restic must be on PATH)")?; let mut cmd = repo.command(); cmd.args([ "backup", "--json", "--quiet", "--tag", &restic::tessera_tag(manifest.snapshot_id), ]); if dry_run { cmd.arg("--dry-run"); } source(&mut cmd); let summary = repo.backup(cmd)?; let tree_root = if dry_run { "dry-run".into() } else { let id = summary .snapshot_id .as_deref() .context("restic did not commit a snapshot")?; restic::validate_id(id)?; format!("{}{id}", restic::PREFIX) }; let snap = StoredSnapshot { id: manifest.snapshot_id, taken_at, manifest, size_bytes: summary.total_bytes_processed, tree_root, stored_bytes: Some(summary.data_added_packed), new_data_chunks: Some(summary.data_blobs), }; Ok(snap) } pub fn import_legacy_payload( &self, manifest: SnapshotManifest, payload: File, taken_at: chrono::DateTime, ) -> Result { let id = manifest.snapshot_id; let receipts = self.root.join("keys/legacy-imports"); fs::create_dir_all(&receipts)?; restrict_dir(&receipts)?; let receipt = receipts.join(id.to_string()); if receipt.try_exists()? { return Ok(false); } let snapshots = self.root.join("snapshots"); let already_imported = || -> Result { Ok(self.has_published_snapshot(id)? || snapshots.join(format!("{id}.expired")).try_exists()?) }; let imported = if already_imported()? { false } else { let mut prepared = self.prepare_payload(manifest, payload, false)?; prepared.taken_at = taken_at; match self.publish_prepared(&prepared) { Ok(()) => true, Err(_) if already_imported()? => { self.discard_prepared(&prepared)?; false } Err(error) => return Err(error), } }; let marker = tempfile::NamedTempFile::new_in(&receipts)?; marker.as_file().sync_all()?; match marker.persist_noclobber(&receipt) { Ok(_) => sync_directory(&receipts)?, Err(error) if error.error.kind() == std::io::ErrorKind::AlreadyExists => (), Err(error) => return Err(error.into()), } Ok(imported) } pub fn legacy_import_exists(&self, id: Uuid) -> Result { Ok(self .root .join("keys/legacy-imports") .join(id.to_string()) .try_exists()?) } pub fn verify_prepared_payload( &self, snap: &StoredSnapshot, expected: &[u8; 32], ) -> Result<()> { use sha2::{Digest, Sha256}; let id = snap .tree_root .strip_prefix(restic::PREFIX) .context("prepared payload is missing")?; let mut file = tempfile::tempfile()?; self.restic.dump(id, restic::PAYLOAD, file.try_clone()?)?; file.seek(SeekFrom::Start(0))?; let mut digest = Sha256::new(); std::io::copy(&mut file, &mut digest)?; anyhow::ensure!( digest.finalize()[..] == expected[..], "stored payload checksum mismatch" ); Ok(()) } pub fn publish_prepared(&self, snap: &StoredSnapshot) -> Result<()> { self.write_snapshot(snap, false) } pub fn discard_prepared(&self, snap: &StoredSnapshot) -> Result<()> { if let Some(id) = snap.tree_root.strip_prefix(restic::PREFIX) { self.restic.forget(&[id.to_owned()])?; } Ok(()) } pub fn has_published_snapshot(&self, id: Uuid) -> Result { Ok(self .root .join("snapshots") .join(format!("{id}.json.enc")) .try_exists()?) } fn index_path(&self) -> PathBuf { self.root.join("index/tessera-main.json") } fn load_index(root: &Path) -> Result { let p = root.join("index/tessera-main.json"); if !p.exists() { return Ok(ChunkIndex::default()); } let data = fs::read_to_string(&p)?; Ok(serde_json::from_str(&data)?) } fn save_index(&self) -> Result<()> { let data = serde_json::to_string_pretty(&self.index)?; fs::write(self.index_path(), data)?; Ok(()) } fn store_chunk(&mut self, plain: &[u8]) -> Result { let id = content_id(plain); if self.index.chunks.contains_key(&id) { return Ok(id); } let enc = self.key.encrypt(plain)?; let pack_id = content_id(&enc); let path = pack_path(&self.root.join("data"), &pack_id); if let Some(parent) = path.parent() { fs::create_dir_all(parent)?; } fs::write(&path, &enc)?; self.index.record(id.clone(), pack_id, 0, enc.len() as u64); Ok(id) } fn read_chunk(&self, id: &str) -> Result> { let entry = self .index .chunks .get(id) .ok_or_else(|| anyhow!("unknown chunk {id}"))?; let path = pack_path(&self.root.join("data"), &entry.pack_id); let enc = fs::read(&path)?; self.key.decrypt(&enc) } pub fn snapshot( &mut self, manifest: SnapshotManifest, payload: &[u8], dry_run: bool, ) -> Result { self.snapshot_at(manifest, payload, dry_run, Utc::now()) } /// Like `snapshot`, but allows a custom timestamp (demo/historical imports). pub fn snapshot_at( &mut self, manifest: SnapshotManifest, payload: &[u8], dry_run: bool, taken_at: DateTime, ) -> Result { if dry_run { return Ok(StoredSnapshot { id: manifest.snapshot_id, taken_at, manifest, size_bytes: payload.len() as u64, tree_root: "dry-run".into(), stored_bytes: None, new_data_chunks: None, }); } let chunk_id = self.store_chunk(payload)?; self.save_index()?; let snap = StoredSnapshot { id: manifest.snapshot_id, taken_at, manifest, size_bytes: payload.len() as u64, tree_root: chunk_id, stored_bytes: None, new_data_chunks: None, }; self.write_snapshot(&snap, true)?; Ok(snap) } fn write_snapshot(&self, snap: &StoredSnapshot, overwrite: bool) -> Result<()> { let plain = serde_json::to_vec(&snap)?; let enc = self.key.encrypt(&plain)?; let dir = self.root.join("snapshots"); let path = dir.join(format!("{}.json.enc", snap.id)); let mut temp = tempfile::NamedTempFile::new_in(&dir)?; temp.write_all(&enc)?; temp.as_file().sync_all()?; if overwrite { temp.persist(path)?; } else { temp.persist_noclobber(path)?; } sync_directory(&dir) } fn read_snapshot_file(&self, path: &Path) -> Result { let name = path.file_name().and_then(|s| s.to_str()).unwrap_or(""); if name.ends_with(".json.enc") || name.ends_with(".expired") { let plain = self.key.decrypt(&fs::read(path)?)?; Ok(serde_json::from_slice(&plain)?) } else if name.ends_with(".json") { let snap: StoredSnapshot = serde_json::from_str(&fs::read_to_string(path)?)?; anyhow::ensure!( !snap.tree_root.starts_with(restic::PREFIX) && !snap.tree_root.starts_with(restic::OUTPOST_PREFIX), "restic snapshot metadata must be encrypted" ); Ok(snap) } else { anyhow::bail!("not a snapshot file"); } } pub fn list_snapshots(&self) -> Result> { let dir = self.root.join("snapshots"); if !dir.exists() { return Ok(vec![]); } let mut out = Vec::new(); for entry in fs::read_dir(&dir)? { let path = entry?.path(); let name = path.file_name().and_then(|s| s.to_str()).unwrap_or(""); if !(name.ends_with(".json") || name.ends_with(".json.enc")) { continue; } out.push(self.read_snapshot_file(&path)?); } out.sort_by(|a, b| b.taken_at.cmp(&a.taken_at)); Ok(out) } pub fn prepare_offsite_copy(&self, id: Uuid) -> Result { let snapshot = self.read_snapshot_file(&self.root.join("snapshots").join(format!("{id}.json.enc")))?; anyhow::ensure!( snapshot.manifest.restore_hints.get("job_id").is_some(), "snapshot is not a capture job" ); let (source, restic_id) = if let Some(id) = snapshot.tree_root.strip_prefix(restic::OUTPOST_PREFIX) { let orbit = snapshot.manifest.orbit_id; ( self.outpost_repository(orbit, self.outpost_config(orbit)?), id, ) } else { ( self.restic.clone(), snapshot .tree_root .strip_prefix(restic::PREFIX) .context("capture Restic snapshot missing")?, ) }; Ok(crate::OffsiteCopy { snapshot: id, source, restic_id: restic_id.to_owned(), }) } pub fn get_snapshot(&self, id: Uuid) -> Result> { for suffix in [".json.enc", ".json"] { let path = self.root.join("snapshots").join(format!("{id}{suffix}")); if path.try_exists()? { return self.read_snapshot_file(&path).map(Some); } } Ok(None) } pub fn restore_snapshot(&self, id: Uuid, dest: &Path) -> Result { let snap = self .get_snapshot(id)? .context("snapshot metadata not found")?; let parent = dest .parent() .filter(|p| !p.as_os_str().is_empty()) .unwrap_or(Path::new(".")); fs::create_dir_all(parent)?; let mut temp = tempfile::NamedTempFile::new_in(parent)?; if let Some(id) = snap.tree_root.strip_prefix(restic::OUTPOST_PREFIX) { let orbit_id = snap.manifest.orbit_id; let path = if snap.manifest.restore_hints["format"] == "tar" { "/" } else { restic::PAYLOAD }; self.outpost_repository(orbit_id, self.outpost_config(orbit_id)?) .dump(id, path, temp.reopen()?)?; } else if let Some(id) = snap.tree_root.strip_prefix(restic::PREFIX) { let path = if snap.manifest.provider == "filesystem" { "/" } else { restic::PAYLOAD }; self.restic.dump(id, path, temp.reopen()?)?; } else { temp.write_all(&self.read_chunk(&snap.tree_root)?)?; } let len = temp.as_file().metadata()?.len(); temp.as_file().sync_all()?; temp.persist(dest)?; Ok(len) } pub fn forget(&mut self, ids: &[Uuid]) -> Result { let mut removed = 0; for id in ids { let mut gone = false; for suffix in [".json.enc", ".json"] { let path = self.root.join("snapshots").join(format!("{id}{suffix}")); if path.exists() { let snap = self.read_snapshot_file(&path)?; if snap.tree_root.starts_with(restic::PREFIX) || snap.tree_root.starts_with(restic::OUTPOST_PREFIX) { fs::rename(&path, path.with_file_name(format!("{id}.expired")))?; } else { fs::remove_file(&path)?; } gone = true; } } if gone { removed += 1; } } Ok(removed) } pub fn collect_garbage(&mut self) -> Result<()> { let dir = self.root.join("snapshots"); let mut expired = std::collections::HashMap::, Vec<(String, PathBuf)>>::new(); for entry in fs::read_dir(&dir)? { let path = entry?.path(); if path.extension().is_some_and(|ext| ext == "expired") { let snap = self.read_snapshot_file(&path)?; let (orbit, id) = if let Some(id) = snap.tree_root.strip_prefix(restic::OUTPOST_PREFIX) { (Some(snap.manifest.orbit_id), id) } else { ( None, snap.tree_root .strip_prefix(restic::PREFIX) .context("invalid expired snapshot")?, ) }; restic::validate_id(id)?; expired .entry(orbit) .or_default() .push((id.to_owned(), path)); } } // The expiry must survive a crash before its backing snapshot can be removed. sync_directory(&dir)?; expired.entry(None).or_default(); for (orbit, snapshots) in expired { let outpost; let repo = if let Some(orbit_id) = orbit { outpost = self.outpost_repository(orbit_id, self.outpost_config(orbit_id)?); &outpost } else { &self.restic }; repo.prune( &snapshots .iter() .map(|(id, _)| id.clone()) .collect::>(), )?; for (_, path) in snapshots { match fs::remove_file(path) { Ok(()) => (), Err(error) if error.kind() == std::io::ErrorKind::NotFound => (), Err(error) => return Err(error.into()), } } } Ok(()) } pub fn prune_with_decay(&mut self, preset: &str) -> Result> { let snaps = self.list_snapshots()?; self.prune_snapshots( preset, None, snaps.into_iter().filter(|snapshot| { snapshot.manifest.provider != "legacy-history" && snapshot.manifest.restore_hints.get("job_id").is_none() && !snapshot.manifest.is_restore_safety() }), ) } pub fn prune_orbit_with_decay( &mut self, orbit_id: Uuid, preset: &str, retention: Option<&RetentionPolicy>, ) -> Result> { let snaps = self.list_snapshots()?; self.prune_snapshots( preset, retention, snaps .into_iter() .filter(|s| s.manifest.orbit_id == orbit_id && !s.manifest.is_restore_safety()), ) } fn prune_snapshots( &mut self, preset: &str, retention: Option<&RetentionPolicy>, snapshots: impl Iterator, ) -> Result> { let refs = snapshots .map(|s| SnapshotRef { id: s.id, taken_at: s.taken_at, }) .collect(); let to_forget = match retention { Some(policy) => evaluate_gfs(policy, refs), None => evaluate_decay(&DecayPolicy::from_preset(preset), refs), }; self.forget(&to_forget)?; Ok(to_forget) } pub fn root(&self) -> &Path { &self.root } } fn sync_directory(path: &Path) -> Result<()> { #[cfg(unix)] File::open(path)?.sync_all()?; #[cfg(not(unix))] let _ = path; Ok(()) } fn restrict_dir(path: &Path) -> Result<()> { #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; if path.exists() { fs::set_permissions(path, fs::Permissions::from_mode(0o700))?; } } #[cfg(not(unix))] let _ = path; Ok(()) } #[cfg(test)] mod tests { use super::*; use tempfile::tempdir; use tessera_core::manifest::SnapshotManifest; #[test] #[ignore = "requires restic on PATH"] fn changed_files_reuse_chunks_and_restore_after_prune() { use rand::{RngCore, SeedableRng}; let dir = tempdir().unwrap(); let source = dir.path().join("source"); fs::create_dir(&source).unwrap(); let mut bytes = vec![0; 24 * 1024 * 1024]; rand::rngs::StdRng::seed_from_u64(7).fill_bytes(&mut bytes); let file = source.join("large.bin"); fs::write(&file, &bytes).unwrap(); let mut vault = Vault::init(dir.path().join("vault"), "secret").unwrap(); let manifest = SnapshotManifest { snapshot_id: Uuid::new_v4(), orbit_id: Uuid::new_v4(), orbit_name: "files".into(), labels: vec![], provider: "filesystem".into(), paths: vec![source.to_str().unwrap().into()], restore_hints: serde_json::json!({}), }; let first = vault.snapshot_files(manifest.clone(), None, false).unwrap(); let mut manifest = manifest; manifest.snapshot_id = Uuid::new_v4(); let identical = vault.snapshot_files(manifest.clone(), None, false).unwrap(); assert_eq!(identical.new_data_chunks, Some(0)); bytes.splice(100..100, [1; 1024]); fs::write(&file, &bytes).unwrap(); fs::write(source.join("added.txt"), b"new file").unwrap(); manifest.snapshot_id = Uuid::new_v4(); let changed = vault.snapshot_files(manifest.clone(), None, false).unwrap(); assert!(changed.stored_bytes.unwrap() < first.stored_bytes.unwrap() / 2); vault.forget(&[first.id, identical.id]).unwrap(); vault.collect_garbage().unwrap(); assert_eq!(vault.list_snapshots().unwrap().len(), 1); let output = dir.path().join("restore.tar"); vault.restore_snapshot(changed.id, &output).unwrap(); let extracted = dir.path().join("extracted"); fs::create_dir(&extracted).unwrap(); assert!(std::process::Command::new("tar") .arg("-xf") .arg(output) .arg("-C") .arg(&extracted) .status() .unwrap() .success()); let restored = extracted.join(source.canonicalize().unwrap().strip_prefix("/").unwrap()); assert_eq!(fs::read(restored.join("large.bin")).unwrap(), bytes); assert_eq!(fs::read(restored.join("added.txt")).unwrap(), b"new file"); manifest .paths .push(dir.path().join("missing").to_string_lossy().into()); manifest.snapshot_id = Uuid::new_v4(); assert!(vault.snapshot_files(manifest, None, false).is_err()); assert_eq!(vault.list_snapshots().unwrap().len(), 1); } #[test] fn init_snap_list_restore() { let dir = tempdir().unwrap(); let mut vault = Vault::init(dir.path(), "secret").unwrap(); let manifest = SnapshotManifest { snapshot_id: Uuid::new_v4(), orbit_id: Uuid::new_v4(), orbit_name: "test".into(), labels: vec![], provider: "filesystem".into(), paths: vec![], restore_hints: serde_json::json!({}), }; let snap = vault.snapshot(manifest, b"payload bytes", false).unwrap(); let list = vault.list_snapshots().unwrap(); assert_eq!(list.len(), 1); assert_eq!(list[0].id, snap.id); let out = dir.path().join("restored.bin"); let n = vault.restore_snapshot(snap.id, &out).unwrap(); assert_eq!(n, 13); assert_eq!(fs::read(&out).unwrap(), b"payload bytes"); } #[test] fn dry_run_writes_nothing() { let dir = tempdir().unwrap(); let mut vault = Vault::init(dir.path(), "secret").unwrap(); let manifest = SnapshotManifest { snapshot_id: Uuid::new_v4(), orbit_id: Uuid::new_v4(), orbit_name: "rehearse".into(), labels: vec![], provider: "filesystem".into(), paths: vec![], restore_hints: serde_json::json!({}), }; vault.snapshot(manifest, b"x", true).unwrap(); assert!(vault.list_snapshots().unwrap().is_empty()); } #[test] fn orbit_decay_keeps_other_orbits_recoverable() { let dir = tempdir().unwrap(); let mut vault = Vault::init(dir.path(), "secret").unwrap(); let orbit_id = Uuid::new_v4(); let other_id = Uuid::new_v4(); let now = DateTime::from_timestamp(1_730_000_000, 0).unwrap(); for (index, id) in [orbit_id, orbit_id, other_id].into_iter().enumerate() { let manifest = SnapshotManifest { snapshot_id: Uuid::new_v4(), orbit_id: id, orbit_name: "same name".into(), labels: vec![], provider: "filesystem".into(), paths: vec![], restore_hints: serde_json::json!({}), }; vault .snapshot_at( manifest, b"x", false, now - chrono::Duration::seconds(index as i64), ) .unwrap(); } let pruned = vault .prune_orbit_with_decay(orbit_id, "month-of-weeklies", None) .unwrap(); assert_eq!(pruned.len(), 1); assert!(vault .list_snapshots() .unwrap() .iter() .any(|s| s.manifest.orbit_id == other_id)); } #[test] fn new_snapshots_are_encrypted_and_legacy_json_still_reads() { let dir = tempdir().unwrap(); let mut vault = Vault::init(dir.path(), "secret").unwrap(); let legacy_id = Uuid::new_v4(); let legacy = StoredSnapshot { id: legacy_id, taken_at: DateTime::from_timestamp(1_700_000_000, 0).unwrap(), manifest: SnapshotManifest { snapshot_id: legacy_id, orbit_id: Uuid::new_v4(), orbit_name: "legacy".into(), labels: vec![], provider: "filesystem".into(), paths: vec![], restore_hints: serde_json::json!({}), }, size_bytes: 4, tree_root: "missing".into(), stored_bytes: None, new_data_chunks: None, }; fs::write( dir.path() .join("snapshots") .join(format!("{legacy_id}.json")), serde_json::to_string(&legacy).unwrap(), ) .unwrap(); let manifest = SnapshotManifest { snapshot_id: Uuid::new_v4(), orbit_id: Uuid::new_v4(), orbit_name: "new".into(), labels: vec![], provider: "filesystem".into(), paths: vec![], restore_hints: serde_json::json!({}), }; let snap = vault.snapshot(manifest, b"cipher", false).unwrap(); assert!(dir .path() .join("snapshots") .join(format!("{}.json.enc", snap.id)) .exists()); assert!(!dir .path() .join("snapshots") .join(format!("{}.json", snap.id)) .exists()); let names: Vec<_> = vault .list_snapshots() .unwrap() .into_iter() .map(|s| s.manifest.orbit_name) .collect(); assert!(names.contains(&"legacy".to_string())); assert!(names.contains(&"new".to_string())); let out = dir.path().join("restored.bin"); assert_eq!(vault.restore_snapshot(snap.id, &out).unwrap(), 6); } #[test] fn init_rejects_published_dev_passphrase() { let dir = tempdir().unwrap(); assert!(Vault::init(dir.path(), "dev-vault-key").is_err()); assert!(Vault::init(dir.path(), "").is_err()); } }