diff --git a/crates/tessera-hub/src/api/access_tests.rs b/crates/tessera-hub/src/api/access_tests.rs index c68455e..5b9efbf 100644 --- a/crates/tessera-hub/src/api/access_tests.rs +++ b/crates/tessera-hub/src/api/access_tests.rs @@ -340,9 +340,9 @@ fn recipe(w: &World, row: &Row) -> (String, Option) { "/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) { ("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(), diff --git a/crates/tessera-hub/src/api/catalog.rs b/crates/tessera-hub/src/api/catalog.rs index cd7560c..62dddb1 100644 --- a/crates/tessera-hub/src/api/catalog.rs +++ b/crates/tessera-hub/src/api/catalog.rs @@ -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( diff --git a/crates/tessera-hub/src/api/export_tests.rs b/crates/tessera-hub/src/api/export_tests.rs index aab4c26..acb8f9e 100644 --- a/crates/tessera-hub/src/api/export_tests.rs +++ b/crates/tessera-hub/src/api/export_tests.rs @@ -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" diff --git a/crates/tessera-hub/src/api/jobs.rs b/crates/tessera-hub/src/api/jobs.rs index e83eebf..8ca9a05 100644 --- a/crates/tessera-hub/src/api/jobs.rs +++ b/crates/tessera-hub/src/api/jobs.rs @@ -25,6 +25,10 @@ pub(super) fn routes() -> Router { "/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>, + #[serde(default, deserialize_with = "present")] + retention: Option>, +} + +/// Tell `null` from an absent field: `Some(None)` for null, `Some(Some(v))` for a value. +fn present<'de, D, T>(deserializer: D) -> Result>, D::Error> +where + D: serde::Deserializer<'de>, + T: serde::Deserialize<'de>, +{ + as serde::Deserialize>::deserialize(deserializer).map(Some) +} + +async fn update_profile( + ConnectInfo(peer): ConnectInfo, + State(state): State, + headers: HeaderMap, + Path(id): Path, + Json(update): Json, +) -> Result, 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, State(state): State, diff --git a/crates/tessera-hub/src/api/refresh_tests.rs b/crates/tessera-hub/src/api/refresh_tests.rs index 2a3bca0..b21e448 100644 --- a/crates/tessera-hub/src/api/refresh_tests.rs +++ b/crates/tessera-hub/src/api/refresh_tests.rs @@ -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 + ); +} diff --git a/crates/tessera-hub/src/db.rs b/crates/tessera-hub/src/db.rs index a05e2b3..7506ee5 100644 --- a/crates/tessera-hub/src/db.rs +++ b/crates/tessera-hub/src/db.rs @@ -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; diff --git a/crates/tessera-hub/src/db/audit.rs b/crates/tessera-hub/src/db/audit.rs index 30e3a23..053e56c 100644 --- a/crates/tessera-hub/src/db/audit.rs +++ b/crates/tessera-hub/src/db/audit.rs @@ -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, diff --git a/crates/tessera-hub/src/db/jobs.rs b/crates/tessera-hub/src/db/jobs.rs index 7261b34..2354512 100644 --- a/crates/tessera-hub/src/db/jobs.rs +++ b/crates/tessera-hub/src/db/jobs.rs @@ -103,6 +103,13 @@ fn read_job(row: &Row<'_>) -> rusqlite::Result { }) } +/// What an operator may change on a capture profile: `None` = leave as is, `Some(None)` = clear. +#[derive(Default)] +pub struct ProfileChange { + pub schedule: Option>, + pub retention: Option>, +} + impl Db { pub fn register_capture_profile(&self, profile: &CaptureProfile, now: i64) -> Result { 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> { + let conn = self.conn.lock().unwrap(); + let current: Option = 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> { let conn = self.conn.lock().unwrap(); let mut stmt = @@ -133,7 +185,7 @@ impl Db { pub fn capture_schedule_cursors(&self) -> Result> { 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 + ); + } } diff --git a/crates/tessera-hub/src/exports.rs b/crates/tessera-hub/src/exports.rs index 002e241..955ac88 100644 --- a/crates/tessera-hub/src/exports.rs +++ b/crates/tessera-hub/src/exports.rs @@ -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::() + .trim_matches(['_', '-']) + .to_string() +} + +/// A readable file name for a download: `_