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:
@@ -1,9 +1,8 @@
|
||||
use crate::db::OrbitRow;
|
||||
use crate::state::HubState;
|
||||
use anyhow::{Context, Result};
|
||||
use tessera_core::config::ProviderKind;
|
||||
use tessera_core::manifest::SnapshotManifest;
|
||||
use tessera_providers::provider_from_config;
|
||||
use tessera_providers::{FilesystemConfig, PostgresProvider};
|
||||
use uuid::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>> {
|
||||
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 provider = provider_from_config(&provider_kind, &config)?;
|
||||
let capture = provider.capture().await.context("capture")?;
|
||||
|
||||
let manifest = SnapshotManifest {
|
||||
let mut manifest = SnapshotManifest {
|
||||
snapshot_id: Uuid::new_v4(),
|
||||
orbit_id: orbit.id,
|
||||
orbit_name: orbit.name.clone(),
|
||||
labels: capture.labels,
|
||||
labels: vec![orbit.provider.clone()],
|
||||
provider: orbit.provider.clone(),
|
||||
paths: vec![],
|
||||
restore_hints: capture.restore_hints,
|
||||
restore_hints: serde_json::Value::Null,
|
||||
};
|
||||
|
||||
let mut vault = state.vault.write().await;
|
||||
let snap = vault
|
||||
.snapshot(manifest, &capture.payload, orbit.dry_run)
|
||||
.context("vault snapshot")?;
|
||||
|
||||
let (payload, max_file_bytes) = match orbit.provider.as_str() {
|
||||
"filesystem" => {
|
||||
let config: FilesystemConfig = serde_json::from_value(config)?;
|
||||
manifest.paths = config.paths;
|
||||
(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 {
|
||||
None
|
||||
} 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
|
||||
.db
|
||||
.audit("decay.pruned", &format!("orbit={}", orbit.name))
|
||||
.await?;
|
||||
(!pruned.contains(&snap.id)).then_some(snap.id)
|
||||
(!pruned.contains(&snap_id)).then_some(snap_id)
|
||||
};
|
||||
|
||||
let status = if orbit.dry_run {
|
||||
@@ -84,7 +100,7 @@ async fn run_orbit_row(state: &HubState, orbit: OrbitRow) -> Result<Option<Uuid>
|
||||
} else {
|
||||
"orbit.completed"
|
||||
},
|
||||
&format!("snapshot={}", snap.id),
|
||||
&format!("snapshot={snap_id}"),
|
||||
)
|
||||
.await?;
|
||||
Ok(retained_snapshot)
|
||||
|
||||
@@ -10,8 +10,7 @@ use axum::{
|
||||
};
|
||||
use base64::Engine;
|
||||
use include_dir::{include_dir, Dir};
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::net::SocketAddr;
|
||||
use tessera_core::manifest::SnapshotManifest;
|
||||
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,
|
||||
wormhole_upload_init,
|
||||
wormhole_upload_chunk,
|
||||
wormhole_restic_commit,
|
||||
),
|
||||
components(schemas(
|
||||
SnapshotSummary,
|
||||
@@ -46,6 +46,7 @@ static WEB_DIST: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/../../web/dist");
|
||||
ClaimResponse,
|
||||
UploadInit,
|
||||
UploadChunk,
|
||||
ResticCommit,
|
||||
))
|
||||
)]
|
||||
struct ApiDoc;
|
||||
@@ -57,6 +58,8 @@ struct SnapshotSummary {
|
||||
taken_at: chrono::DateTime<chrono::Utc>,
|
||||
orbit_name: String,
|
||||
size_bytes: u64,
|
||||
stored_bytes: Option<u64>,
|
||||
new_data_chunks: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, utoipa::ToSchema)]
|
||||
@@ -107,6 +110,12 @@ struct UploadChunk {
|
||||
data_b64: String,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, utoipa::ToSchema)]
|
||||
struct ResticCommit {
|
||||
orbit_id: Uuid,
|
||||
snapshot_id: String,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize, utoipa::ToSchema)]
|
||||
struct ReconstituteStartResponse {
|
||||
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/upload/init", post(wormhole_upload_init))
|
||||
.route("/api/v1/wormhole/upload/chunk", post(wormhole_upload_chunk))
|
||||
.route(
|
||||
"/api/v1/wormhole/restic/commit",
|
||||
post(wormhole_restic_commit),
|
||||
)
|
||||
.with_state(state);
|
||||
|
||||
let api = api.route(
|
||||
@@ -169,6 +182,8 @@ async fn list_snapshots(
|
||||
taken_at: s.taken_at,
|
||||
orbit_name: s.manifest.orbit_name,
|
||||
size_bytes: s.size_bytes,
|
||||
stored_bytes: s.stored_bytes,
|
||||
new_data_chunks: s.new_data_chunks,
|
||||
})
|
||||
.collect();
|
||||
Ok(Json(out))
|
||||
@@ -278,7 +293,9 @@ async fn start_reconstitute(
|
||||
}
|
||||
{
|
||||
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 {
|
||||
return;
|
||||
}
|
||||
@@ -287,8 +304,11 @@ async fn start_reconstitute(
|
||||
}
|
||||
let dest = std::path::PathBuf::from(&target);
|
||||
let result = {
|
||||
let vault = state_bg.vault.read().await;
|
||||
vault.restore_snapshot(req.snapshot_id, &dest)
|
||||
let vault = state_bg.vault.clone().read_owned().await;
|
||||
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;
|
||||
if let Some(s) = map.get_mut(&session_id) {
|
||||
@@ -367,7 +387,10 @@ async fn pairing_start(
|
||||
&expires.to_rfc3339(),
|
||||
)
|
||||
.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)))]
|
||||
@@ -408,6 +431,15 @@ async fn wormhole_upload_init(
|
||||
Json(body): Json<UploadInit>,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
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 session_id = Uuid::new_v4();
|
||||
state
|
||||
@@ -424,7 +456,8 @@ async fn wormhole_upload_init(
|
||||
.record_range(&session_id.to_string(), 0, 0, 0)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
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 })))
|
||||
@@ -476,17 +509,11 @@ async fn wormhole_upload_chunk(
|
||||
)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
if seal {
|
||||
let mut bytes = Vec::new();
|
||||
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 {
|
||||
if !matches!(file.metadata(), Ok(metadata) if metadata.len() == session.total) {
|
||||
let _ = state.db.mark_upload_unsealed(&body.session_id.to_string());
|
||||
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, bytes).await {
|
||||
if let Err(status) = seal_upload(&state, body.session_id, session.orbit_id, file).await {
|
||||
let _ = state.db.mark_upload_unsealed(&body.session_id.to_string());
|
||||
return Err(status);
|
||||
}
|
||||
@@ -513,13 +540,7 @@ fn restrict_part(path: &std::path::Path) {
|
||||
}
|
||||
|
||||
fn verify_upload_token(state: &HubState, headers: &HeaderMap) -> Result<(), StatusCode> {
|
||||
if !state.accept_plain_upload {
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
}
|
||||
let token = headers
|
||||
.get("x-tessera-upload-token")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
let token = upload_token(state, headers)?;
|
||||
if state.upload_token_valid(token) {
|
||||
Ok(())
|
||||
} 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(
|
||||
state: &HubState,
|
||||
session_id: Uuid,
|
||||
orbit_id: Uuid,
|
||||
bytes: Vec<u8>,
|
||||
payload: File,
|
||||
) -> Result<(), StatusCode> {
|
||||
let orbits = state
|
||||
.db
|
||||
@@ -556,14 +650,30 @@ async fn seal_upload(
|
||||
paths: vec![],
|
||||
restore_hints: serde_json::json!({ "session_id": session_id }),
|
||||
};
|
||||
let snap_id = {
|
||||
let mut vault = state.vault.write().await;
|
||||
let snap = vault
|
||||
.snapshot(manifest, &bytes, false)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let _ = vault.prune_orbit_with_decay(orbit_id, &decay);
|
||||
snap.id
|
||||
};
|
||||
let vault = state.vault.clone().read_owned().await;
|
||||
if vault
|
||||
.outpost_repository_configured(orbit_id)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
{
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
}
|
||||
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
|
||||
.db
|
||||
.audit("wormhole.sealed", &format!("snapshot={snap_id}"))
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use anyhow::Result;
|
||||
use rusqlite::{params, Connection};
|
||||
use rusqlite::{params, Connection, OptionalExtension};
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use uuid::Uuid;
|
||||
@@ -197,11 +197,15 @@ impl Db {
|
||||
}
|
||||
|
||||
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 mut stmt = conn.prepare(
|
||||
"SELECT 1 FROM wormhole_tokens WHERE token = ?1 AND state = 'active' LIMIT 1",
|
||||
)?;
|
||||
Ok(stmt.query_row(params![token], |_| Ok(())).is_ok())
|
||||
Ok(conn.query_row(
|
||||
"SELECT outpost_id FROM wormhole_tokens WHERE token = ?1 AND state = 'active' LIMIT 1",
|
||||
params![token], |row| row.get(0),
|
||||
).optional()?)
|
||||
}
|
||||
|
||||
pub fn upload_session(&self, id: &str) -> Result<Option<UploadSession>> {
|
||||
|
||||
Reference in New Issue
Block a user