use super::routes::{admin_write, authenticate}; use crate::auth::{AuditAction, AuditOutcome, AuditResource, Permission}; use crate::exports::{self, Guarded, Refused, EXPORT_PREFIX}; use crate::state::HubState; use async_compression::tokio::bufread::GzipEncoder; use axum::body::Bytes; use axum::{ body::Body, extract::{ConnectInfo, Path, State}, http::{header, HeaderMap, HeaderValue, Method, StatusCode}, response::Response, routing::get, Router, }; use futures_core::Stream; use std::net::SocketAddr; use std::pin::Pin; use tokio::io::{AsyncReadExt, AsyncSeekExt}; 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 { 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, State(state): State, headers: HeaderMap, Path(id): Path, ) -> Result { // 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 .read() .await .get_snapshot(id) .map_err(internal)? .filter(|snapshot| snapshot.manifest.provider != "legacy-history") .ok_or(StatusCode::NOT_FOUND)?; super::gate::scoped( &state, &actor, Permission::SnapshotDownload, snapshot.manifest.orbit_id, )?; let audit = |action: AuditAction, outcome: AuditOutcome| { state .db .audit_event( &actor.principal, action, AuditResource::Snapshot(id), outcome, actor.request_id, ) .map_err(internal) }; 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); // The profile's schedule zone makes the time in the name match the one people see in their schedule. let application = snapshot .manifest .restore_hints .get("application_id") .and_then(|v| v.as_str()) .and_then(|v| Uuid::parse_str(v).ok()); let zone = application.and_then(|application| { state .db .capture_profiles() .ok()? .into_iter() .find(|p| p.application_id == application)? .schedule .map(|s| s.timezone) }); let orbit_name = state .db .orbit_names() .ok() .and_then(|names| names.get(&snapshot.manifest.orbit_id).cloned()) .unwrap_or_else(|| snapshot.manifest.orbit_name.clone()); let file_name = exports::download_name( &orbit_name, snapshot.taken_at, zone.as_deref(), snapshot .manifest .restore_hints .get("engine") .and_then(|v| v.as_str()), id, plan.extension, ); audit(AuditAction::ExportReady, AuditOutcome::Succeeded)?; let reader = tokio::io::BufReader::with_capacity(CHUNK, file); let stream: Pin> + 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(&exports::content_disposition(&file_name)).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( ConnectInfo(peer): ConnectInfo, State(state): State, headers: HeaderMap, Path(id): Path, ) -> Result { let actor = admin_write(&state, peer, &headers)?; let mut vault = state.vault.clone().write_owned().await; if state.db.snapshot_in_restore(id).map_err(internal)? || state.db.offsite_pending(id).map_err(internal)? || state.active_exports().await.contains(&id) { return Err(StatusCode::CONFLICT); } if vault .get_snapshot(id) .map_err(internal)? .is_none_or(|snapshot| snapshot.manifest.provider == "legacy-history") { return Err(StatusCode::NOT_FOUND); } state .db .audit( "snapshot.delete_requested", &format!("actor={actor} snapshot={id}"), ) .await .map_err(internal)?; tokio::task::spawn_blocking(move || vault.forget(&[id])) .await .map_err(internal)? .map_err(internal)?; state .db .audit("snapshot.deleted", &format!("actor={actor} snapshot={id}")) .await .map_err(internal)?; Ok(StatusCode::NO_CONTENT) } fn internal(_: impl std::fmt::Display) -> StatusCode { StatusCode::INTERNAL_SERVER_ERROR }