use crate::crypto::{content_id, pack_path, VaultKey}; use crate::index::ChunkIndex; use anyhow::{anyhow, Context, Result}; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use std::fs; use std::path::{Path, PathBuf}; use tessera_core::decay::{evaluate_decay, DecayPolicy, 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, } pub struct Vault { root: PathBuf, key: VaultKey, index: ChunkIndex, } impl Vault { pub fn init(root: impl AsRef, passphrase: &str) -> Result { 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"))?; 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 { 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"); } let salt = root.join("keys/tessera.salt"); let key = VaultKey::derive_from_passphrase(passphrase, &salt)?; let index = Self::load_index(&root)?; Ok(Self { root, key, index, }) } 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(), }); } 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, }; let path = self .root .join("snapshots") .join(format!("{}.json", snap.id)); fs::write(&path, serde_json::to_string_pretty(&snap)?)?; Ok(snap) } 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(); if path.extension().and_then(|e| e.to_str()) != Some("json") { continue; } let data = fs::read_to_string(&path)?; let snap: StoredSnapshot = serde_json::from_str(&data)?; out.push(snap); } out.sort_by(|a, b| b.taken_at.cmp(&a.taken_at)); Ok(out) } pub fn restore_snapshot(&self, id: Uuid, dest: &Path) -> Result { let path = self.root.join("snapshots").join(format!("{id}.json")); let data = fs::read_to_string(&path).context("snapshot metadata")?; let snap: StoredSnapshot = serde_json::from_str(&data)?; let bytes = self.read_chunk(&snap.tree_root)?; if let Some(parent) = dest.parent() { fs::create_dir_all(parent)?; } fs::write(dest, &bytes)?; Ok(bytes.len() as u64) } pub fn forget(&mut self, ids: &[Uuid]) -> Result { let mut removed = 0; for id in ids { let path = self.root.join("snapshots").join(format!("{id}.json")); if path.exists() { fs::remove_file(&path)?; removed += 1; } } Ok(removed) } pub fn prune_with_decay(&mut self, preset: &str) -> Result> { let policy = DecayPolicy::from_preset(preset); let snaps = self.list_snapshots()?; let refs: Vec = snaps .iter() .map(|s| SnapshotRef { id: s.id, taken_at: s.taken_at, }) .collect(); let to_forget = evaluate_decay(&policy, refs); self.forget(&to_forget)?; Ok(to_forget) } pub fn root(&self) -> &Path { &self.root } } #[cfg(test)] mod tests { use super::*; use tempfile::tempdir; use tessera_core::manifest::SnapshotManifest; #[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()); } }