|
|
|
|
@@ -0,0 +1,675 @@
|
|
|
|
|
//! 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 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);
|
|
|
|
|
}
|