Initial Tessera backup vault (M0–M2)

Scaffold Rust workspace, React canvas, vault engine, hub API,
providers, agent wormhole path, and Docker compose per SPEC.
This commit is contained in:
Tessera Agent
2026-11-09 09:59:42 +00:00
commit a5ffb2c1b4
54 changed files with 8379 additions and 0 deletions

View File

@@ -0,0 +1,90 @@
use aes_gcm::aead::generic_array::GenericArray;
use aes_gcm::aead::{Aead, NewAead};
use aes_gcm::Aes256Gcm;
use anyhow::{anyhow, Result};
use hmac::Hmac;
use pbkdf2::pbkdf2;
use rand::RngCore;
use sha2::Sha256;
use std::fs;
use std::path::Path;
const NONCE_LEN: usize = 12;
const SALT_LEN: usize = 16;
pub struct VaultKey {
cipher: Aes256Gcm,
}
impl VaultKey {
pub fn derive_from_passphrase(passphrase: &str, salt_path: &Path) -> Result<Self> {
let salt = if salt_path.exists() {
fs::read(salt_path)?
} else {
let mut salt = [0u8; SALT_LEN];
rand::thread_rng().fill_bytes(&mut salt);
if let Some(parent) = salt_path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(salt_path, &salt)?;
salt.to_vec()
};
let mut key = [0u8; 32];
pbkdf2::<Hmac<Sha256>>(passphrase.as_bytes(), &salt, 100_000, &mut key);
let cipher =
Aes256Gcm::new_from_slice(&key).map_err(|e| anyhow!("cipher key: {e}"))?;
Ok(Self { cipher })
}
pub fn encrypt(&self, plaintext: &[u8]) -> Result<Vec<u8>> {
let mut nonce_bytes = [0u8; NONCE_LEN];
rand::thread_rng().fill_bytes(&mut nonce_bytes);
let nonce = GenericArray::from_slice(&nonce_bytes);
let ciphertext = self
.cipher
.encrypt(nonce, plaintext)
.map_err(|e| anyhow!("encrypt: {e}"))?;
let mut out = nonce_bytes.to_vec();
out.extend(ciphertext);
Ok(out)
}
pub fn decrypt(&self, blob: &[u8]) -> Result<Vec<u8>> {
if blob.len() < NONCE_LEN {
anyhow::bail!("blob too short");
}
let (nonce_bytes, ct) = blob.split_at(NONCE_LEN);
let nonce = GenericArray::from_slice(nonce_bytes);
self.cipher
.decrypt(nonce, ct)
.map_err(|e| anyhow!("decrypt: {e}"))
}
}
pub fn content_id(data: &[u8]) -> String {
use sha2::Digest;
hex::encode(Sha256::digest(data))
}
pub fn pack_path(data_dir: &Path, id: &str) -> std::path::PathBuf {
let prefix = &id[..2.min(id.len())];
data_dir.join(prefix).join(id)
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
#[test]
fn roundtrip_crypto() {
let dir = tempdir().unwrap();
let salt = dir.path().join("salt");
let key = VaultKey::derive_from_passphrase("test-vault", &salt).unwrap();
let enc = key.encrypt(b"stardust").unwrap();
let plain = key.decrypt(&enc).unwrap();
assert_eq!(plain, b"stardust");
}
}

View File

@@ -0,0 +1,27 @@
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ChunkIndex {
pub chunks: HashMap<String, ChunkEntry>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChunkEntry {
pub pack_id: String,
pub offset: u64,
pub length: u64,
}
impl ChunkIndex {
pub fn record(&mut self, chunk_id: String, pack_id: String, offset: u64, length: u64) {
self.chunks.insert(
chunk_id,
ChunkEntry {
pack_id,
offset,
length,
},
);
}
}

View File

@@ -0,0 +1,17 @@
//! Restic-compatible path layout vault engine.
//!
//! 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.
mod crypto;
mod index;
mod vault;
pub use vault::*;

View File

@@ -0,0 +1,260 @@
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<Utc>,
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<Path>, passphrase: &str) -> Result<Self> {
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<Path>, passphrase: &str) -> Result<Self> {
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<ChunkIndex> {
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<String> {
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<Vec<u8>> {
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<StoredSnapshot> {
if dry_run {
return Ok(StoredSnapshot {
id: manifest.snapshot_id,
taken_at: Utc::now(),
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: Utc::now(),
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<Vec<StoredSnapshot>> {
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<u64> {
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<usize> {
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<Vec<Uuid>> {
let policy = DecayPolicy::from_preset(preset);
let snaps = self.list_snapshots()?;
let refs: Vec<SnapshotRef> = 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());
}
}