feat: undo a restore from the safety copy it took
Some checks failed
ci / rust (push) Has been cancelled
ci / supply-chain (push) Has been cancelled
ci / web (push) Has been cancelled

- 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 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 16:47:02 +07:00
parent 854e3572e9
commit 648c8c6a2a
16 changed files with 457 additions and 41 deletions

View File

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

View File

@@ -69,9 +69,27 @@ struct RunView {
requested_by: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
snapshot_id: Option<String>,
/// 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<RunView, StatusCode> {
/// 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<RunView, StatusCode> {
let Progress {
capture_status,
capture_phase,
@@ -98,6 +116,8 @@ fn view(state: &HubState, run: &RefreshRun, admin: bool) -> Result<RunView, Stat
expires_at: run.expires_at,
requested_by: admin.then(|| run.requester.clone()),
snapshot_id: admin.then(|| run.snapshot_id.clone()).flatten(),
undo: run.is_undo(),
undo_available: can_undo(state, run).await,
})
}
@@ -134,6 +154,10 @@ struct Start {
/// relation's own source.
#[serde(default)]
snapshot_id: Option<Uuid>,
/// 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<Uuid>,
}
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::<Result<Vec<_>, _>>()?;
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")),

View File

@@ -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::<String>(&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::<String>(&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::<String>("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::<i64>("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::<String>("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::<i64>("SELECT COUNT(*) FROM refresh_runs"), 1);
}

View File

@@ -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<RestoreArtifact> {
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<SocketAddr>,
State(state): State<HubState>,