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

@@ -12,9 +12,13 @@ COPY crates ./crates
COPY --from=web /build/dist ./web/dist COPY --from=web /build/dist ./web/dist
RUN cargo build --release -p tessera-hub RUN cargo build --release -p tessera-hub
FROM restic/restic:0.19.1 AS restic
FROM debian:bookworm-slim FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates postgresql-client && rm -rf /var/lib/apt/lists/* RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates postgresql-client && rm -rf /var/lib/apt/lists/*
COPY --from=rust /build/target/release/tessera-hub /usr/local/bin/ COPY --from=rust /build/target/release/tessera-hub /usr/local/bin/
COPY --from=restic /usr/bin/restic /usr/local/bin/restic
RUN restic version
ENV TESSERA_LISTEN=0.0.0.0:8787 ENV TESSERA_LISTEN=0.0.0.0:8787
ENV TESSERA_DATA_DIR=/data ENV TESSERA_DATA_DIR=/data
EXPOSE 8787 EXPOSE 8787

View File

@@ -4,6 +4,8 @@ Self-hosted backup vault with a space-themed canvas: **orbits**, **snapshots**,
## Quick start ## Quick start
For a native install, put [Restic 0.19.1 or newer](https://restic.readthedocs.io/en/stable/020_installation.html) on the hub and CLI's `PATH`. The Docker image includes Restic.
```bash ```bash
# Build UI then hub # Build UI then hub
cd web && npm ci && npm run build && cd .. cd web && npm ci && npm run build && cd ..
@@ -33,22 +35,41 @@ Compose publishes **127.0.0.1:8787** only. The process inside the container list
cargo build --release -p tessera-cli cargo build --release -p tessera-cli
export TESSERA_VAULT_PASSPHRASE='choose a long private passphrase' export TESSERA_VAULT_PASSPHRASE='choose a long private passphrase'
./target/release/tessera init ./target/release/tessera init
./target/release/tessera orbit nightly --path ./docs --dry-run ./target/release/tessera orbit nightly --path ./docs
./target/release/tessera snap ./target/release/tessera snap
./target/release/tessera list ./target/release/tessera list
``` ```
## Deduplicated backups
New captures use Restic. Filesystem orbits back up files directly and share encrypted chunks in `vault/restic`. Each successful run creates a complete restore point. The API reports `size_bytes` for the logical backup, `stored_bytes` for new packed data and metadata, and `new_data_chunks` for newly stored payload chunks. An identical backup can add metadata while reporting zero new data chunks.
Restore a new filesystem or Restic outpost snapshot to a file such as `restore.tar`. PostgreSQL and legacy upload restores still produce the original payload bytes. Existing snapshots use their original storage and restore format. Keep the entire `vault` directory and its passphrase together when moving a Tessera installation.
Decay removes expired snapshots from Tessera's list. Run `tessera gc` periodically from the host or container with the same data directory and vault passphrase to let Restic reclaim their unreferenced chunks. Run it during a quiet period so Restic can acquire its repository locks. Legacy packs and Restic snapshots created outside Tessera's catalog require separate maintenance.
### Incremental Wormhole transfers
Run [Rest Server](https://github.com/restic/rest-server#usage) with TLS, authentication, `--append-only`, and `--private-repos`. Point its storage at the hub's `vault/outposts` directory. Both processes need filesystem access to that directory. Give Rest Server access only to `outposts`, with a separate location for its TLS and authentication files.
1. Pair the agent as usual. Save the outpost UUID and upload token from the pairing response. Create an orbit with `tessera orbit <name> --provider wormhole`. The agent's `run` command handles scheduling.
2. Initialize a Restic repository at `vault/outposts/<orbit-id>` with a unique repository password. Create a Rest Server login named `<orbit-id>` with a separate HTTP password. Put a mode `0600` file named `vault/keys/outpost-<orbit-id>.json` on the hub with the fields `outpost_id` (the paired UUID) and `password` (that repository's password). Back up this configuration with the vault.
3. On the agent, set `TESSERA_HUB_URL`, `TESSERA_UPLOAD_TOKEN`, `TESSERA_ORBIT_ID`, and `TESSERA_RESTIC_REPOSITORY` (for example, `rest:https://backup.example.org/<orbit-id>/`). Supply the repository password via `RESTIC_PASSWORD_FILE` or `RESTIC_PASSWORD`, and Rest Server credentials via `RESTIC_REST_USERNAME` and `RESTIC_REST_PASSWORD`. Run `tessera-agent beam` from the directory to back up. For a private Rest Server CA, set `RESTIC_CACERT` on the agent.
The agent reads files to detect changes, sends missing chunks and metadata through Restic, and then registers the successful snapshot with Tessera. Agents using the original Wormhole upload mode still send their full archive. The hub deduplicates that archive on disk.
If the Restic backup succeeds and registration fails, retry `POST /api/v1/wormhole/restic/commit` with the paired `X-Tessera-Upload-Token` and a JSON body containing `orbit_id` and the Restic `snapshot_id` from the error. Repeating registration for the same snapshot returns the same Tessera snapshot ID.
## Architecture ## Architecture
See [docs/SPEC.md](docs/SPEC.md). Rust workspace crates: `tessera-core`, `tessera-store`, `tessera-providers`, `tessera-hub`, `tessera-agent`, `tessera-cli`. See [docs/SPEC.md](docs/SPEC.md). Rust workspace crates: `tessera-core`, `tessera-store`, `tessera-providers`, `tessera-hub`, `tessera-agent`, `tessera-cli`.
## Limitations (v1) ## Limitations (v1)
- Vault engine uses a **restic-compatible directory layout** with Tessera’s own chunk encryption (Rust 1.83 cannot yet depend on `rustic_core` 0.13+). Emergency tooling may use external `rustic`/`restic` as formats converge.
- New vaults derive the key with Argon2id (19 MiB, 2 iterations, parallelism 1) and record `keys/kdf.json`. A vault that already has a salt and no `kdf.json` still opens with PBKDF2-HMAC-SHA256, 100,000 iterations. New snapshot metadata is written as `{id}.json.enc`. Existing `{id}.json` files still list and restore. - New vaults derive the key with Argon2id (19 MiB, 2 iterations, parallelism 1) and record `keys/kdf.json`. A vault that already has a salt and no `kdf.json` still opens with PBKDF2-HMAC-SHA256, 100,000 iterations. New snapshot metadata is written as `{id}.json.enc`. Existing `{id}.json` files still list and restore.
- Wormhole pairing codes and upload tokens are stored in SQLite and survive a hub restart. Chunks are written at the given offset. When the bytes cover `total_bytes`, the hub seals them into the vault and deletes the `.part` file. `total_bytes` is required. - Wormhole pairing codes and upload tokens are stored in SQLite and survive a hub restart. Chunks are written at the given offset. When the bytes cover `total_bytes`, the hub seals them into the vault and deletes the `.part` file. `total_bytes` is required.
- Set `TESSERA_WORMHOLE_MTLS` to `1` or `true` to open a client-certificate listener. It also needs `TESSERA_WORMHOLE_CERT`, `TESSERA_WORMHOLE_KEY`, and `TESSERA_WORMHOLE_CLIENT_CA`. `TESSERA_WORMHOLE_LISTEN` defaults to `127.0.0.1:8788`. While that listener is up, plain HTTP upload routes answer 403. An agent that uses `https://` needs `TESSERA_WORMHOLE_CA`, `TESSERA_WORMHOLE_CLIENT_CERT`, and `TESSERA_WORMHOLE_CLIENT_KEY`. - Set `TESSERA_WORMHOLE_MTLS` to `1` or `true` to open a client-certificate listener. It also needs `TESSERA_WORMHOLE_CERT`, `TESSERA_WORMHOLE_KEY`, and `TESSERA_WORMHOLE_CLIENT_CA`. `TESSERA_WORMHOLE_LISTEN` defaults to `127.0.0.1:8788`. While that listener is up, plain HTTP upload routes answer 403. An agent that uses `https://` needs `TESSERA_WORMHOLE_CA`, `TESSERA_WORMHOLE_CLIENT_CERT`, and `TESSERA_WORMHOLE_CLIENT_KEY`.
- Postgres capture shells out to `pg_dump`. The connection URL is parsed and the password is written to a mode `0600` pgpass file (`PGPASSFILE`); it is not placed on the process argument list. The release image installs `pg_dump`; a hub built from source needs it on `PATH`. - PostgreSQL captures still run a full `pg_dump` into a private temporary file. Restic can deduplicate matching bytes in the resulting dump. Allow temporary disk space for one full dump per concurrent capture. The release image includes `pg_dump`; a native hub needs it on `PATH`.
- The command provider is outside this release. Creating a command orbit and running it returns `command provider is outside this release; use filesystem or postgres`. - The command provider is outside this release. Creating a command orbit and running it returns `command provider is outside this release; use filesystem or postgres`.
- OIDC is not implemented. The canvas does not attach `TESSERA_ADMIN_TOKEN`. - OIDC is not implemented. The canvas does not attach `TESSERA_ADMIN_TOKEN`.

View File

@@ -9,7 +9,13 @@ use std::sync::Arc;
pub fn post_json(url: &str, body: &serde_json::Value, headers: &[(&str, &str)]) -> Result<String> { pub fn post_json(url: &str, body: &serde_json::Value, headers: &[(&str, &str)]) -> Result<String> {
let payload = serde_json::to_string(body)?; let payload = serde_json::to_string(body)?;
request("POST", url, Some(&payload), Some("application/json"), headers) request(
"POST",
url,
Some(&payload),
Some("application/json"),
headers,
)
} }
fn request( fn request(
@@ -42,8 +48,15 @@ fn request(
stream.write_all(req.as_bytes())?; stream.write_all(req.as_bytes())?;
let mut buf = String::new(); let mut buf = String::new();
stream.read_to_string(&mut buf)?; stream.read_to_string(&mut buf)?;
let body_start = buf.find("\r\n\r\n").map(|i| i + 4).unwrap_or(0); let (response_headers, body) = buf.split_once("\r\n\r\n").context("invalid hub response")?;
Ok(buf[body_start..].trim().to_string()) let status = response_headers
.lines()
.next()
.and_then(|line| line.split_whitespace().nth(1))
.context("missing hub response status")?
.parse::<u16>()?;
anyhow::ensure!((200..300).contains(&status), "hub returned HTTP {status}");
Ok(body.trim().to_string())
} }
trait ReadWrite: Read + Write {} trait ReadWrite: Read + Write {}

View File

@@ -81,6 +81,14 @@ async fn beam_once(cli: &Cli) -> Result<()> {
let token = cli.upload_token.clone().context("TESSERA_UPLOAD_TOKEN")?; let token = cli.upload_token.clone().context("TESSERA_UPLOAD_TOKEN")?;
let orbit_id = cli.orbit_id.clone().context("TESSERA_ORBIT_ID")?; let orbit_id = cli.orbit_id.clone().context("TESSERA_ORBIT_ID")?;
if let Some(repository) = std::env::var_os("TESSERA_RESTIC_REPOSITORY") {
let repository = repository
.to_str()
.context("TESSERA_RESTIC_REPOSITORY must be UTF-8")?;
let id = uuid::Uuid::parse_str(&orbit_id).context("invalid TESSERA_ORBIT_ID")?;
return beam_restic(repository, &hub, &token, id).await;
}
let config = serde_json::json!({ "paths": ["./"] }); let config = serde_json::json!({ "paths": ["./"] });
let provider = provider_from_config(&ProviderKind::Filesystem, &config)?; let provider = provider_from_config(&ProviderKind::Filesystem, &config)?;
let capture = provider.capture().await?; let capture = provider.capture().await?;
@@ -112,3 +120,55 @@ async fn beam_once(cli: &Cli) -> Result<()> {
info!("beamed {} bytes via wormhole session {session_id}", capture.payload.len()); info!("beamed {} bytes via wormhole session {session_id}", capture.payload.len());
Ok(()) Ok(())
} }
async fn beam_restic(repository: &str, hub: &str, token: &str, orbit_id: uuid::Uuid) -> Result<()> {
let authority = repository
.strip_prefix("rest:https://")
.and_then(|url| url.split('/').next());
anyhow::ensure!(
authority.is_some_and(|host| !host.is_empty() && !host.contains('@')),
"TESSERA_RESTIC_REPOSITORY must be a rest:https:// URL without embedded credentials"
);
let output = tokio::process::Command::new("restic")
.env("RESTIC_REPOSITORY", repository)
.env_remove("RESTIC_REPOSITORY_FILE")
.args(["backup", "--json", "--quiet", "--force", "--", "."])
.stdin(std::process::Stdio::null())
.kill_on_drop(true)
.output()
.await
.context("starting restic (install restic on PATH)")?;
anyhow::ensure!(
output.status.success(),
"restic backup failed ({}): {}",
output.status,
String::from_utf8_lossy(&output.stderr).trim()
);
let summary: serde_json::Value = serde_json::from_str(
std::str::from_utf8(&output.stdout)?
.lines()
.last()
.context("missing restic summary")?,
)?;
let snapshot = summary["snapshot_id"]
.as_str()
.context("missing restic snapshot ID")?;
let body = serde_json::json!({ "orbit_id": orbit_id, "snapshot_id": snapshot });
let reply = http::post_json(
&format!("{hub}/api/v1/wormhole/restic/commit"),
&body,
&[("x-tessera-upload-token", token)],
)
.with_context(|| format!("register Restic snapshot {snapshot}"))?;
let reply: serde_json::Value = serde_json::from_str(&reply)?;
let registered = reply["snapshot_id"]
.as_str()
.context("hub did not register the Restic snapshot")?;
info!(
snapshot,
registered,
stored_bytes = summary["data_added_packed"].as_u64(),
"committed Restic backup"
);
Ok(())
}

View File

@@ -47,6 +47,8 @@ enum Commands {
#[arg(long, default_value = "week-of-dailies")] #[arg(long, default_value = "week-of-dailies")]
preset: String, preset: String,
}, },
/// Reclaim unreferenced data from expired Restic snapshots.
Gc,
Wormhole { Wormhole {
#[command(subcommand)] #[command(subcommand)]
cmd: WormholeCmd, cmd: WormholeCmd,
@@ -91,6 +93,9 @@ fn main() -> Result<()> {
target, target,
} => cmd_reconstitute(&cli, snapshot_id, target)?, } => cmd_reconstitute(&cli, snapshot_id, target)?,
Commands::Decay { preset } => cmd_decay(&cli, &preset)?, Commands::Decay { preset } => cmd_decay(&cli, &preset)?,
Commands::Gc => {
Vault::open(&vault_path(&cli.data_dir), require_passphrase(&cli)?)?.collect_garbage()?
}
Commands::Wormhole { ref cmd } => match cmd { Commands::Wormhole { ref cmd } => match cmd {
WormholeCmd::Pair { code, name } => wormhole_pair(&cli, code, name)?, WormholeCmd::Pair { code, name } => wormhole_pair(&cli, code, name)?,
}, },
@@ -172,7 +177,14 @@ fn cmd_orbit(
) -> Result<()> { ) -> Result<()> {
let config = match provider.as_str() { let config = match provider.as_str() {
"filesystem" => serde_json::json!({ "paths": [path.unwrap_or_else(|| ".".into())] }), "filesystem" => serde_json::json!({ "paths": [path.unwrap_or_else(|| ".".into())] }),
"postgres" => serde_json::json!({ "connection_url": path.context("--path or connection url required")? }), "postgres" => {
serde_json::json!({ "connection_url": path.context("--path or connection url required")? })
}
"wormhole" => {
anyhow::ensure!(path.is_none() && schedule.is_none() && !dry_run,
"Wormhole paths and scheduling are set on the outpost");
serde_json::json!({})
}
_ => anyhow::bail!("unknown provider"), _ => anyhow::bail!("unknown provider"),
}; };
let body = serde_json::json!({ let body = serde_json::json!({
@@ -210,12 +222,17 @@ fn cmd_snap(cli: &Cli, orbit_name: Option<String>) -> Result<()> {
fn cmd_list(cli: &Cli) -> Result<()> { fn cmd_list(cli: &Cli) -> Result<()> {
let vault = Vault::open(&vault_path(&cli.data_dir), require_passphrase(cli)?)?; let vault = Vault::open(&vault_path(&cli.data_dir), require_passphrase(cli)?)?;
for s in vault.list_snapshots()? { for s in vault.list_snapshots()? {
let stored = s
.stored_bytes
.map(|n| format!(" +{n} bytes stored"))
.unwrap_or_default();
println!( println!(
"{} {} {} bytes orbit={}", "{} {} {} bytes orbit={}{}",
s.taken_at.to_rfc3339(), s.taken_at.to_rfc3339(),
s.id, s.id,
s.size_bytes, s.size_bytes,
s.manifest.orbit_name s.manifest.orbit_name,
stored,
); );
} }
Ok(()) Ok(())

View File

@@ -30,6 +30,7 @@ utoipa.workspace = true
uuid.workspace = true uuid.workspace = true
hex.workspace = true hex.workspace = true
base64 = "0.22" base64 = "0.22"
tempfile.workspace = true
indexmap = "=2.2.6" indexmap = "=2.2.6"
hyper = { version = "=1.12.0", features = ["server", "http1"] } hyper = { version = "=1.12.0", features = ["server", "http1"] }
hyper-util = { version = "=0.1.21", features = ["tokio"] } hyper-util = { version = "=0.1.21", features = ["tokio"] }
@@ -40,5 +41,4 @@ tower = { workspace = true }
[dev-dependencies] [dev-dependencies]
rcgen = "=0.13.2" rcgen = "=0.13.2"
tempfile.workspace = true
tokio.workspace = true tokio.workspace = true

View File

@@ -1,9 +1,8 @@
use crate::db::OrbitRow; use crate::db::OrbitRow;
use crate::state::HubState; use crate::state::HubState;
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use tessera_core::config::ProviderKind;
use tessera_core::manifest::SnapshotManifest; use tessera_core::manifest::SnapshotManifest;
use tessera_providers::provider_from_config; use tessera_providers::{FilesystemConfig, PostgresProvider};
use uuid::Uuid; use uuid::Uuid;
pub async fn run_orbit_internal(state: HubState, orbit_id: Uuid) -> Result<Option<Uuid>> { pub async fn run_orbit_internal(state: HubState, orbit_id: Uuid) -> Result<Option<Uuid>> {
@@ -34,40 +33,57 @@ pub async fn run_orbit_internal(state: HubState, orbit_id: Uuid) -> Result<Optio
async fn run_orbit_row(state: &HubState, orbit: OrbitRow) -> Result<Option<Uuid>> { async fn run_orbit_row(state: &HubState, orbit: OrbitRow) -> Result<Option<Uuid>> {
state.db.set_orbit_status(orbit.id, "running").await?; state.db.set_orbit_status(orbit.id, "running").await?;
let provider_kind = match orbit.provider.as_str() {
"filesystem" => ProviderKind::Filesystem,
"postgres" => ProviderKind::Postgres,
"command" => ProviderKind::Command,
other => anyhow::bail!("unknown provider '{other}'"),
};
let config: serde_json::Value = serde_json::from_str(&orbit.provider_config)?; let config: serde_json::Value = serde_json::from_str(&orbit.provider_config)?;
let provider = provider_from_config(&provider_kind, &config)?; let mut manifest = SnapshotManifest {
let capture = provider.capture().await.context("capture")?;
let manifest = SnapshotManifest {
snapshot_id: Uuid::new_v4(), snapshot_id: Uuid::new_v4(),
orbit_id: orbit.id, orbit_id: orbit.id,
orbit_name: orbit.name.clone(), orbit_name: orbit.name.clone(),
labels: capture.labels, labels: vec![orbit.provider.clone()],
provider: orbit.provider.clone(), provider: orbit.provider.clone(),
paths: vec![], paths: vec![],
restore_hints: capture.restore_hints, restore_hints: serde_json::Value::Null,
}; };
let (payload, max_file_bytes) = match orbit.provider.as_str() {
let mut vault = state.vault.write().await; "filesystem" => {
let snap = vault let config: FilesystemConfig = serde_json::from_value(config)?;
.snapshot(manifest, &capture.payload, orbit.dry_run) manifest.paths = config.paths;
.context("vault snapshot")?; (None, config.max_file_bytes)
}
"postgres" => {
let provider = PostgresProvider::from_config(&config)?;
let file = tempfile::tempfile()?;
manifest.restore_hints = provider.dump_to(file.try_clone()?).await?;
(Some(file), None)
}
"wormhole" => anyhow::bail!("Wormhole backups are started by the outpost agent"),
"command" => {
anyhow::bail!("command provider is outside this release; use filesystem or postgres")
}
other => anyhow::bail!("unknown provider '{other}'"),
};
let vault = state.vault.clone().read_owned().await;
let snap = tokio::task::spawn_blocking(move || {
match payload {
Some(file) => vault.snapshot_payload(manifest, file, orbit.dry_run),
None => vault.snapshot_files(manifest, max_file_bytes, orbit.dry_run),
}
.context("vault snapshot")
})
.await??;
let snap_id = snap.id;
let retained_snapshot = if orbit.dry_run { let retained_snapshot = if orbit.dry_run {
None None
} else { } else {
let pruned = vault.prune_orbit_with_decay(orbit.id, &orbit.decay_preset)?; let pruned = state
.vault
.write()
.await
.prune_orbit_with_decay(orbit.id, &orbit.decay_preset)?;
state state
.db .db
.audit("decay.pruned", &format!("orbit={}", orbit.name)) .audit("decay.pruned", &format!("orbit={}", orbit.name))
.await?; .await?;
(!pruned.contains(&snap.id)).then_some(snap.id) (!pruned.contains(&snap_id)).then_some(snap_id)
}; };
let status = if orbit.dry_run { let status = if orbit.dry_run {
@@ -84,7 +100,7 @@ async fn run_orbit_row(state: &HubState, orbit: OrbitRow) -> Result<Option<Uuid>
} else { } else {
"orbit.completed" "orbit.completed"
}, },
&format!("snapshot={}", snap.id), &format!("snapshot={snap_id}"),
) )
.await?; .await?;
Ok(retained_snapshot) Ok(retained_snapshot)

View File

@@ -10,8 +10,7 @@ use axum::{
}; };
use base64::Engine; use base64::Engine;
use include_dir::{include_dir, Dir}; use include_dir::{include_dir, Dir};
use std::fs::OpenOptions; use std::fs::{File, OpenOptions};
use std::io::{Read, Seek, SeekFrom};
use std::net::SocketAddr; use std::net::SocketAddr;
use tessera_core::manifest::SnapshotManifest; use tessera_core::manifest::SnapshotManifest;
use tessera_core::reconstitute::{ReconstituteSession, ReconstituteState, RECONSTITUTE_GRACE_SECS}; use tessera_core::reconstitute::{ReconstituteSession, ReconstituteState, RECONSTITUTE_GRACE_SECS};
@@ -34,6 +33,7 @@ static WEB_DIST: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/../../web/dist");
pairing_claim, pairing_claim,
wormhole_upload_init, wormhole_upload_init,
wormhole_upload_chunk, wormhole_upload_chunk,
wormhole_restic_commit,
), ),
components(schemas( components(schemas(
SnapshotSummary, SnapshotSummary,
@@ -46,6 +46,7 @@ static WEB_DIST: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/../../web/dist");
ClaimResponse, ClaimResponse,
UploadInit, UploadInit,
UploadChunk, UploadChunk,
ResticCommit,
)) ))
)] )]
struct ApiDoc; struct ApiDoc;
@@ -57,6 +58,8 @@ struct SnapshotSummary {
taken_at: chrono::DateTime<chrono::Utc>, taken_at: chrono::DateTime<chrono::Utc>,
orbit_name: String, orbit_name: String,
size_bytes: u64, size_bytes: u64,
stored_bytes: Option<u64>,
new_data_chunks: Option<u64>,
} }
#[derive(serde::Deserialize, utoipa::ToSchema)] #[derive(serde::Deserialize, utoipa::ToSchema)]
@@ -107,6 +110,12 @@ struct UploadChunk {
data_b64: String, data_b64: String,
} }
#[derive(serde::Deserialize, utoipa::ToSchema)]
struct ResticCommit {
orbit_id: Uuid,
snapshot_id: String,
}
#[derive(serde::Serialize, utoipa::ToSchema)] #[derive(serde::Serialize, utoipa::ToSchema)]
struct ReconstituteStartResponse { struct ReconstituteStartResponse {
session_id: Uuid, session_id: Uuid,
@@ -136,6 +145,10 @@ pub fn router(state: HubState) -> Router {
.route("/api/v1/wormhole/claim", post(pairing_claim)) .route("/api/v1/wormhole/claim", post(pairing_claim))
.route("/api/v1/wormhole/upload/init", post(wormhole_upload_init)) .route("/api/v1/wormhole/upload/init", post(wormhole_upload_init))
.route("/api/v1/wormhole/upload/chunk", post(wormhole_upload_chunk)) .route("/api/v1/wormhole/upload/chunk", post(wormhole_upload_chunk))
.route(
"/api/v1/wormhole/restic/commit",
post(wormhole_restic_commit),
)
.with_state(state); .with_state(state);
let api = api.route( let api = api.route(
@@ -169,6 +182,8 @@ async fn list_snapshots(
taken_at: s.taken_at, taken_at: s.taken_at,
orbit_name: s.manifest.orbit_name, orbit_name: s.manifest.orbit_name,
size_bytes: s.size_bytes, size_bytes: s.size_bytes,
stored_bytes: s.stored_bytes,
new_data_chunks: s.new_data_chunks,
}) })
.collect(); .collect();
Ok(Json(out)) Ok(Json(out))
@@ -278,7 +293,9 @@ async fn start_reconstitute(
} }
{ {
let mut map = state_bg.reconstitute_sessions.write().await; let mut map = state_bg.reconstitute_sessions.write().await;
let Some(s) = map.get_mut(&session_id) else { return }; let Some(s) = map.get_mut(&session_id) else {
return;
};
if s.state == ReconstituteState::Aborted { if s.state == ReconstituteState::Aborted {
return; return;
} }
@@ -287,8 +304,11 @@ async fn start_reconstitute(
} }
let dest = std::path::PathBuf::from(&target); let dest = std::path::PathBuf::from(&target);
let result = { let result = {
let vault = state_bg.vault.read().await; let vault = state_bg.vault.clone().read_owned().await;
vault.restore_snapshot(req.snapshot_id, &dest) tokio::task::spawn_blocking(move || vault.restore_snapshot(req.snapshot_id, &dest))
.await
.map_err(anyhow::Error::from)
.and_then(|result| result)
}; };
let mut map = state_bg.reconstitute_sessions.write().await; let mut map = state_bg.reconstitute_sessions.write().await;
if let Some(s) = map.get_mut(&session_id) { if let Some(s) = map.get_mut(&session_id) {
@@ -367,7 +387,10 @@ async fn pairing_start(
&expires.to_rfc3339(), &expires.to_rfc3339(),
) )
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(Json(PairingResponse { code, expires_at: expires })) Ok(Json(PairingResponse {
code,
expires_at: expires,
}))
} }
#[utoipa::path(post, path = "/api/v1/wormhole/claim", request_body = ClaimRequest, responses((status = 200, body = ClaimResponse)))] #[utoipa::path(post, path = "/api/v1/wormhole/claim", request_body = ClaimRequest, responses((status = 200, body = ClaimResponse)))]
@@ -408,6 +431,15 @@ async fn wormhole_upload_init(
Json(body): Json<UploadInit>, Json(body): Json<UploadInit>,
) -> Result<Json<serde_json::Value>, StatusCode> { ) -> Result<Json<serde_json::Value>, StatusCode> {
verify_upload_token(&state, &headers)?; verify_upload_token(&state, &headers)?;
if state
.vault
.read()
.await
.outpost_repository_configured(body.orbit_id)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
{
return Err(StatusCode::FORBIDDEN);
}
let total = body.total_bytes.ok_or(StatusCode::BAD_REQUEST)?; let total = body.total_bytes.ok_or(StatusCode::BAD_REQUEST)?;
let session_id = Uuid::new_v4(); let session_id = Uuid::new_v4();
state state
@@ -424,7 +456,8 @@ async fn wormhole_upload_init(
.record_range(&session_id.to_string(), 0, 0, 0) .record_range(&session_id.to_string(), 0, 0, 0)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if seal { if seal {
seal_upload(&state, session_id, body.orbit_id, Vec::new()).await?; let file = tempfile::tempfile().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
seal_upload(&state, session_id, body.orbit_id, file).await?;
} }
} }
Ok(Json(serde_json::json!({ "session_id": session_id }))) Ok(Json(serde_json::json!({ "session_id": session_id })))
@@ -476,17 +509,11 @@ async fn wormhole_upload_chunk(
) )
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if seal { if seal {
let mut bytes = Vec::new(); if !matches!(file.metadata(), Ok(metadata) if metadata.len() == session.total) {
file.seek(SeekFrom::Start(0))
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
file.read_to_end(&mut bytes)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if (bytes.len() as u64) < session.total {
let _ = state.db.mark_upload_unsealed(&body.session_id.to_string()); let _ = state.db.mark_upload_unsealed(&body.session_id.to_string());
return Err(StatusCode::INTERNAL_SERVER_ERROR); return Err(StatusCode::INTERNAL_SERVER_ERROR);
} }
bytes.truncate(session.total as usize); if let Err(status) = seal_upload(&state, body.session_id, session.orbit_id, file).await {
if let Err(status) = seal_upload(&state, body.session_id, session.orbit_id, bytes).await {
let _ = state.db.mark_upload_unsealed(&body.session_id.to_string()); let _ = state.db.mark_upload_unsealed(&body.session_id.to_string());
return Err(status); return Err(status);
} }
@@ -513,13 +540,7 @@ fn restrict_part(path: &std::path::Path) {
} }
fn verify_upload_token(state: &HubState, headers: &HeaderMap) -> Result<(), StatusCode> { fn verify_upload_token(state: &HubState, headers: &HeaderMap) -> Result<(), StatusCode> {
if !state.accept_plain_upload { let token = upload_token(state, headers)?;
return Err(StatusCode::FORBIDDEN);
}
let token = headers
.get("x-tessera-upload-token")
.and_then(|v| v.to_str().ok())
.ok_or(StatusCode::UNAUTHORIZED)?;
if state.upload_token_valid(token) { if state.upload_token_valid(token) {
Ok(()) Ok(())
} else { } else {
@@ -527,11 +548,84 @@ fn verify_upload_token(state: &HubState, headers: &HeaderMap) -> Result<(), Stat
} }
} }
fn upload_token<'a>(state: &HubState, headers: &'a HeaderMap) -> Result<&'a str, StatusCode> {
if !state.accept_plain_upload {
return Err(StatusCode::FORBIDDEN);
}
headers
.get("x-tessera-upload-token")
.and_then(|v| v.to_str().ok())
.ok_or(StatusCode::UNAUTHORIZED)
}
#[utoipa::path(post, path = "/api/v1/wormhole/restic/commit", request_body = ResticCommit, responses((status = 200)))]
async fn wormhole_restic_commit(
State(state): State<HubState>,
headers: HeaderMap,
Json(body): Json<ResticCommit>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let token = upload_token(&state, &headers)?;
let outpost_id = state
.db
.upload_token_outpost(token)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.and_then(|id| Uuid::parse_str(&id).ok())
.ok_or(StatusCode::UNAUTHORIZED)?;
if body.snapshot_id.len() != 64 || !body.snapshot_id.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err(StatusCode::BAD_REQUEST);
}
let orbit = state
.db
.list_orbits()
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.into_iter()
.find(|orbit| orbit.id == body.orbit_id && orbit.provider == "wormhole" && !orbit.dry_run)
.ok_or(StatusCode::NOT_FOUND)?;
let orbit_id = orbit.id;
let mut vault = state.vault.clone().write_owned().await;
let snapshot = tokio::task::spawn_blocking(move || {
let manifest = SnapshotManifest {
snapshot_id: Uuid::nil(),
orbit_id,
orbit_name: orbit.name,
labels: vec!["wormhole".into()],
provider: orbit.provider,
paths: vec![],
restore_hints: serde_json::Value::Null,
};
let id = vault.register_outpost_snapshot(manifest, outpost_id, &body.snapshot_id)?;
if id.is_some() {
if let Err(error) = vault.prune_orbit_with_decay(orbit_id, &orbit.decay_preset) {
tracing::warn!(%orbit_id, %error, "could not apply Wormhole retention");
}
}
Ok::<_, anyhow::Error>(id)
})
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.map_err(|error| {
tracing::error!(%orbit_id, %error, "could not register Restic snapshot");
StatusCode::INTERNAL_SERVER_ERROR
})?
.ok_or(StatusCode::FORBIDDEN)?;
state
.db
.set_orbit_status(orbit_id, "completed")
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let _ = state
.db
.audit("wormhole.restic.committed", &format!("snapshot={snapshot}"))
.await;
Ok(Json(serde_json::json!({ "snapshot_id": snapshot })))
}
async fn seal_upload( async fn seal_upload(
state: &HubState, state: &HubState,
session_id: Uuid, session_id: Uuid,
orbit_id: Uuid, orbit_id: Uuid,
bytes: Vec<u8>, payload: File,
) -> Result<(), StatusCode> { ) -> Result<(), StatusCode> {
let orbits = state let orbits = state
.db .db
@@ -556,14 +650,30 @@ async fn seal_upload(
paths: vec![], paths: vec![],
restore_hints: serde_json::json!({ "session_id": session_id }), restore_hints: serde_json::json!({ "session_id": session_id }),
}; };
let snap_id = { let vault = state.vault.clone().read_owned().await;
let mut vault = state.vault.write().await; if vault
let snap = vault .outpost_repository_configured(orbit_id)
.snapshot(manifest, &bytes, false) .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; {
let _ = vault.prune_orbit_with_decay(orbit_id, &decay); return Err(StatusCode::FORBIDDEN);
snap.id }
}; let snap_id = tokio::task::spawn_blocking(move || {
Ok::<_, anyhow::Error>(vault.snapshot_payload(manifest, payload, false)?.id)
})
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.map_err(|error| {
tracing::error!(%session_id, %error, "could not seal Wormhole snapshot");
StatusCode::INTERNAL_SERVER_ERROR
})?;
if let Err(error) = state
.vault
.write()
.await
.prune_orbit_with_decay(orbit_id, &decay)
{
tracing::warn!(%orbit_id, %error, "could not apply Wormhole retention");
}
let _ = state let _ = state
.db .db
.audit("wormhole.sealed", &format!("snapshot={snap_id}")) .audit("wormhole.sealed", &format!("snapshot={snap_id}"))

View File

@@ -1,5 +1,5 @@
use anyhow::Result; use anyhow::Result;
use rusqlite::{params, Connection}; use rusqlite::{params, Connection, OptionalExtension};
use std::path::Path; use std::path::Path;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use uuid::Uuid; use uuid::Uuid;
@@ -197,11 +197,15 @@ impl Db {
} }
pub fn upload_token_active(&self, token: &str) -> Result<bool> { pub fn upload_token_active(&self, token: &str) -> Result<bool> {
Ok(self.upload_token_outpost(token)?.is_some())
}
pub fn upload_token_outpost(&self, token: &str) -> Result<Option<String>> {
let conn = self.conn.lock().unwrap(); let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare( Ok(conn.query_row(
"SELECT 1 FROM wormhole_tokens WHERE token = ?1 AND state = 'active' LIMIT 1", "SELECT outpost_id FROM wormhole_tokens WHERE token = ?1 AND state = 'active' LIMIT 1",
)?; params![token], |row| row.get(0),
Ok(stmt.query_row(params![token], |_| Ok(())).is_ok()) ).optional()?)
} }
pub fn upload_session(&self, id: &str) -> Result<Option<UploadSession>> { pub fn upload_session(&self, id: &str) -> Result<Option<UploadSession>> {

View File

@@ -49,6 +49,50 @@ impl PostgresProvider {
let config: PostgresConfig = serde_json::from_value(config.clone())?; let config: PostgresConfig = serde_json::from_value(config.clone())?;
Ok(Self { config }) Ok(Self { config })
} }
pub async fn dump_to(&self, file: fs::File) -> Result<serde_json::Value> {
self.dump(Stdio::from(file.try_clone()?)).await?;
anyhow::ensure!(file.metadata()?.len() > 0, "pg_dump produced an empty file");
Ok(self.restore_hints())
}
async fn dump(&self, stdout: Stdio) -> Result<std::process::Output> {
let target = parse_postgres_url(&self.config.connection_url)?;
let args = dump_args(&self.config.format)?;
let pgpass = write_pgpass(&target)?;
let mut cmd = Command::new("pg_dump");
let output = cmd
.args(args)
.env("PGPASSFILE", &pgpass.path)
.env("PGHOST", &target.host)
.env("PGPORT", &target.port)
.env("PGUSER", &target.user)
.env("PGDATABASE", &target.dbname)
.env_remove("PGPASSWORD")
.stdout(stdout)
.stderr(Stdio::piped())
.kill_on_drop(true)
.spawn()
.context("pg_dump failed to start")?
.wait_with_output()
.await
.context("waiting for pg_dump")?;
anyhow::ensure!(
output.status.success(),
"pg_dump failed: {}",
String::from_utf8_lossy(&output.stderr)
);
Ok(output)
}
fn restore_hints(&self) -> serde_json::Value {
let command = if self.config.format == "plain" {
"psql -d \"$DATABASE_URL\" -f dump.file"
} else {
"pg_restore -d \"$DATABASE_URL\" dump.file"
};
json!({ "format": self.config.format, "restore_command_hint": command })
}
} }
fn percent_decode(input: &str) -> Result<String> { fn percent_decode(input: &str) -> Result<String> {
@@ -162,31 +206,11 @@ impl BackupProvider for PostgresProvider {
} }
async fn capture(&self) -> Result<CaptureResult> { async fn capture(&self) -> Result<CaptureResult> {
let target = parse_postgres_url(&self.config.connection_url)?; let output = self.dump(Stdio::piped()).await?;
let args = dump_args(&self.config.format)?;
let pgpass = write_pgpass(&target)?;
let mut cmd = Command::new("pg_dump");
cmd.args(&args);
cmd.env("PGPASSFILE", &pgpass.path);
cmd.env("PGHOST", &target.host);
cmd.env("PGPORT", &target.port);
cmd.env("PGUSER", &target.user);
cmd.env("PGDATABASE", &target.dbname);
cmd.env_remove("PGPASSWORD");
cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
let output = cmd.output().await.context("pg_dump failed to start")?;
drop(pgpass);
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
anyhow::bail!("pg_dump failed: {stderr}");
}
Ok(CaptureResult { Ok(CaptureResult {
payload: output.stdout, payload: output.stdout,
labels: vec!["postgres".into()], labels: vec!["postgres".into()],
restore_hints: json!({ restore_hints: self.restore_hints(),
"format": self.config.format,
"restore_command_hint": "pg_restore -d \"$DATABASE_URL\" dump.file"
}),
}) })
} }
} }

View File

@@ -20,5 +20,5 @@ tempfile.workspace = true
thiserror.workspace = true thiserror.workspace = true
tokio = { workspace = true, features = ["fs", "io-util"] } tokio = { workspace = true, features = ["fs", "io-util"] }
tracing.workspace = true tracing.workspace = true
uuid.workspace = true uuid = { workspace = true, features = ["v5"] }
walkdir.workspace = true 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: //! Layout under vault root:
//! - `config` — repository version marker (restic-compatible sentinel) //! - `restic/` and `outposts/` — Restic repositories
//! - `data/` — content-addressed encrypted packs (`{prefix}/{id}`) //! - `snapshots/` — Tessera snapshot metadata
//! - `snapshots/` — JSON snapshot metadata //! - `keys/` — vault key derivation and outpost configuration
//! - `index/` — chunk index shards //! - `config`, `data/`, `index/` — legacy Tessera storage
//! - `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 crypto;
mod index; mod index;
mod restic;
mod vault; mod vault;
pub use 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::crypto::{content_id, pack_path, VaultKey};
use crate::index::ChunkIndex; use crate::index::ChunkIndex;
use crate::restic::{self, Repository};
use anyhow::{anyhow, Context, Result}; use anyhow::{anyhow, Context, Result};
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize}; 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::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use tessera_core::decay::{evaluate_decay, DecayPolicy, SnapshotRef}; use tessera_core::decay::{evaluate_decay, DecayPolicy, SnapshotRef};
use tessera_core::manifest::SnapshotManifest; use tessera_core::manifest::SnapshotManifest;
use uuid::Uuid; use uuid::Uuid;
@@ -18,12 +21,23 @@ pub struct StoredSnapshot {
pub manifest: SnapshotManifest, pub manifest: SnapshotManifest,
pub size_bytes: u64, pub size_bytes: u64,
pub tree_root: String, 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 { pub struct Vault {
root: PathBuf, root: PathBuf,
key: VaultKey, key: VaultKey,
index: ChunkIndex, index: ChunkIndex,
restic: Repository,
}
#[derive(Deserialize)]
struct OutpostRepository {
outpost_id: Uuid,
password: String,
} }
impl Vault { impl Vault {
@@ -49,6 +63,7 @@ impl Vault {
let key = VaultKey::derive_from_passphrase(passphrase, &salt)?; let key = VaultKey::derive_from_passphrase(passphrase, &salt)?;
let index = ChunkIndex::default(); let index = ChunkIndex::default();
let v = Self { let v = Self {
restic: Self::repository(&root, passphrase)?,
root, root,
key, key,
index, index,
@@ -67,12 +82,214 @@ impl Vault {
let key = VaultKey::derive_from_passphrase(passphrase, &salt)?; let key = VaultKey::derive_from_passphrase(passphrase, &salt)?;
let index = Self::load_index(&root)?; let index = Self::load_index(&root)?;
Ok(Self { Ok(Self {
restic: Self::repository(&root, passphrase)?,
root, root,
key, key,
index, 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 { fn index_path(&self) -> PathBuf {
self.root.join("index/tessera-main.json") self.root.join("index/tessera-main.json")
} }
@@ -143,6 +360,8 @@ impl Vault {
manifest, manifest,
size_bytes: payload.len() as u64, size_bytes: payload.len() as u64,
tree_root: "dry-run".into(), tree_root: "dry-run".into(),
stored_bytes: None,
new_data_chunks: None,
}); });
} }
@@ -155,25 +374,42 @@ impl Vault {
manifest, manifest,
size_bytes: payload.len() as u64, size_bytes: payload.len() as u64,
tree_root: chunk_id, 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 plain = serde_json::to_vec(&snap)?;
let enc = self.key.encrypt(&plain)?; let enc = self.key.encrypt(&plain)?;
let path = self let dir = self.root.join("snapshots");
.root let path = dir.join(format!("{}.json.enc", snap.id));
.join("snapshots") let mut temp = tempfile::NamedTempFile::new_in(&dir)?;
.join(format!("{}.json.enc", snap.id)); temp.write_all(&enc)?;
fs::write(&path, &enc)?; temp.as_file().sync_all()?;
Ok(snap) if overwrite {
temp.persist(path)?;
} else {
temp.persist_noclobber(path)?;
}
sync_directory(&dir)
} }
fn read_snapshot_file(&self, path: &Path) -> Result<StoredSnapshot> { fn read_snapshot_file(&self, path: &Path) -> Result<StoredSnapshot> {
let name = path.file_name().and_then(|s| s.to_str()).unwrap_or(""); 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)?)?; let plain = self.key.decrypt(&fs::read(path)?)?;
Ok(serde_json::from_slice(&plain)?) Ok(serde_json::from_slice(&plain)?)
} else if name.ends_with(".json") { } 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 { } else {
anyhow::bail!("not a snapshot file"); anyhow::bail!("not a snapshot file");
} }
@@ -201,13 +437,33 @@ impl Vault {
let enc = self.root.join("snapshots").join(format!("{id}.json.enc")); let enc = self.root.join("snapshots").join(format!("{id}.json.enc"));
let plain = self.root.join("snapshots").join(format!("{id}.json")); let plain = self.root.join("snapshots").join(format!("{id}.json"));
let path = if enc.exists() { enc } else { plain }; let path = if enc.exists() { enc } else { plain };
let snap = self.read_snapshot_file(&path).context("snapshot metadata")?; let snap = self
let bytes = self.read_chunk(&snap.tree_root)?; .read_snapshot_file(&path)
if let Some(parent) = dest.parent() { .context("snapshot metadata")?;
fs::create_dir_all(parent)?; 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)?; let len = temp.as_file().metadata()?.len();
Ok(bytes.len() as u64) temp.as_file().sync_all()?;
temp.persist(dest)?;
Ok(len)
} }
pub fn forget(&mut self, ids: &[Uuid]) -> Result<usize> { pub fn forget(&mut self, ids: &[Uuid]) -> Result<usize> {
@@ -217,7 +473,14 @@ impl Vault {
for suffix in [".json.enc", ".json"] { for suffix in [".json.enc", ".json"] {
let path = self.root.join("snapshots").join(format!("{id}{suffix}")); let path = self.root.join("snapshots").join(format!("{id}{suffix}"));
if path.exists() { 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; gone = true;
} }
} }
@@ -228,6 +491,59 @@ impl Vault {
Ok(removed) 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>> { pub fn prune_with_decay(&mut self, preset: &str) -> Result<Vec<Uuid>> {
let snaps = self.list_snapshots()?; let snaps = self.list_snapshots()?;
self.prune_snapshots(preset, snaps.into_iter()) 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<()> { fn restrict_dir(path: &Path) -> Result<()> {
#[cfg(unix)] #[cfg(unix)]
{ {
@@ -282,6 +606,67 @@ mod tests {
use tempfile::tempdir; use tempfile::tempdir;
use tessera_core::manifest::SnapshotManifest; 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] #[test]
fn init_snap_list_restore() { fn init_snap_list_restore() {
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
@@ -342,7 +727,12 @@ mod tests {
restore_hints: serde_json::json!({}), restore_hints: serde_json::json!({}),
}; };
vault 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(); .unwrap();
} }
let pruned = vault let pruned = vault
@@ -375,6 +765,8 @@ mod tests {
}, },
size_bytes: 4, size_bytes: 4,
tree_root: "missing".into(), tree_root: "missing".into(),
stored_bytes: None,
new_data_chunks: None,
}; };
fs::write( fs::write(
dir.path().join("snapshots").join(format!("{legacy_id}.json")), dir.path().join("snapshots").join(format!("{legacy_id}.json")),

View File

@@ -142,7 +142,7 @@ Tone: short sentences, metaphor in headings, facts in telemetry panels.
1. **Vault key:** New vaults use Argon2id (19 MiB, time cost 2, parallelism 1). The salt is `keys/tessera.salt` (mode 0600) and the parameters are `keys/kdf.json`. A salt with no `kdf.json` stays PBKDF2-HMAC-SHA256, 100,000 iterations, so vaults created before Argon2id still open. The derived key is not stored. Never log the passphrase. New vaults refuse the published passphrase `dev-vault-key`. New snapshot metadata is AES-GCM ciphertext in `{id}.json.enc`. Existing plaintext `{id}.json` files still list and restore. Chunk index JSON stays plaintext. 1. **Vault key:** New vaults use Argon2id (19 MiB, time cost 2, parallelism 1). The salt is `keys/tessera.salt` (mode 0600) and the parameters are `keys/kdf.json`. A salt with no `kdf.json` stays PBKDF2-HMAC-SHA256, 100,000 iterations, so vaults created before Argon2id still open. The derived key is not stored. Never log the passphrase. New vaults refuse the published passphrase `dev-vault-key`. New snapshot metadata is AES-GCM ciphertext in `{id}.json.enc`. Existing plaintext `{id}.json` files still list and restore. Chunk index JSON stays plaintext.
2. **Hub auth:** `TESSERA_ADMIN_TOKEN` is optional and local. When it is unset, the hub logs that snapshot, orbit list/create/run, reconstitute, and pairing routes are open to loopback peers only; every other peer gets 401. When it is set, every peer, including loopback, must send `Authorization: Bearer <token>` or `X-Tessera-Admin-Token`. The compare is constant time. `/health`, OpenAPI, wormhole claim, and wormhole upload are not on this gate. The default listen address is `127.0.0.1:8787`. The canvas does not send the token, so a token-protected hub and a Docker-published port (the peer inside the container is not loopback) will 401 those routes from the page. OIDC is not implemented. 2. **Hub auth:** `TESSERA_ADMIN_TOKEN` is optional and local. When it is unset, the hub logs that snapshot, orbit list/create/run, reconstitute, and pairing routes are open to loopback peers only; every other peer gets 401. When it is set, every peer, including loopback, must send `Authorization: Bearer <token>` or `X-Tessera-Admin-Token`. The compare is constant time. `/health`, OpenAPI, wormhole claim, and wormhole upload are not on this gate. The default listen address is `127.0.0.1:8787`. The canvas does not send the token, so a token-protected hub and a Docker-published port (the peer inside the container is not loopback) will 401 those routes from the page. OIDC is not implemented.
3. **Agents:** No vault master key. After pairing, the hub issues an upload token stored in SQLite. The token survives a hub restart. Claim is an atomic update of a pairing code that has not expired. 3. **Agents:** No vault master key. After pairing, the hub issues an upload token stored in SQLite. The token survives a hub restart. Claim is an atomic update of a pairing code that has not expired.
4. **Wormhole:** Uploads require `total_bytes`. Chunks are written at `offset` into a mode `0600` `.part` file. When the recorded ranges cover the object from byte 0, the hub seals the bytes with `Vault::snapshot` (encrypted metadata), prunes decay, and deletes the `.part`. A later chunk on a sealed session is 409. `TESSERA_WORMHOLE_MTLS=1` (or `true`) starts a separate rustls listener that requires a client certificate. It needs `TESSERA_WORMHOLE_CERT`, `TESSERA_WORMHOLE_KEY`, and `TESSERA_WORMHOLE_CLIENT_CA`. `TESSERA_WORMHOLE_LISTEN` defaults to `127.0.0.1:8788`. While that listener is running, the plain HTTP upload routes return 403. An `https://` agent needs `TESSERA_WORMHOLE_CA`, `TESSERA_WORMHOLE_CLIENT_CERT`, and `TESSERA_WORMHOLE_CLIENT_KEY`. 4. **Wormhole:** A Restic agent sends missing chunks to its own authenticated, append-only REST repository and registers the finished snapshot using its paired token. The hub checks that the token belongs to the outpost assigned to that orbit. Legacy uploads require `total_bytes`. Chunks are written at `offset` into a mode `0600` `.part` file. When the ranges cover the payload, the hub stores it in Restic, applies decay, and deletes the `.part`. A later chunk on a sealed session is 409. `TESSERA_WORMHOLE_MTLS=1` (or `true`) starts a separate rustls listener that requires a client certificate. It needs `TESSERA_WORMHOLE_CERT`, `TESSERA_WORMHOLE_KEY`, and `TESSERA_WORMHOLE_CLIENT_CA`. `TESSERA_WORMHOLE_LISTEN` defaults to `127.0.0.1:8788`. While that listener is running, the plain HTTP upload and commit routes return 403. An `https://` agent needs `TESSERA_WORMHOLE_CA`, `TESSERA_WORMHOLE_CLIENT_CERT`, and `TESSERA_WORMHOLE_CLIENT_KEY`.
5. **Providers:** Filesystem and Postgres are in this release. The command provider is rejected with `command provider is outside this release; use filesystem or postgres`. Postgres parses `postgres://` or `postgresql://`, writes the password to a mode `0600` pgpass file, and passes `PGPASSFILE`, `PGHOST`, `PGPORT`, `PGUSER`, and `PGDATABASE`. The URL and password are not process arguments. 5. **Providers:** Filesystem and Postgres are in this release. The command provider is rejected with `command provider is outside this release; use filesystem or postgres`. Postgres parses `postgres://` or `postgresql://`, writes the password to a mode `0600` pgpass file, and passes `PGPASSFILE`, `PGHOST`, `PGPORT`, `PGUSER`, and `PGDATABASE`. The URL and password are not process arguments.
6. **Control plane:** SQLite (`data/tessera.db`) holds metadata, pairing codes, upload tokens, and upload ranges — no backup payloads. 6. **Control plane:** SQLite (`data/tessera.db`) holds metadata, pairing codes, upload tokens, and upload ranges — no backup payloads.
7. **Audit:** Pairing, wormhole seal, reconstitute start/complete, and decay prune are logged to `audit_log`. 7. **Audit:** Pairing, wormhole seal, reconstitute start/complete, and decay prune are logged to `audit_log`.