feat: use Restic for encrypted incremental backups

Keep legacy restores readable while using Restic for new captures, scoped Wormhole repositories, and chunk garbage collection.
This commit is contained in:
2026-11-10 10:48:05 +07:00
parent 95778d54e4
commit 749c4cc828
15 changed files with 955 additions and 119 deletions

View File

@@ -20,5 +20,5 @@ tempfile.workspace = true
thiserror.workspace = true
tokio = { workspace = true, features = ["fs", "io-util"] }
tracing.workspace = true
uuid.workspace = true
uuid = { workspace = true, features = ["v5"] }
walkdir.workspace = true

View File

@@ -1,17 +1,14 @@
//! Restic-compatible path layout vault engine.
//! Encrypted snapshot metadata and Restic-backed storage for new captures.
//!
//! Layout under vault root:
//! - `config` — repository version marker (restic-compatible sentinel)
//! - `data/` — content-addressed encrypted packs (`{prefix}/{id}`)
//! - `snapshots/` — JSON snapshot metadata
//! - `index/` — chunk index shards
//! - `keys/` — key material (local key file)
//!
//! Full `rustic_core` integration is deferred until toolchain meets its MSRV;
//! emergency verify may use external `rustic`/`restic` where formats align.
//! - `restic/` and `outposts/` — Restic repositories
//! - `snapshots/` — Tessera snapshot metadata
//! - `keys/` — vault key derivation and outpost configuration
//! - `config`, `data/`, `index/` — legacy Tessera storage
mod crypto;
mod index;
mod restic;
mod vault;
pub use vault::*;

View File

@@ -0,0 +1,178 @@
use anyhow::{ensure, Context, Result};
use serde::Deserialize;
use std::fs::{self, File};
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
pub(crate) const PREFIX: &str = "restic:";
pub(crate) const OUTPOST_PREFIX: &str = "restic-outpost:";
pub(crate) const PAYLOAD: &str = "/payload";
pub(crate) struct Repository {
pub path: PathBuf,
pub password: String,
}
#[derive(Deserialize)]
pub(crate) struct Summary {
pub snapshot_id: Option<String>,
pub total_bytes_processed: u64,
pub data_added_packed: u64,
pub data_blobs: u64,
}
#[derive(Deserialize)]
struct Snapshot {
id: String,
summary: Option<Summary>,
}
impl Repository {
pub fn command(&self) -> Command {
self.command_at(&self.path)
}
fn command_at(&self, path: &Path) -> Command {
let mut cmd = Command::new("restic");
cmd.arg("--repo")
.arg(path)
.arg("--no-cache")
.env("RESTIC_PASSWORD", &self.password)
.env_remove("RESTIC_PASSWORD_FILE")
.env_remove("RESTIC_PASSWORD_COMMAND")
.env_remove("RESTIC_REPOSITORY_FILE")
.env_remove("RESTIC_KEY_HINT")
.env_remove("RESTIC_CACERT")
.env_remove("RESTIC_TLS_CLIENT_CERT")
.stdin(Stdio::null());
cmd
}
pub fn init(&self) -> Result<()> {
if self.path.join("config").try_exists()? {
return Ok(());
}
let temp = tempfile::tempdir_in(self.path.parent().context("repository parent")?)?;
checked(
self.command_at(temp.path())
.arg("init")
.output()
.context("starting restic init")?,
"init",
)?;
match fs::rename(temp.path(), &self.path) {
Ok(()) => Ok(()),
Err(_) if self.path.join("config").try_exists()? => Ok(()),
Err(err) => Err(err).context("publishing the restic repository"),
}
}
pub fn backup(&self, mut cmd: Command) -> Result<Summary> {
let output = cmd
.output()
.context("starting restic backup (install restic on PATH)")?;
let summary = std::str::from_utf8(&output.stdout)?
.lines()
.last()
.and_then(|line| serde_json::from_str::<Summary>(line).ok());
if !output.status.success() {
// Restic can commit an incomplete snapshot on exit 3. Tessera never publishes it.
if let Some(id) = summary.as_ref().and_then(|s| s.snapshot_id.as_deref()) {
if let Err(error) = self.forget(&[id.to_owned()]) {
tracing::warn!(%error, "could not remove incomplete restic snapshot");
}
}
}
checked(output, "backup")?;
summary.context("restic did not report a backup summary")
}
pub fn dump(&self, id: &str, path: &str, file: File) -> Result<()> {
validate_id(id)?;
let output = self
.command()
.args(["dump", id, path])
.stdout(file)
.output()?;
checked(output, "dump")?;
Ok(())
}
pub fn forget(&self, ids: &[String]) -> Result<()> {
if ids.is_empty() {
return Ok(());
}
for id in ids {
validate_id(id)?;
}
checked(self.command().arg("forget").args(ids).output()?, "forget")?;
Ok(())
}
pub fn snapshot_summary(&self, id: &str) -> Result<Summary> {
validate_id(id)?;
let output = checked(
self.command().args(["snapshots", "--json", id]).output()?,
"snapshots",
)?;
let snapshots: Vec<Snapshot> = serde_json::from_slice(&output.stdout)?;
snapshots
.into_iter()
.find(|snap| snap.id == id)
.and_then(|snap| snap.summary)
.context("outpost snapshot or backup summary is missing")
}
pub fn prune(&self, expired: &[String]) -> Result<()> {
if !self.path.exists() {
ensure!(expired.is_empty(), "restic repository is missing");
return Ok(());
}
let output = checked(
self.command().args(["snapshots", "--json"]).output()?,
"snapshots",
)?;
let snapshots: Vec<Snapshot> = serde_json::from_slice(&output.stdout)?;
let ids = snapshots
.into_iter()
.map(|snap| snap.id)
.collect::<std::collections::HashSet<_>>();
let existing: Vec<_> = expired
.iter()
.filter(|id| ids.contains(*id))
.cloned()
.collect();
self.forget(&existing)?;
checked(self.command().arg("prune").output()?, "prune")?;
Ok(())
}
}
pub(crate) fn validate_id(id: &str) -> Result<()> {
ensure!(
id.len() == 64 && id.bytes().all(|b| b.is_ascii_hexdigit()),
"invalid restic snapshot ID"
);
Ok(())
}
fn checked(output: Output, action: &str) -> Result<Output> {
ensure!(
output.status.success(),
"restic {action} failed ({}): {}",
output.status,
String::from_utf8_lossy(&output.stderr).trim()
);
Ok(output)
}
pub(crate) fn literal_pattern(path: &Path) -> Result<String> {
let mut pattern = String::new();
for c in path.to_str().context("vault path must be UTF-8")?.chars() {
if matches!(c, '\\' | '[' | ']' | '*' | '?') {
pattern.push('\\');
}
pattern.push(c);
}
Ok(pattern)
}

View File

@@ -1,10 +1,13 @@
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;
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, DecayPolicy, SnapshotRef};
use tessera_core::manifest::SnapshotManifest;
use uuid::Uuid;
@@ -18,12 +21,23 @@ pub struct StoredSnapshot {
pub manifest: SnapshotManifest,
pub size_bytes: u64,
pub tree_root: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub stored_bytes: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub new_data_chunks: Option<u64>,
}
pub struct Vault {
root: PathBuf,
key: VaultKey,
index: ChunkIndex,
restic: Repository,
}
#[derive(Deserialize)]
struct OutpostRepository {
outpost_id: Uuid,
password: String,
}
impl Vault {
@@ -49,6 +63,7 @@ impl Vault {
let key = VaultKey::derive_from_passphrase(passphrase, &salt)?;
let index = ChunkIndex::default();
let v = Self {
restic: Self::repository(&root, passphrase)?,
root,
key,
index,
@@ -67,12 +82,214 @@ impl Vault {
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<Repository> {
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<bool> {
Ok(self.outpost_config_path(orbit_id).try_exists()?)
}
fn outpost_config(&self, orbit_id: Uuid) -> Result<OutpostRepository> {
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<Option<Uuid>> {
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));
}
let repo = self.outpost_repository(manifest.orbit_id, config);
let summary = repo.snapshot_summary(restic_id)?;
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))
}
pub fn snapshot_files(
&self,
mut manifest: SnapshotManifest,
max_file_bytes: Option<u64>,
dry_run: bool,
) -> Result<StoredSnapshot> {
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::<Result<Vec<_>>>()?;
manifest.restore_hints = serde_json::json!({ "format": "tar" });
let exclude = restic::literal_pattern(&vault)?;
self.restic_snapshot(manifest, dry_run, |cmd| {
cmd.args(["--force", "--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,
mut payload: File,
dry_run: bool,
) -> Result<StoredSnapshot> {
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.restic_snapshot(manifest, dry_run, |cmd| {
cmd.current_dir(temp.path())
.args(["--force", "--", "payload"]);
});
}
payload.seek(SeekFrom::Start(0))?;
self.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<StoredSnapshot> {
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"]);
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),
};
if !dry_run {
self.write_snapshot(&snap, false)?;
}
Ok(snap)
}
fn index_path(&self) -> PathBuf {
self.root.join("index/tessera-main.json")
}
@@ -143,6 +360,8 @@ impl Vault {
manifest,
size_bytes: payload.len() as u64,
tree_root: "dry-run".into(),
stored_bytes: None,
new_data_chunks: None,
});
}
@@ -155,25 +374,42 @@ impl Vault {
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 path = self
.root
.join("snapshots")
.join(format!("{}.json.enc", snap.id));
fs::write(&path, &enc)?;
Ok(snap)
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<StoredSnapshot> {
let name = path.file_name().and_then(|s| s.to_str()).unwrap_or("");
if name.ends_with(".json.enc") {
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") {
Ok(serde_json::from_str(&fs::read_to_string(path)?)?)
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");
}
@@ -201,13 +437,33 @@ impl Vault {
let enc = self.root.join("snapshots").join(format!("{id}.json.enc"));
let plain = self.root.join("snapshots").join(format!("{id}.json"));
let path = if enc.exists() { enc } else { plain };
let snap = self.read_snapshot_file(&path).context("snapshot metadata")?;
let bytes = self.read_chunk(&snap.tree_root)?;
if let Some(parent) = dest.parent() {
fs::create_dir_all(parent)?;
let snap = self
.read_snapshot_file(&path)
.context("snapshot metadata")?;
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;
self.outpost_repository(orbit_id, self.outpost_config(orbit_id)?)
.dump(id, "/", 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)?)?;
}
fs::write(dest, &bytes)?;
Ok(bytes.len() as u64)
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<usize> {
@@ -217,7 +473,14 @@ impl Vault {
for suffix in [".json.enc", ".json"] {
let path = self.root.join("snapshots").join(format!("{id}{suffix}"));
if path.exists() {
fs::remove_file(&path)?;
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;
}
}
@@ -228,6 +491,59 @@ impl Vault {
Ok(removed)
}
pub fn collect_garbage(&mut self) -> Result<()> {
let dir = self.root.join("snapshots");
let mut expired = std::collections::HashMap::<Option<Uuid>, 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::<Vec<_>>(),
)?;
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<Vec<Uuid>> {
let snaps = self.list_snapshots()?;
self.prune_snapshots(preset, snaps.into_iter())
@@ -263,6 +579,14 @@ impl Vault {
}
}
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)]
{
@@ -282,6 +606,67 @@ mod tests {
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();
@@ -342,7 +727,12 @@ mod tests {
restore_hints: serde_json::json!({}),
};
vault
.snapshot_at(manifest, b"x", false, now - chrono::Duration::seconds(index as i64))
.snapshot_at(
manifest,
b"x",
false,
now - chrono::Duration::seconds(index as i64),
)
.unwrap();
}
let pruned = vault
@@ -375,6 +765,8 @@ mod tests {
},
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")),