Files
tessera/crates/tessera-hub/src/api/refresh_tests.rs
Adnan Zahir 62f0c68e89 feat: roll back a failed restore and say when a safety copy is gone
- a restore whose apply failed can be undone from its safety copy, which is its recovery: the failed apply stops
  fencing the target in the transaction that starts the undo (job phase rolled_back, audited restore.rolled_back);
  an apply whose agent went silent still waits for an administrator to reconcile it; reconciled restores can be undone
- run views carry undo_state (available, superseded, expired), undo_kept_until, undo_of and restore_job_id
- undo state for a list is worked out in one database pass and a file lookup per copy; the vault is read only for the
  newest restore of each target
- eligibility is checked again inside the transaction that creates the run

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:37:21 +07:00

2493 lines
82 KiB
Rust

//! Refresh runs end to end. The "agent" is driven through the same Outpost endpoints a real agent
//! uses (capture claim/report/payload, restore claim/report/safety/apply), so the snapshot a run
//! restores is built by the real capture path, with its real manifest hints.
use crate::admin::SessionGate;
use crate::state::HubState;
use axum::body::{to_bytes, Body};
use axum::extract::ConnectInfo;
use axum::http::{header, Request, StatusCode};
use base64::Engine as _;
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use std::net::SocketAddr;
use tessera_core::job::{CaptureFormat, CaptureProfile};
use tessera_core::restore::{DatabaseIdentity, Engine, RestoreTarget};
use tower::ServiceExt;
use uuid::Uuid;
const ADMIN: &str = "synthetic-admin-token";
const AGENT: &str = "synthetic-agent-token";
const ISSUER: &str = "https://idp.example";
fn now() -> i64 {
chrono::Utc::now().timestamp()
}
struct Caller {
cookie: Option<String>,
csrf: Option<String>,
admin_token: bool,
user_id: Option<String>,
}
struct Lab {
app: axum::Router,
state: HubState,
dir: tempfile::TempDir,
orbit: Uuid,
application: Uuid,
outpost: Uuid,
target: Uuid,
relation: String,
relation_version: i64,
}
async fn lab_with(configure: impl FnOnce(&mut HubState)) -> Lab {
let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault")
.await
.unwrap();
state.admin.token = Some(ADMIN.into());
state.sessions = SessionGate::without_operator(state.db.clone()).with_oidc("refresh-fp");
configure(&mut state);
let orbit = Uuid::new_v4();
state
.db
.upsert_orbit(&crate::db::OrbitRow {
id: orbit,
name: "prod-db".into(),
provider: "wormhole".into(),
provider_config: "{}".into(),
schedule: None,
decay_preset: "week-of-dailies".into(),
retention: None,
dry_run: false,
last_status: "idle".into(),
})
.await
.unwrap();
let outpost = Uuid::new_v4();
state
.db
.insert_test_credential(AGENT, &outpost.to_string(), "agent");
let application = Uuid::new_v4();
let profile = CaptureProfile {
application_id: application,
orbit_id: orbit,
outpost_id: outpost,
format: CaptureFormat::PostgresCustom,
schedule: None,
retention: None,
};
assert!(state.db.register_capture_profile(&profile, now()).unwrap());
let target = RestoreTarget {
id: Uuid::new_v4(),
application_id: application,
outpost_id: outpost,
name: "staging-db".into(),
engine: Engine::Postgres,
identity: DatabaseIdentity {
instance: "7300000000000000001".into(),
database: "staging_app".into(),
},
};
assert!(state.db.register_restore_target(&target).unwrap());
state
.db
.set_orbit_environment(orbit, "production", now())
.unwrap();
state
.db
.set_target_environment(target.id, "staging", now())
.unwrap();
let relation = state
.db
.create_relation(orbit, target.id, None, false, false, "seed", now())
.unwrap()
.unwrap();
let app = crate::api::router(state.clone());
Lab {
app,
state,
dir,
orbit,
application,
outpost,
target: target.id,
relation: relation.id,
relation_version: relation.version,
}
}
async fn fresh() -> Lab {
lab_with(|_| {}).await
}
impl Lab {
fn person(&self, name: &str) -> Caller {
let user = self
.state
.db
.upsert_user(ISSUER, name, name, now())
.unwrap();
let session = self
.state
.sessions
.create_oidc(&user, name, false, &[], now())
.unwrap();
Caller {
cookie: Some(format!("__Host-tessera-session={}", session.id)),
csrf: Some(session.csrf),
admin_token: false,
user_id: Some(user),
}
}
/// A person holding `refresh.run` on the relation.
fn refresher(&self, name: &str) -> (Caller, String) {
let person = self.person(name);
let grant = self
.state
.db
.add_relation_grant(
"user",
person.user_id.as_ref().unwrap(),
&self.relation,
None,
"test",
now(),
)
.unwrap()
.unwrap();
(person, grant.id)
}
fn admin(&self) -> Caller {
Caller {
cookie: None,
csrf: None,
admin_token: true,
user_id: None,
}
}
async fn call(&self, request: Request<Body>) -> (StatusCode, Value) {
let response = self.app.clone().oneshot(request).await.unwrap();
let status = response.status();
let bytes = to_bytes(response.into_body(), 1 << 24).await.unwrap();
(
status,
serde_json::from_slice(&bytes).unwrap_or(Value::Null),
)
}
async fn send(
&self,
caller: &Caller,
method: &str,
uri: &str,
body: Option<Value>,
) -> (StatusCode, Value) {
let mut request = Request::builder()
.method(method)
.uri(uri)
.extension(ConnectInfo("127.0.0.1:4000".parse::<SocketAddr>().unwrap()));
if let Some(cookie) = &caller.cookie {
request = request.header(header::COOKIE, cookie);
}
if caller.admin_token {
request = request.header("x-tessera-admin-token", ADMIN);
}
if method != "GET" {
if let Some(csrf) = &caller.csrf {
request = request.header("x-tessera-csrf", csrf);
}
}
let request = match body {
Some(json) => request
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(json.to_string()))
.unwrap(),
None => request.body(Body::empty()).unwrap(),
};
self.call(request).await
}
fn confirmation(&self) -> String {
crate::db::refresh::confirmation_text("prod-db", "staging-db", self.relation_version)
}
async fn start(&self, caller: &Caller, key: &str) -> (StatusCode, Value) {
self.send(caller, "POST", "/api/v1/refresh-runs", Some(json!({"relation_id": self.relation, "confirmation": self.confirmation(), "idempotency_key": key}))).await
}
fn conn(&self) -> rusqlite::Connection {
rusqlite::Connection::open(self.dir.path().join("tessera.db")).unwrap()
}
fn scalar<T: rusqlite::types::FromSql>(&self, sql: &str) -> T {
self.conn().query_row(sql, [], |r| r.get(0)).unwrap()
}
async fn tick(&self) -> usize {
crate::refresh::tick(&self.state).await.unwrap()
}
fn run(&self, id: &str) -> crate::db::refresh::RefreshRun {
self.state.db.refresh_run(id).unwrap().unwrap()
}
// ---- the agent, through the real Outpost endpoints ----
fn agent_request(
&self,
method: &str,
uri: &str,
extra: &[(&str, String)],
body: Option<Vec<u8>>,
) -> Request<Body> {
let mut request = Request::builder()
.method(method)
.uri(uri)
.header("x-tessera-upload-token", AGENT)
.extension(ConnectInfo(
"198.51.100.5:4000".parse::<SocketAddr>().unwrap(),
));
for (name, value) in extra {
request = request.header(*name, value);
}
match body {
Some(bytes) => request
.header(header::CONTENT_LENGTH, bytes.len())
.body(Body::from(bytes))
.unwrap(),
None => request.body(Body::empty()).unwrap(),
}
}
async fn agent_json(
&self,
method: &str,
uri: &str,
extra: &[(&str, String)],
body: Value,
) -> (StatusCode, Value) {
let mut request =
self.agent_request(method, uri, extra, Some(body.to_string().into_bytes()));
request
.headers_mut()
.insert(header::CONTENT_TYPE, "application/json".parse().unwrap());
self.call(request).await
}
/// Run one whole capture as the agent would. `identity` is the source database's identity.
async fn capture(&self, identity: &DatabaseIdentity, fail: bool) -> Option<Uuid> {
let (status, lease) = self
.call(self.agent_request(
"POST",
&format!("/api/v1/wormhole/capture/{}/claim", self.application),
&[],
None,
))
.await;
assert_eq!(status, StatusCode::OK);
if lease.is_null() {
return None;
}
let job = lease["job_id"].as_str().unwrap().to_string();
let lease_id = lease["lease_id"].as_str().unwrap().to_string();
let report = |progress: &'static str| {
let uri = format!("/api/v1/wormhole/capture/{job}/report");
let body = json!({"lease_id": lease_id, "progress": progress});
async move { self.agent_json("POST", &uri, &[], body).await.0 }
};
assert_eq!(report("dumping").await, StatusCode::NO_CONTENT);
if fail {
assert_eq!(report("dump_failed").await, StatusCode::NO_CONTENT);
return Some(Uuid::parse_str(&job).unwrap());
}
assert_eq!(report("uploading").await, StatusCode::NO_CONTENT);
let payload = [
b"PGDMP\x01\x0e\x00".as_slice(),
format!("-- dump of {}", identity.database).as_bytes(),
]
.concat();
let headers = [
("x-tessera-lease-id", lease_id.clone()),
("x-tessera-sha256", hex::encode(Sha256::digest(&payload))),
(
"x-tessera-source-identity",
base64::engine::general_purpose::URL_SAFE_NO_PAD
.encode(serde_json::to_vec(identity).unwrap()),
),
];
let (status, body) = self
.call(self.agent_request(
"POST",
&format!("/api/v1/wormhole/capture/{job}/payload"),
&headers,
Some(payload),
))
.await;
assert_eq!(status, StatusCode::OK, "{body}");
Some(Uuid::parse_str(&job).unwrap())
}
fn production_identity() -> DatabaseIdentity {
DatabaseIdentity {
instance: "9100000000000000009".into(),
database: "prod_app".into(),
}
}
/// Claim the restore, pass checking and the safety backup, and stop just before apply.
async fn restore_until_ready(&self) -> Option<(String, String)> {
let (status, lease) = self
.call(self.agent_request(
"POST",
&format!("/api/v1/wormhole/restore-targets/{}/claim", self.target),
&[],
None,
))
.await;
assert_eq!(status, StatusCode::OK);
if lease.is_null() {
return None;
}
let job = lease["job"]["id"].as_str().unwrap().to_string();
let token = lease["token"].as_str().unwrap().to_string();
let headers = [("x-tessera-restore-token", token.clone())];
for progress in ["checking", "safety"] {
let (status, _) = self
.agent_json(
"POST",
&format!("/api/v1/wormhole/restore/{job}/report"),
&headers,
json!(progress),
)
.await;
assert_eq!(status, StatusCode::NO_CONTENT, "report {progress}");
}
let safety = [
b"PGDMP\x01\x0e\x00".as_slice(),
b"-- safety copy of the target",
]
.concat();
let safety_headers = [
("x-tessera-restore-token", token.clone()),
("x-tessera-sha256", hex::encode(Sha256::digest(&safety))),
];
let (status, body) = self
.call(self.agent_request(
"POST",
&format!("/api/v1/wormhole/restore/{job}/safety"),
&safety_headers,
Some(safety),
))
.await;
assert_eq!(status, StatusCode::OK, "{body}");
Some((job, token))
}
async fn apply(&self, job: &str, token: &str) -> StatusCode {
self.call(self.agent_request(
"POST",
&format!("/api/v1/wormhole/restore/{job}/apply"),
&[("x-tessera-restore-token", token.to_string())],
None,
))
.await
.0
}
async fn report_applied(&self, job: &str, token: &str) {
let (status, _) = self
.agent_json(
"POST",
&format!("/api/v1/wormhole/restore/{job}/report"),
&[("x-tessera-restore-token", token.to_string())],
json!("applied"),
)
.await;
assert_eq!(status, StatusCode::NO_CONTENT);
}
fn audit_log(&self) -> Vec<(String, String)> {
self.state.db.audit_log_events()
}
fn restore_jobs(&self) -> i64 {
self.scalar("SELECT COUNT(*) FROM restore_jobs")
}
fn capture_jobs(&self) -> i64 {
self.scalar("SELECT COUNT(*) FROM capture_jobs")
}
fn restore_status(&self, job: &str) -> String {
self.conn()
.query_row("SELECT status FROM restore_jobs WHERE id=?1", [job], |r| {
r.get(0)
})
.unwrap()
}
fn audit_actions(&self, run: &str) -> Vec<String> {
let conn = self.conn();
let mut stmt = conn.prepare("SELECT action FROM audit_events WHERE resource_type='refresh_run' AND resource_id=?1 AND action LIKE 'refresh.%' ORDER BY id").unwrap();
stmt.query_map([run], |r| r.get(0))
.unwrap()
.collect::<Result<_, _>>()
.unwrap()
}
}
#[tokio::test]
async fn a_refresh_captures_its_own_snapshot_and_restores_exactly_that_onto_the_target() {
let lab = fresh().await;
let (qa, _) = lab.refresher("qa-person");
// an older snapshot of the same source already exists; the run must not use it
let earlier = lab.start(&lab.admin(), "earlier").await.1["id"]
.as_str()
.unwrap()
.to_string();
let first = lab
.capture(&Lab::production_identity(), false)
.await
.unwrap();
assert_eq!(lab.tick().await, 1);
assert_eq!(lab.run(&earlier).status, "restoring");
let (job, token) = lab.restore_until_ready().await.unwrap();
assert_eq!(lab.apply(&job, &token).await, StatusCode::NO_CONTENT);
lab.report_applied(&job, &token).await;
lab.tick().await;
assert_eq!(lab.run(&earlier).status, "completed");
assert_eq!(
lab.run(&earlier).snapshot_id.as_deref(),
Some(first.to_string().as_str())
);
// now the QA person's own run
let (status, started) = lab.start(&qa, "qa-1").await;
assert_eq!(status, StatusCode::ACCEPTED, "{started}");
let run = started["id"].as_str().unwrap().to_string();
assert_eq!(started["status"], "capturing");
assert!(
started.get("requested_by").is_none() && started.get("snapshot_id").is_none(),
"a refresher does not see who or which snapshot"
);
assert_eq!(
lab.tick().await,
0,
"nothing to do until the capture has run"
);
assert_eq!(lab.restore_jobs(), 1);
let second = lab
.capture(&Lab::production_identity(), false)
.await
.unwrap();
assert_ne!(first, second, "a new capture, not the old snapshot");
assert_eq!(lab.tick().await, 1);
assert_eq!(lab.restore_jobs(), 2);
let stored = lab.run(&run);
assert_eq!(
(stored.status.as_str(), stored.snapshot_id.as_deref()),
("restoring", Some(second.to_string().as_str()))
);
// the restore job belongs to this run, names the requester by stable id, and points at this run's snapshot
let (restore_snapshot, actor): (String, String) = lab
.conn()
.query_row(
"SELECT snapshot_id, actor FROM restore_jobs WHERE id=?1",
[stored.restore_job_id.clone().unwrap()],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.unwrap();
assert_eq!(restore_snapshot, second.to_string());
assert_eq!(actor, format!("oidc:{}", qa.user_id.clone().unwrap()));
let (job, token) = lab.restore_until_ready().await.unwrap();
assert_eq!(
lab.apply(&job, &token).await,
StatusCode::NO_CONTENT,
"still authorised, so the agent may apply"
);
assert_eq!(
lab.run(&run).status,
"restoring",
"applying is the restore job's state; the run follows it"
);
lab.report_applied(&job, &token).await;
assert_eq!(lab.tick().await, 1);
assert_eq!(lab.run(&run).status, "completed");
assert_eq!(
lab.audit_actions(&run),
[
"refresh.started",
"refresh.restore_queued",
"refresh.completed"
]
);
// the person can follow it, and sees the capture time but not where the database is
let (status, view) = lab
.send(&qa, "GET", &format!("/api/v1/refresh-runs/{run}"), None)
.await;
assert_eq!(
(
status,
view["status"].clone(),
view["source_name"].clone(),
view["target_name"].clone()
),
(
StatusCode::OK,
json!("completed"),
json!("prod-db"),
json!("staging-db")
)
);
assert!(view["snapshot_taken_at"].is_i64());
for secret in ["instance", "identity", "outpost", "7300000000000000001"] {
assert!(
!view.to_string().contains(secret),
"{secret} leaked: {view}"
);
}
}
#[tokio::test]
async fn a_double_submit_is_one_run_and_two_keys_on_one_target_are_one_run_and_one_conflict() {
let lab = fresh().await;
let (qa, _) = lab.refresher("qa-one");
let (other, _) = lab.refresher("qa-two");
let (status, first) = lab.start(&qa, "same-key").await;
assert_eq!(status, StatusCode::ACCEPTED);
let (status, again) = lab.start(&qa, "same-key").await;
assert_eq!(
(status, again["id"].clone()),
(StatusCode::OK, first["id"].clone()),
"the same key returns the same run"
);
assert_eq!(
(
lab.capture_jobs(),
lab.scalar::<i64>("SELECT COUNT(*) FROM refresh_runs")
),
(1, 1)
);
// another key from the same person: the target is busy, and they are told which run
let (status, busy) = lab.start(&qa, "second-key").await;
assert_eq!(
(status, busy["reason"].clone(), busy["run_id"].clone()),
(
StatusCode::CONFLICT,
json!("run_active"),
first["id"].clone()
)
);
// another person is told it is busy, but not which run it is
let (status, busy) = lab.start(&other, "theirs").await;
assert_eq!(
(status, busy["reason"].clone()),
(StatusCode::CONFLICT, json!("run_active"))
);
assert!(
busy.get("run_id").is_none() || busy["run_id"] == first["id"],
"a grant holder on the relation may see that run"
);
// the key belongs to the person who used it
let (status, _) = lab.start(&other, "same-key").await;
assert_eq!(status, StatusCode::CONFLICT);
assert_eq!(
(
lab.capture_jobs(),
lab.scalar::<i64>("SELECT COUNT(*) FROM refresh_runs")
),
(1, 1),
"nothing extra was created"
);
// key hygiene
let bad = lab.send(&qa, "POST", "/api/v1/refresh-runs", Some(json!({"relation_id": lab.relation, "confirmation": lab.confirmation(), "idempotency_key": "has space"}))).await.0;
assert_eq!(bad, StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn a_failed_capture_ends_the_run_and_never_falls_back_to_an_older_snapshot() {
let lab = fresh().await;
let admin = lab.admin();
// an older, good snapshot exists
let earlier_run = lab.start(&admin, "older").await.1["id"]
.as_str()
.unwrap()
.to_string();
let older = lab
.capture(&Lab::production_identity(), false)
.await
.unwrap();
lab.tick().await;
let (job, token) = lab.restore_until_ready().await.unwrap();
lab.apply(&job, &token).await;
lab.report_applied(&job, &token).await;
lab.tick().await;
assert_eq!(lab.run(&earlier_run).status, "completed");
// the next capture fails
let run = lab.start(&admin, "doomed").await.1["id"]
.as_str()
.unwrap()
.to_string();
lab.capture(&Lab::production_identity(), true)
.await
.unwrap();
assert_eq!(lab.tick().await, 1);
assert_eq!(lab.run(&run).status, "capture_failed");
assert_eq!(
lab.restore_jobs(),
1,
"no restore was queued from the older snapshot"
);
assert_eq!(lab.run(&run).restore_job_id, None);
assert!(!lab.state.db.snapshot_in_restore(older).unwrap());
// the target is free again for a new run, which restores its own new capture
let next = lab.start(&admin, "retry").await.1["id"]
.as_str()
.unwrap()
.to_string();
let newer = lab
.capture(&Lab::production_identity(), false)
.await
.unwrap();
lab.tick().await;
assert_eq!(
lab.run(&next).snapshot_id.as_deref(),
Some(newer.to_string().as_str())
);
assert_ne!(newer, older);
}
/// How an authorisation can be taken away.
#[derive(Clone, Copy, Debug)]
enum Revoke {
GrantDeleted,
UserDisabled,
RelationRetargeted,
TargetRelabelled,
OutpostRevoked,
}
const ALL_REVOKES: [Revoke; 5] = [
Revoke::GrantDeleted,
Revoke::UserDisabled,
Revoke::RelationRetargeted,
Revoke::TargetRelabelled,
Revoke::OutpostRevoked,
];
impl Lab {
async fn revoke(&self, how: Revoke, person: &Caller, grant: &str) {
match how {
Revoke::GrantDeleted => assert!(self
.state
.db
.delete_relation_grant(&self.relation, grant)
.unwrap()),
Revoke::UserDisabled => assert!(self
.state
.db
.set_user_active(person.user_id.as_ref().unwrap(), false)
.unwrap()),
Revoke::RelationRetargeted => {
let other = RestoreTarget {
id: Uuid::new_v4(),
application_id: self.application,
outpost_id: self.outpost,
name: "another-staging".into(),
engine: Engine::Postgres,
identity: DatabaseIdentity {
instance: "7300000000000000002".into(),
database: "other".into(),
},
};
assert!(self.state.db.register_restore_target(&other).unwrap());
self.state
.db
.set_target_environment(other.id, "staging", now())
.unwrap();
self.state
.db
.create_relation(
self.orbit,
other.id,
Some(&self.relation),
false,
false,
"admin",
now(),
)
.unwrap()
.unwrap();
}
Revoke::TargetRelabelled => {
assert!(self
.state
.db
.set_target_environment(self.target, "production", now())
.unwrap()
.is_some());
}
Revoke::OutpostRevoked => assert!(self
.state
.db
.revoke_outpost(&self.outpost.to_string(), now())
.unwrap()),
}
}
}
#[tokio::test]
async fn losing_authorisation_stops_a_run_at_every_stage_before_anything_is_applied() {
for how in ALL_REVOKES {
// stage 1: still capturing
let lab = fresh().await;
let (qa, grant) = lab.refresher("qa");
let run = lab.start(&qa, "k").await.1["id"]
.as_str()
.unwrap()
.to_string();
lab.revoke(how, &qa, &grant).await;
lab.tick().await;
assert_eq!(lab.run(&run).status, "blocked", "{how:?} while capturing");
assert_eq!(lab.restore_jobs(), 0, "{how:?}: no restore was queued");
// stage 2: the capture finished, the restore is not queued yet
let lab = lab_for_stage(how).await;
assert_eq!(lab.restore_jobs(), 0);
// stage 3: the restore is queued but not claimed
let lab = lab_for_queued(how).await;
assert_eq!(lab.restore_jobs(), 1);
}
}
async fn lab_for_stage(how: Revoke) -> Lab {
let lab = fresh().await;
let (qa, grant) = lab.refresher("qa");
let run = lab.start(&qa, "k").await.1["id"]
.as_str()
.unwrap()
.to_string();
lab.capture(&Lab::production_identity(), false)
.await
.unwrap();
lab.revoke(how, &qa, &grant).await;
lab.tick().await;
let stored = lab.run(&run);
assert_eq!(
stored.status, "blocked",
"{how:?} after the capture, before the restore is queued"
);
assert_eq!(stored.restore_job_id, None);
lab
}
async fn lab_for_queued(how: Revoke) -> Lab {
let lab = fresh().await;
let (qa, grant) = lab.refresher("qa");
let run = lab.start(&qa, "k").await.1["id"]
.as_str()
.unwrap()
.to_string();
lab.capture(&Lab::production_identity(), false)
.await
.unwrap();
lab.tick().await;
let job = lab.run(&run).restore_job_id.unwrap();
lab.revoke(how, &qa, &grant).await;
lab.tick().await;
assert_eq!(
lab.run(&run).status,
"blocked",
"{how:?} with the restore queued"
);
assert_eq!(
lab.restore_status(&job),
"cancelled",
"{how:?}: the queued restore was cancelled with it"
);
// the agent finds nothing to do (or, when its Outpost was revoked, nothing at all)
if !matches!(how, Revoke::OutpostRevoked) {
assert!(lab.restore_until_ready().await.is_none());
}
lab
}
#[tokio::test]
async fn the_apply_permit_is_refused_and_the_restore_cancelled_when_authorisation_is_lost_after_the_safety_backup(
) {
for how in [
Revoke::GrantDeleted,
Revoke::UserDisabled,
Revoke::RelationRetargeted,
Revoke::TargetRelabelled,
] {
let lab = fresh().await;
let (qa, grant) = lab.refresher("qa");
let run = lab.start(&qa, "k").await.1["id"]
.as_str()
.unwrap()
.to_string();
lab.capture(&Lab::production_identity(), false)
.await
.unwrap();
lab.tick().await;
let (job, token) = lab.restore_until_ready().await.unwrap();
// the safety backup is done and the agent is about to apply, and then access is taken away, with no tick in between
lab.revoke(how, &qa, &grant).await;
assert_eq!(
lab.apply(&job, &token).await,
StatusCode::CONFLICT,
"{how:?}: the agent must not be allowed to apply"
);
assert_eq!(lab.restore_status(&job), "cancelled", "{how:?}");
assert_ne!(lab.restore_status(&job), "applying");
assert_eq!(lab.run(&run).status, "blocked", "{how:?}");
assert!(
lab.audit_actions(&run)
.contains(&"refresh.blocked".to_string())
|| how_audited_later(&lab, &run).await,
"{how:?}: audited"
);
let refused: i64 =
lab.scalar("SELECT COUNT(*) FROM audit_log WHERE event='restore.apply_refused'");
assert_eq!(refused, 1, "{how:?}");
}
}
/// The apply refusal blocks the run inside the database; the driver audits it on its next pass.
async fn how_audited_later(lab: &Lab, run: &str) -> bool {
lab.tick().await;
let _ = lab.state.db.refresh_run(run);
crate::refresh::audit_run(&lab.state, run, "blocked");
lab.audit_actions(run)
.contains(&"refresh.blocked".to_string())
}
#[tokio::test]
async fn once_applying_has_started_nothing_cancels_it_and_the_run_finishes() {
for how in ALL_REVOKES {
let lab = fresh().await;
let (qa, grant) = lab.refresher("qa");
let run = lab.start(&qa, "k").await.1["id"]
.as_str()
.unwrap()
.to_string();
lab.capture(&Lab::production_identity(), false)
.await
.unwrap();
lab.tick().await;
let (job, token) = lab.restore_until_ready().await.unwrap();
assert_eq!(lab.apply(&job, &token).await, StatusCode::NO_CONTENT);
// authorisation is taken away while the restore is applying
lab.revoke(how, &qa, &grant).await;
lab.tick().await;
assert_eq!(
lab.restore_status(&job),
"applying",
"{how:?}: a half-applied restore is finished, not abandoned"
);
assert_eq!(lab.run(&run).status, "restoring", "{how:?}");
if !matches!(how, Revoke::OutpostRevoked) {
lab.report_applied(&job, &token).await;
lab.tick().await;
assert_eq!(lab.run(&run).status, "completed", "{how:?}");
}
// and it can no longer be cancelled
let (status, body) = lab
.send(
&lab.admin(),
"DELETE",
&format!("/api/v1/refresh-runs/{run}"),
None,
)
.await;
assert_eq!(status, StatusCode::CONFLICT, "{how:?}: {body}");
}
}
#[tokio::test]
async fn restores_started_by_an_administrator_are_not_touched_by_any_of_this() {
let lab = fresh().await;
// a snapshot to restore, from a normal capture
lab.start(&lab.admin(), "seed").await;
let snapshot = lab
.capture(&Lab::production_identity(), false)
.await
.unwrap();
let manifest = lab
.state
.vault
.read()
.await
.get_snapshot(snapshot)
.unwrap()
.unwrap()
.manifest;
let (_, artifact) = crate::api::artifact(&manifest).unwrap();
// an administrator queues a restore directly, as before M6
let job = lab
.state
.db
.enqueue_restore(
snapshot,
lab.application,
lab.target,
"admin:direct",
&artifact,
now(),
)
.unwrap()
.unwrap();
// the relation is ended and the target even relabelled: a refresh would be refused, an admin restore is not
assert!(lab
.state
.db
.set_target_environment(lab.target, "production", now())
.unwrap()
.is_some());
let (restore, token) = lab.restore_until_ready().await.unwrap();
assert_eq!(restore, job.id.to_string());
assert_eq!(
lab.apply(&restore, &token).await,
StatusCode::NO_CONTENT,
"no run, no extra check"
);
assert_eq!(lab.restore_status(&restore), "applying");
}
#[tokio::test]
async fn the_snapshot_is_pinned_from_the_start_and_released_when_the_run_ends() {
let lab = fresh().await;
let admin = lab.admin();
let run = lab.start(&admin, "pin").await.1["id"]
.as_str()
.unwrap()
.to_string();
let capture = Uuid::parse_str(&lab.run(&run).capture_job_id).unwrap();
assert!(
lab.state.db.snapshot_in_restore(capture).unwrap(),
"pinned the moment the run starts"
);
lab.capture(&Lab::production_identity(), false)
.await
.unwrap();
// between the capture finishing and the restore being queued, retention and deletion must still leave it alone
let (status, _) = lab
.send(
&admin,
"DELETE",
&format!("/api/v1/snapshots/{capture}"),
None,
)
.await;
assert_eq!(
status,
StatusCode::CONFLICT,
"deleting a pinned snapshot is refused"
);
lab.state.prune_orbit(lab.orbit).await.unwrap();
assert!(
lab.state
.vault
.read()
.await
.get_snapshot(capture)
.unwrap()
.is_some(),
"retention left it alone"
);
lab.tick().await;
assert!(lab.state.db.snapshot_in_restore(capture).unwrap());
// finishing the run (here: cancelling it) releases the pin
let (status, _) = lab
.send(
&admin,
"DELETE",
&format!("/api/v1/refresh-runs/{run}"),
None,
)
.await;
assert_eq!(status, StatusCode::OK);
assert!(
!lab.state.db.snapshot_in_restore(capture).unwrap(),
"released"
);
}
#[tokio::test]
async fn a_run_expires_before_it_applies_but_never_while_applying() {
let lab = lab_with(|state| {
state.refresh = std::sync::Arc::new(crate::refresh::RefreshConfig {
ttl_secs: 60,
max_active: 4,
})
})
.await;
let (qa, _) = lab.refresher("qa");
let run = lab.start(&qa, "k").await.1["id"]
.as_str()
.unwrap()
.to_string();
let stored = lab.run(&run);
assert_eq!(stored.expires_at - stored.created_at, 60);
// before the deadline nothing changes; after it the run is expired and no restore is ever queued
assert_eq!(
lab.state
.db
.sync_refresh_run(&run, stored.created_at + 59)
.unwrap(),
crate::db::refresh::Sync::Unchanged
);
assert_eq!(
lab.state
.db
.sync_refresh_run(&run, stored.expires_at)
.unwrap(),
crate::db::refresh::Sync::Moved("expired".into())
);
assert_eq!(lab.run(&run).status, "expired");
// a run that is already applying is not cut off by its deadline
let lab = lab_with(|state| {
state.refresh = std::sync::Arc::new(crate::refresh::RefreshConfig {
ttl_secs: 60,
max_active: 4,
})
})
.await;
let run = lab.start(&lab.admin(), "k").await.1["id"]
.as_str()
.unwrap()
.to_string();
lab.capture(&Lab::production_identity(), false)
.await
.unwrap();
lab.tick().await;
let (job, token) = lab.restore_until_ready().await.unwrap();
assert_eq!(lab.apply(&job, &token).await, StatusCode::NO_CONTENT);
let late = lab.run(&run).expires_at + 3600;
assert_eq!(
lab.state.db.sync_refresh_run(&run, late).unwrap(),
crate::db::refresh::Sync::Unchanged
);
assert_eq!(lab.run(&run).status, "restoring");
}
#[tokio::test]
async fn a_stale_confirmation_a_retarget_and_a_busy_system_are_refused_with_a_reason() {
let lab = fresh().await;
let (qa, grant) = lab.refresher("qa");
// the relation is retargeted between the person looking at it and pressing the button
lab.revoke(Revoke::RelationRetargeted, &qa, &grant).await;
let (status, _) = lab.start(&qa, "old-relation").await;
assert_eq!(
status,
StatusCode::NOT_FOUND,
"the old relation no longer exists for them"
);
let new = lab
.state
.db
.relation_views(true, None, now())
.unwrap()
.remove(0)
.relation;
let admin = lab.admin();
let (status, stale) = lab.send(&admin, "POST", "/api/v1/refresh-runs", Some(json!({"relation_id": new.id, "confirmation": lab.confirmation(), "idempotency_key": "stale"}))).await;
assert_eq!(
(status, stale["reason"].clone()),
(StatusCode::CONFLICT, json!("stale_confirmation")),
"the confirmation named version 1 and the target the person saw"
);
assert_eq!(lab.scalar::<i64>("SELECT COUNT(*) FROM refresh_runs"), 0);
// too many refreshes at once
let busy = lab_with(|state| {
state.refresh = std::sync::Arc::new(crate::refresh::RefreshConfig {
ttl_secs: 3600,
max_active: 0,
})
})
.await;
let (status, refusal) = busy.start(&busy.admin(), "k").await;
assert_eq!(
(status, refusal["reason"].clone()),
(StatusCode::TOO_MANY_REQUESTS, json!("too_many_runs"))
);
// a person without a grant gets 404, not a hint that the relation exists
let stranger = busy.person("stranger");
assert_eq!(busy.start(&stranger, "k").await.0, StatusCode::NOT_FOUND);
// an unusable relation is refused before anything is queued
busy.state
.db
.set_target_environment(busy.target, "production", now())
.unwrap();
assert_eq!(busy.capture_jobs(), 0);
}
#[tokio::test]
async fn a_run_can_be_cancelled_by_its_owner_or_an_administrator_and_seen_only_by_those_with_a_reason(
) {
let lab = fresh().await;
let (owner, _) = lab.refresher("owner");
let (colleague, _) = lab.refresher("colleague");
let stranger = lab.person("stranger");
let run = lab.start(&owner, "k").await.1["id"]
.as_str()
.unwrap()
.to_string();
let uri = format!("/api/v1/refresh-runs/{run}");
// visibility: owner, a grant holder on the relation, and an administrator; nobody else
assert_eq!(lab.send(&owner, "GET", &uri, None).await.0, StatusCode::OK);
assert_eq!(
lab.send(&colleague, "GET", &uri, None).await.0,
StatusCode::OK
);
assert_eq!(
lab.send(&stranger, "GET", &uri, None).await.0,
StatusCode::NOT_FOUND
);
let (_, admin_view) = lab.send(&lab.admin(), "GET", &uri, None).await;
assert!(
admin_view["requested_by"]
.as_str()
.unwrap()
.starts_with("oidc:"),
"an administrator sees who started it"
);
assert!(lab
.send(&colleague, "GET", &uri, None)
.await
.1
.get("requested_by")
.is_none());
// lists
assert_eq!(
lab.send(&colleague, "GET", "/api/v1/refresh-runs", None)
.await
.1
.as_array()
.unwrap()
.len(),
1
);
assert_eq!(
lab.send(&stranger, "GET", "/api/v1/refresh-runs", None)
.await
.0,
StatusCode::FORBIDDEN
);
// cancelling: not by a colleague who merely holds a grant, not by a stranger
assert_eq!(
lab.send(&colleague, "DELETE", &uri, None).await.0,
StatusCode::FORBIDDEN
);
assert_eq!(
lab.send(&stranger, "DELETE", &uri, None).await.0,
StatusCode::NOT_FOUND
);
assert_eq!(lab.run(&run).status, "capturing");
let (status, cancelled) = lab.send(&owner, "DELETE", &uri, None).await;
assert_eq!(
(status, cancelled["status"].clone()),
(StatusCode::OK, json!("cancelled"))
);
assert_eq!(
lab.send(&owner, "DELETE", &uri, None).await.1["reason"],
"too_late"
);
// the target is free again
assert_eq!(lab.start(&colleague, "next").await.0, StatusCode::ACCEPTED);
}
#[tokio::test]
async fn a_queued_restore_is_cancelled_with_its_run_and_every_step_is_safe_to_repeat() {
let lab = fresh().await;
let admin = lab.admin();
let run = lab.start(&admin, "k").await.1["id"]
.as_str()
.unwrap()
.to_string();
lab.capture(&Lab::production_identity(), false)
.await
.unwrap();
// a crash after the capture and before the link: the pass can simply run again, any number of times
assert_eq!(lab.tick().await, 1);
assert_eq!((lab.tick().await, lab.tick().await), (0, 0));
assert_eq!(lab.restore_jobs(), 1, "exactly one restore");
let stored = lab.run(&run);
let manifest = lab
.state
.vault
.read()
.await
.get_snapshot(Uuid::parse_str(&stored.capture_job_id).unwrap())
.unwrap()
.unwrap()
.manifest;
let (_, artifact) = crate::api::artifact(&manifest).unwrap();
assert_eq!(
lab.state
.db
.enqueue_refresh_restore(&run, &artifact, false, now())
.unwrap(),
crate::db::refresh::Linked::NotReady,
"a repeated link changes nothing"
);
assert_eq!(lab.restore_jobs(), 1);
assert_eq!(
lab.state.db.sync_refresh_run(&run, now()).unwrap(),
crate::db::refresh::Sync::Unchanged
);
// cancelling before the agent claims it cancels the restore too
let job = lab.run(&run).restore_job_id.unwrap();
assert_eq!(
lab.send(
&admin,
"DELETE",
&format!("/api/v1/refresh-runs/{run}"),
None
)
.await
.0,
StatusCode::OK
);
assert_eq!(lab.restore_status(&job), "cancelled");
assert!(lab.restore_until_ready().await.is_none());
}
#[tokio::test]
async fn a_target_that_is_the_source_or_a_production_database_is_refused_when_the_snapshot_is_known(
) {
// the dump says it came from the very database the relation would overwrite
let lab = fresh().await;
let run = lab.start(&lab.admin(), "k").await.1["id"]
.as_str()
.unwrap()
.to_string();
lab.capture(
&DatabaseIdentity {
instance: "7300000000000000001".into(),
database: "staging_app".into(),
},
false,
)
.await
.unwrap();
lab.tick().await;
let stored = lab.run(&run);
// either rule may be the first to see it: the identity check against every captured source, or the restore's own source/target check
assert_eq!(stored.status, "blocked");
assert!(
matches!(
stored.blocked_reason.as_deref(),
Some("target_rejected" | "target_matches_a_production_source")
),
"{:?}",
stored.blocked_reason
);
assert_eq!(lab.restore_jobs(), 0);
// another orbit captured as production holds the very database this "staging" target points at
let lab = fresh().await;
let other = Uuid::new_v4();
lab.state
.db
.upsert_orbit(&crate::db::OrbitRow {
id: other,
name: "other-prod".into(),
provider: "wormhole".into(),
provider_config: "{}".into(),
schedule: None,
decay_preset: "week-of-dailies".into(),
retention: None,
dry_run: false,
last_status: "idle".into(),
})
.await
.unwrap();
let manifest = tessera_core::manifest::SnapshotManifest {
snapshot_id: Uuid::new_v4(),
orbit_id: other,
orbit_name: "other-prod".into(),
labels: vec![],
provider: "postgres".into(),
paths: vec![],
restore_hints: json!({"format": "custom", "source_identity": {"instance": "7300000000000000001", "database": "staging_app"}}),
};
lab.state
.vault
.write()
.await
.snapshot(manifest, b"PGDMP", false)
.unwrap();
lab.state
.db
.set_orbit_environment(other, "production", now())
.unwrap();
let run = lab.start(&lab.admin(), "k").await.1["id"]
.as_str()
.unwrap()
.to_string();
lab.capture(&Lab::production_identity(), false)
.await
.unwrap();
lab.tick().await;
assert_eq!(
lab.run(&run).blocked_reason.as_deref(),
Some("target_matches_a_production_source")
);
assert_eq!(lab.restore_jobs(), 0);
}
#[tokio::test]
async fn someone_who_may_only_refresh_gets_into_the_app_but_sees_nothing_else() {
let lab = fresh().await;
let nobody = lab.person("nobody");
let status = lab
.send(&nobody, "GET", "/api/v1/operator/session", None)
.await
.1;
assert_eq!(
(status["authorized"].clone(), status["admin"].clone()),
(json!(false), json!(false)),
"no grant at all: closed"
);
let (qa, _) = lab.refresher("qa");
let status = lab
.send(&qa, "GET", "/api/v1/operator/session", None)
.await
.1;
assert_eq!(
(status["authorized"].clone(), status["admin"].clone()),
(json!(true), json!(false)),
"a relation grant opens the app"
);
let me = lab.send(&qa, "GET", "/api/v1/me", None).await.1;
assert_eq!(me["refresh_relations"], json!([lab.relation.clone()]));
assert_eq!(
me["grants"].as_array().unwrap().len(),
0,
"and carries no orbit permission"
);
// nothing about orbits, snapshots or restores is visible to them
for path in [
"/api/v1/orbits",
"/api/v1/snapshots",
"/api/v1/capture-jobs",
"/api/v1/restore-jobs",
"/api/v1/relations",
] {
assert_eq!(
lab.send(&qa, "GET", path, None).await.0,
StatusCode::FORBIDDEN,
"{path}"
);
}
assert_eq!(
lab.send(&qa, "GET", "/api/v1/refresh-relations", None)
.await
.0,
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
);
}
// ---- why a restore failed ----
impl Lab {
async fn report_with_reason(
&self,
job: &str,
token: &str,
progress: &str,
reason: &str,
) -> StatusCode {
self.agent_json(
"POST",
&format!("/api/v1/wormhole/restore/{job}/report"),
&[
("x-tessera-restore-token", token.to_string()),
("x-tessera-failure-reason", reason.to_string()),
],
json!(progress),
)
.await
.0
}
}
#[tokio::test]
async fn a_failed_restore_says_why_to_administrators_only() {
let lab = fresh().await;
let (qa, _) = lab.refresher("qa");
let run = lab.start(&qa, "why").await.1["id"]
.as_str()
.unwrap()
.to_string();
lab.capture(&Lab::production_identity(), false)
.await
.unwrap();
lab.tick().await;
let (job, token) = lab.restore_until_ready().await.unwrap();
assert_eq!(lab.apply(&job, &token).await, StatusCode::NO_CONTENT);
let reason = "psql failed (exit status: 3): ERROR: schema \"drizzle\" already exists";
assert_eq!(
lab.report_with_reason(&job, &token, "apply_failed", reason)
.await,
StatusCode::NO_CONTENT
);
let (status, view) = lab
.send(
&lab.admin(),
"GET",
&format!("/api/v1/restore-jobs/{job}"),
None,
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(view["phase"], "apply_failed");
// whitespace is normalised on the way in (psql pads "ERROR: ")
assert_eq!(
view["failure_reason"],
"psql failed (exit status: 3): ERROR: schema \"drizzle\" already exists"
);
assert!(lab
.audit_log()
.iter()
.any(|(event, detail)| event == "restore.failed" && detail.contains("drizzle")));
// the person who started the refresh sees that it failed, never the database's own words
lab.tick().await;
let (_, seen) = lab
.send(&qa, "GET", &format!("/api/v1/refresh-runs/{run}"), None)
.await;
assert_eq!(seen["status"], "recovery_required", "{seen}");
assert!(
!seen.to_string().contains("drizzle") && seen.get("failure_reason").is_none(),
"{seen}"
);
}
#[tokio::test]
async fn a_failure_reason_is_only_kept_for_failures_and_is_cleaned_and_bounded() {
let lab = fresh().await;
lab.start(&lab.admin(), "clean").await;
lab.capture(&Lab::production_identity(), false)
.await
.unwrap();
lab.tick().await;
let (job, token) = lab.restore_until_ready().await.unwrap();
// a heartbeat that carries a reason does not create one
assert_eq!(
lab.report_with_reason(&job, &token, "heartbeat", "ignored")
.await,
StatusCode::NO_CONTENT
);
let admin = lab.admin();
let uri = format!("/api/v1/restore-jobs/{job}");
assert!(lab
.send(&admin, "GET", &uri, None)
.await
.1
.get("failure_reason")
.is_none());
assert_eq!(lab.apply(&job, &token).await, StatusCode::NO_CONTENT);
let long = format!("ERROR:\t{}\tend", "x".repeat(2000));
assert_eq!(
lab.report_with_reason(&job, &token, "apply_failed", &long)
.await,
StatusCode::NO_CONTENT
);
let reason = lab.send(&admin, "GET", &uri, None).await.1["failure_reason"]
.as_str()
.unwrap()
.to_string();
assert!(
reason.len() <= 300 && reason.starts_with("ERROR: xxx"),
"{}",
reason.len()
);
assert!(
reason.chars().all(|c| c.is_ascii() && !c.is_control()),
"{reason:?}"
);
}
// ---- retention: a safety copy of the target is not a backup of production ----
#[tokio::test]
async fn a_restore_safety_copy_never_pushes_a_production_capture_out_of_retention() {
use tessera_core::decay::CaptureRetention;
let lab = fresh().await;
// the harshest rule: only the newest archive is kept
lab.state
.db
.update_capture_profile(
lab.application,
crate::db::ProfileChange {
schedule: None,
retention: Some(Some(CaptureRetention::Count { keep: 1 })),
},
now(),
)
.unwrap()
.unwrap();
lab.start(&lab.admin(), "safety-retention").await;
let capture = lab
.capture(&Lab::production_identity(), false)
.await
.unwrap();
lab.tick().await;
// the target's safety copy is taken later than the production capture
tokio::time::sleep(std::time::Duration::from_millis(1200)).await;
let (job, token) = lab.restore_until_ready().await.unwrap();
assert_eq!(lab.apply(&job, &token).await, StatusCode::NO_CONTENT);
lab.report_applied(&job, &token).await;
lab.tick().await;
let snapshots = lab.state.vault.read().await.list_snapshots().unwrap();
let safety: Vec<_> = snapshots
.iter()
.filter(|s| s.manifest.is_restore_safety())
.map(|s| s.id)
.collect();
assert_eq!(
safety.len(),
1,
"one safety copy exists next to the capture"
);
let forgotten = lab.state.prune_orbit(lab.orbit).await.unwrap();
assert!(
!forgotten.contains(&capture),
"the production capture survived: {forgotten:?}"
);
assert!(
forgotten.is_empty(),
"and the fresh safety copy is kept too: {forgotten:?}"
);
let vault = lab.state.vault.read().await;
assert!(vault.get_snapshot(capture).unwrap().is_some());
assert!(vault.get_snapshot(safety[0]).unwrap().is_some());
}
#[tokio::test]
async fn reconciling_a_job_that_needs_no_recovery_says_so() {
let lab = fresh().await;
lab.start(&lab.admin(), "reconcile").await;
lab.capture(&Lab::production_identity(), false)
.await
.unwrap();
lab.tick().await;
let (job, _token) = lab.restore_until_ready().await.unwrap();
let uri = format!("/api/v1/restore-jobs/{job}/reconcile");
let (status, body) = lab
.send(
&lab.admin(),
"POST",
&uri,
Some(json!({"confirmation": format!("RECONCILE {job}")})),
)
.await;
assert_eq!(status, StatusCode::CONFLICT);
assert!(
body["error"]
.as_str()
.is_some_and(|text| text.contains("recovery_required")),
"{body}"
);
// the wrong confirmation is still a plain 400
let (status, _) = lab
.send(
&lab.admin(),
"POST",
&uri,
Some(json!({"confirmation": "no"})),
)
.await;
assert_eq!(status, StatusCode::BAD_REQUEST);
}
// ---- naming restore targets ----
#[tokio::test]
async fn an_administrator_can_rename_a_target_and_everything_that_points_at_it_keeps_working() {
let lab = fresh().await;
let admin = lab.admin();
let (qa, _) = lab.refresher("qa");
let uri = format!("/api/v1/restore-targets/{}", lab.target);
let (status, _) = lab
.send(
&admin,
"PUT",
&uri,
Some(json!({"name": "billing · dev · app_dev"})),
)
.await;
assert_eq!(status, StatusCode::NO_CONTENT);
let (_, overview) = lab.send(&admin, "GET", "/api/v1/relations", None).await;
let target = &overview["targets"][0];
assert_eq!(target["name"], "billing · dev · app_dev");
assert_eq!(target["id"], lab.target.to_string());
assert_eq!(
target["identity"]["database"], "staging_app",
"identity is untouched"
);
let relation = &overview["relations"][0];
assert_eq!(relation["target_name"], "billing · dev · app_dev");
assert_eq!(
relation["id"], lab.relation,
"the relation is the same relation"
);
assert!(relation["usable"].as_bool().unwrap());
// the person who refreshes through it sees the new name, and a run through it still starts
let (_, mine) = lab
.send(&qa, "GET", "/api/v1/refresh-relations", None)
.await;
assert_eq!(mine[0]["target_name"], "billing · dev · app_dev");
let confirmation = format!(
"REFRESH prod-db TO billing · dev · app_dev v{}",
lab.relation_version
);
let (status, body) = lab
.send(&qa, "POST", "/api/v1/refresh-runs", Some(json!({"relation_id": lab.relation, "confirmation": confirmation, "idempotency_key": "after-rename"})))
.await;
assert_eq!(status, StatusCode::ACCEPTED, "{body}");
assert!(lab
.audit_log()
.iter()
.any(|(event, detail)| event == "restore_target.renamed"
&& detail.contains(&lab.target.to_string())));
}
#[tokio::test]
async fn a_target_name_is_validated_like_a_registration_and_only_administrators_set_it() {
let lab = fresh().await;
let admin = lab.admin();
let uri = format!("/api/v1/restore-targets/{}", lab.target);
for name in ["", " ", &"x".repeat(129), "bad\nname", "tab\tname"] {
let (status, _) = lab
.send(&admin, "PUT", &uri, Some(json!({"name": name})))
.await;
assert_eq!(status, StatusCode::BAD_REQUEST, "{name:?}");
}
let (status, _) = lab
.send(
&admin,
"PUT",
&uri,
Some(json!({"name": "ok", "identity": {}})),
)
.await;
assert_eq!(
status,
StatusCode::UNPROCESSABLE_ENTITY,
"only the name is editable"
);
let unknown = format!("/api/v1/restore-targets/{}", Uuid::new_v4());
assert_eq!(
lab.send(&admin, "PUT", &unknown, Some(json!({"name": "ok"})))
.await
.0,
StatusCode::NOT_FOUND
);
let (qa, _) = lab.refresher("qa");
let status = lab
.send(&qa, "PUT", &uri, Some(json!({"name": "mine"})))
.await
.0;
assert!(
status == StatusCode::FORBIDDEN || status == StatusCode::NOT_FOUND,
"{status}"
);
let (_, overview) = lab.send(&admin, "GET", "/api/v1/relations", None).await;
assert_eq!(
overview["targets"][0]["name"], "staging-db",
"nothing above changed it"
);
// the longest allowed name is fine
assert_eq!(
lab.send(&admin, "PUT", &uri, Some(json!({"name": "y".repeat(128)})))
.await
.0,
StatusCode::NO_CONTENT
);
}
// ---- renaming orbits ----
impl Lab {
async fn download_disposition(&self, snapshot: Uuid) -> String {
let request = Request::builder()
.method("GET")
.uri(format!("/api/v1/snapshots/{snapshot}/download"))
.header("x-tessera-admin-token", ADMIN)
.extension(ConnectInfo("127.0.0.1:4000".parse::<SocketAddr>().unwrap()))
.body(Body::empty())
.unwrap();
let response = self.app.clone().oneshot(request).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
response.headers()[header::CONTENT_DISPOSITION]
.to_str()
.unwrap()
.to_string()
}
}
#[tokio::test]
async fn renaming_an_orbit_renames_its_old_snapshots_everywhere_they_are_shown() {
let lab = fresh().await;
let admin = lab.admin();
let (qa, _) = lab.refresher("qa");
lab.start(&admin, "orbit-rename").await;
let snapshot = lab
.capture(&Lab::production_identity(), false)
.await
.unwrap();
assert!(lab
.download_disposition(snapshot)
.await
.contains("filename=\"prod-db_"));
let uri = format!("/api/v1/orbits/{}", lab.orbit);
assert_eq!(
lab.send(&admin, "PUT", &uri, Some(json!({"name": " warehouse "})))
.await
.0,
StatusCode::NO_CONTENT
);
// the snapshot was written under the old name; it is shown under the current one
let (_, listed) = lab.send(&admin, "GET", "/api/v1/snapshots", None).await;
assert_eq!(listed[0]["orbit_name"], "warehouse", "{listed}");
assert!(lab
.download_disposition(snapshot)
.await
.contains("filename=\"warehouse_"));
let (_, overview) = lab.send(&admin, "GET", "/api/v1/relations", None).await;
assert!(overview["orbits"]
.as_array()
.unwrap()
.iter()
.any(|o| o["name"] == "warehouse"));
let (_, mine) = lab
.send(&qa, "GET", "/api/v1/refresh-relations", None)
.await;
assert_eq!(mine[0]["source_name"], "warehouse");
// nothing but the name moved: the relation, its confirmation text and the id are the same relation
assert_eq!(overview["relations"][0]["id"], lab.relation);
assert!(
lab.audit_log()
.iter()
.any(|(event, detail)| event == "orbit.renamed"
&& detail.contains(&lab.orbit.to_string()))
);
}
#[tokio::test]
async fn an_orbit_name_is_validated_unique_and_only_administrators_change_it() {
let lab = fresh().await;
let admin = lab.admin();
let uri = format!("/api/v1/orbits/{}", lab.orbit);
for name in ["", " ", &"x".repeat(129), "bad\nname"] {
assert_eq!(
lab.send(&admin, "PUT", &uri, Some(json!({"name": name})))
.await
.0,
StatusCode::BAD_REQUEST,
"{name:?}"
);
}
assert_eq!(
lab.send(
&admin,
"PUT",
&uri,
Some(json!({"name": "ok", "provider": "x"}))
)
.await
.0,
StatusCode::UNPROCESSABLE_ENTITY
);
let unknown = format!("/api/v1/orbits/{}", Uuid::new_v4());
assert_eq!(
lab.send(&admin, "PUT", &unknown, Some(json!({"name": "ok"})))
.await
.0,
StatusCode::NOT_FOUND
);
// another orbit already has that name (compared without regard to case); keeping your own name is fine
lab.state
.db
.upsert_orbit(&crate::db::OrbitRow {
id: Uuid::new_v4(),
name: "Other".into(),
provider: "wormhole".into(),
provider_config: "{}".into(),
schedule: None,
decay_preset: "week-of-dailies".into(),
retention: None,
dry_run: false,
last_status: "idle".into(),
})
.await
.unwrap();
assert_eq!(
lab.send(&admin, "PUT", &uri, Some(json!({"name": "other"})))
.await
.0,
StatusCode::CONFLICT
);
assert_eq!(
lab.send(&admin, "PUT", &uri, Some(json!({"name": "prod-db"})))
.await
.0,
StatusCode::NO_CONTENT
);
let (qa, _) = lab.refresher("qa");
let status = lab
.send(&qa, "PUT", &uri, Some(json!({"name": "mine"})))
.await
.0;
assert!(
status == StatusCode::FORBIDDEN || status == StatusCode::NOT_FOUND,
"{status}"
);
}
// ---- restoring a snapshot that already exists (the Restore button on a snapshot) ----
impl Lab {
async fn start_snapshot(
&self,
caller: &Caller,
key: &str,
snapshot: Uuid,
) -> (StatusCode, Value) {
self.send(
caller,
"POST",
"/api/v1/refresh-runs",
Some(json!({"relation_id": self.relation, "confirmation": self.confirmation(), "idempotency_key": key, "snapshot_id": snapshot})),
)
.await
}
/// A snapshot written straight into the vault, to stand in for one of another orbit or a safety copy.
async fn plant_snapshot(&self, orbit: Uuid, labels: &[&str], hints: Value) -> Uuid {
let id = Uuid::new_v4();
let manifest = tessera_core::manifest::SnapshotManifest {
snapshot_id: id,
orbit_id: orbit,
orbit_name: "planted".into(),
labels: labels.iter().map(|s| s.to_string()).collect(),
provider: "postgres".into(),
paths: vec![],
restore_hints: hints,
};
self.state
.vault
.write()
.await
.snapshot(manifest, b"PGDMP planted", false)
.unwrap();
id
}
/// Walk a restore job through to the end the way the agent does.
async fn finish_restore(&self) -> String {
let (job, token) = self
.restore_until_ready()
.await
.expect("a restore job is waiting");
assert_eq!(self.apply(&job, &token).await, StatusCode::NO_CONTENT);
self.report_applied(&job, &token).await;
self.tick().await;
job
}
}
#[tokio::test]
async fn an_existing_snapshot_is_restored_without_a_new_capture_and_can_be_restored_again() {
let lab = fresh().await;
let (qa, _) = lab.refresher("qa");
// a snapshot exists from an earlier refresh
lab.start(&lab.admin(), "seed").await;
let snapshot = lab
.capture(&Lab::production_identity(), false)
.await
.unwrap();
lab.tick().await;
lab.finish_restore().await;
let captures = lab.capture_jobs();
let (status, run) = lab.start_snapshot(&qa, "again", snapshot).await;
assert_eq!(status, StatusCode::ACCEPTED, "{run}");
let run_id = run["id"].as_str().unwrap().to_string();
lab.tick().await;
assert_eq!(lab.run(&run_id).status, "restoring");
assert_eq!(
lab.run(&run_id).snapshot_id.as_deref(),
Some(snapshot.to_string().as_str())
);
assert_eq!(
lab.capture_jobs(),
captures,
"no new capture: the person picked a backup"
);
lab.finish_restore().await;
assert_eq!(lab.run(&run_id).status, "completed");
// and the same snapshot can go to the target again
let (status, again) = lab.start_snapshot(&qa, "third", snapshot).await;
assert_eq!(status, StatusCode::ACCEPTED, "{again}");
}
#[tokio::test]
async fn only_a_restorable_snapshot_of_the_relations_own_source_is_accepted() {
let lab = fresh().await;
let admin = lab.admin();
// a real capture, so the planted copies below are as restorable as it is
lab.start(&admin, "seed").await;
let real = lab
.capture(&Lab::production_identity(), false)
.await
.unwrap();
let hints = lab
.state
.vault
.read()
.await
.get_snapshot(real)
.unwrap()
.unwrap()
.manifest
.restore_hints;
let other_orbit = lab.plant_snapshot(Uuid::new_v4(), &[], hints.clone()).await;
let safety = lab
.plant_snapshot(lab.orbit, &["restore-safety"], hints)
.await;
lab.tick().await;
lab.finish_restore().await;
let runs = lab.scalar::<i64>("SELECT COUNT(*) FROM refresh_runs");
let jobs = lab.restore_jobs();
// the real one is accepted, so the refusals below are about the snapshot and nothing else
assert_eq!(
lab.start_snapshot(&admin, "good", real).await.0,
StatusCode::ACCEPTED
);
lab.tick().await;
lab.finish_restore().await;
let runs = runs + 1;
let jobs = jobs + 1;
for (n, (what, snapshot)) in [
("another orbit's", other_orbit),
("a safety copy", safety),
("an unknown one", Uuid::new_v4()),
]
.into_iter()
.enumerate()
{
let (status, body) = lab
.start_snapshot(&admin, &format!("bad-{n}"), snapshot)
.await;
assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{what}: {body}");
assert_eq!(body["reason"], "snapshot_unusable", "{what}");
}
assert_eq!(lab.restore_jobs(), jobs);
assert_eq!(
lab.scalar::<i64>("SELECT COUNT(*) FROM refresh_runs"),
runs,
"nothing was started"
);
}
#[tokio::test]
async fn a_restore_of_an_existing_snapshot_is_stopped_when_the_grant_goes_before_it_is_queued() {
let lab = fresh().await;
let (qa, grant) = lab.refresher("qa");
lab.start(&lab.admin(), "seed").await;
let snapshot = lab
.capture(&Lab::production_identity(), false)
.await
.unwrap();
lab.tick().await;
lab.finish_restore().await;
let jobs = lab.restore_jobs();
let (_, run) = lab.start_snapshot(&qa, "revoked", snapshot).await;
let run_id = run["id"].as_str().unwrap().to_string();
lab.revoke(Revoke::GrantDeleted, &qa, &grant).await;
lab.tick().await;
assert_eq!(lab.run(&run_id).status, "blocked");
assert_eq!(
lab.run(&run_id).blocked_reason.as_deref(),
Some("access_revoked")
);
assert_eq!(lab.restore_jobs(), jobs, "no restore job was ever queued");
}
#[tokio::test]
async fn the_screens_get_what_they_need_to_offer_restore_for_an_orbit() {
let lab = fresh().await;
let (qa, _) = lab.refresher("qa");
let (_, mine) = lab
.send(&qa, "GET", "/api/v1/refresh-relations", None)
.await;
assert_eq!(mine[0]["source_orbit_id"], lab.orbit.to_string(), "{mine}");
// a snapshot knows whether it is a capture or a safety copy, so pickers can leave the latter out
lab.start(&lab.admin(), "kind").await;
lab.capture(&Lab::production_identity(), false)
.await
.unwrap();
lab.tick().await;
lab.restore_until_ready().await.unwrap();
let (_, listed) = lab
.send(&lab.admin(), "GET", "/api/v1/snapshots", None)
.await;
let kinds: Vec<_> = listed
.as_array()
.unwrap()
.iter()
.map(|s| s["kind"].as_str().unwrap().to_string())
.collect();
assert!(
kinds.contains(&"capture".to_string()) && kinds.contains(&"safety".to_string()),
"{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");
// the undo says which restore it puts back, and the restore says which job it queued
let (_, child) = lab
.send(&qa, "GET", &format!("/api/v1/refresh-runs/{undo_id}"), None)
.await;
assert_eq!(child["undo_of"], json!(first), "{child}");
assert!(child["restore_job_id"].is_string(), "{child}");
let (_, parent) = lab
.send(&qa, "GET", &format!("/api/v1/refresh-runs/{first}"), None)
.await;
assert!(parent.get("undo_of").is_none(), "{parent}");
// 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);
}
// ---- why a restore can or cannot be put back, and rolling back a restore that failed ----
impl Lab {
async fn run_view(&self, run: &str) -> Value {
self.send(&self.admin(), "GET", &format!("/api/v1/refresh-runs/{run}"), None)
.await
.1
}
fn safety_of(&self, run: &str) -> Uuid {
Uuid::parse_str(&self.scalar::<String>(&format!(
"SELECT safety_id FROM restore_jobs WHERE id=(SELECT restore_job_id FROM refresh_runs WHERE id='{run}')"
)))
.unwrap()
}
/// A restore that got as far as overwriting the target and then failed, as the agent reports it.
async fn failed_apply(&self, key: &str) -> (String, 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;
let (job, token) = self.restore_until_ready().await.expect("a restore job is waiting");
assert_eq!(self.apply(&job, &token).await, StatusCode::NO_CONTENT);
let (status, _) = self
.agent_json(
"POST",
&format!("/api/v1/wormhole/restore/{job}/report"),
&[("x-tessera-restore-token", token)],
json!("apply_failed"),
)
.await;
assert_eq!(status, StatusCode::NO_CONTENT);
self.tick().await;
assert_eq!(self.run(&run).status, "recovery_required");
(run, job)
}
}
#[tokio::test]
async fn a_restore_says_why_it_can_or_cannot_be_put_back_and_how_long_for() {
let lab = fresh().await;
let first = lab.restored_once("first").await;
let view = lab.run_view(&first).await;
assert_eq!((view["undo_available"].clone(), view["undo_state"].clone()), (json!(true), json!("available")), "{view}");
let until = view["undo_kept_until"].as_i64().expect("a date while it can be undone");
assert!(until > chrono::Utc::now().timestamp() + 6 * 86_400, "a week from when it was taken: {view}");
// a later restore of the same target supersedes it; only the newest can be undone
let second = lab.restored_once("second").await;
let (old, new) = (lab.run_view(&first).await, lab.run_view(&second).await);
assert_eq!((old["undo_state"].clone(), old["undo_available"].clone()), (json!("superseded"), json!(false)), "{old}");
assert_eq!(new["undo_state"], "available", "{new}");
// retention forgets the newest copy: it says so, instead of offering something that would be refused
lab.state.vault.write().await.forget(&[lab.safety_of(&second)]).unwrap();
let new = lab.run_view(&second).await;
assert_eq!((new["undo_state"].clone(), new["undo_available"].clone()), (json!("expired"), json!(false)), "{new}");
assert!(new.get("undo_kept_until").is_none(), "{new}");
// expired wins over superseded, so nobody is told to look for a copy that is gone
lab.state.vault.write().await.forget(&[lab.safety_of(&first)]).unwrap();
assert_eq!(lab.run_view(&first).await["undo_state"], "expired");
// the list says the same, for a person who may only use the relation
let (qa, _) = lab.refresher("qa");
let (_, list) = lab.send(&qa, "GET", "/api/v1/refresh-runs", None).await;
let states: Vec<_> = list.as_array().unwrap().iter().map(|r| r["undo_state"].clone()).collect();
assert_eq!(states, vec![json!("expired"), json!("expired")], "{list}");
}
#[tokio::test]
async fn a_restore_whose_apply_failed_is_rolled_back_from_its_safety_copy() {
let lab = fresh().await;
let (qa, _) = lab.refresher("qa");
let (run, job) = lab.failed_apply("broken").await;
let view = lab.run_view(&run).await;
assert_eq!(view["undo_available"], true, "rolling back is offered: {view}");
// while the failed apply fences the target nothing else may start, but the rollback may
let (status, other) = lab.start(&qa, "other").await;
assert_eq!((status, other["reason"].clone()), (StatusCode::CONFLICT, json!("run_active")), "{other}");
let (status, undo) = lab.start_undo(&qa, "rollback", &run).await;
assert_eq!(status, StatusCode::ACCEPTED, "{undo}");
assert_eq!(undo["undo_of"], json!(run));
assert_eq!(lab.run(&run).status, "reconciled");
assert_eq!(lab.scalar::<String>(&format!("SELECT phase FROM restore_jobs WHERE id='{job}'")), "rolled_back");
assert!(lab.audit_log().iter().any(|(event, _)| event == "restore.rolled_back"));
// it goes through the same engine and puts the copy back
lab.tick().await;
lab.finish_restore().await;
assert_eq!(lab.run(undo["id"].as_str().unwrap()).status, "completed");
assert_eq!(lab.run_view(&run).await["undo_state"], "superseded", "it is not offered twice");
}
#[tokio::test]
async fn an_apply_that_lost_its_agent_waits_for_an_administrator_before_it_can_be_rolled_back() {
let lab = fresh().await;
let (run, job) = lab.failed_apply("silent").await;
// the agent did not say it stopped: the apply may still be writing
lab.conn()
.execute("UPDATE restore_jobs SET phase='lease_lost' WHERE id=?1", [&job])
.unwrap();
assert_eq!(lab.run_view(&run).await["undo_available"], false);
let (status, body) = lab.start_undo(&lab.admin(), "early", &run).await;
assert_eq!((status, body["reason"].clone()), (StatusCode::UNPROCESSABLE_ENTITY, json!("nothing_to_undo")), "{body}");
// once an administrator has verified it, the same safety copy can put the target back
assert!(lab.state.db.reconcile_restore(Uuid::parse_str(&job).unwrap(), "admin", now()).unwrap());
lab.tick().await;
assert_eq!(lab.run(&run).status, "reconciled");
assert_eq!(lab.run_view(&run).await["undo_available"], true);
let (status, undo) = lab.start_undo(&lab.admin(), "after", &run).await;
assert_eq!(status, StatusCode::ACCEPTED, "{undo}");
}