Files
tessera/crates/tessera-hub/src/exports.rs
Adnan Zahir 854e3572e9 chore: take deployment-specific material out of the repository for the first release
- MBU parity map, cutover runbook and the tasks/ planning notes move outside the repo
- tests/mbu becomes tests/fixtures with generic application names and no placement inventory
- test fixtures in Rust and web use neutral names
- scripts/export-public.sh checks an external list of private terms instead of naming them

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 21:50:27 +07:00

600 lines
20 KiB
Rust

//! 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;
/// Reduce free text to `[a-z0-9_-]`: anything else becomes `_`, runs collapse, and the ends are trimmed.
fn slug(text: &str, limit: usize) -> String {
let mut out = String::new();
for c in text.chars() {
let c = if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
c.to_ascii_lowercase()
} else {
'_'
};
if c == '_' && out.ends_with('_') {
continue;
}
out.push(c);
}
let out = out.trim_matches(['_', '-']);
out.chars()
.take(limit)
.collect::<String>()
.trim_matches(['_', '-'])
.to_string()
}
/// A readable file name for a download: `<application>_<time>_<engine>_<id8>.<extension>`.
///
/// The application is the orbit name reduced to `[a-z0-9_-]`; the time is when the backup was taken in the
/// profile's schedule zone (UTC with `Z` when there is none); the first eight characters of the snapshot id
/// keep two backups from the same minute apart. Nothing from the orbit name can reach the header unfiltered.
pub fn download_name(
orbit: &str,
taken_at: chrono::DateTime<chrono::Utc>,
zone: Option<&str>,
engine: Option<&str>,
id: Uuid,
extension: &str,
) -> String {
let when = match zone.and_then(|zone| zone.parse::<chrono_tz::Tz>().ok()) {
Some(tz) => taken_at
.with_timezone(&tz)
.format("%Y-%m-%dT%H%M%z")
.to_string(),
None => taken_at.format("%Y-%m-%dT%H%MZ").to_string(),
};
let application = match slug(orbit, 48) {
name if name.is_empty() => "snapshot".to_string(),
name => name,
};
let mut name = format!("{application}_{when}");
if let Some(engine) = engine
.map(|engine| slug(engine, 16))
.filter(|engine| !engine.is_empty())
{
name.push('_');
name.push_str(&engine);
}
let short: String = id.simple().to_string().chars().take(8).collect();
format!("{name}_{short}.{extension}")
}
/// `Content-Disposition` with both the plain `filename` and the RFC 5987 `filename*` forms.
pub fn content_disposition(name: &str) -> String {
let plain: String = name
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || "-._+".contains(c) {
c
} else {
'_'
}
})
.collect();
let mut encoded = String::new();
for byte in name.bytes() {
if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) {
encoded.push(byte as char);
} else {
encoded.push_str(&format!("%{byte:02X}"));
}
}
format!("attachment; filename=\"{plain}\"; filename*=UTF-8''{encoded}")
}
/// 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 chrono::{TimeZone, Utc};
fn taken() -> chrono::DateTime<Utc> {
Utc.with_ymd_and_hms(2026, 11, 14, 19, 30, 5).unwrap()
}
fn id() -> Uuid {
Uuid::parse_str("a1b2c3d4-0000-4000-8000-000000000000").unwrap()
}
#[test]
fn a_download_is_named_after_the_application_the_time_and_the_engine() {
let name = download_name(
"lti",
taken(),
Some("Asia/Jakarta"),
Some("postgres"),
id(),
"dump",
);
assert_eq!(name, "lti_2026-11-15T0230+0700_postgres_a1b2c3d4.dump");
let name = download_name("ledger", taken(), None, Some("mysql"), id(), "sql.gz");
assert_eq!(name, "ledger_2026-11-14T1930Z_mysql_a1b2c3d4.sql.gz");
// no engine (a folder snapshot): the part is left out
assert_eq!(
download_name("docs", taken(), None, None, id(), "tar.gz"),
"docs_2026-11-14T1930Z_a1b2c3d4.tar.gz"
);
}
#[test]
fn an_unknown_time_zone_falls_back_to_utc() {
let name = download_name(
"lti",
taken(),
Some("Mars/Olympus"),
Some("postgres"),
id(),
"dump",
);
assert!(name.contains("_2026-11-14T1930Z_"), "{name}");
}
#[test]
fn two_snapshots_in_the_same_minute_get_different_names() {
let other = Uuid::parse_str("ffffffff-0000-4000-8000-000000000000").unwrap();
let a = download_name("lti", taken(), None, Some("postgres"), id(), "dump");
let b = download_name("lti", taken(), None, Some("postgres"), other, "dump");
assert_ne!(a, b);
}
#[test]
fn hostile_orbit_names_cannot_escape_the_file_name_or_the_header() {
for orbit in [
"../../etc/passwd",
"a\"b\r\nSet-Cookie: x=1",
"name; filename=evil.exe",
"Ünïcode データ",
"\u{202e}gnp.exe",
" ",
"",
&"x".repeat(500),
] {
let name = download_name(orbit, taken(), None, Some("postgres"), id(), "dump");
assert!(
name.bytes().all(|b| b.is_ascii_lowercase()
|| b.is_ascii_digit()
|| b"_-.+TZ".contains(&b)),
"{name:?}"
);
assert!(!name.contains(".."), "{name:?}");
assert!(name.len() <= 100, "{name:?}");
let header = content_disposition(&name);
let value = axum::http::HeaderValue::from_str(&header).expect("a valid header value");
// the only `=` signs are the two the header itself writes: nothing from the name adds a parameter
assert_eq!(header.matches("filename=").count(), 1, "{header}");
assert_eq!(header.matches("filename*=").count(), 1, "{header}");
assert_eq!(header.matches(';').count(), 2, "{header}");
assert_eq!(value.to_str().unwrap(), header);
assert!(!header.contains(['\r', '\n']));
}
let name = download_name("", taken(), None, None, id(), "dump");
assert!(name.starts_with("snapshot_"), "{name}");
}
#[test]
fn the_header_carries_both_filename_forms() {
let header = content_disposition("lti_2026-11-15T0230+0700_postgres_a1b2c3d4.dump");
assert_eq!(
header,
"attachment; filename=\"lti_2026-11-15T0230+0700_postgres_a1b2c3d4.dump\"; \
filename*=UTF-8''lti_2026-11-15T0230%2B0700_postgres_a1b2c3d4.dump"
);
}
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"
);
}
}