feat: readable download names and PUT /capture-profiles/:id
- downloads are named <orbit>_<time>_<engine>_<id8>.<ext> (schedule zone or UTC), orbit names are reduced to [a-z0-9_-], and the header carries filename and filename* - operators can change a profile's schedule and retention (absent = keep, null = clear), validated like registration, audited, and a changed schedule never replays slots that already passed Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -340,9 +340,9 @@ fn recipe(w: &World, row: &Row) -> (String, Option<Value>) {
|
||||
"/api/v1/orbits/:id/retention"
|
||||
| "/api/v1/orbits/:id/run"
|
||||
| "/api/v1/orbits/:id/outpost" => a.orbit,
|
||||
"/api/v1/capture-profiles/:id/jobs" | "/api/v1/capture-profiles/:id/restore-targets" => {
|
||||
a.application
|
||||
}
|
||||
"/api/v1/capture-profiles/:id"
|
||||
| "/api/v1/capture-profiles/:id/jobs"
|
||||
| "/api/v1/capture-profiles/:id/restore-targets" => a.application,
|
||||
"/api/v1/capture-jobs/:id" | "/api/v1/capture-jobs/:id/events" => a.job,
|
||||
"/api/v1/wormhole/outposts/:id/rotate" | "/api/v1/wormhole/outposts/:id/revoke" => {
|
||||
a.outpost
|
||||
@@ -379,6 +379,7 @@ fn recipe(w: &World, row: &Row) -> (String, Option<Value>) {
|
||||
("POST", "/api/v1/reconstitute") => {
|
||||
Some(json!({"snapshot_id": a.snapshot, "target_path": "out"}))
|
||||
}
|
||||
("PUT", "/api/v1/capture-profiles/:id") => Some(json!({"schedule": null})),
|
||||
("POST", "/api/v1/capture-profiles") => Some(
|
||||
serde_json::to_value(CaptureProfile {
|
||||
application_id: Uuid::new_v4(),
|
||||
|
||||
@@ -99,6 +99,35 @@ async fn download(
|
||||
.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 file_name = exports::download_name(
|
||||
&snapshot.manifest.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);
|
||||
@@ -124,8 +153,7 @@ async fn download(
|
||||
);
|
||||
headers.insert(
|
||||
header::CONTENT_DISPOSITION,
|
||||
HeaderValue::from_str(&format!("attachment; filename=\"{id}.{}\"", plan.extension))
|
||||
.map_err(internal)?,
|
||||
HeaderValue::from_str(&exports::content_disposition(&file_name)).map_err(internal)?,
|
||||
);
|
||||
headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
|
||||
headers.insert(
|
||||
|
||||
@@ -204,10 +204,17 @@ async fn each_kind_of_snapshot_downloads_with_the_right_format_and_honest_header
|
||||
);
|
||||
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 disposition = headers[header::CONTENT_DISPOSITION].to_str().unwrap();
|
||||
let short: String = id.simple().to_string().chars().take(8).collect();
|
||||
assert!(
|
||||
disposition.starts_with("attachment; filename=\"")
|
||||
&& disposition.contains(&format!("_{short}.{extension}\""))
|
||||
&& disposition.contains("filename*=UTF-8''"),
|
||||
"{name}: {disposition}"
|
||||
);
|
||||
assert!(
|
||||
!disposition.contains(&id.to_string()),
|
||||
"{name}: the full id is not the file name any more"
|
||||
);
|
||||
let content_type = if extension.ends_with("gz") {
|
||||
"application/gzip"
|
||||
|
||||
@@ -25,6 +25,10 @@ pub(super) fn routes() -> Router<HubState> {
|
||||
"/api/v1/capture-profiles",
|
||||
get(profiles).post(register_profile),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/capture-profiles/:id",
|
||||
axum::routing::put(update_profile),
|
||||
)
|
||||
.route("/api/v1/capture-profiles/:id/jobs", post(enqueue))
|
||||
.route("/api/v1/capture-jobs", get(history))
|
||||
.route("/api/v1/capture-jobs/:id", get(job))
|
||||
@@ -86,6 +90,73 @@ async fn register_profile(
|
||||
Ok((StatusCode::CREATED, Json(profile)))
|
||||
}
|
||||
|
||||
/// Editable parts of a profile. A field that is absent stays as it is; `null` clears it. Anything else
|
||||
/// (format, orbit, Outpost) is part of the profile's identity and is refused.
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct ProfileUpdate {
|
||||
#[serde(default, deserialize_with = "present")]
|
||||
schedule: Option<Option<tessera_core::job::CaptureSchedule>>,
|
||||
#[serde(default, deserialize_with = "present")]
|
||||
retention: Option<Option<tessera_core::decay::CaptureRetention>>,
|
||||
}
|
||||
|
||||
/// Tell `null` from an absent field: `Some(None)` for null, `Some(Some(v))` for a value.
|
||||
fn present<'de, D, T>(deserializer: D) -> Result<Option<Option<T>>, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
T: serde::Deserialize<'de>,
|
||||
{
|
||||
<Option<T> as serde::Deserialize>::deserialize(deserializer).map(Some)
|
||||
}
|
||||
|
||||
async fn update_profile(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(update): Json<ProfileUpdate>,
|
||||
) -> Result<Json<CaptureProfile>, StatusCode> {
|
||||
let actor = admin_write(&state, peer, &headers)?;
|
||||
if let Some(Some(retention)) = &update.retention {
|
||||
if !retention.is_valid() {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
if let Some(Some(schedule)) = &update.schedule {
|
||||
crate::scheduler::capture_schedule(schedule).ok_or(StatusCode::BAD_REQUEST)?;
|
||||
}
|
||||
let mut fields = Vec::new();
|
||||
if update.schedule.is_some() {
|
||||
fields.push("schedule");
|
||||
}
|
||||
if update.retention.is_some() {
|
||||
fields.push("retention");
|
||||
}
|
||||
let _vault = state.vault.write().await;
|
||||
let profile = state
|
||||
.db
|
||||
.update_capture_profile(
|
||||
id,
|
||||
crate::db::ProfileChange {
|
||||
schedule: update.schedule,
|
||||
retention: update.retention,
|
||||
},
|
||||
now(),
|
||||
)
|
||||
.map_err(internal)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
state
|
||||
.db
|
||||
.audit(
|
||||
"capture.profile_updated",
|
||||
&format!("actor={actor} application={id} fields={}", fields.join(",")),
|
||||
)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
Ok(Json(profile))
|
||||
}
|
||||
|
||||
async fn enqueue(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
|
||||
@@ -1395,3 +1395,126 @@ async fn someone_who_may_only_refresh_gets_into_the_app_but_sees_nothing_else()
|
||||
StatusCode::OK
|
||||
);
|
||||
}
|
||||
|
||||
// ---- capture profile updates (shares this file's lab: a real profile with a real Outpost)
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_operator_can_change_a_profiles_schedule_and_retention_and_nothing_else() {
|
||||
let lab = fresh().await;
|
||||
let admin = lab.admin();
|
||||
let uri = format!("/api/v1/capture-profiles/{}", lab.application);
|
||||
let (status, profile) = lab
|
||||
.send(
|
||||
&admin,
|
||||
"PUT",
|
||||
&uri,
|
||||
Some(json!({"schedule": {"hour": 2, "minute": 30, "timezone": "Asia/Jakarta"}, "retention": {"mode": "count"}})),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK, "{profile}");
|
||||
assert_eq!(profile["schedule"]["minute"], 30);
|
||||
assert_eq!(profile["application_id"], lab.application.to_string());
|
||||
let (_, listed) = lab
|
||||
.send(&admin, "GET", "/api/v1/capture-profiles", None)
|
||||
.await;
|
||||
assert_eq!(listed[0]["schedule"]["hour"], 2);
|
||||
// null clears the schedule; the retention override stays because it was not mentioned
|
||||
let (status, profile) = lab
|
||||
.send(&admin, "PUT", &uri, Some(json!({"schedule": null})))
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert!(
|
||||
profile["schedule"].is_null() && !profile["retention"].is_null(),
|
||||
"{profile}"
|
||||
);
|
||||
let audited = lab.state.db.audit_log_events();
|
||||
assert!(
|
||||
audited
|
||||
.iter()
|
||||
.any(|(event, detail)| event == "capture.profile_updated"
|
||||
&& detail.contains(&lab.application.to_string())),
|
||||
"{audited:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_profile_update_is_validated_like_a_registration() {
|
||||
let lab = fresh().await;
|
||||
let admin = lab.admin();
|
||||
let uri = format!("/api/v1/capture-profiles/{}", lab.application);
|
||||
for (body, expected) in [
|
||||
(
|
||||
json!({"schedule": {"hour": 24, "minute": 0, "timezone": "Asia/Jakarta"}}),
|
||||
StatusCode::BAD_REQUEST,
|
||||
),
|
||||
(
|
||||
json!({"schedule": {"hour": 2, "minute": 0, "timezone": "Mars/Olympus"}}),
|
||||
StatusCode::BAD_REQUEST,
|
||||
),
|
||||
(
|
||||
json!({"retention": {"mode": "count", "keep": 0}}),
|
||||
StatusCode::BAD_REQUEST,
|
||||
),
|
||||
// identity and wiring are not editable here
|
||||
(
|
||||
json!({"format": "postgres_sql"}),
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
),
|
||||
(
|
||||
json!({"outpost_id": Uuid::new_v4()}),
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
),
|
||||
] {
|
||||
assert_eq!(
|
||||
lab.send(&admin, "PUT", &uri, Some(body.clone())).await.0,
|
||||
expected,
|
||||
"{body}"
|
||||
);
|
||||
}
|
||||
let unknown = format!("/api/v1/capture-profiles/{}", Uuid::new_v4());
|
||||
assert_eq!(
|
||||
lab.send(&admin, "PUT", &unknown, Some(json!({"schedule": null})))
|
||||
.await
|
||||
.0,
|
||||
StatusCode::NOT_FOUND
|
||||
);
|
||||
// nothing above changed the profile
|
||||
let (_, listed) = lab
|
||||
.send(&admin, "GET", "/api/v1/capture-profiles", None)
|
||||
.await;
|
||||
assert!(listed[0]["schedule"].is_null());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn only_an_administrator_can_change_a_profile() {
|
||||
let lab = fresh().await;
|
||||
let (qa, _) = lab.refresher("qa");
|
||||
let stranger = lab.person("stranger");
|
||||
let uri = format!("/api/v1/capture-profiles/{}", lab.application);
|
||||
for caller in [&qa, &stranger] {
|
||||
let status = lab
|
||||
.send(caller, "PUT", &uri, Some(json!({"schedule": null})))
|
||||
.await
|
||||
.0;
|
||||
assert!(
|
||||
status == StatusCode::FORBIDDEN || status == StatusCode::NOT_FOUND,
|
||||
"{status}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
lab.send(
|
||||
&Caller {
|
||||
cookie: None,
|
||||
csrf: None,
|
||||
admin_token: false,
|
||||
user_id: None
|
||||
},
|
||||
"PUT",
|
||||
&uri,
|
||||
Some(json!({"schedule": null}))
|
||||
)
|
||||
.await
|
||||
.0,
|
||||
StatusCode::UNAUTHORIZED
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ pub(crate) mod access;
|
||||
mod audit;
|
||||
pub(crate) mod credentials;
|
||||
mod jobs;
|
||||
pub use jobs::ProfileChange;
|
||||
pub(crate) mod oidc_login;
|
||||
pub(crate) mod refresh;
|
||||
pub(crate) mod relations;
|
||||
|
||||
@@ -20,6 +20,19 @@ pub(super) fn migrate(conn: &Connection) -> Result<()> {
|
||||
}
|
||||
|
||||
impl Db {
|
||||
/// Test helper: the free-form audit log as (event, detail).
|
||||
#[cfg(test)]
|
||||
pub fn audit_log_events(&self) -> Vec<(String, String)> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn
|
||||
.prepare("SELECT event, detail FROM audit_log ORDER BY rowid")
|
||||
.unwrap();
|
||||
stmt.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))
|
||||
.unwrap()
|
||||
.filter_map(Result::ok)
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn audit_event(
|
||||
&self,
|
||||
actor: &Principal,
|
||||
|
||||
@@ -103,6 +103,13 @@ fn read_job(row: &Row<'_>) -> rusqlite::Result<CaptureJob> {
|
||||
})
|
||||
}
|
||||
|
||||
/// What an operator may change on a capture profile: `None` = leave as is, `Some(None)` = clear.
|
||||
#[derive(Default)]
|
||||
pub struct ProfileChange {
|
||||
pub schedule: Option<Option<tessera_core::job::CaptureSchedule>>,
|
||||
pub retention: Option<Option<tessera_core::decay::CaptureRetention>>,
|
||||
}
|
||||
|
||||
impl Db {
|
||||
pub fn register_capture_profile(&self, profile: &CaptureProfile, now: i64) -> Result<bool> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
@@ -122,6 +129,51 @@ impl Db {
|
||||
Ok(changed == 1)
|
||||
}
|
||||
|
||||
/// Change the parts of a profile an operator may edit. Absent = unchanged, `Some(None)` = cleared.
|
||||
///
|
||||
/// A changed schedule moves the schedule cursor up to `now` (the cursor is the later of the newest
|
||||
/// scheduled job and `registered_at`), so a slot that is already past under the new schedule is never
|
||||
/// replayed: the first job comes from the next slot. Returns `None` when there is no such profile.
|
||||
pub fn update_capture_profile(
|
||||
&self,
|
||||
application: Uuid,
|
||||
change: ProfileChange,
|
||||
now: i64,
|
||||
) -> Result<Option<CaptureProfile>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let current: Option<CaptureProfile> = conn
|
||||
.query_row(
|
||||
"SELECT profile FROM capture_profiles WHERE application_id = ?1",
|
||||
params![application.to_string()],
|
||||
|row| parse_profile(row, 0),
|
||||
)
|
||||
.optional()?;
|
||||
let Some(mut profile) = current else {
|
||||
return Ok(None);
|
||||
};
|
||||
let schedule_changed = change.schedule.as_ref().is_some_and(|new| {
|
||||
serde_json::to_string(new).ok() != serde_json::to_string(&profile.schedule).ok()
|
||||
});
|
||||
if let Some(schedule) = change.schedule {
|
||||
profile.schedule = schedule;
|
||||
}
|
||||
if let Some(retention) = change.retention {
|
||||
profile.retention = retention;
|
||||
}
|
||||
conn.execute(
|
||||
"UPDATE capture_profiles SET profile = ?2,
|
||||
registered_at = CASE WHEN ?4 THEN max(registered_at, ?3) ELSE registered_at END
|
||||
WHERE application_id = ?1",
|
||||
params![
|
||||
application.to_string(),
|
||||
serde_json::to_string(&profile)?,
|
||||
now,
|
||||
schedule_changed
|
||||
],
|
||||
)?;
|
||||
Ok(Some(profile))
|
||||
}
|
||||
|
||||
pub fn capture_profiles(&self) -> Result<Vec<CaptureProfile>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt =
|
||||
@@ -133,7 +185,7 @@ impl Db {
|
||||
pub fn capture_schedule_cursors(&self) -> Result<Vec<(CaptureProfile, i64)>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT p.profile, COALESCE(MAX(j.schedule_slot), p.registered_at)
|
||||
"SELECT p.profile, max(COALESCE(MAX(j.schedule_slot), 0), p.registered_at)
|
||||
FROM capture_profiles p LEFT JOIN capture_jobs j USING(application_id)
|
||||
GROUP BY p.application_id",
|
||||
)?;
|
||||
@@ -718,4 +770,120 @@ mod tests {
|
||||
["queued", "claimed", "dumping", "dump_failed"]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_profile_changes_only_its_schedule_and_retention() {
|
||||
use tessera_core::job::CaptureSchedule;
|
||||
let db = Db::connect(std::path::Path::new(":memory:")).await.unwrap();
|
||||
db.migrate().await.unwrap();
|
||||
let outpost = Uuid::new_v4();
|
||||
db.insert_test_credential("token", &outpost.to_string(), "agent");
|
||||
let profile = profile(&db, outpost).await;
|
||||
assert!(db.register_capture_profile(&profile, 100).unwrap());
|
||||
let schedule = CaptureSchedule {
|
||||
hour: 3,
|
||||
minute: 15,
|
||||
timezone: "Asia/Jakarta".into(),
|
||||
};
|
||||
let changed = db
|
||||
.update_capture_profile(
|
||||
profile.application_id,
|
||||
ProfileChange {
|
||||
schedule: Some(Some(schedule.clone())),
|
||||
retention: None,
|
||||
},
|
||||
200,
|
||||
)
|
||||
.unwrap()
|
||||
.expect("the profile exists");
|
||||
assert_eq!(
|
||||
changed.schedule.as_ref().map(|s| (s.hour, s.minute)),
|
||||
Some((3, 15))
|
||||
);
|
||||
assert_eq!(
|
||||
(changed.orbit_id, changed.outpost_id),
|
||||
(profile.orbit_id, profile.outpost_id)
|
||||
);
|
||||
assert_eq!(
|
||||
db.capture_profiles().unwrap()[0]
|
||||
.schedule
|
||||
.as_ref()
|
||||
.map(|s| s.hour),
|
||||
Some(3)
|
||||
);
|
||||
// absent means unchanged, null means cleared
|
||||
let cleared = db
|
||||
.update_capture_profile(
|
||||
profile.application_id,
|
||||
ProfileChange {
|
||||
schedule: Some(None),
|
||||
retention: None,
|
||||
},
|
||||
300,
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(cleared.schedule.is_none());
|
||||
assert!(db
|
||||
.update_capture_profile(Uuid::new_v4(), ProfileChange::default(), 300)
|
||||
.unwrap()
|
||||
.is_none());
|
||||
}
|
||||
|
||||
/// Moving a schedule must never run slots that already passed under the new one: the first job comes
|
||||
/// from the next slot after the change.
|
||||
#[tokio::test]
|
||||
async fn changing_a_schedule_does_not_replay_slots_that_are_already_past() {
|
||||
use chrono::{TimeZone, Utc};
|
||||
use tessera_core::job::CaptureSchedule;
|
||||
let db = Db::connect(std::path::Path::new(":memory:")).await.unwrap();
|
||||
db.migrate().await.unwrap();
|
||||
let outpost = Uuid::new_v4();
|
||||
db.insert_test_credential("token", &outpost.to_string(), "agent");
|
||||
let mut profile = profile(&db, outpost).await;
|
||||
profile.schedule = Some(CaptureSchedule {
|
||||
hour: 2,
|
||||
minute: 30,
|
||||
timezone: "Asia/Jakarta".into(),
|
||||
});
|
||||
let registered = Utc.with_ymd_and_hms(2026, 11, 1, 0, 0, 0).unwrap();
|
||||
assert!(db
|
||||
.register_capture_profile(&profile, registered.timestamp())
|
||||
.unwrap());
|
||||
let tick = crate::scheduler::tick_capture_schedules;
|
||||
// days of ordinary running: the last slot is 2026-11-14 02:30 WIB
|
||||
tick(&db, Utc.with_ymd_and_hms(2026, 11, 14, 20, 0, 0).unwrap()).unwrap();
|
||||
let before = db.capture_jobs(None, None, 1000, None).unwrap().len();
|
||||
|
||||
// at 10:00 WIB (03:00 UTC) on the 15th the operator moves the schedule to 03:00 WIB, whose slot
|
||||
// for the 15th is already in the past
|
||||
let change_time = Utc.with_ymd_and_hms(2026, 11, 15, 3, 0, 0).unwrap();
|
||||
let moved = CaptureSchedule {
|
||||
hour: 3,
|
||||
minute: 0,
|
||||
timezone: "Asia/Jakarta".into(),
|
||||
};
|
||||
db.update_capture_profile(
|
||||
profile.application_id,
|
||||
ProfileChange {
|
||||
schedule: Some(Some(moved)),
|
||||
retention: None,
|
||||
},
|
||||
change_time.timestamp(),
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
tick(&db, change_time).unwrap();
|
||||
assert_eq!(
|
||||
db.capture_jobs(None, None, 1000, None).unwrap().len(),
|
||||
before,
|
||||
"no replay of a past slot"
|
||||
);
|
||||
// the next 03:00 WIB (20:00 UTC on the 15th) fires once
|
||||
tick(&db, Utc.with_ymd_and_hms(2026, 11, 15, 20, 0, 0).unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
db.capture_jobs(None, None, 1000, None).unwrap().len(),
|
||||
before + 1
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,87 @@ 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 {
|
||||
@@ -237,6 +318,100 @@ impl<S> Drop for Guarded<S> {
|
||||
|
||||
#[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("boiler", taken(), None, Some("mysql"), id(), "sql.gz");
|
||||
assert_eq!(name, "boiler_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;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user