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:
@@ -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(
|
||||
|
||||
Reference in New Issue
Block a user