From 648c8c6a2a7248390e1f83b83f6de200d675e749 Mon Sep 17 00:00:00 2001 From: Adnan Zahir Date: Mon, 16 Nov 2026 16:47:02 +0700 Subject: [PATCH] feat: undo a restore from the safety copy it took - POST /refresh-runs accepts undo_of: restores the safety copy of a completed restore back onto the same target through the normal run engine (checks, countdown, progress, and a new safety copy so the undo can be undone); refused when something was restored after it or the copy is gone - a safety copy is accepted as a source only for the target it was taken from (hub and agent both check) - run views carry undo and undo_available; audited as refresh.undo_started - the modal offers Undo last restore and, after a restore, Undo this restore - proven with a real agent and PostgreSQL: restore, undo back to the original contents, undo of the undo Co-Authored-By: Claude Sonnet 5.5 --- crates/tessera-agent/src/restore.rs | 3 +- crates/tessera-core/src/restore.rs | 4 + crates/tessera-hub/src/api/mod.rs | 2 +- crates/tessera-hub/src/api/refresh.rs | 93 ++++++++-- crates/tessera-hub/src/api/refresh_tests.rs | 177 +++++++++++++++++++ crates/tessera-hub/src/api/restore.rs | 32 ++++ crates/tessera-hub/src/db/refresh.rs | 80 ++++++++- crates/tessera-hub/src/db/restore.rs | 3 +- crates/tessera-hub/src/refresh.rs | 24 ++- docs/DATABASE-CAPTURE.md | 12 +- docs/auth-endpoint-contract.md | 2 +- web/scripts/restoreRun.test.mjs | 8 + web/src/api.ts | 8 +- web/src/components/restore/RestoreWizard.tsx | 34 +++- web/src/index.css | 3 + web/src/lib/restoreRun.ts | 13 +- 16 files changed, 457 insertions(+), 41 deletions(-) diff --git a/crates/tessera-agent/src/restore.rs b/crates/tessera-agent/src/restore.rs index 66b91ab..0c0cef8 100644 --- a/crates/tessera-agent/src/restore.rs +++ b/crates/tessera-agent/src/restore.rs @@ -126,7 +126,8 @@ async fn run( let verified = tokio::time::timeout(timeout, async { let identity = target.identity().await?; ensure!( - identity == lease.job.target.identity && identity != lease.artifact.identity, + identity == lease.job.target.identity + && (lease.artifact.rollback || identity != lease.artifact.identity), "restore target identity does not match" ); if let Some(source) = source { diff --git a/crates/tessera-core/src/restore.rs b/crates/tessera-core/src/restore.rs index ac3c42b..a18a7bf 100644 --- a/crates/tessera-core/src/restore.rs +++ b/crates/tessera-core/src/restore.rs @@ -89,6 +89,10 @@ pub struct RestoreArtifact { pub format: CaptureFormat, pub identity: DatabaseIdentity, pub sha256: String, + /// The artifact is the safety copy a restore took of the very target it is now restored onto (an undo). + /// Its source identity is then the target's own, so the "target is the source" refusal does not apply. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub rollback: bool, } #[derive(Deserialize, Serialize)] diff --git a/crates/tessera-hub/src/api/mod.rs b/crates/tessera-hub/src/api/mod.rs index 128e580..e19538c 100644 --- a/crates/tessera-hub/src/api/mod.rs +++ b/crates/tessera-hub/src/api/mod.rs @@ -24,5 +24,5 @@ mod session; pub use orbit::run_orbit_internal; pub(crate) use relations::identity_facts; -pub(crate) use restore::artifact; +pub(crate) use restore::{artifact, rollback_artifact}; pub use routes::router; diff --git a/crates/tessera-hub/src/api/refresh.rs b/crates/tessera-hub/src/api/refresh.rs index e9825b5..a925970 100644 --- a/crates/tessera-hub/src/api/refresh.rs +++ b/crates/tessera-hub/src/api/refresh.rs @@ -69,9 +69,27 @@ struct RunView { requested_by: Option, #[serde(skip_serializing_if = "Option::is_none")] snapshot_id: Option, + /// This run put a target back from the safety copy of an earlier restore. + undo: bool, + /// A completed restore that can still be undone: the newest restore of its target, with its safety copy in + /// the vault. Never says where the copy is. + undo_available: bool, } -fn view(state: &HubState, run: &RefreshRun, admin: bool) -> Result { +/// Can this run still be undone: see `Db::undo_candidate`, and the safety copy must still exist. +async fn can_undo(state: &HubState, run: &RefreshRun) -> bool { + if run.status != "completed" { + return false; + } + match state.db.undo_candidate(&run.id, &run.relation_id) { + Ok(Ok(safety)) => snapshot_fits(state, &run.relation_id, safety) + .await + .unwrap_or(false), + _ => false, + } +} + +async fn view(state: &HubState, run: &RefreshRun, admin: bool) -> Result { let Progress { capture_status, capture_phase, @@ -98,6 +116,8 @@ fn view(state: &HubState, run: &RefreshRun, admin: bool) -> Result, + /// Put the target back as it was before this earlier restore: restore that restore's safety copy onto the same + /// target. The run must be a completed restore of this relation and the newest one of its target. + #[serde(default)] + undo_of: Option, } fn valid_key(key: &str) -> bool { @@ -160,10 +184,22 @@ async fn snapshot_fits( .get_snapshot(snapshot) .map_err(internal)? .map(|s| s.manifest); + let target = match state.db.relation_target(relation).map_err(internal)? { + Some(id) => Uuid::parse_str(&id) + .ok() + .and_then(|id| state.db.restore_target(id).ok().flatten()), + None => None, + }; Ok(manifest.is_some_and(|manifest| { manifest.orbit_id.to_string() == source - && !manifest.is_restore_safety() - && crate::api::artifact(&manifest).is_some() + && if manifest.is_restore_safety() { + // a safety copy only ever goes back onto the target it was taken from + target.as_ref().is_some_and(|target| { + crate::api::rollback_artifact(&manifest, target).is_some() + }) + } else { + crate::api::artifact(&manifest).is_some() + } })) } @@ -179,13 +215,33 @@ async fn start( } super::gate::relation(&state, &actor, body.relation_id)?; let relation = body.relation_id.to_string(); - if let Some(snapshot) = body.snapshot_id { + // What to restore: a snapshot the person picked, the safety copy that undoes an earlier restore, or (neither) + // a fresh capture. + let mut chosen: Option<(Uuid, bool)> = None; + if let Some(of) = body.undo_of { + if body.snapshot_id.is_some() { + return Err(StatusCode::BAD_REQUEST); + } + let candidate = state + .db + .undo_candidate(&of.to_string(), &relation) + .map_err(internal)?; + let Ok(safety) = candidate else { + return Ok(reason(StatusCode::UNPROCESSABLE_ENTITY, "nothing_to_undo")); + }; + // the copy may have been removed since + if !snapshot_fits(&state, &relation, safety).await? { + return Ok(reason(StatusCode::UNPROCESSABLE_ENTITY, "nothing_to_undo")); + } + chosen = Some((safety, true)); + } else if let Some(snapshot) = body.snapshot_id { if !snapshot_fits(&state, &relation, snapshot).await? { return Ok(reason( StatusCode::UNPROCESSABLE_ENTITY, "snapshot_unusable", )); } + chosen = Some((snapshot, false)); } // What authorised this run, recorded so it can be checked again before anything is overwritten. let authorized_by = if actor.subject.admin { @@ -214,7 +270,7 @@ async fn start( actor.subject.user_id.as_deref(), &authorized_by, &body.idempotency_key, - body.snapshot_id, + chosen, state.refresh.ttl_secs, state.refresh.max_active, now(), @@ -223,7 +279,11 @@ async fn start( match started { Ok((run, created)) => { if created { - crate::refresh::audit_run(&state, &run.id, "capturing"); + crate::refresh::audit_run( + &state, + &run.id, + if run.is_undo() { "undo" } else { "capturing" }, + ); } let status = if created { StatusCode::ACCEPTED @@ -233,7 +293,7 @@ async fn start( Ok(( status, no_store(), - Json(view(&state, &run, actor.subject.admin)?), + Json(view(&state, &run, actor.subject.admin).await?), ) .into_response()) } @@ -283,10 +343,10 @@ async fn list( } } .map_err(internal)?; - let views = runs - .iter() - .map(|run| view(&state, run, actor.subject.admin)) - .collect::, _>>()?; + let mut views = Vec::with_capacity(runs.len()); + for run in &runs { + views.push(view(&state, run, actor.subject.admin).await?); + } Ok((no_store(), Json(views))) } @@ -318,7 +378,10 @@ async fn show( ) .map_err(internal)?; let run = run.ok_or(StatusCode::NOT_FOUND)?; - Ok((no_store(), Json(view(&state, &run, actor.subject.admin)?))) + Ok(( + no_store(), + Json(view(&state, &run, actor.subject.admin).await?), + )) } async fn cancel( @@ -364,7 +427,11 @@ async fn cancel( { Ok(run) => { crate::refresh::audit_run(&state, &run.id, "cancelled"); - Ok((no_store(), Json(view(&state, &run, actor.subject.admin)?)).into_response()) + Ok(( + no_store(), + Json(view(&state, &run, actor.subject.admin).await?), + ) + .into_response()) } Err(CancelError::Unknown) => Err(StatusCode::NOT_FOUND), Err(CancelError::TooLate) => Ok(reason(StatusCode::CONFLICT, "too_late")), diff --git a/crates/tessera-hub/src/api/refresh_tests.rs b/crates/tessera-hub/src/api/refresh_tests.rs index 7cb162b..e7cc20e 100644 --- a/crates/tessera-hub/src/api/refresh_tests.rs +++ b/crates/tessera-hub/src/api/refresh_tests.rs @@ -2188,3 +2188,180 @@ async fn the_screens_get_what_they_need_to_offer_restore_for_an_orbit() { "{kinds:?}" ); } + +// ---- undoing a restore: put the target back from the safety copy the restore took ---- + +impl Lab { + async fn start_undo(&self, caller: &Caller, key: &str, run: &str) -> (StatusCode, Value) { + self.send( + caller, + "POST", + "/api/v1/refresh-runs", + Some(json!({"relation_id": self.relation, "confirmation": self.confirmation(), "idempotency_key": key, "undo_of": run})), + ) + .await + } + + /// A completed restore of a fresh capture, with its safety copy in the vault. + async fn restored_once(&self, key: &str) -> String { + let (_, run) = self.start(&self.admin(), key).await; + let run = run["id"].as_str().unwrap().to_string(); + self.capture(&Lab::production_identity(), false) + .await + .unwrap(); + self.tick().await; + self.finish_restore().await; + assert_eq!(self.run(&run).status, "completed"); + run + } +} + +#[tokio::test] +async fn a_completed_restore_can_be_undone_from_its_safety_copy_and_the_undo_can_be_undone() { + let lab = fresh().await; + let (qa, _) = lab.refresher("qa"); + let first = lab.restored_once("first").await; + let (_, view) = lab + .send(&qa, "GET", &format!("/api/v1/refresh-runs/{first}"), None) + .await; + assert_eq!(view["undo_available"], true, "{view}"); + assert!( + view.get("safety_snapshot_id").is_none(), + "no snapshot id reaches a non-administrator: {view}" + ); + + let (status, undo) = lab.start_undo(&qa, "undo-1", &first).await; + assert_eq!(status, StatusCode::ACCEPTED, "{undo}"); + assert_eq!(undo["undo"], true); + let undo_id = undo["id"].as_str().unwrap().to_string(); + let captures = lab.capture_jobs(); + lab.tick().await; + // the restore job takes the first restore's safety copy back onto the same target + let (job, _) = lab + .restore_until_ready() + .await + .expect("an undo job is waiting"); + let artifact: Value = serde_json::from_str(&lab.scalar::(&format!( + "SELECT artifact FROM restore_jobs WHERE id='{job}'" + ))) + .unwrap(); + assert_eq!(artifact["rollback"], true, "{artifact}"); + assert_eq!(lab.capture_jobs(), captures, "an undo captures nothing"); + let (_, token) = ( + job.clone(), + lab.scalar::(&format!( + "SELECT lease_token FROM restore_jobs WHERE id='{job}'" + )), + ); + assert_eq!(lab.apply(&job, &token).await, StatusCode::NO_CONTENT); + lab.report_applied(&job, &token).await; + lab.tick().await; + assert_eq!(lab.run(&undo_id).status, "completed"); + + // only the newest restore of a target can be undone: the first one no longer can, the undo can + let (_, old) = lab + .send(&qa, "GET", &format!("/api/v1/refresh-runs/{first}"), None) + .await; + let (_, new) = lab + .send(&qa, "GET", &format!("/api/v1/refresh-runs/{undo_id}"), None) + .await; + assert_eq!( + (old["undo_available"].clone(), new["undo_available"].clone()), + (json!(false), json!(true)) + ); + assert!(lab + .audit_log() + .iter() + .any(|(event, _)| event == "restore.queued")); +} + +#[tokio::test] +async fn an_undo_is_refused_when_there_is_nothing_sound_to_go_back_to() { + let lab = fresh().await; + let admin = lab.admin(); + // a run that has not finished, and one that does not exist + let (_, running) = lab.start(&admin, "running").await; + let running = running["id"].as_str().unwrap().to_string(); + for (what, id) in [ + ("unfinished", running.clone()), + ("unknown", Uuid::new_v4().to_string()), + ] { + let (status, body) = lab.start_undo(&admin, &format!("u-{what}"), &id).await; + assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{what}: {body}"); + assert_eq!(body["reason"], "nothing_to_undo", "{what}"); + } + lab.capture(&Lab::production_identity(), false) + .await + .unwrap(); + lab.tick().await; + lab.finish_restore().await; + + // the safety copy has been removed from the vault + let safety = lab.scalar::("SELECT safety_id FROM restore_jobs LIMIT 1"); + lab.state + .vault + .write() + .await + .forget(&[Uuid::parse_str(&safety).unwrap()]) + .unwrap(); + let (status, body) = lab.start_undo(&admin, "gone", &running).await; + assert_eq!( + (status, body["reason"].clone()), + (StatusCode::UNPROCESSABLE_ENTITY, json!("nothing_to_undo")), + "{body}" + ); + assert_eq!( + lab.scalar::("SELECT COUNT(*) FROM refresh_runs"), + 1, + "nothing was started" + ); +} + +#[tokio::test] +async fn a_safety_copy_is_only_ever_restored_onto_the_target_it_came_from() { + let lab = fresh().await; + let admin = lab.admin(); + let first = lab.restored_once("first").await; + let own_safety = + Uuid::parse_str(&lab.scalar::("SELECT safety_id FROM restore_jobs LIMIT 1")) + .unwrap(); + let hints = lab + .state + .vault + .read() + .await + .get_snapshot(own_safety) + .unwrap() + .unwrap() + .manifest + .restore_hints; + // the same kind of copy, but taken from some other target + let mut foreign_hints = hints.clone(); + foreign_hints["target_id"] = json!(Uuid::new_v4()); + let foreign = lab + .plant_snapshot(lab.orbit, &["restore-safety"], foreign_hints) + .await; + let (status, body) = lab.start_snapshot(&admin, "foreign", foreign).await; + assert_eq!( + (status, body["reason"].clone()), + (StatusCode::UNPROCESSABLE_ENTITY, json!("snapshot_unusable")), + "{body}" + ); + // its own copy is fine, through the plain snapshot route as well + let (status, body) = lab.start_snapshot(&admin, "own", own_safety).await; + assert_eq!(status, StatusCode::ACCEPTED, "{body}"); + let _ = first; +} + +#[tokio::test] +async fn only_someone_who_may_use_the_relation_can_undo_through_it() { + let lab = fresh().await; + let first = lab.restored_once("first").await; + let stranger = lab.person("stranger"); + let status = lab.start_undo(&stranger, "s", &first).await.0; + assert!( + status == StatusCode::FORBIDDEN || status == StatusCode::NOT_FOUND, + "{status}" + ); + assert_eq!(lab.scalar::("SELECT COUNT(*) FROM refresh_runs"), 1); +} diff --git a/crates/tessera-hub/src/api/restore.rs b/crates/tessera-hub/src/api/restore.rs index e8d24e0..48161ac 100644 --- a/crates/tessera-hub/src/api/restore.rs +++ b/crates/tessera-hub/src/api/restore.rs @@ -234,10 +234,42 @@ pub(crate) fn artifact(manifest: &SnapshotManifest) -> Option<(Uuid, RestoreArti format, identity, sha256, + rollback: false, }, )) } +/// The artifact for putting a target back from the safety copy a restore took of it, or `None` when the +/// snapshot is not such a copy, was taken from some other target, or lacks what a restore needs. The copy is a +/// dump of the target itself, so its source identity is the target's own. +pub(crate) fn rollback_artifact( + manifest: &SnapshotManifest, + target: &tessera_core::restore::RestoreTarget, +) -> Option { + if !manifest.is_restore_safety() || manifest.safety_target()? != target.id.to_string() { + return None; + } + let format = match ( + manifest.provider.as_str(), + manifest.restore_hints.get("format")?.as_str()?, + ) { + ("postgres", "custom") => CaptureFormat::PostgresCustom, + ("postgres", "plain") => CaptureFormat::PostgresSql, + ("mysql", "plain") => CaptureFormat::MysqlSql, + _ => return None, + }; + let sha256 = manifest.restore_hints.get("sha256")?.as_str()?.to_owned(); + if sha256.len() != 64 || !sha256.bytes().all(|b| b.is_ascii_hexdigit()) { + return None; + } + (format.engine() == Some(target.engine)).then(|| RestoreArtifact { + format, + identity: target.identity.clone(), + sha256, + rollback: true, + }) +} + async fn job( ConnectInfo(peer): ConnectInfo, State(state): State, diff --git a/crates/tessera-hub/src/db/refresh.rs b/crates/tessera-hub/src/db/refresh.rs index e870ee6..7d7ebee 100644 --- a/crates/tessera-hub/src/db/refresh.rs +++ b/crates/tessera-hub/src/db/refresh.rs @@ -84,9 +84,77 @@ pub enum StartError { /// What the confirmation must say: it names exactly what the person saw, including the version. /// `capture_job_id` of a run that restores a snapshot somebody picked instead of capturing a new one. const EXISTING: &str = "existing:"; +/// Same, for a run that puts a target back from the safety copy of an earlier restore. +const UNDO: &str = "undo:"; + +/// Does this run take its snapshot from the request instead of from a capture of its own? +fn picked_snapshot(run: &RefreshRun) -> bool { + run.capture_job_id.starts_with(EXISTING) || run.capture_job_id.starts_with(UNDO) +} + +impl RefreshRun { + /// This run put a target back from a safety copy. + pub fn is_undo(&self) -> bool { + self.capture_job_id.starts_with(UNDO) + } +} /// A relation's source orbit, for checking that a snapshot belongs to it. +/// Why a restore cannot be undone. +#[derive(Debug, PartialEq, Eq)] +pub enum UndoRefusal { + /// No such run, not of this relation, not completed, or it took no safety copy. + NothingToUndo, + /// Something else was restored onto the target after it. Undoing an older restore would also undo that. + NotTheLatest, +} + impl Db { + /// The safety copy that undoes `run`, if the run is a completed restore of this relation and the newest + /// restore of its target. Whether the copy still exists in the vault is for the caller to check. + pub fn undo_candidate( + &self, + run: &str, + relation: &str, + ) -> Result> { + let conn = self.conn.lock().unwrap(); + let Some(run) = + get(&conn, run)?.filter(|r| r.relation_id == relation && r.status == "completed") + else { + return Ok(Err(UndoRefusal::NothingToUndo)); + }; + let Some(job) = &run.restore_job_id else { + return Ok(Err(UndoRefusal::NothingToUndo)); + }; + let safety: Option> = conn + .query_row( + "SELECT safety_id FROM restore_jobs WHERE id = ?1 AND status = 'completed'", + params![job], + |r| r.get(0), + ) + .optional()?; + let Some(Some(safety)) = safety else { + return Ok(Err(UndoRefusal::NothingToUndo)); + }; + // Jobs are numbered in the order they were queued. + let later: bool = conn.query_row( + "SELECT EXISTS(SELECT 1 FROM restore_jobs WHERE target_id = ?1 + AND rowid > (SELECT rowid FROM restore_jobs WHERE id = ?2) + AND status IN ('queued','running','applying','completed','recovery_required'))", + params![run.target_id, job], + |r| r.get(0), + )?; + if later { + return Ok(Err(UndoRefusal::NotTheLatest)); + } + Ok(Ok(Uuid::parse_str(&safety)?)) + } + + pub fn relation_target(&self, relation: &str) -> Result> { + let conn = self.conn.lock().unwrap(); + Ok(relation_of(&conn, relation)?.map(|r| r.target_id)) + } + pub fn relation_source_orbit(&self, relation: &str) -> Result> { let conn = self.conn.lock().unwrap(); Ok(relation_of(&conn, relation)?.map(|r| r.source_orbit_id)) @@ -282,7 +350,8 @@ impl Db { requester_user_id: Option<&str>, authorized_by: &str, idempotency_key: &str, - snapshot: Option, + // a snapshot to restore instead of capturing one, and whether it is an undo of an earlier restore + snapshot: Option<(Uuid, bool)>, ttl_secs: i64, max_active: i64, now: i64, @@ -324,7 +393,8 @@ impl Db { // A run either takes a fresh backup first, or restores a snapshot the person picked: then it has // no capture job, only a placeholder, and the snapshot is recorded from the start. let capture = match snapshot { - Some(_) => format!("{EXISTING}{id}"), + Some((_, true)) => format!("{UNDO}{id}"), + Some((_, false)) => format!("{EXISTING}{id}"), None => { let application = Uuid::parse_str(&relation.source_application_id)?; let Some(capture) = @@ -340,7 +410,7 @@ impl Db { authorized_by,idempotency_key,status,capture_job_id,snapshot_id,created_at,updated_at,expires_at) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,'capturing',?11,?12,?13,?13,?14)", params![id, relation.id, relation.version, relation.source_orbit_id, relation.source_application_id, relation.target_id, - requester, requester_user_id, authorized_by, idempotency_key, capture, snapshot.map(|s| s.to_string()), now, now + ttl_secs], + requester, requester_user_id, authorized_by, idempotency_key, capture, snapshot.map(|(s, _)| s.to_string()), now, now + ttl_secs], )?; Ok(Ok((get(&tx, &id)?.expect("just inserted"), true))) })()?; @@ -446,7 +516,7 @@ impl Db { if run.status != "capturing" || run.restore_job_id.is_some() { return Ok(Linked::NotReady); } - let snapshot = if run.capture_job_id.starts_with(EXISTING) { + let snapshot = if picked_snapshot(&run) { let Some(snapshot) = run.snapshot_id.clone() else { return Ok(Linked::NotReady); }; @@ -613,7 +683,7 @@ fn sync_in(tx: &Transaction<'_>, id: &str, now: i64) -> Result { Ok(Sync::Moved(status.into())) }; match run.status.as_str() { - "capturing" if run.capture_job_id.starts_with(EXISTING) => { + "capturing" if picked_snapshot(&run) => { // Nothing to capture: the snapshot was chosen when the run was started. match (&run.snapshot_id, &run.restore_job_id) { (Some(snapshot), None) => Ok(Sync::NeedRestore(snapshot.clone())), diff --git a/crates/tessera-hub/src/db/restore.rs b/crates/tessera-hub/src/db/restore.rs index 7af7a3b..b81f767 100644 --- a/crates/tessera-hub/src/db/restore.rs +++ b/crates/tessera-hub/src/db/restore.rs @@ -76,7 +76,7 @@ pub(crate) fn restore_target_mismatch( ) -> Option<&'static str> { if Some(target.engine) != artifact.format.engine() { Some("Database engine differs from the snapshot") - } else if target.identity == artifact.identity { + } else if target.identity == artifact.identity && !artifact.rollback { Some("Target is the source database") } else { None @@ -562,6 +562,7 @@ mod tests { let artifact = RestoreArtifact { format: CaptureFormat::PostgresCustom, sha256: "0".repeat(64), + rollback: false, identity: DatabaseIdentity { instance: "123".into(), database: "source".into(), diff --git a/crates/tessera-hub/src/refresh.rs b/crates/tessera-hub/src/refresh.rs index f52cbf3..a9b845e 100644 --- a/crates/tessera-hub/src/refresh.rs +++ b/crates/tessera-hub/src/refresh.rs @@ -47,6 +47,7 @@ fn now() -> i64 { pub fn audit_name(status: &str) -> (&'static str, AuditOutcome) { match status { "capturing" => ("refresh.started", AuditOutcome::Succeeded), + "undo" => ("refresh.undo_started", AuditOutcome::Succeeded), "restoring" => ("refresh.restore_queued", AuditOutcome::Succeeded), "completed" => ("refresh.completed", AuditOutcome::Succeeded), "reconciled" => ("refresh.reconciled", AuditOutcome::Succeeded), @@ -104,10 +105,18 @@ async fn queue_restore(state: &HubState, run: &RefreshRun, snapshot: &str) -> an .await .get_snapshot(snapshot_id)? .map(|s| s.manifest); - let artifact = manifest - .as_ref() - .and_then(crate::api::artifact) - .map(|(_, artifact)| artifact); + let target = state.db.restore_target(Uuid::parse_str(&run.target_id)?)?; + // A safety copy is restorable only onto the target it was taken from (an undo); anything else must be a + // capture with its source identity. + let artifact = manifest.as_ref().and_then(|manifest| { + if manifest.is_restore_safety() { + target + .as_ref() + .and_then(|target| crate::api::rollback_artifact(manifest, target)) + } else { + crate::api::artifact(manifest).map(|(_, artifact)| artifact) + } + }); let Some(artifact) = artifact else { // The snapshot is missing or lacks what a restore needs (format, checksum, source identity). state @@ -117,9 +126,9 @@ async fn queue_restore(state: &HubState, run: &RefreshRun, snapshot: &str) -> an return Ok(true); }; // The driver looks again: a run that was told to restore a snapshot only restores one of its own source. - let belongs = manifest.as_ref().is_some_and(|manifest| { - manifest.orbit_id.to_string() == run.source_orbit_id && !manifest.is_restore_safety() - }); + let belongs = manifest + .as_ref() + .is_some_and(|manifest| manifest.orbit_id.to_string() == run.source_orbit_id); if !belongs { state .db @@ -127,7 +136,6 @@ async fn queue_restore(state: &HubState, run: &RefreshRun, snapshot: &str) -> an audit_run(state, &run.id, "blocked"); return Ok(true); } - let target = state.db.restore_target(Uuid::parse_str(&run.target_id)?)?; let clash = match target { Some(target) => { let source = Uuid::parse_str(&run.source_orbit_id)?; diff --git a/docs/DATABASE-CAPTURE.md b/docs/DATABASE-CAPTURE.md index d96ee09..c2da125 100644 --- a/docs/DATABASE-CAPTURE.md +++ b/docs/DATABASE-CAPTURE.md @@ -378,12 +378,22 @@ orbit's); otherwise the answer is `422 snapshot_unusable` and nothing is started everything else is the same: one run per target at a time, idempotency, cancelling until the target is overwritten, and the authorisation checks right before overwriting. The same snapshot can be restored to several targets, and again later. +A completed restore can be undone: `undo_of` (the id of that run) restores the safety copy the restore took of its target +back onto the same target, through the same checks, countdown, progress and a new safety copy, so the undo can itself be +undone. It is refused with `422 nothing_to_undo` when the run is not a completed restore of this relation, when something +was restored onto the target after it (only the newest restore of a target can be undone), or when the safety copy has +been removed. A safety copy is only ever accepted as a source for the target it was taken from, whether it arrives through +`undo_of` or `snapshot_id`; the check is made by the hub, and again by the agent (its restore artifact carries +`rollback`). Run views say `undo` and `undo_available`, never where the copy is. The run is audited as +`refresh.undo_started`. Undoing needs the same permission as restoring. + In the web UI there is no separate Refresh screen. Restoring lives in the Vault: pick an orbit, capture it if you want the latest data (or click a snapshot that is already there), and in the snapshot detail press **Restore**. The button is disabled with "No restore point" when no relation has been set up for the orbit. The modal offers the restore points (Development and/or Staging) that the person may use, shows what will be overwritten, and after **Begin restore** counts ten seconds in the browser, during which **Abort** sends nothing. Then it follows four steps (Checking, Safety copy, -Applying, Completed) from the run, and Abort still works until Applying starts. Safety copies are not listed with the +Applying, Completed) from the run, and Abort still works until Applying starts. A finished restore offers **Undo this restore**, and the modal offers +**Undo last restore** for the chosen restore point while that is still possible. Safety copies are not listed with the backups. A person needs to see the orbit's snapshots (for example the viewer role on the orbit) and a relation grant; administrators can also restore to any other registered target from the same modal. diff --git a/docs/auth-endpoint-contract.md b/docs/auth-endpoint-contract.md index 77b1f51..4205b33 100644 --- a/docs/auth-endpoint-contract.md +++ b/docs/auth-endpoint-contract.md @@ -38,7 +38,7 @@ admin/browser. Semua status/data job hanya di scope owner/admin yang berizin. | /api/v1/relations/:id/access | GET,POST | human | relation.manage | admin | grant refresh.run per relasi (user atau grup, expiry); diaudit | | /api/v1/relations/:id/access/:grant | DELETE | human | relation.manage | admin | berlaku pada request berikutnya; diaudit | | /api/v1/refresh-relations | GET | human | refresh.run | relasi yang di-grant | nama dan environment saja; tanpa identity, host, Outpost, application id; 403 bila tanpa grant | -| /api/v1/refresh-runs | GET,POST | human | refresh.run | relasi yang di-grant | POST: relation_id + konfirmasi `REFRESH TO v` + kunci idempotensi; `snapshot_id` opsional: restore snapshot yang sudah ada milik orbit sumber relasi itu (bukan safety, bukan orbit lain; 422 `snapshot_unusable`), tanpa itu run mengambil capture baru; tidak memilih target; 404 bila bukan pemegang grant; GET: run milik sendiri atau relasi yang di-grant (admin: semua), tanpa snapshot id dan pemohon untuk non-admin | +| /api/v1/refresh-runs | GET,POST | human | refresh.run | relasi yang di-grant | POST: relation_id + konfirmasi `REFRESH TO v` + kunci idempotensi; `undo_of` opsional (id run restore selesai terbaru pada targetnya): kembalikan target dari safety copy restore itu (422 `nothing_to_undo`; safety hanya diterima untuk target asalnya); `snapshot_id` opsional: restore snapshot yang sudah ada milik orbit sumber relasi itu (bukan safety, bukan orbit lain; 422 `snapshot_unusable`), tanpa itu run mengambil capture baru; tidak memilih target; 404 bila bukan pemegang grant; GET: run milik sendiri atau relasi yang di-grant (admin: semua), tanpa snapshot id dan pemohon untuk non-admin | | /api/v1/refresh-runs/:id | GET,DELETE | human | refresh.run | admin, pemohon, atau pemegang grant relasinya | GET 404 bagi yang lain; DELETE hanya pemohon atau admin (pemegang grant lain 403) dan hanya sebelum apply, sesudahnya 409 | | /api/v1/operator/login | POST | public | — | emergency account | cookie opaque dan CSRF; limiter, no-store | | /api/v1/snapshots | GET | human | snapshot.read | orbit | metadata aman terfilter | diff --git a/web/scripts/restoreRun.test.mjs b/web/scripts/restoreRun.test.mjs index d7c106f..6f06481 100644 --- a/web/scripts/restoreRun.test.mjs +++ b/web/scripts/restoreRun.test.mjs @@ -39,6 +39,14 @@ test("what the person is told never contains the database's own words", () => { assert.equal(outcomeOf(run("restoring", "safety"), { target: "Staging" }).tone, "busy"); }); +test("an undo is worded as putting the target back, and its own safety copy keeps it undoable", () => { + const done = outcomeOf({ ...run("completed"), undo: true }, { target: "Staging", orbit: "ledger", when: "Nov 15, 11:57 AM" }); + assert.equal(done.tone, "good"); + assert.match(done.title, /Staging was rolled back/); + assert.match(done.detail, /holds what it held before that restore/); + assert.match(outcomeOf({ ...run("restore_failed", "apply_failed"), undo: true }, { target: "Staging" }).title, /undo failed/i); +}); + test("restore points are named by environment, and by target only when two share one", () => { const rel = (id, env, name) => ({ id, target_environment: env, target_name: name, usable: true }); assert.deepEqual( diff --git a/web/src/api.ts b/web/src/api.ts index d09179a..d9ef735 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -135,6 +135,10 @@ export type RefreshRelation = { target_name: string; target_environment: Environment | null; usable: boolean; unusable_reason: string | null; }; export type RefreshRun = { + /** Put a target back from the safety copy of an earlier restore. */ + undo?: boolean; + /** A completed restore that can still be undone (the newest of its target, safety copy still there). */ + undo_available?: boolean; id: string; relation_id: string; source_name: string; target_name: string; status: string; blocked_reason: string | null; capture_status: string | null; capture_phase: string | null; snapshot_taken_at: number | null; restore_status: string | null; restore_phase: string | null; @@ -143,13 +147,13 @@ export type RefreshRun = { export const fetchRefreshRelations = () => api("/api/v1/refresh-relations"); export const fetchRefreshRuns = () => api("/api/v1/refresh-runs"); /** Restore `snapshot_id` onto the relation's target (or, without one, capture first and restore that). */ -export const startRefresh = (relation: RefreshRelation, idempotency_key: string, snapshot_id?: string) => +export const startRefresh = (relation: RefreshRelation, idempotency_key: string, pick: { snapshot_id?: string; undo_of?: string } = {}) => api("/api/v1/refresh-runs", json("POST", { relation_id: relation.id, // exactly what the person was shown, so a relation changed in the meantime is refused confirmation: `REFRESH ${relation.source_name} TO ${relation.target_name} v${relation.version}`, idempotency_key, - ...(snapshot_id ? { snapshot_id } : {}), + ...(pick.undo_of ? { undo_of: pick.undo_of } : pick.snapshot_id ? { snapshot_id: pick.snapshot_id } : {}), })); export const fetchRefreshRun = (id: string) => api(`/api/v1/refresh-runs/${id}`); export const cancelRefresh = (id: string) => api(`/api/v1/refresh-runs/${id}`, { method: "DELETE" }); diff --git a/web/src/components/restore/RestoreWizard.tsx b/web/src/components/restore/RestoreWizard.tsx index be803a0..0f61b36 100644 --- a/web/src/components/restore/RestoreWizard.tsx +++ b/web/src/components/restore/RestoreWizard.tsx @@ -1,7 +1,7 @@ import { useEffect, useMemo, useRef, useState } from "react"; import { motion } from "motion/react"; import { useQuery } from "@tanstack/react-query"; -import { cancelRefresh, fetchRefreshRun, refusalReason, startRefresh, type RefreshRelation, type RefreshRun, type Snapshot } from "../../api"; +import { cancelRefresh, fetchRefreshRun, fetchRefreshRuns, refusalReason, startRefresh, type RefreshRelation, type RefreshRun, type Snapshot } from "../../api"; import { formatBytes, formatWhen } from "../../lib/format"; import { isFinal, outcomeOf, progressOf, relationLabels, STAGES } from "../../lib/restoreRun"; import { Button } from "../ui/Button"; @@ -17,6 +17,7 @@ const REFUSALS: Record = { relation_unusable: "This restore point cannot be used right now. Ask an administrator.", too_many_runs: "Too many restores are running at once. Try again in a few minutes.", snapshot_unusable: "This backup cannot be restored to that database.", + nothing_to_undo: "There is nothing to undo any more: something was restored after it, or its safety copy was removed.", source_unavailable: "The source cannot be reached right now.", }; @@ -42,6 +43,8 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: { const [runId, setRunId] = useState(); const [refusal, setRefusal] = useState(); const [other, setOther] = useState(false); + // Set while an undo is being started or followed: the run whose restore is being put back. + const [undoOf, setUndoOf] = useState(); // One key per attempt: the same press can never start two restores, even if the request is retried. const attempt = useRef(globalThis.crypto?.randomUUID?.() ?? String(Math.random())); @@ -66,7 +69,7 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: { if (left <= 0) { setPhase("running"); if (!point) return; - startRefresh(point, attempt.current, snapshot.id) + startRefresh(point, attempt.current, undoOf ? { undo_of: undoOf } : { snapshot_id: snapshot.id }) .then((started) => setRunId(started.id)) .catch((error) => { setRefusal(REFUSALS[refusalReason(error) ?? ""] ?? "The restore could not be started."); @@ -77,7 +80,7 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: { } const timer = window.setTimeout(() => setLeft((value) => value - 1), 1000); return () => clearTimeout(timer); - }, [phase, left, point, snapshot.id]); + }, [phase, left, point, snapshot.id, undoOf]); const abortable = phase === "countdown" || (phase === "running" && !finished && progress.index < 2); const abort = async () => { @@ -89,7 +92,15 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: { } }; const again = () => { - setPhase("idle"); setLeft(COUNTDOWN); setRunId(undefined); setRefusal(undefined); + setPhase("idle"); setLeft(COUNTDOWN); setRunId(undefined); setRefusal(undefined); setUndoOf(undefined); + attempt.current = globalThis.crypto?.randomUUID?.() ?? String(Math.random()); + }; + + // The newest restore on the chosen restore point, if it can still be undone. + const recent = useQuery({ queryKey: ["restore-runs"], queryFn: fetchRefreshRuns, enabled: phase === "idle", retry: false, refetchInterval: 15_000 }); + const undoable = Array.isArray(recent.data) ? recent.data.find((r) => r.relation_id === point?.id && r.undo_available) : undefined; + const beginUndo = (of: string) => { + setRefusal(undefined); setRunId(undefined); setUndoOf(of); setLeft(COUNTDOWN); setPhase("countdown"); attempt.current = globalThis.crypto?.randomUUID?.() ?? String(Math.random()); }; @@ -132,11 +143,17 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: {
-
{refusal &&

{refusal}

} + {undoable && phase === "idle" && !runId && ( +
+

The last restore on {target} was {formatWhen(new Date(undoable.updated_at * 1000).toISOString())}. Its safety copy can put {target} back as it was before.

+ +
+ )} {admin && database && phase === "idle" && !runId && ( )} @@ -155,7 +172,7 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: { {left}seconds -

Restoring to {target} in {left}s.
Abort restores nothing.

+

{undoOf ? `Undoing the last restore on ${target} in ${left}s.` : `Restoring to ${target} in ${left}s.`}
Abort restores nothing.

)} {phase === "running" && ( @@ -182,7 +199,10 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: {

{outcome.title}

{outcome.detail}

- +
+ {run.data?.undo_available && } + +
)} {run.isError &&

Reconnecting to the restore…

} diff --git a/web/src/index.css b/web/src/index.css index f5151b3..5ca5360 100644 --- a/web/src/index.css +++ b/web/src/index.css @@ -1219,3 +1219,6 @@ button.act-row[data-group="needs"]:hover { background: #20161a; } .restore-outcome.good p:first-child { color: var(--color-orbit-green, #8fd0b0); } .restore-outcome.bad { border-color: #6b2f26; } .restore-outcome.bad p:first-child { color: var(--color-orbit-red); } + +.restore-undo { display: flex; flex-direction: column; align-items: flex-start; gap: 8px; padding: 12px; border: 1px dashed var(--line); border-radius: 12px; } +.restore-undo p { margin: 0; font-size: 13px; line-height: 1.5; color: var(--quiet); } diff --git a/web/src/lib/restoreRun.ts b/web/src/lib/restoreRun.ts index 9107e7f..a79600a 100644 --- a/web/src/lib/restoreRun.ts +++ b/web/src/lib/restoreRun.ts @@ -2,7 +2,7 @@ export const STAGES = ["Checking", "Safety copy", "Applying", "Completed"] as const; -type RunLike = { status: string; restore_phase: string | null; blocked_reason?: string | null }; +type RunLike = { status: string; restore_phase: string | null; blocked_reason?: string | null; undo?: boolean }; const STOPPED = new Set(["restore_failed", "recovery_required", "blocked", "expired", "capture_failed"]); @@ -52,6 +52,17 @@ export function outcomeOf( names: { target: string; orbit?: string; when?: string }, ): Outcome { const { target } = names; + if (run.undo) { + switch (run.status) { + case "completed": + case "reconciled": + return { tone: "good", title: `${target} was rolled back`, detail: `${target} holds what it held before that restore. A safety copy of the state you undid was kept, so this can be undone too.` }; + case "restore_failed": + return { tone: "bad", title: "The undo failed", detail: `${target} was most likely not changed, but ask an administrator to check it before you rely on it.` }; + default: + break; // the other outcomes read the same for an undo + } + } switch (run.status) { case "completed": case "reconciled":