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:
@@ -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");
|
||||
}
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
222
crates/tessera-hub/src/api/export_tests.rs
Normal file
222
crates/tessera-hub/src/api/export_tests.rs
Normal 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");
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
259
crates/tessera-hub/src/exports.rs
Normal file
259
crates/tessera-hub/src/exports.rs
Normal 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");
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user