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

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()),
(
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())
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,
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;