feat: durable refresh runs from a source to a staging target (auth M6c)
A refresh captures a new dump of the relation's source, then restores exactly that snapshot onto the relation's target through the existing restore path. - refresh_runs in SQLite, one active run per target, per-requester idempotency keys, a cap on concurrent runs and a TTL that only applies until the restore starts overwriting - the run and its capture job are created in one transaction; the run follows its own capture job, never the latest snapshot, and pins that snapshot until it ends - the restore is queued and linked in one guarded transaction; every step is safe to repeat after a crash; a background driver only reads the database - authorize_apply re-checks, in the transaction that allows the overwrite, that the relation is still usable, the requester is still active, the authorising grant still exists, the deadline has not passed and the target is not the source; otherwise the restore is cancelled, the run is blocked and the agent gets 409. Administrator restores are untouched - POST/GET/DELETE /api/v1/refresh-runs: confirmation names source, target and version; non-administrators never see the snapshot id, the requester or the database identity - audit refresh.* per run Tests drive the agent through the real Outpost endpoints and cover revocation at every stage; the access matrix gains a RunRow kind. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -43,6 +43,8 @@ struct World {
|
||||
state: HubState,
|
||||
a: Fixture,
|
||||
b: Fixture,
|
||||
/// A refresh run on orbit A's relation, started by an administrator.
|
||||
run: String,
|
||||
_dir: tempfile::TempDir,
|
||||
}
|
||||
|
||||
@@ -113,8 +115,14 @@ async fn world_with(exports: Option<crate::exports::ExportGate>) -> World {
|
||||
state.sessions = SessionGate::without_operator(state.db.clone()).with_oidc("matrix-fp");
|
||||
let a = fixture(&state, "orbit-a").await;
|
||||
let b = fixture(&state, "orbit-b").await;
|
||||
let confirmation = crate::db::refresh::confirmation_text("orbit-a", "orbit-a-staging", 1);
|
||||
let (run, _) = state
|
||||
.db
|
||||
.create_refresh_run(&a.relation.to_string(), &confirmation, "seed", None, "admin", "seed-run", 3600, 50, now())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let app = crate::api::router(state.clone());
|
||||
World { app, state, a, b, _dir: dir }
|
||||
World { app, state, a, b, run: run.id, _dir: dir }
|
||||
}
|
||||
|
||||
impl World {
|
||||
@@ -173,6 +181,8 @@ fn anonymous() -> Caller {
|
||||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||||
enum Kind {
|
||||
SelfOnly,
|
||||
/// `/refresh-runs`: starting, listing, watching and cancelling a refresh; per-method expectations.
|
||||
RunRow,
|
||||
/// Visible only to people holding a grant on a relation (`refresh.run`).
|
||||
RelationList,
|
||||
AdminOnly,
|
||||
@@ -196,6 +206,8 @@ fn rows() -> Vec<Row> {
|
||||
}
|
||||
let kind = if f[4] == "session.self" {
|
||||
Kind::SelfOnly
|
||||
} else if f[4] == "refresh.run" && f[1].starts_with("/api/v1/refresh-runs") {
|
||||
Kind::RunRow
|
||||
} else if f[4] == "refresh.run" {
|
||||
Kind::RelationList
|
||||
} else {
|
||||
@@ -225,6 +237,7 @@ fn recipe(w: &World, row: &Row) -> (String, Option<Value>) {
|
||||
"/api/v1/capture-profiles/:id/jobs" | "/api/v1/capture-profiles/:id/restore-targets" => a.application,
|
||||
"/api/v1/capture-jobs/:id" | "/api/v1/capture-jobs/:id/events" => a.job,
|
||||
"/api/v1/wormhole/outposts/:id/rotate" | "/api/v1/wormhole/outposts/:id/revoke" => a.outpost,
|
||||
"/api/v1/refresh-runs/:id" => Uuid::parse_str(&w.run).unwrap(),
|
||||
"/api/v1/orbits/:id/environment" => a.orbit,
|
||||
"/api/v1/restore-targets/:id/environment" => a.target,
|
||||
"/api/v1/relations/:id" | "/api/v1/relations/:id/access" | "/api/v1/relations/:id/access/:grant" => a.relation,
|
||||
@@ -247,6 +260,11 @@ fn recipe(w: &World, row: &Row) -> (String, Option<Value>) {
|
||||
("POST", "/api/v1/access/grants") => Some(json!({"principal_type": "group", "principal": "matrix-group", "role": "viewer"})),
|
||||
("PUT", "/api/v1/access/users/:id") => Some(json!({"active": true})),
|
||||
("PUT", "/api/v1/orbits/:id/environment") | ("PUT", "/api/v1/restore-targets/:id/environment") => Some(json!({"environment": "staging"})),
|
||||
("POST", "/api/v1/refresh-runs") => Some(json!({
|
||||
"relation_id": a.relation,
|
||||
"confirmation": crate::db::refresh::confirmation_text("orbit-a", "orbit-a-staging", 1),
|
||||
"idempotency_key": format!("matrix-{}", Uuid::new_v4()),
|
||||
})),
|
||||
("POST", "/api/v1/relations") => Some(json!({"source_orbit_id": a.orbit, "target_id": a.target})),
|
||||
("PUT", "/api/v1/relations/:id") => Some(json!({"target_id": a.target})),
|
||||
("POST", "/api/v1/relations/:id/access") => Some(json!({"principal_type": "group", "principal": "matrix-refreshers"})),
|
||||
@@ -341,6 +359,25 @@ async fn every_human_route_enforces_the_matrix_for_every_kind_of_caller() {
|
||||
};
|
||||
assert_eq!(status, expected, "{who}");
|
||||
}
|
||||
Kind::RunRow => match (row.method.as_str(), caller.name) {
|
||||
// someone who holds a grant on the relation, and did not start this run
|
||||
("GET", "refresher-a") => {
|
||||
assert_eq!(status, StatusCode::OK, "{who}");
|
||||
if row.template.ends_with(":id") {
|
||||
assert_eq!(body_out["id"], w.run.as_str());
|
||||
} else {
|
||||
assert_eq!(body_out.as_array().unwrap().len(), 1, "{who} sees only runs on its relation");
|
||||
}
|
||||
for secret in ["requested_by", "snapshot_id", "identity", "instance", "outpost"] {
|
||||
assert!(!body_out.to_string().contains(secret), "{who}: a refresher's view leaks {secret}");
|
||||
}
|
||||
}
|
||||
("POST", "refresher-a") => assert!(!denied(status), "{who}: {status}"),
|
||||
("DELETE", "refresher-a") => assert_eq!(status, StatusCode::FORBIDDEN, "{who}: may see the run but not cancel someone else's"),
|
||||
// everyone else: not a holder of any relation grant
|
||||
("GET", _) if !row.template.ends_with(":id") => assert_eq!(status, StatusCode::FORBIDDEN, "{who}"),
|
||||
_ => assert_eq!(status, StatusCode::NOT_FOUND, "{who}: a relation or run they hold no grant on does not exist for them"),
|
||||
},
|
||||
Kind::RelationList => {
|
||||
if caller.name == "refresher-a" {
|
||||
assert_eq!(status, StatusCode::OK, "{who}");
|
||||
@@ -373,7 +410,7 @@ async fn every_human_route_enforces_the_matrix_for_every_kind_of_caller() {
|
||||
Kind::SelfOnly => unreachable!(),
|
||||
}
|
||||
// the invariant that catches a forgotten gate: no grant, no success
|
||||
if no_orbit_access && !(caller.name == "refresher-a" && row.kind == Kind::RelationList) {
|
||||
if no_orbit_access && !(caller.name == "refresher-a" && matches!(row.kind, Kind::RelationList | Kind::RunRow)) {
|
||||
assert!(!status.is_success(), "{who}: a caller without any matching grant got {status}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ mod catalog;
|
||||
mod gate;
|
||||
mod jobs;
|
||||
mod oidc;
|
||||
mod refresh;
|
||||
mod relations;
|
||||
mod orbit;
|
||||
mod restore;
|
||||
@@ -18,6 +19,10 @@ mod credentials_tests;
|
||||
mod access_tests;
|
||||
#[cfg(test)]
|
||||
mod export_tests;
|
||||
#[cfg(test)]
|
||||
mod refresh_tests;
|
||||
|
||||
pub use orbit::run_orbit_internal;
|
||||
pub use routes::router;
|
||||
pub(crate) use restore::artifact;
|
||||
pub(crate) use relations::identity_facts;
|
||||
|
||||
237
crates/tessera-hub/src/api/refresh.rs
Normal file
237
crates/tessera-hub/src/api/refresh.rs
Normal file
@@ -0,0 +1,237 @@
|
||||
//! Starting, watching and cancelling a refresh of a staging database.
|
||||
//!
|
||||
//! The caller names a relation they hold a grant on and confirms what they saw (source, target and
|
||||
//! version). They never choose the snapshot or the target: the run captures its own fresh dump and
|
||||
//! restores exactly that onto the relation's target.
|
||||
use super::routes::{authenticate, OperatorActor};
|
||||
use crate::auth::{AuditAction, AuditOutcome, AuditResource};
|
||||
use crate::db::refresh::{CancelError, Progress, RefreshRun, StartError};
|
||||
use crate::state::HubState;
|
||||
use axum::{
|
||||
extract::{ConnectInfo, Path, State},
|
||||
http::{header, HeaderMap, HeaderValue, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
routing::get,
|
||||
Json, Router,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::net::SocketAddr;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub(super) fn routes() -> Router<HubState> {
|
||||
Router::new()
|
||||
.route("/api/v1/refresh-runs", get(list).post(start))
|
||||
.route("/api/v1/refresh-runs/:id", get(show).delete(cancel))
|
||||
}
|
||||
|
||||
fn now() -> i64 {
|
||||
chrono::Utc::now().timestamp()
|
||||
}
|
||||
|
||||
fn no_store() -> HeaderMap {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
|
||||
headers
|
||||
}
|
||||
|
||||
fn internal(error: impl std::fmt::Display) -> StatusCode {
|
||||
tracing::error!("refresh: {error:#}");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
}
|
||||
|
||||
fn reason(status: StatusCode, reason: &str) -> Response {
|
||||
(status, no_store(), Json(serde_json::json!({ "reason": reason }))).into_response()
|
||||
}
|
||||
|
||||
/// A run as its viewer may see it. Only administrators see who started it and the snapshot id.
|
||||
#[derive(Serialize)]
|
||||
struct RunView {
|
||||
id: String,
|
||||
relation_id: String,
|
||||
source_name: String,
|
||||
target_name: String,
|
||||
status: String,
|
||||
blocked_reason: Option<String>,
|
||||
capture_status: Option<String>,
|
||||
capture_phase: Option<String>,
|
||||
snapshot_taken_at: Option<i64>,
|
||||
restore_status: Option<String>,
|
||||
restore_phase: Option<String>,
|
||||
created_at: i64,
|
||||
updated_at: i64,
|
||||
expires_at: i64,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
requested_by: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
snapshot_id: Option<String>,
|
||||
}
|
||||
|
||||
fn view(state: &HubState, run: &RefreshRun, admin: bool) -> Result<RunView, StatusCode> {
|
||||
let Progress { capture_status, capture_phase, snapshot_taken_at, restore_status, restore_phase, source_name, target_name } =
|
||||
state.db.refresh_progress(run).map_err(internal)?;
|
||||
Ok(RunView {
|
||||
id: run.id.clone(),
|
||||
relation_id: run.relation_id.clone(),
|
||||
source_name,
|
||||
target_name,
|
||||
status: run.status.clone(),
|
||||
blocked_reason: run.blocked_reason.clone(),
|
||||
capture_status,
|
||||
capture_phase,
|
||||
snapshot_taken_at,
|
||||
restore_status,
|
||||
restore_phase,
|
||||
created_at: run.created_at,
|
||||
updated_at: run.updated_at,
|
||||
expires_at: run.expires_at,
|
||||
requested_by: admin.then(|| run.requester.clone()),
|
||||
snapshot_id: admin.then(|| run.snapshot_id.clone()).flatten(),
|
||||
})
|
||||
}
|
||||
|
||||
fn owns(actor: &OperatorActor, run: &RefreshRun) -> bool {
|
||||
actor.subject.user_id.is_some() && actor.subject.user_id == run.requester_user_id
|
||||
}
|
||||
|
||||
/// May this caller look at this run: an administrator, whoever started it, or someone holding a
|
||||
/// grant on its relation. Anyone else gets 404.
|
||||
fn can_see(state: &HubState, actor: &OperatorActor, run: &RefreshRun) -> Result<bool, StatusCode> {
|
||||
if actor.subject.admin || owns(actor, run) {
|
||||
return Ok(true);
|
||||
}
|
||||
let granted = state.db.granted_relations(actor.subject.user_id.as_deref(), &actor.subject.groups, now()).map_err(internal)?;
|
||||
Ok(granted.iter().any(|id| id == &run.relation_id))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Start {
|
||||
relation_id: Uuid,
|
||||
/// `REFRESH <source> TO <target> v<version>`: exactly what the person was shown.
|
||||
confirmation: String,
|
||||
/// Chosen by the client so a double click or a retry starts one run, not two.
|
||||
idempotency_key: String,
|
||||
}
|
||||
|
||||
fn valid_key(key: &str) -> bool {
|
||||
(1..=128).contains(&key.len()) && key.bytes().all(|b| b.is_ascii_alphanumeric() || b"-_.:".contains(&b))
|
||||
}
|
||||
|
||||
async fn start(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Json(body): Json<Start>,
|
||||
) -> Result<Response, StatusCode> {
|
||||
let actor = authenticate(&state, peer, &headers, true)?;
|
||||
if !valid_key(&body.idempotency_key) {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
super::gate::relation(&state, &actor, body.relation_id)?;
|
||||
let relation = body.relation_id.to_string();
|
||||
// What authorised this run, recorded so it can be checked again before anything is overwritten.
|
||||
let authorized_by = if actor.subject.admin {
|
||||
"admin".to_string()
|
||||
} else {
|
||||
match state.db.granting_relation_grant(actor.subject.user_id.as_deref(), &actor.subject.groups, &relation, now()).map_err(internal)? {
|
||||
Some(grant) => format!("grant:{grant}"),
|
||||
None => return Err(StatusCode::NOT_FOUND),
|
||||
}
|
||||
};
|
||||
let started = state
|
||||
.db
|
||||
.create_refresh_run(
|
||||
&relation, &body.confirmation, &actor.id(), actor.subject.user_id.as_deref(), &authorized_by, &body.idempotency_key,
|
||||
state.refresh.ttl_secs, state.refresh.max_active, now(),
|
||||
)
|
||||
.map_err(internal)?;
|
||||
match started {
|
||||
Ok((run, created)) => {
|
||||
if created {
|
||||
crate::refresh::audit_run(&state, &run.id, "capturing");
|
||||
}
|
||||
let status = if created { StatusCode::ACCEPTED } else { StatusCode::OK };
|
||||
Ok((status, no_store(), Json(view(&state, &run, actor.subject.admin)?)).into_response())
|
||||
}
|
||||
Err(StartError::UnknownRelation) => Err(StatusCode::NOT_FOUND),
|
||||
Err(StartError::Unusable(why)) => Ok((StatusCode::CONFLICT, no_store(), Json(serde_json::json!({"reason": "relation_unusable", "detail": why}))).into_response()),
|
||||
Err(StartError::StaleConfirmation) => Ok(reason(StatusCode::CONFLICT, "stale_confirmation")),
|
||||
Err(StartError::SourceUnavailable) => Ok(reason(StatusCode::CONFLICT, "source_unavailable")),
|
||||
Err(StartError::KeyReused) => Ok(reason(StatusCode::CONFLICT, "key_reused")),
|
||||
Err(StartError::TooManyRuns) => Ok(reason(StatusCode::TOO_MANY_REQUESTS, "too_many_runs")),
|
||||
Err(StartError::TargetBusy(id)) => {
|
||||
// Only someone who may see that run is told which one it is.
|
||||
let visible = match state.db.refresh_run(&id).map_err(internal)? {
|
||||
Some(run) => can_see(&state, &actor, &run)?,
|
||||
None => false,
|
||||
};
|
||||
let mut payload = serde_json::json!({"reason": "run_active"});
|
||||
if visible {
|
||||
payload["run_id"] = serde_json::json!(id);
|
||||
}
|
||||
Ok((StatusCode::CONFLICT, no_store(), Json(payload)).into_response())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn list(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<(HeaderMap, Json<Vec<RunView>>), StatusCode> {
|
||||
let actor = authenticate(&state, peer, &headers, false)?;
|
||||
let granted = super::gate::visible_relations(&state, &actor)?;
|
||||
let runs = match (&granted, actor.subject.admin) {
|
||||
(None, _) => state.db.refresh_runs(None, None, 50),
|
||||
(Some(relations), _) => state.db.refresh_runs(actor.subject.user_id.as_deref(), Some(relations), 50),
|
||||
}
|
||||
.map_err(internal)?;
|
||||
let views = runs.iter().map(|run| view(&state, run, actor.subject.admin)).collect::<Result<Vec<_>, _>>()?;
|
||||
Ok((no_store(), Json(views)))
|
||||
}
|
||||
|
||||
async fn show(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<(HeaderMap, Json<RunView>), StatusCode> {
|
||||
let actor = authenticate(&state, peer, &headers, false)?;
|
||||
let run = state.db.refresh_run(&id.to_string()).map_err(internal)?.filter(|run| can_see(&state, &actor, run).unwrap_or(false));
|
||||
let allowed = run.is_some();
|
||||
state.db.audit_event(&actor.principal, AuditAction::Authorization, AuditResource::RefreshRun(id),
|
||||
if allowed { AuditOutcome::Allowed } else { AuditOutcome::Denied }, actor.request_id).map_err(internal)?;
|
||||
let run = run.ok_or(StatusCode::NOT_FOUND)?;
|
||||
Ok((no_store(), Json(view(&state, &run, actor.subject.admin)?)))
|
||||
}
|
||||
|
||||
async fn cancel(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<Response, StatusCode> {
|
||||
let actor = authenticate(&state, peer, &headers, true)?;
|
||||
let run = state.db.refresh_run(&id.to_string()).map_err(internal)?;
|
||||
let (visible, allowed) = match &run {
|
||||
Some(run) => (can_see(&state, &actor, run)?, actor.subject.admin || owns(&actor, run)),
|
||||
None => (false, false),
|
||||
};
|
||||
state.db.audit_event(&actor.principal, AuditAction::Authorization, AuditResource::RefreshRun(id),
|
||||
if allowed { AuditOutcome::Allowed } else { AuditOutcome::Denied }, actor.request_id).map_err(internal)?;
|
||||
if !visible {
|
||||
return Err(StatusCode::NOT_FOUND);
|
||||
}
|
||||
if !allowed {
|
||||
// Someone who may see the run but did not start it and is not an administrator.
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
}
|
||||
match state.db.cancel_refresh_run(&id.to_string(), now()).map_err(internal)? {
|
||||
Ok(run) => {
|
||||
crate::refresh::audit_run(&state, &run.id, "cancelled");
|
||||
Ok((no_store(), Json(view(&state, &run, actor.subject.admin)?)).into_response())
|
||||
}
|
||||
Err(CancelError::Unknown) => Err(StatusCode::NOT_FOUND),
|
||||
Err(CancelError::TooLate) => Ok(reason(StatusCode::CONFLICT, "too_late")),
|
||||
}
|
||||
}
|
||||
675
crates/tessera-hub/src/api/refresh_tests.rs
Normal file
675
crates/tessera-hub/src/api/refresh_tests.rs
Normal file
@@ -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);
|
||||
}
|
||||
@@ -207,7 +207,7 @@ async fn list(
|
||||
|
||||
/// What the snapshots say about a target: does its identity match a database that is captured as a
|
||||
/// production (or unlabelled) source, and has the source itself been seen at all?
|
||||
async fn identity_facts(state: &HubState, source: Uuid, target: &DatabaseIdentity) -> Result<(bool, bool), StatusCode> {
|
||||
pub(crate) async fn identity_facts(state: &HubState, source: Uuid, target: &DatabaseIdentity) -> Result<(bool, bool), StatusCode> {
|
||||
let (orbit_env, _) = state.db.environments().map_err(internal)?;
|
||||
let vault = state.vault.read().await;
|
||||
let snapshots = vault.list_snapshots().map_err(internal)?;
|
||||
|
||||
@@ -165,7 +165,7 @@ async fn enqueue(
|
||||
Ok((StatusCode::ACCEPTED, Json(job)))
|
||||
}
|
||||
|
||||
pub(super) fn artifact(manifest: &SnapshotManifest) -> Option<(Uuid, RestoreArtifact)> {
|
||||
pub(crate) fn artifact(manifest: &SnapshotManifest) -> Option<(Uuid, RestoreArtifact)> {
|
||||
let hints = &manifest.restore_hints;
|
||||
let application = Uuid::parse_str(hints.get("application_id")?.as_str()?).ok()?;
|
||||
let format = match (manifest.provider.as_str(), hints.get("format")?.as_str()?) {
|
||||
|
||||
@@ -349,6 +349,7 @@ pub fn router(state: HubState) -> Router {
|
||||
.merge(super::oidc::routes())
|
||||
.merge(super::access::routes())
|
||||
.merge(super::relations::routes())
|
||||
.merge(super::refresh::routes())
|
||||
.merge(super::restore::routes())
|
||||
.with_state(state);
|
||||
|
||||
|
||||
@@ -48,6 +48,8 @@ pub enum AuditAction {
|
||||
RelationDeactivate,
|
||||
RelationGrantCreate,
|
||||
RelationGrantDelete,
|
||||
/// One of the refresh run's states or steps; the name is the audit action (`refresh.completed`, ...).
|
||||
RefreshEvent(&'static str),
|
||||
}
|
||||
|
||||
impl AuditAction {
|
||||
@@ -75,6 +77,7 @@ impl AuditAction {
|
||||
Self::RelationDeactivate => "relation.deactivate",
|
||||
Self::RelationGrantCreate => "relation.grant_create",
|
||||
Self::RelationGrantDelete => "relation.grant_delete",
|
||||
Self::RefreshEvent(name) => name,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -108,6 +111,7 @@ pub enum AuditResource {
|
||||
Snapshot(Uuid),
|
||||
Relation(Uuid),
|
||||
RestoreTarget(Uuid),
|
||||
RefreshRun(Uuid),
|
||||
}
|
||||
|
||||
impl AuditResource {
|
||||
@@ -123,6 +127,7 @@ impl AuditResource {
|
||||
Self::Snapshot(id) => ("snapshot", Some(id.to_string())),
|
||||
Self::Relation(id) => ("relation", Some(id.to_string())),
|
||||
Self::RestoreTarget(id) => ("restore_target", Some(id.to_string())),
|
||||
Self::RefreshRun(id) => ("refresh_run", Some(id.to_string())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ pub(crate) mod oidc_login;
|
||||
pub(crate) mod credentials;
|
||||
pub(crate) mod access;
|
||||
pub(crate) mod relations;
|
||||
pub(crate) mod refresh;
|
||||
pub(crate) use restore::restore_target_mismatch;
|
||||
|
||||
use anyhow::Result;
|
||||
@@ -101,6 +102,7 @@ impl Db {
|
||||
oidc_login::migrate(&conn)?;
|
||||
access::migrate(&conn)?;
|
||||
relations::migrate(&conn)?;
|
||||
refresh::migrate(&conn)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -160,15 +160,10 @@ impl Db {
|
||||
now: i64,
|
||||
) -> Result<Option<CaptureJob>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let id = Uuid::new_v4();
|
||||
conn.execute(
|
||||
"INSERT INTO capture_jobs (id, application_id, actor, created_at, updated_at)
|
||||
SELECT ?1, application_id, ?3, ?4, ?4 FROM capture_profiles p
|
||||
WHERE application_id = ?2
|
||||
AND EXISTS (SELECT 1 FROM outpost_credentials WHERE outpost_id = p.outpost_id AND state = 'active' AND expires_at > ?4)",
|
||||
params![id.to_string(), application_id.to_string(), actor, now],
|
||||
)?;
|
||||
capture_job(&conn, id)
|
||||
match insert_capture_job(&conn, application_id, actor, now)? {
|
||||
Some(id) => capture_job(&conn, id),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn capture_jobs(
|
||||
@@ -421,6 +416,21 @@ impl Db {
|
||||
}
|
||||
}
|
||||
|
||||
/// Queue a capture for a managed application whose Outpost is usable. Returns the job id, or
|
||||
/// `None` when there is no such profile or its Outpost has no usable credential. Takes a plain
|
||||
/// connection so a refresh run can queue the capture in the same transaction as the run itself.
|
||||
pub(super) fn insert_capture_job(conn: &Connection, application_id: Uuid, actor: &str, now: i64) -> Result<Option<Uuid>> {
|
||||
let id = Uuid::new_v4();
|
||||
let changed = conn.execute(
|
||||
"INSERT INTO capture_jobs (id, application_id, actor, created_at, updated_at)
|
||||
SELECT ?1, application_id, ?3, ?4, ?4 FROM capture_profiles p
|
||||
WHERE application_id = ?2
|
||||
AND EXISTS (SELECT 1 FROM outpost_credentials WHERE outpost_id = p.outpost_id AND state = 'active' AND expires_at > ?4)",
|
||||
params![id.to_string(), application_id.to_string(), actor, now],
|
||||
)?;
|
||||
Ok((changed == 1).then_some(id))
|
||||
}
|
||||
|
||||
fn capture_upload(
|
||||
conn: &Connection,
|
||||
outpost: Uuid,
|
||||
|
||||
472
crates/tessera-hub/src/db/refresh.rs
Normal file
472
crates/tessera-hub/src/db/refresh.rs
Normal file
@@ -0,0 +1,472 @@
|
||||
//! Durable refresh runs: capture a fresh dump of a source, then restore exactly that snapshot onto
|
||||
//! the target of a relation.
|
||||
//!
|
||||
//! Every step is one transaction and can be repeated safely after a crash:
|
||||
//! * the run and its capture job are created together, so there is never a run without a capture or the reverse;
|
||||
//! * the restore job is queued and linked in one transaction guarded by `restore_job_id IS NULL`;
|
||||
//! * a run follows its own capture job (`capture_job_id`), never "the latest snapshot", and that id is a
|
||||
//! retention pin for as long as the run is active;
|
||||
//! * everything that can change is checked again right before anything destructive: this module's
|
||||
//! [`invalid_reason`] is also called from `authorize_apply`, in the same transaction that flips the
|
||||
//! restore job to `applying`.
|
||||
use super::*;
|
||||
use crate::db::relations::{read_relation, unusable, Relation, RELATION_COLUMNS};
|
||||
use rusqlite::{Transaction, TransactionBehavior};
|
||||
use tessera_core::restore::RestoreArtifact;
|
||||
|
||||
/// While a run is in one of these states its target is locked and its snapshot is pinned.
|
||||
pub const ACTIVE: [&str; 3] = ["capturing", "restoring", "recovery_required"];
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize)]
|
||||
pub struct RefreshRun {
|
||||
pub id: String,
|
||||
pub relation_id: String,
|
||||
pub relation_version: i64,
|
||||
pub source_orbit_id: String,
|
||||
pub source_application_id: String,
|
||||
pub target_id: String,
|
||||
pub requester: String,
|
||||
pub requester_user_id: Option<String>,
|
||||
/// `admin`, or `grant:<relation_grants.id>`. Group membership can only be verified as of the request.
|
||||
pub authorized_by: String,
|
||||
pub status: String,
|
||||
pub blocked_reason: Option<String>,
|
||||
pub capture_job_id: String,
|
||||
pub snapshot_id: Option<String>,
|
||||
pub restore_job_id: Option<String>,
|
||||
pub created_at: i64,
|
||||
pub updated_at: i64,
|
||||
pub expires_at: i64,
|
||||
}
|
||||
|
||||
const COLUMNS: &str = "id,relation_id,relation_version,source_orbit_id,source_application_id,target_id,requester,requester_user_id,authorized_by,status,blocked_reason,capture_job_id,snapshot_id,restore_job_id,created_at,updated_at,expires_at";
|
||||
|
||||
fn read_run(r: &rusqlite::Row<'_>) -> rusqlite::Result<RefreshRun> {
|
||||
Ok(RefreshRun {
|
||||
id: r.get(0)?, relation_id: r.get(1)?, relation_version: r.get(2)?, source_orbit_id: r.get(3)?, source_application_id: r.get(4)?,
|
||||
target_id: r.get(5)?, requester: r.get(6)?, requester_user_id: r.get(7)?, authorized_by: r.get(8)?, status: r.get(9)?,
|
||||
blocked_reason: r.get(10)?, capture_job_id: r.get(11)?, snapshot_id: r.get(12)?, restore_job_id: r.get(13)?,
|
||||
created_at: r.get(14)?, updated_at: r.get(15)?, expires_at: r.get(16)?,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum StartError {
|
||||
/// No such active relation.
|
||||
UnknownRelation,
|
||||
/// The relation exists but cannot be used right now (target relabelled, Outpost gone, ...).
|
||||
Unusable(&'static str),
|
||||
/// The caller confirmed a different source, target or version than the relation has now.
|
||||
StaleConfirmation,
|
||||
/// The source's Outpost cannot take a capture job.
|
||||
SourceUnavailable,
|
||||
/// This target already has a run in progress; the id is returned so the caller can be shown it if allowed.
|
||||
TargetBusy(String),
|
||||
/// The same idempotency key was used for a different relation.
|
||||
KeyReused,
|
||||
/// Too many refreshes are running at once.
|
||||
TooManyRuns,
|
||||
}
|
||||
|
||||
/// What the confirmation must say: it names exactly what the person saw, including the version.
|
||||
pub fn confirmation_text(source: &str, target: &str, version: i64) -> String {
|
||||
format!("REFRESH {source} TO {target} v{version}")
|
||||
}
|
||||
|
||||
pub(super) fn migrate(conn: &Connection) -> Result<()> {
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE IF NOT EXISTS refresh_runs (
|
||||
id TEXT PRIMARY KEY,
|
||||
relation_id TEXT NOT NULL,
|
||||
relation_version INTEGER NOT NULL,
|
||||
source_orbit_id TEXT NOT NULL,
|
||||
source_application_id TEXT NOT NULL,
|
||||
target_id TEXT NOT NULL,
|
||||
requester TEXT NOT NULL,
|
||||
requester_user_id TEXT,
|
||||
authorized_by TEXT NOT NULL,
|
||||
idempotency_key TEXT NOT NULL,
|
||||
status TEXT NOT NULL CHECK(status IN ('capturing','restoring','recovery_required','completed','capture_failed',
|
||||
'restore_failed','blocked','cancelled','expired','reconciled')),
|
||||
blocked_reason TEXT,
|
||||
capture_job_id TEXT NOT NULL UNIQUE,
|
||||
snapshot_id TEXT,
|
||||
restore_job_id TEXT UNIQUE,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
expires_at INTEGER NOT NULL,
|
||||
UNIQUE(requester, idempotency_key)
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS refresh_runs_one_active_per_target ON refresh_runs(target_id)
|
||||
WHERE status IN ('capturing','restoring','recovery_required');
|
||||
CREATE INDEX IF NOT EXISTS refresh_runs_recent ON refresh_runs(created_at);",
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get(conn: &Connection, id: &str) -> Result<Option<RefreshRun>> {
|
||||
Ok(conn.query_row(&format!("SELECT {COLUMNS} FROM refresh_runs WHERE id=?1"), params![id], read_run).optional()?)
|
||||
}
|
||||
|
||||
/// The run that owns a restore job, if the job was queued by a refresh. Admin restores have none.
|
||||
pub(super) fn run_for_restore(conn: &Connection, restore_job: &str) -> Result<Option<RefreshRun>> {
|
||||
Ok(conn.query_row(&format!("SELECT {COLUMNS} FROM refresh_runs WHERE restore_job_id=?1"), params![restore_job], read_run).optional()?)
|
||||
}
|
||||
|
||||
fn relation_of(conn: &Connection, id: &str) -> Result<Option<Relation>> {
|
||||
Ok(conn.query_row(&format!("SELECT {RELATION_COLUMNS} FROM orbit_relations WHERE id=?1"), params![id], read_relation).optional()?)
|
||||
}
|
||||
|
||||
fn names(conn: &Connection, relation: &Relation) -> rusqlite::Result<(String, String)> {
|
||||
let source: String = conn
|
||||
.query_row("SELECT name FROM orbits WHERE id=?1", params![relation.source_orbit_id], |r| r.get(0))
|
||||
.optional()?
|
||||
.unwrap_or_default();
|
||||
let target_profile: Option<String> =
|
||||
conn.query_row("SELECT profile FROM restore_targets WHERE id=?1", params![relation.target_id], |r| r.get(0)).optional()?;
|
||||
let target = target_profile
|
||||
.and_then(|p| serde_json::from_str::<serde_json::Value>(&p).ok())
|
||||
.and_then(|p| p["name"].as_str().map(str::to_string))
|
||||
.unwrap_or_default();
|
||||
Ok((source, target))
|
||||
}
|
||||
|
||||
/// Why this run must not go on, if anything has changed since it was started. Nothing here is cached:
|
||||
/// the relation, the requester and the grant that authorised the run are read again each time.
|
||||
pub(super) fn invalid_reason(conn: &Connection, run: &RefreshRun, now: i64) -> Result<Option<&'static str>> {
|
||||
let Some(relation) = relation_of(conn, &run.relation_id)? else { return Ok(Some("relation_ended")) };
|
||||
if !relation.active {
|
||||
return Ok(Some("relation_ended"));
|
||||
}
|
||||
if unusable(conn, &relation, now)?.is_some() {
|
||||
return Ok(Some("relation_unusable"));
|
||||
}
|
||||
if let Some(user) = &run.requester_user_id {
|
||||
let active: bool = conn.query_row("SELECT EXISTS(SELECT 1 FROM users WHERE id=?1 AND active=1)", params![user], |r| r.get(0))?;
|
||||
if !active {
|
||||
return Ok(Some("user_disabled"));
|
||||
}
|
||||
}
|
||||
if let Some(grant) = run.authorized_by.strip_prefix("grant:") {
|
||||
let alive: bool = conn.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM relation_grants WHERE id=?1 AND relation_id=?2 AND (expires_at IS NULL OR expires_at > ?3))",
|
||||
params![grant, run.relation_id, now],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
if !alive {
|
||||
return Ok(Some("access_revoked"));
|
||||
}
|
||||
}
|
||||
if now >= run.expires_at {
|
||||
return Ok(Some("expired"));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn finish(conn: &Connection, run: &str, status: &str, reason: Option<&str>, now: i64) -> Result<()> {
|
||||
conn.execute(
|
||||
"UPDATE refresh_runs SET status=?2, blocked_reason=?3, updated_at=?4 WHERE id=?1 AND status IN ('capturing','restoring','recovery_required')",
|
||||
params![run, status, reason, now],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stop a run that is no longer allowed to continue. A restore that has not started applying is cancelled;
|
||||
/// one that has is left to finish (a half-applied restore must be finished or reconciled, not abandoned).
|
||||
pub(super) fn block(conn: &Connection, run: &RefreshRun, reason: &str, now: i64) -> Result<()> {
|
||||
if let Some(job) = &run.restore_job_id {
|
||||
conn.execute(
|
||||
"UPDATE restore_jobs SET status='cancelled', phase='cancelled', updated_at=?2 WHERE id=?1 AND status IN ('queued','running')",
|
||||
params![job, now],
|
||||
)?;
|
||||
}
|
||||
finish(conn, &run.id, if reason == "expired" { "expired" } else { "blocked" }, Some(reason), now)
|
||||
}
|
||||
|
||||
fn restore_status(conn: &Connection, job: &str) -> Result<Option<String>> {
|
||||
Ok(conn.query_row("SELECT status FROM restore_jobs WHERE id=?1", params![job], |r| r.get(0)).optional()?)
|
||||
}
|
||||
|
||||
impl Db {
|
||||
/// Start a run. Returns the run and whether it was newly created (`false` = the same idempotency key
|
||||
/// from the same requester, so the existing run is returned and nothing else happens).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn create_refresh_run(
|
||||
&self,
|
||||
relation_id: &str,
|
||||
confirmation: &str,
|
||||
requester: &str,
|
||||
requester_user_id: Option<&str>,
|
||||
authorized_by: &str,
|
||||
idempotency_key: &str,
|
||||
ttl_secs: i64,
|
||||
max_active: i64,
|
||||
now: i64,
|
||||
) -> Result<std::result::Result<(RefreshRun, bool), StartError>> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let result = (|| -> Result<std::result::Result<(RefreshRun, bool), StartError>> {
|
||||
let existing: Option<RefreshRun> = tx
|
||||
.query_row(&format!("SELECT {COLUMNS} FROM refresh_runs WHERE requester=?1 AND idempotency_key=?2"), params![requester, idempotency_key], read_run)
|
||||
.optional()?;
|
||||
if let Some(run) = existing {
|
||||
return Ok(if run.relation_id == relation_id { Ok((run, false)) } else { Err(StartError::KeyReused) });
|
||||
}
|
||||
let Some(relation) = relation_of(&tx, relation_id)?.filter(|r| r.active) else { return Ok(Err(StartError::UnknownRelation)) };
|
||||
if let Some(reason) = unusable(&tx, &relation, now)? {
|
||||
return Ok(Err(StartError::Unusable(reason)));
|
||||
}
|
||||
let (source, target) = names(&tx, &relation)?;
|
||||
if confirmation != confirmation_text(&source, &target, relation.version) {
|
||||
return Ok(Err(StartError::StaleConfirmation));
|
||||
}
|
||||
let busy: Option<String> = tx
|
||||
.query_row("SELECT id FROM refresh_runs WHERE target_id=?1 AND status IN ('capturing','restoring','recovery_required')", params![relation.target_id], |r| r.get(0))
|
||||
.optional()?;
|
||||
if let Some(id) = busy {
|
||||
return Ok(Err(StartError::TargetBusy(id)));
|
||||
}
|
||||
let running: i64 = tx.query_row("SELECT COUNT(*) FROM refresh_runs WHERE status IN ('capturing','restoring','recovery_required')", [], |r| r.get(0))?;
|
||||
if running >= max_active {
|
||||
return Ok(Err(StartError::TooManyRuns));
|
||||
}
|
||||
let application = Uuid::parse_str(&relation.source_application_id)?;
|
||||
let Some(capture) = super::jobs::insert_capture_job(&tx, application, requester, now)? else {
|
||||
return Ok(Err(StartError::SourceUnavailable));
|
||||
};
|
||||
let id = Uuid::new_v4().to_string();
|
||||
tx.execute(
|
||||
"INSERT INTO refresh_runs(id,relation_id,relation_version,source_orbit_id,source_application_id,target_id,requester,requester_user_id,
|
||||
authorized_by,idempotency_key,status,capture_job_id,created_at,updated_at,expires_at)
|
||||
VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,'capturing',?11,?12,?12,?13)",
|
||||
params![id, relation.id, relation.version, relation.source_orbit_id, relation.source_application_id, relation.target_id,
|
||||
requester, requester_user_id, authorized_by, idempotency_key, capture.to_string(), now, now + ttl_secs],
|
||||
)?;
|
||||
Ok(Ok((get(&tx, &id)?.expect("just inserted"), true)))
|
||||
})()?;
|
||||
if result.is_ok() {
|
||||
tx.commit()?;
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub fn refresh_run(&self, id: &str) -> Result<Option<RefreshRun>> {
|
||||
get(&self.conn.lock().unwrap(), id)
|
||||
}
|
||||
|
||||
/// Runs still in progress, oldest first.
|
||||
pub fn active_refresh_runs(&self) -> Result<Vec<RefreshRun>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare(&format!("SELECT {COLUMNS} FROM refresh_runs WHERE status IN ('capturing','restoring','recovery_required') ORDER BY created_at"))?;
|
||||
let rows = stmt.query_map([], read_run)?.collect::<rusqlite::Result<_>>()?;
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
/// Recent runs (all of them, or only those of one requester / a set of relations), newest first.
|
||||
pub fn refresh_runs(&self, requester_user: Option<&str>, relations: Option<&[String]>, limit: i64) -> Result<Vec<RefreshRun>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare(&format!(
|
||||
"SELECT {COLUMNS} FROM refresh_runs WHERE (?1 IS NULL AND ?2 IS NULL) OR requester_user_id = ?1
|
||||
OR relation_id IN (SELECT value FROM json_each(?2)) ORDER BY created_at DESC, rowid DESC LIMIT ?3"
|
||||
))?;
|
||||
let relations_json = relations.map(serde_json::to_string).transpose()?;
|
||||
let rows = stmt.query_map(params![requester_user, relations_json, limit], read_run)?.collect::<rusqlite::Result<_>>()?;
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
/// Everything the status screens need about a run, with the capture and restore job state it follows.
|
||||
pub fn refresh_progress(&self, run: &RefreshRun) -> Result<Progress> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let capture: Option<(String, String, i64)> = conn
|
||||
.query_row("SELECT status, phase, updated_at FROM capture_jobs WHERE id=?1", params![run.capture_job_id], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))
|
||||
.optional()?;
|
||||
let restore: Option<(String, String)> = match &run.restore_job_id {
|
||||
Some(job) => conn.query_row("SELECT status, phase FROM restore_jobs WHERE id=?1", params![job], |r| Ok((r.get(0)?, r.get(1)?))).optional()?,
|
||||
None => None,
|
||||
};
|
||||
let relation = relation_of(&conn, &run.relation_id)?;
|
||||
let (source_name, target_name) = match &relation {
|
||||
Some(r) => names(&conn, r)?,
|
||||
None => Default::default(),
|
||||
};
|
||||
Ok(Progress {
|
||||
capture_status: capture.as_ref().map(|c| c.0.clone()),
|
||||
capture_phase: capture.as_ref().map(|c| c.1.clone()),
|
||||
snapshot_taken_at: capture.filter(|c| c.0 == "completed").map(|c| c.2),
|
||||
restore_status: restore.as_ref().map(|r| r.0.clone()),
|
||||
restore_phase: restore.map(|r| r.1),
|
||||
source_name,
|
||||
target_name,
|
||||
})
|
||||
}
|
||||
|
||||
/// Advance one run by looking at what its jobs and its authorisation say now. Idempotent.
|
||||
pub fn sync_refresh_run(&self, id: &str, now: i64) -> Result<Sync> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let outcome = sync_in(&tx, id, now)?;
|
||||
tx.commit()?;
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
/// Queue the restore of the run's own snapshot. Everything is checked again inside the transaction, the
|
||||
/// restore job is linked only if the run does not have one yet, and a second call changes nothing.
|
||||
pub fn enqueue_refresh_restore(&self, id: &str, artifact: &RestoreArtifact, identity_clash: bool, now: i64) -> Result<Linked> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let outcome = (|| -> Result<Linked> {
|
||||
let Some(run) = get(&tx, id)? else { return Ok(Linked::NotReady) };
|
||||
if run.status != "capturing" || run.restore_job_id.is_some() {
|
||||
return Ok(Linked::NotReady);
|
||||
}
|
||||
let capture: Option<(String, Option<String>)> = tx
|
||||
.query_row("SELECT status, snapshot_id FROM capture_jobs WHERE id=?1", params![run.capture_job_id], |r| Ok((r.get(0)?, r.get(1)?)))
|
||||
.optional()?;
|
||||
let Some((status, Some(snapshot))) = capture.filter(|c| c.0 == "completed") else { return Ok(Linked::NotReady) };
|
||||
let _ = status;
|
||||
if let Some(reason) = invalid_reason(&tx, &run, now)? {
|
||||
block(&tx, &run, reason, now)?;
|
||||
return Ok(Linked::Blocked(reason));
|
||||
}
|
||||
if identity_clash {
|
||||
block(&tx, &run, "target_matches_a_production_source", now)?;
|
||||
return Ok(Linked::Blocked("target_matches_a_production_source"));
|
||||
}
|
||||
let snapshot = Uuid::parse_str(&snapshot)?;
|
||||
let job = super::restore::enqueue_restore_in(
|
||||
&tx, snapshot, Uuid::parse_str(&run.source_application_id)?, Uuid::parse_str(&run.target_id)?, &run.requester, artifact, now,
|
||||
)?;
|
||||
let Some(job) = job else {
|
||||
block(&tx, &run, "target_rejected", now)?;
|
||||
return Ok(Linked::Blocked("target_rejected"));
|
||||
};
|
||||
let changed = tx.execute(
|
||||
"UPDATE refresh_runs SET status='restoring', snapshot_id=?2, restore_job_id=?3, updated_at=?4
|
||||
WHERE id=?1 AND status='capturing' AND restore_job_id IS NULL",
|
||||
params![run.id, snapshot.to_string(), job.id.to_string(), now],
|
||||
)?;
|
||||
if changed != 1 {
|
||||
return Ok(Linked::NotReady);
|
||||
}
|
||||
Ok(Linked::Queued(job.id.to_string()))
|
||||
})()?;
|
||||
tx.commit()?;
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
/// Stop a run for a reason found outside the database (for example its snapshot cannot be restored).
|
||||
pub fn block_refresh_run(&self, id: &str, reason: &str, now: i64) -> Result<()> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
if let Some(run) = get(&tx, id)? {
|
||||
block(&tx, &run, reason, now)?;
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Cancel a run before anything has been applied. `Err` carries why it could not be.
|
||||
pub fn cancel_refresh_run(&self, id: &str, now: i64) -> Result<std::result::Result<RefreshRun, CancelError>> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let result = (|| -> Result<std::result::Result<RefreshRun, CancelError>> {
|
||||
let Some(run) = get(&tx, id)? else { return Ok(Err(CancelError::Unknown)) };
|
||||
if !ACTIVE.contains(&run.status.as_str()) || run.status == "recovery_required" {
|
||||
return Ok(Err(CancelError::TooLate));
|
||||
}
|
||||
if let Some(job) = &run.restore_job_id {
|
||||
match restore_status(&tx, job)?.as_deref() {
|
||||
Some("applying") | Some("recovery_required") | Some("completed") => return Ok(Err(CancelError::TooLate)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let Some(job) = &run.restore_job_id {
|
||||
tx.execute("UPDATE restore_jobs SET status='cancelled', phase='cancelled', updated_at=?2 WHERE id=?1 AND status IN ('queued','running')", params![job, now])?;
|
||||
}
|
||||
finish(&tx, &run.id, "cancelled", None, now)?;
|
||||
Ok(Ok(get(&tx, id)?.expect("exists")))
|
||||
})()?;
|
||||
tx.commit()?;
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum CancelError {
|
||||
Unknown,
|
||||
TooLate,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum Linked {
|
||||
Queued(String),
|
||||
Blocked(&'static str),
|
||||
/// Nothing to do: not at that step yet, or it was already done.
|
||||
NotReady,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum Sync {
|
||||
Unchanged,
|
||||
/// The run moved to this status.
|
||||
Moved(String),
|
||||
/// The capture finished; the caller must now read the snapshot and call `enqueue_refresh_restore`.
|
||||
NeedRestore(String),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize)]
|
||||
pub struct Progress {
|
||||
pub capture_status: Option<String>,
|
||||
pub capture_phase: Option<String>,
|
||||
pub snapshot_taken_at: Option<i64>,
|
||||
pub restore_status: Option<String>,
|
||||
pub restore_phase: Option<String>,
|
||||
pub source_name: String,
|
||||
pub target_name: String,
|
||||
}
|
||||
|
||||
fn sync_in(tx: &Transaction<'_>, id: &str, now: i64) -> Result<Sync> {
|
||||
let Some(run) = get(tx, id)? else { return Ok(Sync::Unchanged) };
|
||||
if !ACTIVE.contains(&run.status.as_str()) {
|
||||
return Ok(Sync::Unchanged);
|
||||
}
|
||||
let restore = match &run.restore_job_id {
|
||||
Some(job) => restore_status(tx, job)?,
|
||||
None => None,
|
||||
};
|
||||
// Until the restore starts applying, any change in what authorised the run stops it.
|
||||
let past_the_point_of_no_return = matches!(restore.as_deref(), Some("applying" | "recovery_required" | "completed" | "failed" | "reconciled"));
|
||||
if !past_the_point_of_no_return {
|
||||
if let Some(reason) = invalid_reason(tx, &run, now)? {
|
||||
block(tx, &run, reason, now)?;
|
||||
return Ok(Sync::Moved(if reason == "expired" { "expired" } else { "blocked" }.into()));
|
||||
}
|
||||
}
|
||||
let move_to = |status: &str| -> Result<Sync> {
|
||||
finish(tx, &run.id, status, None, now)?;
|
||||
Ok(Sync::Moved(status.into()))
|
||||
};
|
||||
match run.status.as_str() {
|
||||
"capturing" => {
|
||||
let capture: Option<(String, Option<String>)> = tx
|
||||
.query_row("SELECT status, snapshot_id FROM capture_jobs WHERE id=?1", params![run.capture_job_id], |r| Ok((r.get(0)?, r.get(1)?)))
|
||||
.optional()?;
|
||||
match capture {
|
||||
Some((status, _)) if status == "failed" => move_to("capture_failed"),
|
||||
Some((status, Some(snapshot))) if status == "completed" && run.restore_job_id.is_none() => Ok(Sync::NeedRestore(snapshot)),
|
||||
None => move_to("capture_failed"),
|
||||
_ => Ok(Sync::Unchanged),
|
||||
}
|
||||
}
|
||||
"restoring" | "recovery_required" => match restore.as_deref() {
|
||||
Some("completed") => move_to("completed"),
|
||||
Some("failed") => move_to("restore_failed"),
|
||||
Some("cancelled") => move_to("cancelled"),
|
||||
Some("reconciled") => move_to("reconciled"),
|
||||
Some("recovery_required") if run.status == "restoring" => move_to("recovery_required"),
|
||||
None => move_to("restore_failed"),
|
||||
_ => Ok(Sync::Unchanged),
|
||||
},
|
||||
_ => Ok(Sync::Unchanged),
|
||||
}
|
||||
}
|
||||
@@ -141,7 +141,7 @@ fn engine_of_profile(profile: &str) -> Option<Engine> {
|
||||
serde_json::from_str::<tessera_core::job::CaptureProfile>(profile).ok()?.format.engine()
|
||||
}
|
||||
|
||||
fn read_relation(r: &rusqlite::Row<'_>) -> rusqlite::Result<Relation> {
|
||||
pub(super) fn read_relation(r: &rusqlite::Row<'_>) -> rusqlite::Result<Relation> {
|
||||
let identity: String = r.get(6)?;
|
||||
Ok(Relation {
|
||||
id: r.get(0)?,
|
||||
@@ -161,7 +161,7 @@ fn read_relation(r: &rusqlite::Row<'_>) -> rusqlite::Result<Relation> {
|
||||
})
|
||||
}
|
||||
|
||||
const RELATION_COLUMNS: &str = "id,lineage,version,source_orbit_id,source_application_id,target_id,target_identity,engine,verified,active,created_by,created_at,deactivated_at,deactivated_reason";
|
||||
pub(super) const RELATION_COLUMNS: &str = "id,lineage,version,source_orbit_id,source_application_id,target_id,target_identity,engine,verified,active,created_by,created_at,deactivated_at,deactivated_reason";
|
||||
|
||||
/// Does this Outpost currently hold a usable credential?
|
||||
fn outpost_active(conn: &Connection, outpost: &str, now: i64) -> rusqlite::Result<bool> {
|
||||
@@ -173,7 +173,7 @@ fn outpost_active(conn: &Connection, outpost: &str, now: i64) -> rusqlite::Resul
|
||||
}
|
||||
|
||||
/// Why a relation cannot be used right now, if it cannot.
|
||||
fn unusable(conn: &Connection, relation: &Relation, now: i64) -> rusqlite::Result<Option<&'static str>> {
|
||||
pub(super) fn unusable(conn: &Connection, relation: &Relation, now: i64) -> rusqlite::Result<Option<&'static str>> {
|
||||
if !relation.active {
|
||||
return Ok(Some("deactivated"));
|
||||
}
|
||||
@@ -424,6 +424,21 @@ impl Db {
|
||||
Ok(profile.and_then(|p| serde_json::from_str(&p).ok()))
|
||||
}
|
||||
|
||||
/// The grant that currently lets this subject use the relation, if any: its id, for recording on a run.
|
||||
pub fn granting_relation_grant(&self, user: Option<&str>, groups: &[String], relation: &str, now: i64) -> Result<Option<String>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let groups_json = serde_json::to_string(groups)?;
|
||||
Ok(conn
|
||||
.query_row(
|
||||
"SELECT id FROM relation_grants WHERE relation_id=?1 AND (expires_at IS NULL OR expires_at > ?2)
|
||||
AND ((principal_type='user' AND principal=?3) OR (principal_type='group' AND principal IN (SELECT value FROM json_each(?4))))
|
||||
ORDER BY principal_type LIMIT 1",
|
||||
params![relation, now, user, groups_json],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
// ---- grants of the refresh permission, one relation at a time ----
|
||||
|
||||
pub fn add_relation_grant(&self, principal_type: &str, principal: &str, relation: &str, expires_at: Option<i64>, created_by: &str, now: i64) -> Result<Option<RelationGrant>> {
|
||||
|
||||
@@ -127,37 +127,9 @@ impl Db {
|
||||
) -> Result<Option<RestoreJob>> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let registered: Option<RestoreTarget> = tx.query_row(
|
||||
"SELECT t.profile FROM restore_targets t WHERE t.id = ?1 AND t.application_id = ?2
|
||||
AND EXISTS (SELECT 1 FROM outpost_credentials WHERE outpost_id = t.outpost_id AND state = 'active' AND expires_at > ?3)",
|
||||
params![target.to_string(), application.to_string(), now],
|
||||
|row| json(row, 0),
|
||||
).optional()?;
|
||||
let Some(registered) = registered else {
|
||||
return Ok(None);
|
||||
};
|
||||
if restore_target_mismatch(®istered, artifact).is_some() {
|
||||
return Ok(None);
|
||||
}
|
||||
let id = Uuid::new_v4();
|
||||
tx.execute(
|
||||
"INSERT INTO restore_jobs(id, snapshot_id, target_id, actor, artifact, created_at, updated_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6)",
|
||||
params![id.to_string(), snapshot.to_string(), target.to_string(), actor,
|
||||
serde_json::to_string(artifact)?, now],
|
||||
)?;
|
||||
audit(
|
||||
&tx,
|
||||
"restore.queued",
|
||||
&format!("actor={actor} job={id} snapshot={snapshot} target={target}"),
|
||||
)?;
|
||||
let job = tx.query_row(
|
||||
&format!("{VIEW} WHERE j.id = ?1"),
|
||||
[id.to_string()],
|
||||
read_job,
|
||||
)?;
|
||||
let job = enqueue_restore_in(&tx, snapshot, application, target, actor, artifact, now)?;
|
||||
tx.commit()?;
|
||||
Ok(Some(job))
|
||||
Ok(job)
|
||||
}
|
||||
|
||||
pub fn restore_job(&self, id: Uuid, now: i64) -> Result<Option<RestoreJob>> {
|
||||
@@ -195,7 +167,10 @@ impl Db {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
Ok(conn.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM restore_jobs WHERE (snapshot_id = ?1 OR safety_id = ?1 OR attempt_safety_id = ?1)
|
||||
AND status IN ('queued','running','applying','recovery_required'))",
|
||||
AND status IN ('queued','running','applying','recovery_required'))
|
||||
-- a refresh run pins its own snapshot from the moment it starts: the snapshot id is its capture job id
|
||||
OR EXISTS(SELECT 1 FROM refresh_runs WHERE capture_job_id = ?1
|
||||
AND status IN ('capturing','restoring','recovery_required'))",
|
||||
[id.to_string()], |row| row.get(0),
|
||||
)?)
|
||||
}
|
||||
@@ -302,6 +277,18 @@ impl Db {
|
||||
if job.status != "running" || job.phase != "ready" || job.safety_snapshot_id.is_none() {
|
||||
return Ok(false);
|
||||
}
|
||||
// A refresh is only allowed to overwrite its target while what authorised it still holds. The check
|
||||
// and the flip to `applying` are one transaction, and the agent applies nothing without this answer.
|
||||
// Restores an administrator queued directly have no run and behave exactly as before.
|
||||
if let Some(run) = super::refresh::run_for_restore(&tx, &id.to_string())? {
|
||||
if let Some(reason) = super::refresh::invalid_reason(&tx, &run, now)? {
|
||||
super::refresh::block(&tx, &run, reason, now)?;
|
||||
tx.execute("UPDATE restore_jobs SET status='cancelled', phase='cancelled', updated_at=?2 WHERE id=?1 AND status='running'", params![id.to_string(), now])?;
|
||||
audit(&tx, "restore.apply_refused", &format!("job={id} run={} reason={reason}", run.id))?;
|
||||
tx.commit()?;
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
tx.execute("UPDATE restore_jobs SET status = 'applying', phase = 'applying', updated_at = ?2, lease_until = ?3 WHERE id = ?1",
|
||||
params![id.to_string(), now, now + CAPTURE_LEASE_SECONDS])?;
|
||||
audit(
|
||||
@@ -388,6 +375,48 @@ impl Db {
|
||||
}
|
||||
}
|
||||
|
||||
/// Queue a restore inside a transaction the caller owns, so a refresh run can link it atomically.
|
||||
pub(super) fn enqueue_restore_in(
|
||||
tx: &Transaction<'_>,
|
||||
snapshot: Uuid,
|
||||
application: Uuid,
|
||||
target: Uuid,
|
||||
actor: &str,
|
||||
artifact: &RestoreArtifact,
|
||||
now: i64,
|
||||
) -> Result<Option<RestoreJob>> {
|
||||
let registered: Option<RestoreTarget> = tx.query_row(
|
||||
"SELECT t.profile FROM restore_targets t WHERE t.id = ?1 AND t.application_id = ?2
|
||||
AND EXISTS (SELECT 1 FROM outpost_credentials WHERE outpost_id = t.outpost_id AND state = 'active' AND expires_at > ?3)",
|
||||
params![target.to_string(), application.to_string(), now],
|
||||
|row| json(row, 0),
|
||||
).optional()?;
|
||||
let Some(registered) = registered else {
|
||||
return Ok(None);
|
||||
};
|
||||
if restore_target_mismatch(®istered, artifact).is_some() {
|
||||
return Ok(None);
|
||||
}
|
||||
let id = Uuid::new_v4();
|
||||
tx.execute(
|
||||
"INSERT INTO restore_jobs(id, snapshot_id, target_id, actor, artifact, created_at, updated_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6)",
|
||||
params![id.to_string(), snapshot.to_string(), target.to_string(), actor,
|
||||
serde_json::to_string(artifact)?, now],
|
||||
)?;
|
||||
audit(
|
||||
&tx,
|
||||
"restore.queued",
|
||||
&format!("actor={actor} job={id} snapshot={snapshot} target={target}"),
|
||||
)?;
|
||||
let job = tx.query_row(
|
||||
&format!("{VIEW} WHERE j.id = ?1"),
|
||||
[id.to_string()],
|
||||
read_job,
|
||||
)?;
|
||||
Ok(Some(job))
|
||||
}
|
||||
|
||||
fn restore_access(
|
||||
conn: &Connection,
|
||||
outpost: Uuid,
|
||||
|
||||
@@ -6,6 +6,7 @@ mod exports;
|
||||
mod limits;
|
||||
mod mtls;
|
||||
mod oidc;
|
||||
mod refresh;
|
||||
mod scheduler;
|
||||
mod state;
|
||||
mod upload;
|
||||
@@ -81,6 +82,7 @@ async fn main() -> Result<()> {
|
||||
state.reconcile_capture_catalog().await?;
|
||||
state.start_offsite_worker();
|
||||
scheduler::start_orbit_scheduler(state.clone()).await?;
|
||||
refresh::start(state.clone());
|
||||
if state.sessions.enabled() {
|
||||
tracing::info!("operator sessions enabled; CLI access uses a separate admin token");
|
||||
} else {
|
||||
|
||||
125
crates/tessera-hub/src/refresh.rs
Normal file
125
crates/tessera-hub/src/refresh.rs
Normal file
@@ -0,0 +1,125 @@
|
||||
//! The refresh driver: moves durable refresh runs forward.
|
||||
//!
|
||||
//! The runs and every transition live in SQLite (`db/refresh.rs`); this loop only looks at them. It
|
||||
//! holds no state, so a restart simply carries on. The one step that needs the vault (reading the
|
||||
//! snapshot a run's capture produced) happens outside any database lock, and the store re-checks
|
||||
//! everything inside its transaction before it queues the restore.
|
||||
use crate::auth::{AuditAction, AuditOutcome, AuditResource, Principal};
|
||||
use crate::db::refresh::{Linked, RefreshRun, Sync};
|
||||
use crate::state::HubState;
|
||||
use std::time::Duration;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub const DEFAULT_TTL_MINUTES: i64 = 120;
|
||||
pub const DEFAULT_MAX_ACTIVE: i64 = 4;
|
||||
|
||||
pub struct RefreshConfig {
|
||||
/// How long a run may take before it starts applying. After that it expires. Once applying, it is never cut off.
|
||||
pub ttl_secs: i64,
|
||||
/// Refreshes running at once, to bound the load on production sources.
|
||||
pub max_active: i64,
|
||||
}
|
||||
|
||||
impl RefreshConfig {
|
||||
pub fn from_env() -> Self {
|
||||
let number = |name: &str| std::env::var(name).ok().and_then(|v| v.trim().parse::<i64>().ok());
|
||||
Self {
|
||||
ttl_secs: number("TESSERA_REFRESH_TTL_MINUTES").filter(|m| (1..=1440).contains(m)).unwrap_or(DEFAULT_TTL_MINUTES) * 60,
|
||||
max_active: number("TESSERA_REFRESH_MAX_ACTIVE").filter(|m| (1..=64).contains(m)).unwrap_or(DEFAULT_MAX_ACTIVE),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn now() -> i64 {
|
||||
chrono::Utc::now().timestamp()
|
||||
}
|
||||
|
||||
/// The audit action and outcome that go with a run reaching a state.
|
||||
pub fn audit_name(status: &str) -> (&'static str, AuditOutcome) {
|
||||
match status {
|
||||
"capturing" => ("refresh.started", AuditOutcome::Succeeded),
|
||||
"restoring" => ("refresh.restore_queued", AuditOutcome::Succeeded),
|
||||
"completed" => ("refresh.completed", AuditOutcome::Succeeded),
|
||||
"reconciled" => ("refresh.reconciled", AuditOutcome::Succeeded),
|
||||
"cancelled" => ("refresh.cancelled", AuditOutcome::Succeeded),
|
||||
"capture_failed" => ("refresh.capture_failed", AuditOutcome::Failed),
|
||||
"restore_failed" => ("refresh.restore_failed", AuditOutcome::Failed),
|
||||
"recovery_required" => ("refresh.recovery_required", AuditOutcome::Failed),
|
||||
"blocked" => ("refresh.blocked", AuditOutcome::Denied),
|
||||
"expired" => ("refresh.expired", AuditOutcome::Denied),
|
||||
_ => ("refresh.changed", AuditOutcome::Succeeded),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn audit_run(state: &HubState, run: &str, status: &str) {
|
||||
let (action, outcome) = audit_name(status);
|
||||
if let Ok(id) = Uuid::parse_str(run) {
|
||||
if let Err(error) = state.db.audit_event(&Principal::Service("refresh"), AuditAction::RefreshEvent(action), AuditResource::RefreshRun(id), outcome, Uuid::new_v4()) {
|
||||
tracing::error!("could not audit refresh run {run}: {error:#}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One pass over every active run. Returns how many changed.
|
||||
pub async fn tick(state: &HubState) -> anyhow::Result<usize> {
|
||||
let mut changed = 0;
|
||||
for run in state.db.active_refresh_runs()? {
|
||||
match state.db.sync_refresh_run(&run.id, now())? {
|
||||
Sync::Unchanged => {}
|
||||
Sync::Moved(status) => {
|
||||
changed += 1;
|
||||
audit_run(state, &run.id, &status);
|
||||
}
|
||||
Sync::NeedRestore(snapshot) => {
|
||||
if queue_restore(state, &run, &snapshot).await? {
|
||||
changed += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(changed)
|
||||
}
|
||||
|
||||
/// Read the run's own snapshot and queue its restore. Idempotent: a second call finds the job already linked.
|
||||
async fn queue_restore(state: &HubState, run: &RefreshRun, snapshot: &str) -> anyhow::Result<bool> {
|
||||
let snapshot_id = Uuid::parse_str(snapshot)?;
|
||||
let manifest = state.vault.read().await.get_snapshot(snapshot_id)?.map(|s| s.manifest);
|
||||
let artifact = manifest.as_ref().and_then(|m| crate::api::artifact(m)).map(|(_, artifact)| artifact);
|
||||
let Some(artifact) = artifact else {
|
||||
// The snapshot is missing or lacks what a restore needs (format, checksum, source identity).
|
||||
state.db.block_refresh_run(&run.id, "snapshot_not_restorable", now())?;
|
||||
audit_run(state, &run.id, "blocked");
|
||||
return Ok(true);
|
||||
};
|
||||
let target = state.db.restore_target(Uuid::parse_str(&run.target_id)?)?;
|
||||
let clash = match target {
|
||||
Some(target) => {
|
||||
let source = Uuid::parse_str(&run.source_orbit_id)?;
|
||||
crate::api::identity_facts(state, source, &target.identity).await.map_err(|status| anyhow::anyhow!("identity check failed: {status}"))?.0
|
||||
}
|
||||
None => true,
|
||||
};
|
||||
match state.db.enqueue_refresh_restore(&run.id, &artifact, clash, now())? {
|
||||
Linked::Queued(_) => {
|
||||
audit_run(state, &run.id, "restoring");
|
||||
Ok(true)
|
||||
}
|
||||
Linked::Blocked(_) => {
|
||||
audit_run(state, &run.id, "blocked");
|
||||
Ok(true)
|
||||
}
|
||||
Linked::NotReady => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// Start the background loop. Cheap when nothing is running.
|
||||
pub fn start(state: HubState) {
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
tokio::time::sleep(Duration::from_secs(3)).await;
|
||||
if let Err(error) = tick(&state).await {
|
||||
tracing::warn!("refresh driver: {error:#}");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -43,6 +43,7 @@ pub struct HubState {
|
||||
pub oidc: Option<std::sync::Arc<crate::oidc::OidcProvider>>,
|
||||
pub limits: Arc<crate::limits::Limits>,
|
||||
pub exports: Arc<crate::exports::ExportGate>,
|
||||
pub refresh: Arc<crate::refresh::RefreshConfig>,
|
||||
pub wormhole_mtls: bool,
|
||||
/// Token uploads are accepted on this listener. Plain HTTP turns this off
|
||||
/// when wormhole mTLS is required, so those routes are not a bypass.
|
||||
@@ -77,6 +78,7 @@ impl HubState {
|
||||
sessions: SessionGate::from_env(db.clone(), oidc_config.as_ref().map(|c| c.fingerprint()))?,
|
||||
limits: Arc::new(crate::limits::Limits::from_env()?),
|
||||
exports: Arc::new(crate::exports::ExportGate::from_env()),
|
||||
refresh: Arc::new(crate::refresh::RefreshConfig::from_env()),
|
||||
oidc: oidc_config.map(|c| crate::oidc::OidcProvider::new(c).map(Arc::new)).transpose()?,
|
||||
wormhole_mtls: false,
|
||||
accept_plain_upload: true,
|
||||
|
||||
Reference in New Issue
Block a user