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:
2026-11-15 12:19:32 +07:00
parent 1bff2ab234
commit fb277249f7
11 changed files with 602 additions and 10 deletions

View File

@@ -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(),

View File

@@ -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(

View File

@@ -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"

View File

@@ -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>,

View File

@@ -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
);
}