feat: download snapshots as real compressed archives (auth M6a)

- the download format follows the file's first bytes and manifest hints: plain SQL ->
  .sql.gz, tar -> .tar.gz, SQLite -> .sqlite.gz, hub filesystem archive -> .tessera-fs.gz,
  unknown -> .dump.gz; pg_dump -Fc stays .dump; gzip/zstd/xz/bzip2/zip pass through
- gzip is streamed (async-compression) in 64 KiB frames; no Content-Encoding, no
  Content-Length on compressed bodies, application/gzip, nosniff, no-store; HEAD is 405
- order: authenticate, find, permission, then admission (export slots and free disk), so a
  caller without permission cannot use up the slots
- the export directory, the slot and the audit end-of-download row live with the response
  body: finished, client disconnect, and a sweep of tessera-export-* at start after a crash
- audit export.requested / ready / finished / disconnected

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-14 17:27:06 +07:00
parent 228ca42801
commit e72b72111d
14 changed files with 725 additions and 41 deletions

82
Cargo.lock generated
View File

@@ -2,6 +2,12 @@
# It is not intended for manual editing.
version = 4
[[package]]
name = "adler2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "aead"
version = "0.5.2"
@@ -139,6 +145,19 @@ dependencies = [
"serde_json",
]
[[package]]
name = "async-compression"
version = "0.4.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "98ec5f6c2f8bc326c994cb9e241cc257ddaba9afa8555a43cffbb5dd86efaa37"
dependencies = [
"compression-codecs",
"compression-core",
"futures-core",
"pin-project-lite",
"tokio",
]
[[package]]
name = "async-trait"
version = "0.1.92"
@@ -449,6 +468,23 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[package]]
name = "compression-codecs"
version = "0.4.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84f840cff84d10085260e460023934d0af699e71212b09b2a41452e8bd9cda43"
dependencies = [
"compression-core",
"flate2",
"memchr",
]
[[package]]
name = "compression-core"
version = "0.4.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ebdda89edc534bf8d5dd2857562633b6495557e5846552ade994b99ed13c36a"
[[package]]
name = "const-oid"
version = "0.9.6"
@@ -507,6 +543,15 @@ dependencies = [
"libc",
]
[[package]]
name = "crc32fast"
version = "1.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64"
dependencies = [
"cfg-if",
]
[[package]]
name = "cron"
version = "0.12.1"
@@ -869,6 +914,17 @@ version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
[[package]]
name = "flate2"
version = "1.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"
dependencies = [
"crc32fast",
"miniz_oxide",
"zlib-rs",
]
[[package]]
name = "fnv"
version = "1.0.7"
@@ -1679,6 +1735,16 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]]
name = "miniz_oxide"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "mio"
version = "1.2.4"
@@ -2838,6 +2904,12 @@ dependencies = [
"rand_core 0.10.1",
]
[[package]]
name = "simd-adler32"
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
[[package]]
name = "simdutf8"
version = "0.1.5"
@@ -3083,11 +3155,14 @@ version = "0.1.0"
dependencies = [
"anyhow",
"argon2",
"async-compression",
"axum",
"base64 0.22.1",
"chrono",
"chrono-tz",
"cron",
"futures-core",
"futures-util",
"governor",
"hex",
"hmac 0.12.1",
@@ -3100,6 +3175,7 @@ dependencies = [
"rcgen",
"rsa",
"rusqlite",
"rustix",
"rustls",
"serde",
"serde_json",
@@ -3965,6 +4041,12 @@ dependencies = [
"syn 3.0.10",
]
[[package]]
name = "zlib-rs"
version = "0.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
[[package]]
name = "zmij"
version = "1.0.23"

View File

@@ -35,6 +35,9 @@ uuid.workspace = true
hex.workspace = true
sha2.workspace = true
base64 = "0.22"
async-compression = { version = "=0.4.36", default-features = false, features = ["tokio", "gzip"] }
futures-core = "0.3"
rustix = { version = "=1.1.6", default-features = false, features = ["fs", "std"] }
governor = { version = "=0.10.4", default-features = false, features = ["std"] }
openidconnect = { version = "=4.1.0", default-features = false, features = ["reqwest", "rustls-tls"] }
tempfile.workspace = true
@@ -48,6 +51,7 @@ tower = { workspace = true }
[dev-dependencies]
rcgen = "=0.13.2"
wiremock = "=0.6.5"
futures-util = "0.3"
rsa = { version = "=0.9.10", features = ["sha2"] }
hmac.workspace = true
tokio.workspace = true

View File

@@ -95,8 +95,15 @@ async fn fixture(state: &HubState, name: &str) -> Fixture {
}
async fn world() -> World {
world_with(None).await
}
async fn world_with(exports: Option<crate::exports::ExportGate>) -> World {
let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault").await.unwrap();
if let Some(gate) = exports {
state.exports = std::sync::Arc::new(gate);
}
state.sessions = SessionGate::without_operator(state.db.clone()).with_oidc("matrix-fp");
let a = fixture(&state, "orbit-a").await;
let b = fixture(&state, "orbit-b").await;
@@ -571,3 +578,25 @@ async fn display_preferences_stick_to_the_account_and_are_validated() {
*request.uri_mut() = prefs.parse().unwrap();
assert_eq!(app.oneshot(request).await.unwrap().status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn a_caller_who_may_not_download_cannot_use_up_the_export_slots() {
// One slot in total. If admission ran before the permission check, a capture-only user could starve everyone.
let w = world_with(Some(crate::exports::ExportGate::new(1, 0))).await;
let capturer = w.caller("capturer", false, &[]);
let downloader = w.caller("downloader", false, &[]);
let nobody = w.caller("nobody", false, &[]);
w.grant_role(capturer.user_id.as_ref().unwrap(), "capturer", Some(w.a.orbit));
w.grant_role(downloader.user_id.as_ref().unwrap(), "downloader", Some(w.a.orbit));
let uri = format!("/api/v1/snapshots/{}/download", w.a.snapshot);
for _ in 0..5 {
assert_eq!(w.send(&capturer, "GET", &uri, None).await.0, StatusCode::FORBIDDEN);
assert_eq!(w.send(&nobody, "GET", &uri, None).await.0, StatusCode::NOT_FOUND);
assert_eq!(w.send(&anonymous(), "GET", &uri, None).await.0, StatusCode::UNAUTHORIZED);
}
assert_eq!(w.send(&downloader, "GET", &uri, None).await.0, StatusCode::OK, "the slot was never taken by the refused callers");
let audited: i64 = rusqlite::Connection::open(w._dir.path().join("tessera.db")).unwrap()
.query_row("SELECT COUNT(*) FROM audit_events WHERE action='export.requested'", [], |r| r.get(0)).unwrap();
assert_eq!(audited, 1, "only the permitted request counts as an export request");
}

View File

@@ -1,11 +1,17 @@
use super::routes::{admin_write, authenticate};
use crate::auth::Permission;
use crate::auth::{AuditAction, AuditOutcome, AuditResource, Permission};
use crate::exports::{self, Guarded, Refused, EXPORT_PREFIX};
use async_compression::tokio::bufread::GzipEncoder;
use axum::body::Bytes;
use futures_core::Stream;
use std::pin::Pin;
use tokio::io::{AsyncReadExt, AsyncSeekExt};
use crate::state::HubState;
use axum::{
body::Body,
extract::{ConnectInfo, Path, State},
http::{header, HeaderMap, StatusCode},
response::{IntoResponse, Response},
http::{header, HeaderMap, HeaderValue, Method, StatusCode},
response::Response,
routing::get,
Router,
};
@@ -13,18 +19,29 @@ use std::net::SocketAddr;
use tokio_util::io::ReaderStream;
use uuid::Uuid;
/// Frames sent to the client: small and bounded, whatever the size of the snapshot.
const CHUNK: usize = 64 * 1024;
pub(super) fn routes() -> Router<HubState> {
Router::new()
.route("/api/v1/snapshots/:id", axum::routing::delete(delete))
.route("/api/v1/snapshots/:id/download", get(download))
}
/// Download a snapshot as a file. The order matters: authenticate, find the snapshot, check the
/// permission on its orbit, and only then admit the export, so a caller who may not download can
/// never use up the export slots or disk.
async fn download(
method: Method,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<Response, StatusCode> {
// Axum would answer HEAD with the GET handler, i.e. run a whole export for nothing.
if method == Method::HEAD {
return Err(StatusCode::METHOD_NOT_ALLOWED);
}
let actor = authenticate(&state, peer, &headers, false)?;
let snapshot = state
.vault
@@ -35,38 +52,55 @@ async fn download(
.filter(|snapshot| snapshot.manifest.provider != "legacy-history")
.ok_or(StatusCode::NOT_FOUND)?;
super::gate::scoped(&state, &actor, Permission::SnapshotDownload, snapshot.manifest.orbit_id)?;
let staging = tempfile::tempdir_in(&state.data_dir).map_err(internal)?;
let path = staging.path().join("download");
let size = state
.export_snapshot(id, path.clone())
.await
.map_err(internal)?;
let file = tokio::fs::File::open(path).await.map_err(internal)?;
let extension = match snapshot
.manifest
.restore_hints
.get("format")
.and_then(|format| format.as_str())
{
Some("plain") => "sql",
Some("sql_gzip") => "sql.gz",
Some("sqlite") => "sqlite",
Some("tar") => "tar",
_ => "dump",
let audit = |action: AuditAction, outcome: AuditOutcome| {
state.db.audit_event(&actor.principal, action, AuditResource::Snapshot(id), outcome, actor.request_id).map_err(internal)
};
Ok((
[
(header::CONTENT_TYPE, "application/octet-stream".to_owned()),
(
audit(AuditAction::ExportRequested, AuditOutcome::Allowed)?;
let permit = match state.exports.admit(&state.data_dir, snapshot.size_bytes) {
Ok(permit) => permit,
Err(refused) => {
audit(AuditAction::ExportRequested, AuditOutcome::Failed)?;
return Err(match refused {
Refused::Busy => StatusCode::TOO_MANY_REQUESTS,
Refused::NoSpace => StatusCode::INSUFFICIENT_STORAGE,
});
}
};
let staging = tempfile::Builder::new().prefix(EXPORT_PREFIX).tempdir_in(&state.data_dir).map_err(internal)?;
let path = staging.path().join("download");
state.export_snapshot(id, path.clone()).await.map_err(internal)?;
let mut file = tokio::fs::File::open(&path).await.map_err(internal)?;
let size = file.metadata().await.map_err(internal)?.len();
let mut head = vec![0u8; 512];
let read = file.read(&mut head).await.map_err(internal)?;
head.truncate(read);
file.seek(std::io::SeekFrom::Start(0)).await.map_err(internal)?;
let plan = exports::plan(&snapshot.manifest.restore_hints, &head);
audit(AuditAction::ExportReady, AuditOutcome::Succeeded)?;
let reader = tokio::io::BufReader::with_capacity(CHUNK, file);
let stream: Pin<Box<dyn Stream<Item = std::io::Result<Bytes>> + Send>> = if plan.compress {
Box::pin(ReaderStream::with_capacity(GzipEncoder::new(reader), CHUNK))
} else {
Box::pin(ReaderStream::with_capacity(reader, CHUNK))
};
let body = Guarded::new(stream, permit, staging, state.db.clone(), actor.principal.clone(), id, actor.request_id);
let mut response = Response::new(Body::from_stream(body));
let headers = response.headers_mut();
headers.insert(header::CONTENT_TYPE, HeaderValue::from_static(plan.content_type));
headers.insert(
header::CONTENT_DISPOSITION,
format!("attachment; filename=\"{id}.{extension}\""),
),
(header::CONTENT_LENGTH, size.to_string()),
(header::CACHE_CONTROL, "no-store".to_owned()),
],
Body::from_stream(ReaderStream::new(file)),
)
.into_response())
HeaderValue::from_str(&format!("attachment; filename=\"{id}.{}\"", plan.extension)).map_err(internal)?,
);
headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
headers.insert(header::X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));
// The exact size is only known when the bytes are sent as they are. Never `Content-Encoding`: this
// is the file itself, and a browser must not unpack it.
if !plan.compress {
headers.insert(header::CONTENT_LENGTH, HeaderValue::from(size));
}
Ok(response)
}
async fn delete(

View File

@@ -0,0 +1,222 @@
//! Snapshot downloads over HTTP: formats, headers, streaming, cleanup, audit and limits.
use crate::exports::ExportGate;
use crate::state::HubState;
use async_compression::tokio::bufread::{GzipDecoder, GzipEncoder};
use axum::body::{to_bytes, Body};
use axum::extract::ConnectInfo;
use axum::http::{header, Method, Request, Response, StatusCode};
use futures_util::StreamExt;
use sha2::{Digest, Sha256};
use std::net::SocketAddr;
use tessera_core::manifest::SnapshotManifest;
use tokio::io::AsyncReadExt;
use tower::ServiceExt;
use uuid::Uuid;
const ADMIN: &str = "synthetic-admin-token";
struct Harness {
app: axum::Router,
state: HubState,
dir: tempfile::TempDir,
}
async fn harness_with(gate: Option<ExportGate>) -> Harness {
let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault").await.unwrap();
state.admin.token = Some(ADMIN.into());
if let Some(gate) = gate {
state.exports = std::sync::Arc::new(gate);
}
let app = crate::api::router(state.clone());
Harness { app, state, dir }
}
async fn harness() -> Harness {
harness_with(None).await
}
impl Harness {
async fn snapshot(&self, hints: serde_json::Value, payload: &[u8]) -> Uuid {
let id = Uuid::new_v4();
let manifest = SnapshotManifest {
snapshot_id: id,
orbit_id: Uuid::new_v4(),
orbit_name: "fixture".into(),
labels: vec![],
provider: "postgres".into(),
paths: vec![],
restore_hints: hints,
};
self.state.vault.write().await.snapshot(manifest, payload, false).unwrap();
id
}
async fn download(&self, id: Uuid, method: Method) -> Response<Body> {
let request = Request::builder()
.method(method)
.uri(format!("/api/v1/snapshots/{id}/download"))
.extension(ConnectInfo("127.0.0.1:4000".parse::<SocketAddr>().unwrap()))
.header("x-tessera-admin-token", ADMIN)
.body(Body::empty())
.unwrap();
self.app.clone().oneshot(request).await.unwrap()
}
fn export_dirs(&self) -> Vec<String> {
std::fs::read_dir(self.dir.path())
.unwrap()
.flatten()
.filter_map(|e| e.file_name().into_string().ok())
.filter(|name| name.starts_with(crate::exports::EXPORT_PREFIX))
.collect()
}
fn audit(&self, snapshot: Uuid) -> Vec<(String, String)> {
let conn = rusqlite::Connection::open(self.dir.path().join("tessera.db")).unwrap();
let mut stmt = conn
.prepare("SELECT action, outcome FROM audit_events WHERE resource_type='snapshot' AND resource_id=?1 ORDER BY id")
.unwrap();
stmt.query_map([snapshot.to_string()], |r| Ok((r.get(0)?, r.get(1)?))).unwrap().collect::<Result<_, _>>().unwrap()
}
}
async fn gunzip(bytes: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
GzipDecoder::new(tokio::io::BufReader::new(bytes)).read_to_end(&mut out).await.unwrap();
out
}
async fn gzip(bytes: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
GzipEncoder::new(tokio::io::BufReader::new(bytes)).read_to_end(&mut out).await.unwrap();
out
}
fn ustar(extra: &[u8]) -> Vec<u8> {
let mut block = vec![0u8; 512];
block[257..262].copy_from_slice(b"ustar");
block.extend_from_slice(extra);
block
}
#[tokio::test]
async fn each_kind_of_snapshot_downloads_with_the_right_format_and_honest_headers() {
let h = harness().await;
let already_gzip = gzip(b"SELECT 1;\n").await;
let pg_custom = [b"PGDMP\x01\x0e\x00".as_slice(), &[7u8; 300]].concat();
let cases: Vec<(&str, serde_json::Value, Vec<u8>, &str, bool)> = vec![
("postgres plain", serde_json::json!({"engine": "postgres", "format": "plain"}), b"CREATE TABLE t (x int);\n".repeat(200), "sql.gz", true),
("mysql plain", serde_json::json!({"engine": "mysql", "format": "plain"}), b"INSERT INTO t VALUES (1);\n".repeat(200), "sql.gz", true),
("postgres custom", serde_json::json!({"format": "custom"}), pg_custom, "dump", false),
("tar by hint", serde_json::json!({"format": "tar"}), ustar(b"file contents"), "tar.gz", true),
("tar with no hint (legacy restic)", serde_json::Value::Null, ustar(b"file contents"), "tar.gz", true),
("hub filesystem archive", serde_json::json!({"format": "tessera-fs-v1", "paths": []}), b"k\0\x02\0\0\0\0\0\0\0ab".to_vec(), "tessera-fs.gz", true),
("sqlite", serde_json::json!({"format": "sqlite"}), [b"SQLite format 3\0".as_slice(), &[0u8; 200]].concat(), "sqlite.gz", true),
("sql already gzip", serde_json::json!({"format": "sql_gzip"}), already_gzip.clone(), "sql.gz", false),
("labelled plain but gzip", serde_json::json!({"format": "plain"}), already_gzip, "sql.gz", false),
("no hints at all", serde_json::Value::Null, b"opaque".repeat(100), "dump.gz", true),
];
for (name, hints, payload, extension, compressed) in cases {
let id = h.snapshot(hints, &payload).await;
let response = h.download(id, Method::GET).await;
assert_eq!(response.status(), StatusCode::OK, "{name}");
let headers = response.headers().clone();
assert!(headers.get(header::CONTENT_ENCODING).is_none(), "{name}: the file must not be content-encoded");
assert_eq!(headers[header::CACHE_CONTROL], "no-store", "{name}");
assert_eq!(headers[header::X_CONTENT_TYPE_OPTIONS], "nosniff", "{name}");
assert_eq!(headers[header::CONTENT_DISPOSITION], format!("attachment; filename=\"{id}.{extension}\""), "{name}");
let content_type = if extension.ends_with("gz") { "application/gzip" } else { "application/octet-stream" };
assert_eq!(headers[header::CONTENT_TYPE], content_type, "{name}");
let body = to_bytes(response.into_body(), 1 << 26).await.unwrap().to_vec();
if compressed {
assert!(headers.get(header::CONTENT_LENGTH).is_none(), "{name}: the compressed size is not known up front");
assert_eq!(&body[..2], &[0x1f, 0x8b], "{name}: a real gzip stream");
assert_eq!(gunzip(&body).await, payload, "{name}: decompresses to exactly the original bytes");
} else {
assert_eq!(body, payload, "{name}: sent untouched");
assert_eq!(headers[header::CONTENT_LENGTH], payload.len().to_string(), "{name}: exact length");
}
}
assert!(h.export_dirs().is_empty(), "nothing is left behind after the downloads");
}
#[tokio::test]
async fn a_large_snapshot_is_streamed_in_small_frames_and_arrives_intact() {
let h = harness().await;
let line = b"INSERT INTO events VALUES (1, 'a fairly ordinary row of text');\n";
let payload: Vec<u8> = line.iter().copied().cycle().take(24 * 1024 * 1024).collect();
let id = h.snapshot(serde_json::json!({"format": "plain"}), &payload).await;
let response = h.download(id, Method::GET).await;
let mut stream = response.into_body().into_data_stream();
let (mut compressed, mut frames, mut largest) = (Vec::new(), 0, 0);
while let Some(frame) = stream.next().await {
let frame = frame.unwrap();
frames += 1;
largest = largest.max(frame.len());
compressed.extend_from_slice(&frame);
}
assert!(frames > 5 && largest <= 256 * 1024, "{frames} frames, largest {largest} bytes");
let restored = gunzip(&compressed).await;
assert_eq!((restored.len(), Sha256::digest(&restored)), (payload.len(), Sha256::digest(&payload)));
assert!(compressed.len() < payload.len() / 10, "the stream really is compressed");
}
#[tokio::test]
async fn the_audit_trail_and_cleanup_cover_a_finished_and_an_abandoned_download() {
let h = harness().await;
let finished = h.snapshot(serde_json::json!({"format": "plain"}), &b"SELECT 1;\n".repeat(50_000)).await;
let body = to_bytes(h.download(finished, Method::GET).await.into_body(), 1 << 26).await.unwrap();
assert!(!body.is_empty());
let expected = |last: (&str, &str)| {
vec![("export.requested".to_string(), "allowed".to_string()), ("export.ready".into(), "succeeded".into()), (last.0.to_string(), last.1.to_string())]
};
assert_eq!(h.audit(finished), expected(("export.finished", "succeeded")));
assert!(h.export_dirs().is_empty());
// The client reads one frame and goes away.
let abandoned = h.snapshot(serde_json::json!({"format": "plain"}), &b"SELECT 2;\n".repeat(2_000_000)).await;
let response = h.download(abandoned, Method::GET).await;
assert_eq!(h.export_dirs().len(), 1, "the export exists while the body is alive");
let mut stream = response.into_body().into_data_stream();
stream.next().await.unwrap().unwrap();
drop(stream);
assert_eq!(h.audit(abandoned), expected(("export.disconnected", "failed")));
assert!(h.export_dirs().is_empty(), "the export is deleted when the client disconnects");
}
#[tokio::test]
async fn only_one_export_runs_when_the_limit_is_one_and_a_refused_request_leaks_nothing() {
let h = harness_with(Some(ExportGate::new(1, 0))).await;
let id = h.snapshot(serde_json::json!({"format": "plain"}), &b"SELECT 1;\n".repeat(10_000)).await;
let first = h.download(id, Method::GET).await;
assert_eq!(first.status(), StatusCode::OK);
let started = std::time::Instant::now();
let second = h.download(id, Method::GET).await;
assert_eq!(second.status(), StatusCode::TOO_MANY_REQUESTS);
assert!(started.elapsed() < std::time::Duration::from_secs(1), "refused at once, not queued");
assert_eq!(h.export_dirs().len(), 1, "the refused request wrote nothing");
drop(first);
let third = h.download(id, Method::GET).await;
assert_eq!(third.status(), StatusCode::OK, "the slot returns when the first download ends");
let audited = h.audit(id);
assert!(audited.contains(&("export.requested".to_string(), "failed".to_string())), "{audited:?}");
}
#[tokio::test]
async fn an_export_that_would_not_fit_on_the_disk_is_refused_before_anything_is_written() {
let h = harness_with(Some(ExportGate::new(2, u64::MAX / 2))).await;
let id = h.snapshot(serde_json::json!({"format": "plain"}), b"SELECT 1;\n").await;
assert_eq!(h.download(id, Method::GET).await.status(), StatusCode::INSUFFICIENT_STORAGE);
assert!(h.export_dirs().is_empty());
}
#[tokio::test]
async fn head_requests_do_not_run_an_export() {
let h = harness().await;
let id = h.snapshot(serde_json::json!({"format": "plain"}), b"SELECT 1;\n").await;
let response = h.download(id, Method::HEAD).await;
assert_eq!(response.status(), StatusCode::METHOD_NOT_ALLOWED);
assert!(h.export_dirs().is_empty());
assert!(h.audit(id).is_empty(), "no export was requested");
}

View File

@@ -15,6 +15,8 @@ mod oidc_tests;
mod credentials_tests;
#[cfg(test)]
mod access_tests;
#[cfg(test)]
mod export_tests;
pub use orbit::run_orbit_internal;
pub use routes::router;

View File

@@ -38,6 +38,10 @@ pub enum AuditAction {
GrantDelete,
UserState,
SessionsRevoke,
ExportRequested,
ExportReady,
ExportFinished,
ExportDisconnected,
}
impl AuditAction {
@@ -55,6 +59,10 @@ impl AuditAction {
Self::GrantDelete => "access.grant_delete",
Self::UserState => "access.user_state",
Self::SessionsRevoke => "access.sessions_revoke",
Self::ExportRequested => "export.requested",
Self::ExportReady => "export.ready",
Self::ExportFinished => "export.finished",
Self::ExportDisconnected => "export.disconnected",
}
}
}
@@ -85,6 +93,7 @@ pub enum AuditResource {
UploadSession(Uuid),
Grant(Uuid),
User(Uuid),
Snapshot(Uuid),
}
impl AuditResource {
@@ -97,6 +106,7 @@ impl AuditResource {
Self::UploadSession(id) => ("upload_session", Some(id.to_string())),
Self::Grant(id) => ("grant", Some(id.to_string())),
Self::User(id) => ("user", Some(id.to_string())),
Self::Snapshot(id) => ("snapshot", Some(id.to_string())),
}
}
}

View File

@@ -0,0 +1,259 @@
//! Snapshot downloads: what the file is, how it is compressed, and the limits around producing it.
//!
//! The export is first written to a private directory by the vault, then streamed to the client,
//! compressed on the fly when it is not already a compressed format. The decision uses both the
//! manifest hints and the first bytes of the real file; the bytes win, because hints are written by
//! many producers and one of them (a legacy Restic commit) writes none.
use crate::auth::{AuditAction, AuditOutcome, AuditResource, Principal};
use crate::db::Db;
use axum::body::Bytes;
use futures_core::Stream;
use std::io;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
use uuid::Uuid;
pub const EXPORT_PREFIX: &str = "tessera-export-";
const DEFAULT_CONCURRENCY: usize = 2;
const DEFAULT_MARGIN: u64 = 512 * 1024 * 1024;
/// How a snapshot is delivered.
#[derive(Debug, PartialEq, Eq)]
pub struct Plan {
/// File extension of the download, without the dot.
pub extension: &'static str,
/// Compress with gzip while streaming. Formats that are already compressed pass through unchanged.
pub compress: bool,
pub content_type: &'static str,
}
fn plan_of(extension: &'static str, compress: bool) -> Plan {
let gz = extension.ends_with("gz");
Plan { extension, compress, content_type: if gz || compress { "application/gzip" } else { "application/octet-stream" } }
}
/// Decide the delivery from the manifest `restore_hints` and the first bytes of the exported file.
pub fn plan(hints: &serde_json::Value, head: &[u8]) -> Plan {
let format = hints.get("format").and_then(|f| f.as_str()).unwrap_or("");
let starts = |magic: &[u8]| head.starts_with(magic);
// Already compressed or a self-compressing dump: send the bytes untouched.
if starts(&[0x1f, 0x8b]) {
let ext = match format {
"tar" => "tar.gz",
"plain" | "sql_gzip" => "sql.gz",
_ => "gz",
};
return plan_of(ext, false);
}
if starts(b"PGDMP") {
return plan_of("dump", false); // pg_dump -Fc compresses its own data
}
if starts(&[0x28, 0xb5, 0x2f, 0xfd]) {
return plan_of("zst", false);
}
if starts(&[0xfd, b'7', b'z', b'X', b'Z', 0x00]) {
return plan_of("xz", false);
}
if starts(b"BZh") {
return plan_of("bz2", false);
}
if starts(b"PK\x03\x04") {
return plan_of("zip", false);
}
// Compressible content.
if starts(b"SQLite format 3\0") || format == "sqlite" {
return plan_of("sqlite.gz", true);
}
if head.len() > 262 && &head[257..262] == b"ustar" || format == "tar" {
return plan_of("tar.gz", true);
}
match format {
"plain" | "sql" => plan_of("sql.gz", true),
"tessera-fs-v1" => plan_of("tessera-fs.gz", true),
_ => plan_of("dump.gz", true),
}
}
/// Limits on how many exports run at once and how much disk one may need.
pub struct ExportGate {
permits: Arc<Semaphore>,
/// Free space that must remain after the export has been written.
min_free: u64,
}
pub enum Refused {
/// Too many exports are already running.
Busy,
/// Not enough free disk for this snapshot.
NoSpace,
}
impl ExportGate {
pub fn new(concurrency: usize, min_free: u64) -> Self {
Self { permits: Arc::new(Semaphore::new(concurrency)), min_free }
}
pub fn from_env() -> Self {
let number = |name: &str| std::env::var(name).ok().and_then(|v| v.trim().parse::<u64>().ok());
Self::new(
number("TESSERA_EXPORT_CONCURRENCY").map_or(DEFAULT_CONCURRENCY, |n| n.clamp(1, 64) as usize),
number("TESSERA_EXPORT_MIN_FREE_BYTES").unwrap_or(DEFAULT_MARGIN),
)
}
/// Admit one export of about `size` bytes into `dir`. The permit lives as long as the response body.
pub fn admit(&self, dir: &std::path::Path, size: u64) -> Result<OwnedSemaphorePermit, Refused> {
let permit = self.permits.clone().try_acquire_owned().map_err(|_| Refused::Busy)?;
match free_bytes(dir) {
// `size` is the snapshot's recorded size; when a producer did not record one it is 0 and the margin alone applies.
Some(free) if free < size.saturating_add(self.min_free) => Err(Refused::NoSpace),
_ => Ok(permit),
}
}
}
#[cfg(unix)]
fn free_bytes(dir: &std::path::Path) -> Option<u64> {
let stat = rustix::fs::statvfs(dir).ok()?;
Some(stat.f_bavail.saturating_mul(stat.f_frsize))
}
#[cfg(not(unix))]
fn free_bytes(_dir: &std::path::Path) -> Option<u64> {
None
}
/// Remove export directories a crash left behind. Only directories with our own prefix, only directly
/// inside `data_dir`; run before the listener starts. Older `.tmp*` leftovers are deliberately not touched.
pub fn sweep_stale(data_dir: &std::path::Path) -> usize {
let Ok(entries) = std::fs::read_dir(data_dir) else { return 0 };
let mut removed = 0;
for entry in entries.flatten() {
let name = entry.file_name();
let is_ours = name.to_str().is_some_and(|n| n.starts_with(EXPORT_PREFIX));
let is_dir = entry.file_type().is_ok_and(|t| t.is_dir());
if is_ours && is_dir && std::fs::remove_dir_all(entry.path()).is_ok() {
removed += 1;
}
}
removed
}
/// Owns everything an in-flight download needs and reports how it ended. Dropping it (the stream ended,
/// the client went away, or the response was discarded) releases the permit and deletes the export.
pub struct Guarded<S> {
inner: Pin<Box<S>>,
_permit: OwnedSemaphorePermit,
_dir: tempfile::TempDir,
db: Db,
principal: Principal,
snapshot: Uuid,
request: Uuid,
completed: bool,
failed: bool,
}
impl<S> Guarded<S> {
pub fn new(inner: S, permit: OwnedSemaphorePermit, dir: tempfile::TempDir, db: Db, principal: Principal, snapshot: Uuid, request: Uuid) -> Self {
Self { inner: Box::pin(inner), _permit: permit, _dir: dir, db, principal, snapshot, request, completed: false, failed: false }
}
}
impl<S: Stream<Item = io::Result<Bytes>>> Stream for Guarded<S> {
type Item = io::Result<Bytes>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let polled = self.inner.as_mut().poll_next(cx);
match &polled {
Poll::Ready(None) => self.completed = true,
Poll::Ready(Some(Err(_))) => self.failed = true,
_ => {}
}
polled
}
}
impl<S> Drop for Guarded<S> {
fn drop(&mut self) {
// "Finished" means the body was handed to the connection, not that a file reached a disk.
let (action, outcome) = if self.completed && !self.failed {
(AuditAction::ExportFinished, AuditOutcome::Succeeded)
} else {
(AuditAction::ExportDisconnected, AuditOutcome::Failed)
};
if let Err(error) = self.db.audit_event(&self.principal, action, AuditResource::Snapshot(self.snapshot), outcome, self.request) {
tracing::error!("could not audit the end of an export: {error:#}");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn ustar() -> Vec<u8> {
let mut block = vec![0u8; 512];
block[257..262].copy_from_slice(b"ustar");
block
}
#[test]
fn every_producer_of_a_snapshot_gets_the_right_delivery() {
let gz = [0x1f, 0x8b, 8, 0];
let cases: Vec<(&str, serde_json::Value, Vec<u8>, &str, bool)> = vec![
("hub database orbit, postgres plain SQL", json!({"engine": "postgres", "format": "plain"}), b"-- PostgreSQL dump\n".to_vec(), "sql.gz", true),
("hub database orbit, mysql plain SQL", json!({"engine": "mysql", "format": "plain"}), b"-- MySQL dump\n".to_vec(), "sql.gz", true),
("agent capture, postgres custom", json!({"engine": "postgres", "format": "custom", "sha256": "x"}), b"PGDMP\x01\x0e\x00".to_vec(), "dump", false),
("hub postgres provider, custom", json!({"format": "custom", "restore_command_hint": "pg_restore"}), b"PGDMP\x01".to_vec(), "dump", false),
("restic filesystem, tar by hint", json!({"format": "tar"}), ustar(), "tar.gz", true),
("restic filesystem snapshot with no hint but a tar payload", serde_json::Value::Null, ustar(), "tar.gz", true),
("hub filesystem orbit archive", json!({"paths": [], "format": "tessera-fs-v1"}), b"a/b\0\x03\0\0\0\0\0\0\0xyz".to_vec(), "tessera-fs.gz", true),
("sqlite database", json!({"format": "sqlite"}), b"SQLite format 3\0....".to_vec(), "sqlite.gz", true),
("SQL that is already gzip", json!({"format": "sql_gzip"}), gz.to_vec(), "sql.gz", false),
("hint says plain SQL but the file is gzip: no double compression", json!({"format": "plain"}), gz.to_vec(), "sql.gz", false),
("a tar that is already gzip", json!({"format": "tar"}), gz.to_vec(), "tar.gz", false),
("zstd payload", serde_json::Value::Null, vec![0x28, 0xb5, 0x2f, 0xfd, 0], "zst", false),
("legacy wormhole commit with no hints", serde_json::Value::Null, b"opaque payload".to_vec(), "dump.gz", true),
("demo seed", json!({"demo": true}), b"demo".to_vec(), "dump.gz", true),
];
for (name, hints, head, extension, compress) in cases {
let got = plan(&hints, &head);
assert_eq!((got.extension, got.compress), (extension, compress), "{name}");
let ct = if extension.ends_with("gz") { "application/gzip" } else { "application/octet-stream" };
assert_eq!(got.content_type, ct, "{name}");
}
}
#[test]
fn sweeping_removes_only_our_own_export_directories() {
let dir = tempfile::tempdir().unwrap();
let make = |name: &str| std::fs::create_dir(dir.path().join(name)).unwrap();
make("tessera-export-aaaa");
make("tessera-export-bbbb");
make("vault");
make(".tmpXYZ");
std::fs::write(dir.path().join("tessera-export-file"), b"a file, not a directory").unwrap();
std::fs::create_dir_all(dir.path().join("vault/tessera-export-nested")).unwrap();
assert_eq!(sweep_stale(dir.path()), 2);
for kept in ["vault", ".tmpXYZ", "tessera-export-file", "vault/tessera-export-nested"] {
assert!(dir.path().join(kept).exists(), "{kept} must survive");
}
assert!(!dir.path().join("tessera-export-aaaa").exists());
}
#[test]
fn admission_is_bounded_by_concurrency_and_by_free_disk() {
let dir = tempfile::tempdir().unwrap();
let gate = ExportGate::new(1, 0);
let held = gate.admit(dir.path(), 1).ok().expect("first export is admitted");
assert!(matches!(gate.admit(dir.path(), 1), Err(Refused::Busy)), "second export is refused at once");
drop(held);
assert!(gate.admit(dir.path(), 1).is_ok(), "the permit comes back when the first ends");
let greedy = ExportGate::new(4, u64::MAX / 2);
assert!(matches!(greedy.admit(dir.path(), 10), Err(Refused::NoSpace)));
assert!(matches!(ExportGate::new(4, 0).admit(dir.path(), u64::MAX), Err(Refused::NoSpace)), "a snapshot bigger than the disk");
}
}

View File

@@ -2,6 +2,7 @@ mod admin;
mod auth;
mod api;
mod db;
mod exports;
mod limits;
mod mtls;
mod oidc;
@@ -47,6 +48,11 @@ async fn main() -> Result<()> {
}
let mut state = HubState::bootstrap(&data_dir, &vault_pass).await?;
// Exports a crash left half-written; nothing is serving yet, so nothing can be using them.
let swept = exports::sweep_stale(std::path::Path::new(&data_dir));
if swept > 0 {
tracing::info!("removed {swept} unfinished snapshot export(s) from a previous run");
}
anyhow::ensure!(state.sessions.enabled() || state.admin.token_active() || state.admin.local_development,
"configure a named emergency operator and/or TESSERA_ADMIN_TOKEN; anonymous local access requires explicit TESSERA_LOCAL_DEVELOPMENT=true");

View File

@@ -42,6 +42,7 @@ pub struct HubState {
pub sessions: SessionGate,
pub oidc: Option<std::sync::Arc<crate::oidc::OidcProvider>>,
pub limits: Arc<crate::limits::Limits>,
pub exports: Arc<crate::exports::ExportGate>,
pub wormhole_mtls: bool,
/// Token uploads are accepted on this listener. Plain HTTP turns this off
/// when wormhole mTLS is required, so those routes are not a bypass.
@@ -75,6 +76,7 @@ impl HubState {
admin,
sessions: SessionGate::from_env(db.clone(), oidc_config.as_ref().map(|c| c.fingerprint()))?,
limits: Arc::new(crate::limits::Limits::from_env()?),
exports: Arc::new(crate::exports::ExportGate::from_env()),
oidc: oidc_config.map(|c| crate::oidc::OidcProvider::new(c).map(Arc::new)).transpose()?,
wormhole_mtls: false,
accept_plain_upload: true,

View File

@@ -290,3 +290,32 @@ administrators and cannot be delegated.
a person to another browser. Accounts without a user row (the shared admin token, local development) keep the
choice in the browser only.
## Downloading a snapshot
`GET /api/v1/snapshots/{id}/download` (needs `snapshot.download` on the orbit) returns the snapshot as a file.
The format follows what the snapshot really contains, judged from its first bytes and its manifest:
| Snapshot | Downloaded as |
| --- | --- |
| PostgreSQL or MySQL plain SQL | `.sql.gz` (gzip, compressed while streaming) |
| Filesystem backup (tar) | `.tar.gz` |
| SQLite | `.sqlite.gz` |
| Hub filesystem archive | `.tessera-fs.gz` |
| PostgreSQL custom dump (`pg_dump -Fc`) | `.dump`, unchanged: it already compresses its own data |
| Anything already gzip, zstd, xz, bzip2 or zip | unchanged, never compressed twice |
| Unknown content | `.dump.gz` |
The response is the file itself: there is no `Content-Encoding`, so a browser saves the `.gz` as it is; unpack
it with `gunzip`. `Content-Length` is only sent when the bytes are passed through unchanged. `HEAD` answers `405`.
The vault first writes the export to a private `tessera-export-*` directory inside the data directory, then streams it
in small frames (the hub does not hold the archive in memory while compressing). A chunk-stored snapshot is still read
from the vault in one piece when it is exported, so a very large snapshot of that kind needs that much memory once.
The directory is deleted when the download ends, when the client disconnects, and at the next start if the hub crashed.
Limits: `TESSERA_EXPORT_CONCURRENCY` exports at once (default 2; more get `429` at once) and
`TESSERA_EXPORT_MIN_FREE_BYTES` of free disk that must remain after the export (default 512 MiB; otherwise `507`).
The snapshot's recorded size is added to that margin; if a producer did not record one, only the margin applies.
The audit log records `export.requested`, `export.ready` and then `export.finished` or `export.disconnected` for each
download. "Finished" means the body was handed to the connection, not that a file reached the person's disk.

View File

@@ -32,7 +32,7 @@ admin/browser. Semua status/data job hanya di scope owner/admin yang berizin.
| /api/v1/operator/login | POST | public | — | emergency account | cookie opaque dan CSRF; limiter, no-store |
| /api/v1/snapshots | GET | human | snapshot.read | orbit | metadata aman terfilter |
| /api/v1/snapshots/:id | DELETE | human | snapshot.delete | snapshot→orbit | tidak ada; cek pin |
| /api/v1/snapshots/:id/download | GET | human | snapshot.download | snapshot→orbit | raw archive eksplisit, no-store |
| /api/v1/snapshots/:id/download | GET | human | snapshot.download | snapshot→orbit | arsip mentah: gzip atau format yang sudah terkompresi (`.sql.gz`, `.tar.gz`, `.sqlite.gz`, `.dump`), tanpa Content-Encoding, no-store, nosniff; HEAD 405; slot ekspor dan disk dibatasi |
| /api/v1/orbits | GET | human | orbit.read | orbit | metadata tanpa provider_config |
| /api/v1/orbits | POST | human | orbit.manage | admin | metadata aman |
| /api/v1/orbits/:id/retention | PUT | human | retention.manage | orbit | tidak ada |

View File

@@ -80,12 +80,14 @@ Belum ada / batas: principal `service` bergrant (hanya user dan grup; token admi
Desain rinci lama: `archive/auth-self-service-plan.md` bagian 7–9. M6 menyentuh restore ke database sungguhan, jadi dipecah menjadi empat sub-milestone yang masing-masing bisa dirilis dan diuji sendiri.
### M6a — Download terkompresi untuk developer
Hasil: `GET /snapshots/:id/download` mengembalikan arsip yang memang terkompresi, tanpa menahan dump besar di memori.
- SQL polos → `.sql.gz`, tar filesystem → `.tar.gz`, SQLite → `.sqlite.gz`; PostgreSQL custom (`-Fc`, sudah terkompresi) tetap `.dump`; `sql_gzip` yang sudah gzip tidak dikompresi dua kali. Format ditentukan dari metadata snapshot, bukan ekstensi. `async-compression` (tokio, gzip) di atas `ReaderStream`; `CompressionLayer` bukan pengganti.
- Batas concurrency ekspor (semaphore) dan kuota disk, pin snapshot selama ekspor, direktori privat yang dibersihkan saat sukses, gagal, klien putus, dan restart. `Content-Length` hanya bila ukuran gzip sudah diketahui.
- Audit `export requested/ready/finished/disconnected` per snapshot dan principal.
Selesai bila: magic gzip dan hasil dekompresi sama persis dengan byte asli, memori terbatas pada file besar, klien putus membersihkan sisa, ekspor ke-N+1 ditolak cepat, audit lengkap.
### M6a — Download terkompresi untuk developer (selesai di working tree, belum di-commit, 14 November 2026)
Hasil: `GET /snapshots/:id/download` mengirim arsip yang memang terkompresi, bukan dump mentah.
- Format ditentukan dari isi file (magic byte) dan metadata, bukan dari nama: SQL polos jadi `.sql.gz`, tar jadi `.tar.gz`, SQLite jadi `.sqlite.gz`, arsip filesystem hub jadi `.tessera-fs.gz`, konten tak dikenal jadi `.dump.gz`; `pg_dump -Fc` tetap `.dump`; gzip/zstd/xz/bzip2/zip tidak dikompresi dua kali (isi menang atas label). Tabel diturunkan dari setiap produsen manifest yang ada (agen, provider hub, restic filesystem, wormhole lama, SQLite lama, demo). Konsumen endpoint ini hanya tautan unduh di UI; agen dan CLI tidak memakainya.
- Header jujur: tanpa `Content-Encoding`, `Content-Length` hanya untuk byte yang dikirim apa adanya, `application/gzip`, `nosniff`, `no-store`; HEAD 405 (tidak menjalankan ekspor).
- Urutan: autentikasi, cari snapshot, cek izin pada orbitnya, baru admission (semaphore, default 2, dan sisa disk 512 MiB) sehingga pemanggil tanpa izin tidak dapat menghabiskan slot. Permit dan direktori ekspor ikut hidup bersama body respons; frame dibatasi 64 KiB.
- Audit `export.requested/ready/finished/disconnected` per snapshot dan principal; direktori `tessera-export-*` dihapus saat selesai, klien putus, dan saat start berikutnya setelah crash (hanya awalan itu, hanya di level atas data dir).
Bukti: `cargo test --workspace` hijau (hub 94 tes). Tes: tiap jenis snapshot dengan hasil dekompresi sama persis dengan byte asli, header, 24 MiB dialirkan dalam frame di bawah 256 KiB, audit dan pembersihan untuk unduhan selesai dan ditinggalkan, batas satu slot (ditolak seketika, slot kembali), disk tidak cukup (507), HEAD, pemanggil tanpa izin tidak memakai slot, sweep hanya menyentuh milik sendiri; tiga mutasi sengaja tertangkap (Content-Length pada gzip, PGDMP dikompres ganda, unduhan ditinggalkan tercatat selesai). Proses nyata dengan producer asli (orbit filesystem via restic): `.tar.gz`, `gunzip -t` ok, hasil ekstrak identik dengan file asli (termasuk 24 MiB acak); curl dibatasi lajunya lalu dibunuh di tengah: direktori ekspor hilang dan tercatat `export.disconnected`; stale dir dibersihkan saat restart tanpa menyentuh folder lain; HEAD 405. `cargo audit`/`deny` tidak berubah (async-compression 0.4.36, rustix 1.1.6, tanpa duplikat baru).
Batas: snapshot yang tersimpan sebagai chunk vault dibaca utuh ke memori saat diekspor (hanya yang berbasis restic dan tahap kompresi yang terbatas); SQL asli dari PostgreSQL/MySQL baru diuji lewat fixture, rehearsal dengan database sungguhan ada di M6d; tidak ada checksum arsip hasil kompresi karena streaming; sisa `.tmp*` dari kode lama tidak disapu.
### M6b — Environment dan relasi production → staging (admin)
Hasil: DevOps menyatakan "target staging X boleh ditimpa dari orbit production Y", dan QA dapat diberi hak memakainya.

View File

@@ -114,6 +114,9 @@ export function SnapshotSheet({
<path d="M8 2v8M4.5 7 8 10.5 11.5 7M3 13.5h10" />
</svg>
</a>}
{canDownload && <p className="mt-1 text-xs text-star-300">
Contains the source's raw data. It is downloaded as a .gz archive unless the format is already compressed; unpack it with gunzip.
</p>}
{canManage && (confirmDelete ? (
<div className="sheet-confirm" role="alertdialog" aria-label="Confirm deletion">
<p>Remove this recovery point from the hub catalogue? This cannot be undone.</p>