feat: environments and production-to-staging relations (auth M6b)
- environment (production/staging/development) on source orbits and on restore targets; an unlabelled target fails closed and a production target is refused - directed, versioned relations from a managed source orbit to a restore target: one active relation per pair, retargeting makes a new id and ends the old one - refusals name the rule: unknown or unlabelled source/target, not a managed capture profile, not restore-ready, application or engine mismatch, inactive Outpost, and a target whose identity matches a database captured as production in any snapshot - relations end in the same transaction when their target is relabelled production or an Outpost is revoked; usability is re-read live - refresh.run is granted per relation id in its own table (user or group, expiry), never global, never carried to a new version, and never accepted by the orbit gate - admin API under /api/v1/relations plus environment endpoints; people holding only a relation grant see names and environments, never identity, host, Outpost or application - Relations console; sign-in form without SSO no longer shows a stray "Details" label Tests extend the access matrix with relation fixtures and a caller that holds only a relation grant. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -27,6 +27,8 @@ struct Fixture {
|
||||
outpost: Uuid,
|
||||
snapshot: Uuid,
|
||||
job: Uuid,
|
||||
target: Uuid,
|
||||
relation: Uuid,
|
||||
}
|
||||
|
||||
struct Caller {
|
||||
@@ -91,7 +93,11 @@ async fn fixture(state: &HubState, name: &str) -> Fixture {
|
||||
identity: DatabaseIdentity { instance: if name == "orbit-a" { "123" } else { "124" }.into(), database: "app".into() },
|
||||
};
|
||||
assert!(state.db.register_restore_target(&target).unwrap());
|
||||
Fixture { orbit, application, outpost, snapshot, job }
|
||||
// orbit -> its staging database, with both environments set explicitly
|
||||
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, true, "seed", now()).unwrap().unwrap();
|
||||
Fixture { orbit, application, outpost, snapshot, job, target: target.id, relation: Uuid::parse_str(&relation.id).unwrap() }
|
||||
}
|
||||
|
||||
async fn world() -> World {
|
||||
@@ -167,6 +173,8 @@ fn anonymous() -> Caller {
|
||||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||||
enum Kind {
|
||||
SelfOnly,
|
||||
/// Visible only to people holding a grant on a relation (`refresh.run`).
|
||||
RelationList,
|
||||
AdminOnly,
|
||||
List(Permission),
|
||||
Resource(Permission),
|
||||
@@ -188,6 +196,8 @@ fn rows() -> Vec<Row> {
|
||||
}
|
||||
let kind = if f[4] == "session.self" {
|
||||
Kind::SelfOnly
|
||||
} else if f[4] == "refresh.run" {
|
||||
Kind::RelationList
|
||||
} else {
|
||||
let permission = Permission::parse(f[4]).unwrap_or_else(|| panic!("unknown permission {} in the contract", f[4]));
|
||||
if !permission.grantable() {
|
||||
@@ -215,9 +225,12 @@ 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/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,
|
||||
_ => unknown,
|
||||
};
|
||||
let uri = row.template.replace(":id", &id.to_string());
|
||||
let uri = row.template.replace(":id", &id.to_string()).replace(":grant", &unknown.to_string());
|
||||
let target = RestoreTarget {
|
||||
id: Uuid::new_v4(), application_id: a.application, outpost_id: a.outpost, name: "new-target".into(), engine: Engine::Postgres,
|
||||
identity: DatabaseIdentity { instance: "456".into(), database: "other".into() },
|
||||
@@ -233,6 +246,10 @@ fn recipe(w: &World, row: &Row) -> (String, Option<Value>) {
|
||||
("POST", "/api/v1/restore-jobs/:id/reconcile") => Some(json!({"confirmation": "x"})),
|
||||
("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/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"})),
|
||||
("POST" | "PUT" | "DELETE" | "GET", _) => None,
|
||||
other => panic!("no request recipe for {other:?}"),
|
||||
};
|
||||
@@ -277,6 +294,9 @@ async fn every_human_route_enforces_the_matrix_for_every_kind_of_caller() {
|
||||
w.grant_role(capturer_a.user_id.as_ref().unwrap(), "capturer", Some(w.a.orbit));
|
||||
w.grant_role(downloader_a.user_id.as_ref().unwrap(), "downloader", Some(w.a.orbit));
|
||||
w.grant("group", "qa", "viewer", Some(w.a.orbit));
|
||||
// holds nothing on any orbit, only the right to refresh through orbit A's relation
|
||||
let refresher_a = w.caller("refresher-a", false, &[]);
|
||||
w.state.db.add_relation_grant("user", refresher_a.user_id.as_ref().unwrap(), &w.a.relation.to_string(), None, "test", now()).unwrap().unwrap();
|
||||
let (a, b) = (w.a.orbit.to_string(), w.b.orbit.to_string());
|
||||
|
||||
// scoped routes first, so the destructive admin-only ones cannot disturb their fixtures
|
||||
@@ -296,9 +316,10 @@ async fn every_human_route_enforces_the_matrix_for_every_kind_of_caller() {
|
||||
assert_eq!(status, StatusCode::UNAUTHORIZED, "{label} anonymous");
|
||||
|
||||
// every non-admin caller, with the exact status the contract implies
|
||||
for caller in [&nogrant, &viewer_b, &viewer_a, &capturer_a, &downloader_a, &group_a] {
|
||||
for caller in [&nogrant, &refresher_a, &viewer_b, &viewer_a, &capturer_a, &downloader_a, &group_a] {
|
||||
let (status, body_out) = w.send(caller, &row.method, &uri, body.clone()).await;
|
||||
let on_a = !std::ptr::eq(caller, &viewer_b) && !std::ptr::eq(caller, &nogrant);
|
||||
let no_orbit_access = matches!(caller.name, "nogrant" | "refresher-a");
|
||||
let on_a = !std::ptr::eq(caller, &viewer_b) && !no_orbit_access;
|
||||
let held: &[Permission] = match caller.name {
|
||||
"viewer-a" | "viewer-b" | "group-a" => role("viewer").unwrap(),
|
||||
"capturer-a" => role("capturer").unwrap(),
|
||||
@@ -320,8 +341,25 @@ async fn every_human_route_enforces_the_matrix_for_every_kind_of_caller() {
|
||||
};
|
||||
assert_eq!(status, expected, "{who}");
|
||||
}
|
||||
Kind::RelationList => {
|
||||
if caller.name == "refresher-a" {
|
||||
assert_eq!(status, StatusCode::OK, "{who}");
|
||||
let relations = body_out.as_array().unwrap();
|
||||
assert_eq!(relations.len(), 1, "{who} sees only the relation it was granted");
|
||||
assert_eq!(relations[0]["id"], w.a.relation.to_string());
|
||||
// never where the database is
|
||||
let shown = body_out.to_string();
|
||||
for secret in ["identity", "instance", "outpost", "application", "\"database\"", "host"] {
|
||||
assert!(!shown.contains(secret), "{who}: the refresher's view leaks {secret}: {shown}");
|
||||
}
|
||||
assert_eq!((relations[0]["source_name"].as_str(), relations[0]["target_name"].as_str()), (Some("orbit-a"), Some("orbit-a-staging")));
|
||||
} else {
|
||||
// orbit access of any kind is not the right to refresh
|
||||
assert_eq!(status, StatusCode::FORBIDDEN, "{who}");
|
||||
}
|
||||
}
|
||||
Kind::List(_) => {
|
||||
if caller.name == "nogrant" {
|
||||
if no_orbit_access {
|
||||
assert_eq!(status, StatusCode::FORBIDDEN, "{who}");
|
||||
} else if row.method == "GET" {
|
||||
assert_eq!(status, StatusCode::OK, "{who}");
|
||||
@@ -335,8 +373,8 @@ 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 caller.name == "nogrant" {
|
||||
assert!(!status.is_success(), "{who}: a caller without any grant got {status}");
|
||||
if no_orbit_access && !(caller.name == "refresher-a" && row.kind == Kind::RelationList) {
|
||||
assert!(!status.is_success(), "{who}: a caller without any matching grant got {status}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -347,6 +385,10 @@ async fn every_human_route_enforces_the_matrix_for_every_kind_of_caller() {
|
||||
let seen = orbits_in(&row.template, &body_out);
|
||||
assert!(seen.contains(&a) && seen.contains(&b), "{label}: the administrator sees every orbit");
|
||||
}
|
||||
if row.kind == Kind::RelationList {
|
||||
let ids: Vec<_> = body_out.as_array().unwrap().iter().map(|r| r["id"].as_str().unwrap().to_string()).collect();
|
||||
assert!(ids.contains(&w.a.relation.to_string()) && ids.contains(&w.b.relation.to_string()), "{label}: the administrator sees every relation");
|
||||
}
|
||||
}
|
||||
assert!(covered >= 25, "the matrix covered {covered} routes");
|
||||
}
|
||||
@@ -600,3 +642,161 @@ async fn a_caller_who_may_not_download_cannot_use_up_the_export_slots() {
|
||||
assert_eq!(audited, 1, "only the permitted request counts as an export request");
|
||||
}
|
||||
|
||||
|
||||
async fn snapshot_with_identity(w: &World, orbit: Uuid, instance: &str, database: &str) {
|
||||
let id = Uuid::new_v4();
|
||||
let manifest = SnapshotManifest {
|
||||
snapshot_id: id,
|
||||
orbit_id: orbit,
|
||||
orbit_name: "fixture".into(),
|
||||
labels: vec![],
|
||||
provider: "postgres".into(),
|
||||
paths: vec![],
|
||||
restore_hints: json!({"format": "custom", "source_identity": {"instance": instance, "database": database}}),
|
||||
};
|
||||
w.state.vault.write().await.snapshot(manifest, b"PGDMP", false).unwrap();
|
||||
}
|
||||
|
||||
fn db_conn(w: &World) -> rusqlite::Connection {
|
||||
rusqlite::Connection::open(w._dir.path().join("tessera.db")).unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn relations_follow_their_rules_over_http_and_name_the_rule_that_refused() {
|
||||
let w = world().await;
|
||||
let admin = w.caller("admin", true, &[]);
|
||||
let rel = "/api/v1/relations";
|
||||
// the fixture already has A -> its staging target; asking again is a conflict, not a second relation
|
||||
let body = json!({"source_orbit_id": w.a.orbit, "target_id": w.a.target});
|
||||
let (status, refusal) = w.send(&admin, "POST", rel, Some(body.clone())).await;
|
||||
assert_eq!((status, refusal["reason"].clone()), (StatusCode::CONFLICT, json!("relation_exists")));
|
||||
// a target is for its own application; and an unlabelled or production target fails closed
|
||||
let (status, refusal) = w.send(&admin, "POST", rel, Some(json!({"source_orbit_id": w.a.orbit, "target_id": w.b.target}))).await;
|
||||
assert_eq!((status, refusal["reason"].clone()), (StatusCode::UNPROCESSABLE_ENTITY, json!("application_mismatch")));
|
||||
let (status, refusal) = w.send(&admin, "POST", rel, Some(json!({"source_orbit_id": Uuid::new_v4(), "target_id": w.a.target}))).await;
|
||||
assert_eq!((status, refusal["reason"].clone()), (StatusCode::NOT_FOUND, json!("unknown_source")));
|
||||
assert_eq!(w.send(&admin, "POST", rel, Some(json!({"source_orbit_id": w.a.orbit, "target_id": Uuid::new_v4()}))).await.1["reason"], "unknown_target");
|
||||
assert_eq!(w.send(&admin, "POST", rel, Some(json!({"source_orbit_id": w.a.orbit}))).await.0, StatusCode::UNPROCESSABLE_ENTITY, "malformed body");
|
||||
|
||||
// environments: only the three names, and nothing is assumed
|
||||
let orbit_env = format!("/api/v1/orbits/{}/environment", w.a.orbit);
|
||||
assert_eq!(w.send(&admin, "PUT", &orbit_env, Some(json!({"environment": "prod"}))).await.0, StatusCode::BAD_REQUEST);
|
||||
assert_eq!(w.send(&admin, "PUT", &format!("/api/v1/orbits/{}/environment", Uuid::new_v4()), Some(json!({"environment": "staging"}))).await.0, StatusCode::NOT_FOUND);
|
||||
let overview = w.send(&admin, "GET", rel, None).await.1;
|
||||
let orbit = overview["orbits"].as_array().unwrap().iter().find(|o| o["id"] == w.a.orbit.to_string()).unwrap();
|
||||
assert_eq!((orbit["ready"].clone(), orbit["environment"].clone(), orbit["engine"].clone()), (json!(true), json!("production"), json!("postgres")));
|
||||
let target = overview["targets"].as_array().unwrap().iter().find(|t| t["id"] == w.a.target.to_string()).unwrap();
|
||||
assert_eq!((target["environment"].clone(), target["outpost_active"].clone(), target["identity"]["instance"].clone()), (json!("staging"), json!(true), json!("123")));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_production_database_labelled_staging_is_caught_by_the_snapshots() {
|
||||
let w = world().await;
|
||||
let admin = w.caller("admin", true, &[]);
|
||||
let rel = "/api/v1/relations";
|
||||
let existing = w.a.relation.to_string();
|
||||
assert_eq!(w.send(&admin, "DELETE", &format!("{rel}/{existing}"), None).await.0, StatusCode::NO_CONTENT);
|
||||
// orbit B (production) captures a database whose identity is exactly orbit A's "staging" target
|
||||
snapshot_with_identity(&w, w.b.orbit, "123", "app").await;
|
||||
let body = json!({"source_orbit_id": w.a.orbit, "target_id": w.a.target});
|
||||
let (status, refusal) = w.send(&admin, "POST", rel, Some(body.clone())).await;
|
||||
assert_eq!((status, refusal["reason"].clone()), (StatusCode::UNPROCESSABLE_ENTITY, json!("target_matches_a_production_source")));
|
||||
// if that capturing orbit is itself a staging orbit, it is the target's own backup and does not count
|
||||
let b_env = format!("/api/v1/orbits/{}/environment", w.b.orbit);
|
||||
assert_eq!(w.send(&admin, "PUT", &b_env, Some(json!({"environment": "staging"}))).await.0, StatusCode::NO_CONTENT);
|
||||
let (status, created) = w.send(&admin, "POST", rel, Some(body)).await;
|
||||
assert_eq!(status, StatusCode::CREATED);
|
||||
assert_eq!(created["verified"], false, "the source has no snapshot yet, so the refresh must check again before applying");
|
||||
// once the source itself has been seen, a relation is verified
|
||||
let retarget = format!("{rel}/{}", created["id"].as_str().unwrap());
|
||||
snapshot_with_identity(&w, w.a.orbit, "999", "prod").await;
|
||||
let (status, second) = w.send(&admin, "PUT", &retarget, Some(json!({"target_id": w.a.target}))).await;
|
||||
assert_eq!(status, StatusCode::CREATED);
|
||||
assert_eq!((second["verified"].clone(), second["version"].clone()), (json!(true), json!(2)));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refresh_access_binds_to_one_relation_and_ends_when_that_relation_does() {
|
||||
let w = world().await;
|
||||
let admin = w.caller("admin", true, &[]);
|
||||
let qa = w.caller("qa", false, &["testers"]);
|
||||
let qa_id = qa.user_id.clone().unwrap();
|
||||
let rel = w.a.relation.to_string();
|
||||
let access = format!("/api/v1/relations/{rel}/access");
|
||||
let mine = "/api/v1/refresh-relations";
|
||||
assert_eq!(w.send(&qa, "GET", mine, None).await.0, StatusCode::FORBIDDEN, "nothing granted yet");
|
||||
assert_eq!(w.send(&qa, "POST", &access, Some(json!({"principal_type": "user", "principal": qa_id}))).await.0, StatusCode::FORBIDDEN, "not for non-administrators");
|
||||
|
||||
// validation
|
||||
for (what, body, expected) in [
|
||||
("unknown user", json!({"principal_type": "user", "principal": Uuid::new_v4()}), StatusCode::UNPROCESSABLE_ENTITY),
|
||||
("not a uuid", json!({"principal_type": "user", "principal": "bob"}), StatusCode::BAD_REQUEST),
|
||||
("unknown type", json!({"principal_type": "service", "principal": "x"}), StatusCode::BAD_REQUEST),
|
||||
("oversized group", json!({"principal_type": "group", "principal": "g".repeat(200)}), StatusCode::BAD_REQUEST),
|
||||
("past expiry", json!({"principal_type": "user", "principal": qa_id, "expires_at": "2020-01-01T00:00:00Z"}), StatusCode::BAD_REQUEST),
|
||||
] {
|
||||
assert_eq!(w.send(&admin, "POST", &access, Some(body)).await.0, expected, "{what}");
|
||||
}
|
||||
assert_eq!(w.send(&admin, "POST", &format!("/api/v1/relations/{}/access", Uuid::new_v4()), Some(json!({"principal_type": "group", "principal": "testers"}))).await.0, StatusCode::NOT_FOUND);
|
||||
|
||||
// by group: effective on the very next request; removing it ends it
|
||||
let (status, grant) = w.send(&admin, "POST", &access, Some(json!({"principal_type": "group", "principal": "testers"}))).await;
|
||||
assert_eq!(status, StatusCode::CREATED);
|
||||
assert_eq!(w.send(&qa, "GET", mine, None).await.0, StatusCode::OK);
|
||||
assert_eq!(w.send(&admin, "POST", &access, Some(json!({"principal_type": "group", "principal": "testers"}))).await.0, StatusCode::CONFLICT);
|
||||
assert_eq!(w.send(&admin, "GET", &access, None).await.1.as_array().unwrap().len(), 1);
|
||||
let revoke = format!("{access}/{}", grant["id"].as_str().unwrap());
|
||||
assert_eq!(w.send(&admin, "DELETE", &revoke, None).await.0, StatusCode::NO_CONTENT);
|
||||
assert_eq!(w.send(&qa, "GET", mine, None).await.0, StatusCode::FORBIDDEN, "revoked at once");
|
||||
|
||||
// by person; a retarget gives a new relation id and the old access does not follow
|
||||
w.send(&admin, "POST", &access, Some(json!({"principal_type": "user", "principal": qa_id}))).await;
|
||||
assert_eq!(w.send(&qa, "GET", mine, None).await.1[0]["id"], rel);
|
||||
let other_target = RestoreTarget {
|
||||
id: Uuid::new_v4(), application_id: w.a.application, outpost_id: w.a.outpost, name: "second-staging".into(), engine: Engine::Postgres,
|
||||
identity: DatabaseIdentity { instance: "777".into(), database: "app".into() },
|
||||
};
|
||||
assert!(w.state.db.register_restore_target(&other_target).unwrap());
|
||||
let target_env = format!("/api/v1/restore-targets/{}/environment", other_target.id);
|
||||
assert_eq!(w.send(&admin, "PUT", &target_env, Some(json!({"environment": "development"}))).await.0, StatusCode::OK);
|
||||
let (status, next) = w.send(&admin, "PUT", &format!("/api/v1/relations/{rel}"), Some(json!({"target_id": other_target.id}))).await;
|
||||
assert_eq!(status, StatusCode::CREATED);
|
||||
assert_ne!(next["id"], rel.as_str());
|
||||
assert_eq!(w.send(&qa, "GET", mine, None).await.0, StatusCode::FORBIDDEN, "the new database starts with no access");
|
||||
|
||||
// grant it, then relabel the target as production: the relation ends in that very request
|
||||
let new_access = format!("/api/v1/relations/{}/access", next["id"].as_str().unwrap());
|
||||
w.send(&admin, "POST", &new_access, Some(json!({"principal_type": "user", "principal": qa_id}))).await;
|
||||
assert_eq!(w.send(&qa, "GET", mine, None).await.1[0]["usable"], true);
|
||||
let (status, ended) = w.send(&admin, "PUT", &target_env, Some(json!({"environment": "production"}))).await;
|
||||
assert_eq!((status, ended["ended_relations"].as_array().unwrap().len()), (StatusCode::OK, 1));
|
||||
assert_eq!(w.send(&qa, "GET", mine, None).await.0, StatusCode::FORBIDDEN);
|
||||
let (status, refusal) = w.send(&admin, "PUT", &format!("/api/v1/relations/{rel}"), Some(json!({"target_id": other_target.id}))).await;
|
||||
assert_eq!(status, StatusCode::NOT_FOUND, "a replaced relation cannot be replaced again: {refusal}");
|
||||
|
||||
// every administrative step left a trail
|
||||
let conn = db_conn(&w);
|
||||
let count = |action: &str| -> i64 { conn.query_row("SELECT COUNT(*) FROM audit_events WHERE action=?1 AND outcome='succeeded'", [action], |r| r.get(0)).unwrap() };
|
||||
assert_eq!((count("relation.grant_create"), count("relation.grant_delete"), count("relation.retarget"), count("environment.set")), (3, 1, 1, 2));
|
||||
assert!(count("relation.deactivate") >= 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn revoking_an_outpost_or_deleting_a_relation_takes_refreshers_off_immediately() {
|
||||
let w = world().await;
|
||||
let admin = w.caller("admin", true, &[]);
|
||||
let qa = w.caller("qa", false, &[]);
|
||||
let rel = w.a.relation.to_string();
|
||||
w.send(&admin, "POST", &format!("/api/v1/relations/{rel}/access"), Some(json!({"principal_type": "user", "principal": qa.user_id.clone().unwrap()}))).await;
|
||||
assert_eq!(w.send(&qa, "GET", "/api/v1/refresh-relations", None).await.0, StatusCode::OK);
|
||||
assert_eq!(w.send(&admin, "POST", &format!("/api/v1/wormhole/outposts/{}/revoke", w.a.outpost), None).await.0, StatusCode::NO_CONTENT);
|
||||
assert_eq!(w.send(&qa, "GET", "/api/v1/refresh-relations", None).await.0, StatusCode::FORBIDDEN);
|
||||
let overview = w.send(&admin, "GET", "/api/v1/relations", None).await.1;
|
||||
let stored = overview["relations"].as_array().unwrap().iter().find(|r| r["id"] == rel.as_str()).unwrap();
|
||||
assert_eq!((stored["active"].clone(), stored["deactivated_reason"].clone()), (json!(false), json!("outpost_revoked")));
|
||||
// deleting an already ended relation is a 404, not a second success
|
||||
assert_eq!(w.send(&admin, "DELETE", &format!("/api/v1/relations/{rel}"), None).await.0, StatusCode::NOT_FOUND);
|
||||
// orbit B's relation is untouched by A's Outpost
|
||||
let b = overview["relations"].as_array().unwrap().iter().find(|r| r["id"] == w.b.relation.to_string()).unwrap();
|
||||
assert_eq!(b["active"], true);
|
||||
}
|
||||
|
||||
@@ -66,6 +66,39 @@ pub(super) fn scoped(state: &HubState, actor: &OperatorActor, permission: Permis
|
||||
if allowed { Ok(()) } else { Err(StatusCode::FORBIDDEN) }
|
||||
}
|
||||
|
||||
/// Use one relation. Administrators always; anyone else only through a live grant on that very relation
|
||||
/// (not on its orbit, not on an older version of it). Everything else answers 404, so a relation's
|
||||
/// existence is not confirmed to someone who cannot use it.
|
||||
#[allow(dead_code)] // used by the refresh run (M6c); the matrix already exercises the list built on the same grants
|
||||
pub(super) fn relation(state: &HubState, actor: &OperatorActor, relation: Uuid) -> Result<(), StatusCode> {
|
||||
let resource = AuditResource::Relation(relation);
|
||||
if actor.subject.admin {
|
||||
return audit(state, actor, resource, true);
|
||||
}
|
||||
let granted = state
|
||||
.db
|
||||
.granted_relations(actor.subject.user_id.as_deref(), &actor.subject.groups, now())
|
||||
.map_err(internal)?;
|
||||
let allowed = granted.iter().any(|id| id == &relation.to_string());
|
||||
audit(state, actor, resource, allowed)?;
|
||||
if allowed { Ok(()) } else { Err(StatusCode::NOT_FOUND) }
|
||||
}
|
||||
|
||||
/// The relations a caller may use: `None` for an administrator (all), otherwise their granted ids.
|
||||
/// A caller with none gets 403 rather than an empty list.
|
||||
pub(super) fn visible_relations(state: &HubState, actor: &OperatorActor) -> Result<Option<Vec<String>>, StatusCode> {
|
||||
if actor.subject.admin {
|
||||
audit(state, actor, AuditResource::Api, true)?;
|
||||
return Ok(None);
|
||||
}
|
||||
let granted = state
|
||||
.db
|
||||
.granted_relations(actor.subject.user_id.as_deref(), &actor.subject.groups, now())
|
||||
.map_err(internal)?;
|
||||
audit(state, actor, AuditResource::Api, !granted.is_empty())?;
|
||||
if granted.is_empty() { Err(StatusCode::FORBIDDEN) } else { Ok(Some(granted)) }
|
||||
}
|
||||
|
||||
/// Which orbits a list may show.
|
||||
pub(super) enum Visible {
|
||||
All,
|
||||
|
||||
@@ -3,6 +3,7 @@ mod catalog;
|
||||
mod gate;
|
||||
mod jobs;
|
||||
mod oidc;
|
||||
mod relations;
|
||||
mod orbit;
|
||||
mod restore;
|
||||
mod routes;
|
||||
|
||||
413
crates/tessera-hub/src/api/relations.rs
Normal file
413
crates/tessera-hub/src/api/relations.rs
Normal file
@@ -0,0 +1,413 @@
|
||||
//! Environments, relations and who may use them.
|
||||
//!
|
||||
//! Administrators configure everything here. The one endpoint a refresher sees is
|
||||
//! `GET /api/v1/refresh-relations`, which lists only the relations they hold a grant on and
|
||||
//! never shows where the database is (no identity, host, Outpost or application id).
|
||||
use super::routes::{admin_read, admin_write, authenticate};
|
||||
use crate::auth::{AuditAction, AuditOutcome, AuditResource};
|
||||
use crate::db::relations::{Reject, ENVIRONMENTS};
|
||||
use crate::state::HubState;
|
||||
use axum::{
|
||||
extract::{ConnectInfo, Path, State},
|
||||
http::{header, HeaderMap, HeaderValue, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
routing::{get, put},
|
||||
Json, Router,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::net::SocketAddr;
|
||||
use tessera_core::restore::{DatabaseIdentity, Engine};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub(super) fn routes() -> Router<HubState> {
|
||||
Router::new()
|
||||
.route("/api/v1/orbits/:id/environment", put(set_orbit_environment))
|
||||
.route("/api/v1/restore-targets/:id/environment", put(set_target_environment))
|
||||
.route("/api/v1/relations", get(list).post(create))
|
||||
.route("/api/v1/relations/:id", put(retarget).delete(deactivate))
|
||||
.route("/api/v1/relations/:id/access", get(list_access).post(grant_access))
|
||||
.route("/api/v1/relations/:id/access/:grant", axum::routing::delete(revoke_access))
|
||||
.route("/api/v1/refresh-relations", get(mine))
|
||||
}
|
||||
|
||||
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!("relations: {error:#}");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
}
|
||||
|
||||
/// A refused request names the rule that refused it, so an administrator can fix the setup.
|
||||
fn refused(reject: Reject) -> Response {
|
||||
let status = match reject {
|
||||
Reject::UnknownSource | Reject::UnknownTarget => StatusCode::NOT_FOUND,
|
||||
Reject::Duplicate => StatusCode::CONFLICT,
|
||||
_ => StatusCode::UNPROCESSABLE_ENTITY,
|
||||
};
|
||||
(status, Json(serde_json::json!({ "reason": reject.code() }))).into_response()
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct SetEnvironment {
|
||||
environment: String,
|
||||
}
|
||||
|
||||
fn valid_environment(value: &str) -> bool {
|
||||
ENVIRONMENTS.contains(&value)
|
||||
}
|
||||
|
||||
async fn set_orbit_environment(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(body): Json<SetEnvironment>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
let actor = admin_write(&state, peer, &headers)?;
|
||||
if !valid_environment(&body.environment) {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
if !state.db.set_orbit_environment(id, &body.environment, now()).map_err(internal)? {
|
||||
return Err(StatusCode::NOT_FOUND);
|
||||
}
|
||||
state.db.audit_event(&actor.principal, AuditAction::EnvironmentSet, AuditResource::Orbit(id), AuditOutcome::Succeeded, actor.request_id).map_err(internal)?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct EnvironmentChange {
|
||||
/// Relations that stopped working because of this change.
|
||||
ended_relations: Vec<String>,
|
||||
}
|
||||
|
||||
async fn set_target_environment(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(body): Json<SetEnvironment>,
|
||||
) -> Result<Json<EnvironmentChange>, StatusCode> {
|
||||
let actor = admin_write(&state, peer, &headers)?;
|
||||
if !valid_environment(&body.environment) {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
let ended = state.db.set_target_environment(id, &body.environment, now()).map_err(internal)?.ok_or(StatusCode::NOT_FOUND)?;
|
||||
state.db.audit_event(&actor.principal, AuditAction::EnvironmentSet, AuditResource::RestoreTarget(id), AuditOutcome::Succeeded, actor.request_id).map_err(internal)?;
|
||||
for relation in &ended {
|
||||
if let Ok(relation) = Uuid::parse_str(relation) {
|
||||
state.db.audit_event(&actor.principal, AuditAction::RelationDeactivate, AuditResource::Relation(relation), AuditOutcome::Succeeded, actor.request_id).map_err(internal)?;
|
||||
}
|
||||
}
|
||||
Ok(Json(EnvironmentChange { ended_relations: ended }))
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct OrbitSetup {
|
||||
id: String,
|
||||
name: String,
|
||||
environment: Option<String>,
|
||||
application_id: Option<String>,
|
||||
engine: Option<&'static str>,
|
||||
/// Can this orbit be the source of a relation, and if not, why not.
|
||||
ready: bool,
|
||||
reason: Option<&'static str>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct TargetSetup {
|
||||
id: String,
|
||||
name: String,
|
||||
engine: &'static str,
|
||||
identity: DatabaseIdentity,
|
||||
application_id: String,
|
||||
environment: Option<String>,
|
||||
outpost_active: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Overview {
|
||||
relations: Vec<crate::db::relations::RelationView>,
|
||||
orbits: Vec<OrbitSetup>,
|
||||
targets: Vec<TargetSetup>,
|
||||
}
|
||||
|
||||
fn engine_name(engine: Engine) -> &'static str {
|
||||
match engine {
|
||||
Engine::Postgres => "postgres",
|
||||
Engine::Mysql => "mysql",
|
||||
}
|
||||
}
|
||||
|
||||
async fn list(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<(HeaderMap, Json<Overview>), StatusCode> {
|
||||
admin_read(&state, peer, &headers)?;
|
||||
let (orbit_env, target_env) = state.db.environments().map_err(internal)?;
|
||||
let profiles: std::collections::HashMap<_, _> =
|
||||
state.db.capture_profiles().map_err(internal)?.into_iter().map(|p| (p.orbit_id, p)).collect();
|
||||
let orbits = state
|
||||
.db
|
||||
.list_orbits()
|
||||
.await
|
||||
.map_err(internal)?
|
||||
.into_iter()
|
||||
.map(|orbit| {
|
||||
let profile = profiles.get(&orbit.id);
|
||||
let engine = profile.and_then(|p| p.format.engine());
|
||||
let environment = orbit_env.get(&orbit.id.to_string()).cloned();
|
||||
let reason = if profile.is_none() {
|
||||
Some("not_managed")
|
||||
} else if engine.is_none() {
|
||||
Some("not_restore_ready")
|
||||
} else if environment.is_none() {
|
||||
Some("environment_unset")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
OrbitSetup {
|
||||
id: orbit.id.to_string(),
|
||||
name: orbit.name,
|
||||
environment,
|
||||
application_id: profile.map(|p| p.application_id.to_string()),
|
||||
engine: engine.map(engine_name),
|
||||
ready: reason.is_none(),
|
||||
reason,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let targets = state
|
||||
.db
|
||||
.all_restore_targets(now())
|
||||
.map_err(internal)?
|
||||
.into_iter()
|
||||
.map(|(target, outpost_active)| TargetSetup {
|
||||
environment: target_env.get(&target.id.to_string()).cloned(),
|
||||
id: target.id.to_string(),
|
||||
name: target.name,
|
||||
engine: engine_name(target.engine),
|
||||
identity: target.identity,
|
||||
application_id: target.application_id.to_string(),
|
||||
outpost_active,
|
||||
})
|
||||
.collect();
|
||||
let relations = state.db.relation_views(false, None, now()).map_err(internal)?;
|
||||
Ok((no_store(), Json(Overview { relations, orbits, targets })))
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
let (orbit_env, _) = state.db.environments().map_err(internal)?;
|
||||
let vault = state.vault.read().await;
|
||||
let snapshots = vault.list_snapshots().map_err(internal)?;
|
||||
let (mut clash, mut verified) = (false, false);
|
||||
for snapshot in snapshots {
|
||||
let Some(identity) = snapshot.manifest.restore_hints.get("source_identity").cloned() else { continue };
|
||||
let Ok(identity) = serde_json::from_value::<DatabaseIdentity>(identity) else { continue };
|
||||
let from = snapshot.manifest.orbit_id;
|
||||
if from == source {
|
||||
verified = true;
|
||||
}
|
||||
if &identity == target {
|
||||
// A staging or development orbit that backs up the target itself is fine; anything else is
|
||||
// a database captured as production (or never classified) under a staging label.
|
||||
let own_backup = from != source && matches!(orbit_env.get(&from.to_string()).map(String::as_str), Some("staging" | "development"));
|
||||
if !own_backup {
|
||||
clash = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok((clash, verified))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct NewRelation {
|
||||
source_orbit_id: Uuid,
|
||||
target_id: Uuid,
|
||||
}
|
||||
|
||||
async fn create(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Json(body): Json<NewRelation>,
|
||||
) -> Result<Response, StatusCode> {
|
||||
let actor = admin_write(&state, peer, &headers)?;
|
||||
let Some(target) = state.db.restore_target(body.target_id).map_err(internal)? else {
|
||||
return Ok(refused(Reject::UnknownTarget));
|
||||
};
|
||||
let (clash, verified) = identity_facts(&state, body.source_orbit_id, &target.identity).await?;
|
||||
match state.db.create_relation(body.source_orbit_id, body.target_id, None, clash, verified, &actor.id(), now()).map_err(internal)? {
|
||||
Ok(relation) => {
|
||||
let id = Uuid::parse_str(&relation.id).map_err(internal)?;
|
||||
state.db.audit_event(&actor.principal, AuditAction::RelationCreate, AuditResource::Relation(id), AuditOutcome::Succeeded, actor.request_id).map_err(internal)?;
|
||||
Ok((StatusCode::CREATED, no_store(), Json(relation)).into_response())
|
||||
}
|
||||
Err(reject) => Ok(refused(reject)),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Retarget {
|
||||
target_id: Uuid,
|
||||
}
|
||||
|
||||
async fn retarget(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(body): Json<Retarget>,
|
||||
) -> Result<Response, StatusCode> {
|
||||
let actor = admin_write(&state, peer, &headers)?;
|
||||
let old = state.db.relation(&id.to_string()).map_err(internal)?.filter(|r| r.active).ok_or(StatusCode::NOT_FOUND)?;
|
||||
let source = Uuid::parse_str(&old.source_orbit_id).map_err(internal)?;
|
||||
let Some(target) = state.db.restore_target(body.target_id).map_err(internal)? else {
|
||||
return Ok(refused(Reject::UnknownTarget));
|
||||
};
|
||||
let (clash, verified) = identity_facts(&state, source, &target.identity).await?;
|
||||
match state.db.create_relation(source, body.target_id, Some(&old.id), clash, verified, &actor.id(), now()).map_err(internal)? {
|
||||
Ok(relation) => {
|
||||
let new_id = Uuid::parse_str(&relation.id).map_err(internal)?;
|
||||
state.db.audit_event(&actor.principal, AuditAction::RelationRetarget, AuditResource::Relation(new_id), AuditOutcome::Succeeded, actor.request_id).map_err(internal)?;
|
||||
Ok((StatusCode::CREATED, no_store(), Json(relation)).into_response())
|
||||
}
|
||||
Err(reject) => Ok(refused(reject)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn deactivate(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
let actor = admin_write(&state, peer, &headers)?;
|
||||
let done = state.db.deactivate_relation(&id.to_string(), "deactivated_by_admin", now()).map_err(internal)?;
|
||||
state.db.audit_event(&actor.principal, AuditAction::RelationDeactivate, AuditResource::Relation(id),
|
||||
if done { AuditOutcome::Succeeded } else { AuditOutcome::Failed }, actor.request_id).map_err(internal)?;
|
||||
if done { Ok(StatusCode::NO_CONTENT) } else { Err(StatusCode::NOT_FOUND) }
|
||||
}
|
||||
|
||||
async fn list_access(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<(HeaderMap, Json<Vec<crate::db::relations::RelationGrant>>), StatusCode> {
|
||||
admin_read(&state, peer, &headers)?;
|
||||
state.db.relation(&id.to_string()).map_err(internal)?.ok_or(StatusCode::NOT_FOUND)?;
|
||||
Ok((no_store(), Json(state.db.relation_grants(&id.to_string()).map_err(internal)?)))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct NewAccess {
|
||||
principal_type: String,
|
||||
principal: String,
|
||||
expires_at: Option<String>,
|
||||
}
|
||||
|
||||
async fn grant_access(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(body): Json<NewAccess>,
|
||||
) -> Result<(StatusCode, HeaderMap, Json<crate::db::relations::RelationGrant>), StatusCode> {
|
||||
let actor = admin_write(&state, peer, &headers)?;
|
||||
let now = now();
|
||||
match body.principal_type.as_str() {
|
||||
"user" => {
|
||||
Uuid::parse_str(&body.principal).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
if !state.db.user_exists(&body.principal).map_err(internal)? {
|
||||
return Err(StatusCode::UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
}
|
||||
"group" => {
|
||||
if body.principal.is_empty() || body.principal.len() > 128 || body.principal.chars().any(char::is_control) {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
_ => return Err(StatusCode::BAD_REQUEST),
|
||||
}
|
||||
let expires_at = body
|
||||
.expires_at
|
||||
.as_deref()
|
||||
.map(|text| chrono::DateTime::parse_from_rfc3339(text).map(|t| t.timestamp()).map_err(|_| StatusCode::BAD_REQUEST))
|
||||
.transpose()?;
|
||||
if expires_at.is_some_and(|end| end <= now || end > now + 2 * 366 * 86_400) {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
state.db.relation(&id.to_string()).map_err(internal)?.filter(|r| r.active).ok_or(StatusCode::NOT_FOUND)?;
|
||||
let grant = state
|
||||
.db
|
||||
.add_relation_grant(&body.principal_type, &body.principal, &id.to_string(), expires_at, &actor.id(), now)
|
||||
.map_err(internal)?
|
||||
.ok_or(StatusCode::CONFLICT)?;
|
||||
state.db.audit_event(&actor.principal, AuditAction::RelationGrantCreate, AuditResource::Relation(id), AuditOutcome::Succeeded, actor.request_id).map_err(internal)?;
|
||||
Ok((StatusCode::CREATED, no_store(), Json(grant)))
|
||||
}
|
||||
|
||||
async fn revoke_access(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path((id, grant)): Path<(Uuid, Uuid)>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
let actor = admin_write(&state, peer, &headers)?;
|
||||
let removed = state.db.delete_relation_grant(&id.to_string(), &grant.to_string()).map_err(internal)?;
|
||||
state.db.audit_event(&actor.principal, AuditAction::RelationGrantDelete, AuditResource::Relation(id),
|
||||
if removed { AuditOutcome::Succeeded } else { AuditOutcome::Failed }, actor.request_id).map_err(internal)?;
|
||||
if removed { Ok(StatusCode::NO_CONTENT) } else { Err(StatusCode::NOT_FOUND) }
|
||||
}
|
||||
|
||||
/// A relation as a refresher sees it: names and environments, never where the database is.
|
||||
#[derive(Serialize)]
|
||||
struct MyRelation {
|
||||
id: String,
|
||||
version: i64,
|
||||
source_name: String,
|
||||
source_environment: Option<String>,
|
||||
target_name: String,
|
||||
target_environment: Option<String>,
|
||||
usable: bool,
|
||||
unusable_reason: Option<&'static str>,
|
||||
}
|
||||
|
||||
async fn mine(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<(HeaderMap, Json<Vec<MyRelation>>), StatusCode> {
|
||||
let actor = authenticate(&state, peer, &headers, false)?;
|
||||
let granted = super::gate::visible_relations(&state, &actor)?;
|
||||
let views = state.db.relation_views(true, granted.as_deref(), now()).map_err(internal)?;
|
||||
let list = views
|
||||
.into_iter()
|
||||
.map(|view| MyRelation {
|
||||
id: view.relation.id,
|
||||
version: view.relation.version,
|
||||
source_name: view.source_name,
|
||||
source_environment: view.source_environment,
|
||||
target_name: view.target_name,
|
||||
target_environment: view.target_environment,
|
||||
usable: view.usable,
|
||||
unusable_reason: view.unusable_reason,
|
||||
})
|
||||
.collect();
|
||||
Ok((no_store(), Json(list)))
|
||||
}
|
||||
@@ -348,6 +348,7 @@ pub fn router(state: HubState) -> Router {
|
||||
.merge(super::session::routes())
|
||||
.merge(super::oidc::routes())
|
||||
.merge(super::access::routes())
|
||||
.merge(super::relations::routes())
|
||||
.merge(super::restore::routes())
|
||||
.with_state(state);
|
||||
|
||||
|
||||
@@ -42,6 +42,12 @@ pub enum AuditAction {
|
||||
ExportReady,
|
||||
ExportFinished,
|
||||
ExportDisconnected,
|
||||
EnvironmentSet,
|
||||
RelationCreate,
|
||||
RelationRetarget,
|
||||
RelationDeactivate,
|
||||
RelationGrantCreate,
|
||||
RelationGrantDelete,
|
||||
}
|
||||
|
||||
impl AuditAction {
|
||||
@@ -63,6 +69,12 @@ impl AuditAction {
|
||||
Self::ExportReady => "export.ready",
|
||||
Self::ExportFinished => "export.finished",
|
||||
Self::ExportDisconnected => "export.disconnected",
|
||||
Self::EnvironmentSet => "environment.set",
|
||||
Self::RelationCreate => "relation.create",
|
||||
Self::RelationRetarget => "relation.retarget",
|
||||
Self::RelationDeactivate => "relation.deactivate",
|
||||
Self::RelationGrantCreate => "relation.grant_create",
|
||||
Self::RelationGrantDelete => "relation.grant_delete",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -94,6 +106,8 @@ pub enum AuditResource {
|
||||
Grant(Uuid),
|
||||
User(Uuid),
|
||||
Snapshot(Uuid),
|
||||
Relation(Uuid),
|
||||
RestoreTarget(Uuid),
|
||||
}
|
||||
|
||||
impl AuditResource {
|
||||
@@ -107,6 +121,8 @@ impl AuditResource {
|
||||
Self::Grant(id) => ("grant", Some(id.to_string())),
|
||||
Self::User(id) => ("user", Some(id.to_string())),
|
||||
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())),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -127,6 +143,10 @@ pub enum Permission {
|
||||
SnapshotDelete,
|
||||
RecoveryManage,
|
||||
AccessManage,
|
||||
/// Configuring environments and relations. Administrators only.
|
||||
RelationManage,
|
||||
/// Refreshing a staging target. Never held through `access_grants`: it is granted per relation, in `relation_grants`.
|
||||
RefreshRun,
|
||||
}
|
||||
|
||||
impl Permission {
|
||||
@@ -142,13 +162,15 @@ impl Permission {
|
||||
Self::SnapshotDelete => "snapshot.delete",
|
||||
Self::RecoveryManage => "recovery.manage",
|
||||
Self::AccessManage => "access.manage",
|
||||
Self::RelationManage => "relation.manage",
|
||||
Self::RefreshRun => "refresh.run",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(text: &str) -> Option<Self> {
|
||||
[
|
||||
Self::OrbitRead, Self::SnapshotRead, Self::CaptureRun, Self::SnapshotDownload, Self::OrbitManage,
|
||||
Self::OutpostManage, Self::RetentionManage, Self::SnapshotDelete, Self::RecoveryManage, Self::AccessManage,
|
||||
Self::OutpostManage, Self::RetentionManage, Self::SnapshotDelete, Self::RecoveryManage, Self::AccessManage, Self::RelationManage, Self::RefreshRun,
|
||||
]
|
||||
.into_iter()
|
||||
.find(|permission| permission.as_str() == text)
|
||||
|
||||
@@ -5,6 +5,7 @@ pub mod sessions;
|
||||
pub(crate) mod oidc_login;
|
||||
pub(crate) mod credentials;
|
||||
pub(crate) mod access;
|
||||
pub(crate) mod relations;
|
||||
pub(crate) use restore::restore_target_mismatch;
|
||||
|
||||
use anyhow::Result;
|
||||
@@ -99,6 +100,7 @@ impl Db {
|
||||
sessions::migrate(&conn)?;
|
||||
oidc_login::migrate(&conn)?;
|
||||
access::migrate(&conn)?;
|
||||
relations::migrate(&conn)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -239,6 +239,13 @@ impl Db {
|
||||
params![outpost, now],
|
||||
)?;
|
||||
let known = tx.execute("UPDATE outposts SET pairing_state='revoked' WHERE id=?1", params![outpost])? == 1;
|
||||
// Anything that overwrites through, or reads from, this Outpost must stop working with it.
|
||||
tx.execute(
|
||||
"UPDATE orbit_relations SET active=0, deactivated_at=?2, deactivated_reason='outpost_revoked'
|
||||
WHERE active=1 AND (target_id IN (SELECT id FROM restore_targets WHERE outpost_id=?1)
|
||||
OR source_application_id IN (SELECT application_id FROM capture_profiles WHERE outpost_id=?1))",
|
||||
params![outpost, now],
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok(known)
|
||||
}
|
||||
|
||||
672
crates/tessera-hub/src/db/relations.rs
Normal file
672
crates/tessera-hub/src/db/relations.rs
Normal file
@@ -0,0 +1,672 @@
|
||||
//! Environments and directed relations "this source may overwrite that target".
|
||||
//!
|
||||
//! * A source orbit and a restore target each carry an explicit environment. Nothing is assumed:
|
||||
//! an unset environment is never accepted as a target, and a target labelled `production` is refused.
|
||||
//! * A relation points from one managed source orbit to one restore target, in that direction only.
|
||||
//! It is never symmetric or transitive, and it is versioned: retargeting creates a new relation
|
||||
//! (new id, same lineage) and deactivates the old one. Access is granted to a relation id, so a
|
||||
//! new version starts with no grants rather than silently pointing people at another database.
|
||||
//! * A relation stops being usable in the same transaction in which its target is relabelled as
|
||||
//! production or its Outpost is revoked; reading it also re-checks the facts that can lapse (credential expiry).
|
||||
use super::*;
|
||||
use tessera_core::restore::{Engine, RestoreTarget};
|
||||
|
||||
pub const ENVIRONMENTS: [&str; 3] = ["production", "staging", "development"];
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
|
||||
pub enum Reject {
|
||||
UnknownSource,
|
||||
SourceEnvironmentUnset,
|
||||
SourceNotManaged,
|
||||
SourceNotRestoreReady,
|
||||
UnknownTarget,
|
||||
TargetEnvironmentUnset,
|
||||
TargetIsProduction,
|
||||
ApplicationMismatch,
|
||||
EngineMismatch,
|
||||
TargetMatchesSource,
|
||||
OutpostInactive,
|
||||
Duplicate,
|
||||
}
|
||||
|
||||
impl Reject {
|
||||
pub fn code(self) -> &'static str {
|
||||
match self {
|
||||
Self::UnknownSource => "unknown_source",
|
||||
Self::SourceEnvironmentUnset => "source_environment_unset",
|
||||
Self::SourceNotManaged => "source_not_managed",
|
||||
Self::SourceNotRestoreReady => "source_not_restore_ready",
|
||||
Self::UnknownTarget => "unknown_target",
|
||||
Self::TargetEnvironmentUnset => "target_environment_unset",
|
||||
Self::TargetIsProduction => "target_is_production",
|
||||
Self::ApplicationMismatch => "application_mismatch",
|
||||
Self::EngineMismatch => "engine_mismatch",
|
||||
Self::TargetMatchesSource => "target_matches_a_production_source",
|
||||
Self::OutpostInactive => "outpost_inactive",
|
||||
Self::Duplicate => "relation_exists",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize)]
|
||||
pub struct Relation {
|
||||
pub id: String,
|
||||
pub lineage: String,
|
||||
pub version: i64,
|
||||
pub source_orbit_id: String,
|
||||
pub source_application_id: String,
|
||||
pub target_id: String,
|
||||
pub target_identity: serde_json::Value,
|
||||
pub engine: String,
|
||||
/// False when the source had no snapshot yet to compare the target against; the refresh re-checks before applying.
|
||||
pub verified: bool,
|
||||
pub active: bool,
|
||||
pub created_by: String,
|
||||
pub created_at: i64,
|
||||
pub deactivated_at: Option<i64>,
|
||||
pub deactivated_reason: Option<String>,
|
||||
}
|
||||
|
||||
/// A relation with the names and the facts that can lapse, for display and for deciding whether it is usable now.
|
||||
#[derive(Clone, Debug, serde::Serialize)]
|
||||
pub struct RelationView {
|
||||
#[serde(flatten)]
|
||||
pub relation: Relation,
|
||||
pub source_name: String,
|
||||
pub source_environment: Option<String>,
|
||||
pub target_name: String,
|
||||
pub target_environment: Option<String>,
|
||||
pub usable: bool,
|
||||
pub unusable_reason: Option<&'static str>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize)]
|
||||
pub struct RelationGrant {
|
||||
pub id: String,
|
||||
pub principal_type: String,
|
||||
pub principal: String,
|
||||
pub relation_id: String,
|
||||
pub expires_at: Option<i64>,
|
||||
pub created_by: String,
|
||||
pub created_at: i64,
|
||||
}
|
||||
|
||||
pub(super) fn migrate(conn: &Connection) -> Result<()> {
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE IF NOT EXISTS orbit_environments (
|
||||
orbit_id TEXT PRIMARY KEY,
|
||||
environment TEXT NOT NULL CHECK(environment IN ('production','staging','development')),
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS target_environments (
|
||||
target_id TEXT PRIMARY KEY,
|
||||
environment TEXT NOT NULL CHECK(environment IN ('production','staging','development')),
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS orbit_relations (
|
||||
id TEXT PRIMARY KEY,
|
||||
lineage TEXT NOT NULL,
|
||||
version INTEGER NOT NULL,
|
||||
source_orbit_id TEXT NOT NULL,
|
||||
source_application_id TEXT NOT NULL,
|
||||
target_id TEXT NOT NULL,
|
||||
target_identity TEXT NOT NULL,
|
||||
engine TEXT NOT NULL,
|
||||
verified INTEGER NOT NULL,
|
||||
active INTEGER NOT NULL DEFAULT 1,
|
||||
created_by TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
deactivated_at INTEGER,
|
||||
deactivated_reason TEXT,
|
||||
UNIQUE(lineage, version)
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS orbit_relations_active ON orbit_relations(source_orbit_id, target_id) WHERE active = 1;
|
||||
CREATE INDEX IF NOT EXISTS orbit_relations_target ON orbit_relations(target_id, active);
|
||||
CREATE TABLE IF NOT EXISTS relation_grants (
|
||||
id TEXT PRIMARY KEY,
|
||||
principal_type TEXT NOT NULL CHECK(principal_type IN ('user','group')),
|
||||
principal TEXT NOT NULL,
|
||||
relation_id TEXT NOT NULL,
|
||||
expires_at INTEGER,
|
||||
created_by TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
UNIQUE(principal_type, principal, relation_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS relation_grants_principal ON relation_grants(principal_type, principal);",
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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> {
|
||||
let identity: String = r.get(6)?;
|
||||
Ok(Relation {
|
||||
id: r.get(0)?,
|
||||
lineage: r.get(1)?,
|
||||
version: r.get(2)?,
|
||||
source_orbit_id: r.get(3)?,
|
||||
source_application_id: r.get(4)?,
|
||||
target_id: r.get(5)?,
|
||||
target_identity: serde_json::from_str(&identity).unwrap_or(serde_json::Value::Null),
|
||||
engine: r.get(7)?,
|
||||
verified: r.get::<_, i64>(8)? == 1,
|
||||
active: r.get::<_, i64>(9)? == 1,
|
||||
created_by: r.get(10)?,
|
||||
created_at: r.get(11)?,
|
||||
deactivated_at: r.get(12)?,
|
||||
deactivated_reason: r.get(13)?,
|
||||
})
|
||||
}
|
||||
|
||||
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> {
|
||||
conn.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM outpost_credentials WHERE outpost_id=?1 AND state='active' AND expires_at>?2)",
|
||||
params![outpost, now],
|
||||
|r| r.get(0),
|
||||
)
|
||||
}
|
||||
|
||||
/// Why a relation cannot be used right now, if it cannot.
|
||||
fn unusable(conn: &Connection, relation: &Relation, now: i64) -> rusqlite::Result<Option<&'static str>> {
|
||||
if !relation.active {
|
||||
return Ok(Some("deactivated"));
|
||||
}
|
||||
let target_env: Option<String> =
|
||||
conn.query_row("SELECT environment FROM target_environments WHERE target_id=?1", params![relation.target_id], |r| r.get(0)).optional()?;
|
||||
if !matches!(target_env.as_deref(), Some("staging" | "development")) {
|
||||
return Ok(Some("target_environment"));
|
||||
}
|
||||
let outposts: (Option<String>, Option<String>) = (
|
||||
conn.query_row("SELECT outpost_id FROM restore_targets WHERE id=?1", params![relation.target_id], |r| r.get(0)).optional()?,
|
||||
conn.query_row("SELECT outpost_id FROM capture_profiles WHERE application_id=?1", params![relation.source_application_id], |r| r.get(0)).optional()?,
|
||||
);
|
||||
for outpost in [outposts.0, outposts.1] {
|
||||
match outpost {
|
||||
Some(id) if outpost_active(conn, &id, now)? => {}
|
||||
_ => return Ok(Some("outpost_inactive")),
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
impl Db {
|
||||
pub fn set_orbit_environment(&self, orbit: Uuid, environment: &str, now: i64) -> Result<bool> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let exists: bool = conn.query_row("SELECT EXISTS(SELECT 1 FROM orbits WHERE id=?1)", params![orbit.to_string()], |r| r.get(0))?;
|
||||
if !exists {
|
||||
return Ok(false);
|
||||
}
|
||||
conn.execute(
|
||||
"INSERT INTO orbit_environments(orbit_id,environment,updated_at) VALUES (?1,?2,?3)
|
||||
ON CONFLICT(orbit_id) DO UPDATE SET environment=excluded.environment, updated_at=excluded.updated_at",
|
||||
params![orbit.to_string(), environment, now],
|
||||
)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Label a restore target. Labelling it production ends every active relation into it in the same
|
||||
/// transaction. Returns the ids of the relations that were ended, or `None` for an unknown target.
|
||||
pub fn set_target_environment(&self, target: Uuid, environment: &str, now: i64) -> Result<Option<Vec<String>>> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction()?;
|
||||
let exists: bool = tx.query_row("SELECT EXISTS(SELECT 1 FROM restore_targets WHERE id=?1)", params![target.to_string()], |r| r.get(0))?;
|
||||
if !exists {
|
||||
return Ok(None);
|
||||
}
|
||||
tx.execute(
|
||||
"INSERT INTO target_environments(target_id,environment,updated_at) VALUES (?1,?2,?3)
|
||||
ON CONFLICT(target_id) DO UPDATE SET environment=excluded.environment, updated_at=excluded.updated_at",
|
||||
params![target.to_string(), environment, now],
|
||||
)?;
|
||||
let mut ended = Vec::new();
|
||||
if !matches!(environment, "staging" | "development") {
|
||||
let mut stmt = tx.prepare("SELECT id FROM orbit_relations WHERE target_id=?1 AND active=1")?;
|
||||
ended = stmt.query_map(params![target.to_string()], |r| r.get::<_, String>(0))?.collect::<rusqlite::Result<_>>()?;
|
||||
drop(stmt);
|
||||
tx.execute(
|
||||
"UPDATE orbit_relations SET active=0, deactivated_at=?2, deactivated_reason='target_relabelled' WHERE target_id=?1 AND active=1",
|
||||
params![target.to_string(), now],
|
||||
)?;
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(Some(ended))
|
||||
}
|
||||
|
||||
/// Create a relation, or with `replace` retarget an existing one (new id, next version, old one deactivated).
|
||||
/// Every fact that lives in the database is re-checked inside the transaction. `identity_clash` and
|
||||
/// `verified` come from the snapshots in the vault, which the caller has already read.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn create_relation(
|
||||
&self,
|
||||
source_orbit: Uuid,
|
||||
target: Uuid,
|
||||
replace: Option<&str>,
|
||||
identity_clash: bool,
|
||||
verified: bool,
|
||||
created_by: &str,
|
||||
now: i64,
|
||||
) -> Result<std::result::Result<Relation, Reject>> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction()?;
|
||||
let result = (|| -> Result<std::result::Result<Relation, Reject>> {
|
||||
let orbit_known: bool = tx.query_row("SELECT EXISTS(SELECT 1 FROM orbits WHERE id=?1)", params![source_orbit.to_string()], |r| r.get(0))?;
|
||||
if !orbit_known {
|
||||
return Ok(Err(Reject::UnknownSource));
|
||||
}
|
||||
let profile: Option<(String, String, String)> = tx
|
||||
.query_row(
|
||||
"SELECT application_id, outpost_id, profile FROM capture_profiles WHERE orbit_id=?1",
|
||||
params![source_orbit.to_string()],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||
)
|
||||
.optional()?;
|
||||
let Some((application, source_outpost, profile_json)) = profile else { return Ok(Err(Reject::SourceNotManaged)) };
|
||||
let Some(engine) = engine_of_profile(&profile_json) else { return Ok(Err(Reject::SourceNotRestoreReady)) };
|
||||
let source_env: Option<String> = tx
|
||||
.query_row("SELECT environment FROM orbit_environments WHERE orbit_id=?1", params![source_orbit.to_string()], |r| r.get(0))
|
||||
.optional()?;
|
||||
if source_env.is_none() {
|
||||
return Ok(Err(Reject::SourceEnvironmentUnset));
|
||||
}
|
||||
let target_row: Option<(String, String, String, String)> = tx
|
||||
.query_row(
|
||||
"SELECT application_id, outpost_id, identity, profile FROM restore_targets WHERE id=?1",
|
||||
params![target.to_string()],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
|
||||
)
|
||||
.optional()?;
|
||||
let Some((target_application, target_outpost, identity, target_profile)) = target_row else { return Ok(Err(Reject::UnknownTarget)) };
|
||||
let target_env: Option<String> = tx
|
||||
.query_row("SELECT environment FROM target_environments WHERE target_id=?1", params![target.to_string()], |r| r.get(0))
|
||||
.optional()?;
|
||||
match target_env.as_deref() {
|
||||
None => return Ok(Err(Reject::TargetEnvironmentUnset)),
|
||||
Some("production") => return Ok(Err(Reject::TargetIsProduction)),
|
||||
_ => {}
|
||||
}
|
||||
if target_application != application {
|
||||
return Ok(Err(Reject::ApplicationMismatch));
|
||||
}
|
||||
let target_engine = serde_json::from_str::<tessera_core::restore::RestoreTarget>(&target_profile).ok().map(|t| t.engine);
|
||||
if target_engine != Some(engine) {
|
||||
return Ok(Err(Reject::EngineMismatch));
|
||||
}
|
||||
// The table keeps `(engine, identity)`; the relation records just the identity it was checked against.
|
||||
let identity = serde_json::from_str::<(Engine, tessera_core::restore::DatabaseIdentity)>(&identity)
|
||||
.ok()
|
||||
.and_then(|(_, identity)| serde_json::to_string(&identity).ok())
|
||||
.unwrap_or(identity);
|
||||
if identity_clash {
|
||||
return Ok(Err(Reject::TargetMatchesSource));
|
||||
}
|
||||
if !outpost_active(&tx, &source_outpost, now)? || !outpost_active(&tx, &target_outpost, now)? {
|
||||
return Ok(Err(Reject::OutpostInactive));
|
||||
}
|
||||
let (lineage, version) = match replace {
|
||||
Some(old) => {
|
||||
let found: Option<(String, i64)> = tx
|
||||
.query_row("SELECT lineage, version FROM orbit_relations WHERE id=?1 AND source_orbit_id=?2 AND active=1", params![old, source_orbit.to_string()], |r| Ok((r.get(0)?, r.get(1)?)))
|
||||
.optional()?;
|
||||
let Some((lineage, version)) = found else { return Ok(Err(Reject::UnknownSource)) };
|
||||
let next: i64 = tx.query_row("SELECT MAX(version) FROM orbit_relations WHERE lineage=?1", params![lineage], |r| r.get(0))?;
|
||||
tx.execute(
|
||||
"UPDATE orbit_relations SET active=0, deactivated_at=?2, deactivated_reason='replaced' WHERE id=?1",
|
||||
params![old, now],
|
||||
)?;
|
||||
let _ = version;
|
||||
(lineage, next + 1)
|
||||
}
|
||||
None => (Uuid::new_v4().to_string(), 1),
|
||||
};
|
||||
let id = Uuid::new_v4().to_string();
|
||||
let inserted = tx.execute(
|
||||
"INSERT INTO orbit_relations(id,lineage,version,source_orbit_id,source_application_id,target_id,target_identity,engine,verified,active,created_by,created_at)
|
||||
VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,1,?10,?11)",
|
||||
params![id, lineage, version, source_orbit.to_string(), application, target.to_string(), identity, format!("{engine:?}").to_lowercase(), verified, created_by, now],
|
||||
);
|
||||
match inserted {
|
||||
Ok(_) => {}
|
||||
Err(rusqlite::Error::SqliteFailure(error, _)) if error.code == rusqlite::ErrorCode::ConstraintViolation => return Ok(Err(Reject::Duplicate)),
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
let relation = tx.query_row(&format!("SELECT {RELATION_COLUMNS} FROM orbit_relations WHERE id=?1"), params![id], read_relation)?;
|
||||
Ok(Ok(relation))
|
||||
})()?;
|
||||
if result.is_ok() {
|
||||
tx.commit()?;
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub fn deactivate_relation(&self, id: &str, reason: &str, now: i64) -> Result<bool> {
|
||||
Ok(self.conn.lock().unwrap().execute(
|
||||
"UPDATE orbit_relations SET active=0, deactivated_at=?2, deactivated_reason=?3 WHERE id=?1 AND active=1",
|
||||
params![id, now, reason],
|
||||
)? == 1)
|
||||
}
|
||||
|
||||
pub fn relation(&self, id: &str) -> Result<Option<Relation>> {
|
||||
Ok(self.conn.lock().unwrap()
|
||||
.query_row(&format!("SELECT {RELATION_COLUMNS} FROM orbit_relations WHERE id=?1"), params![id], read_relation)
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
/// Relations with names and live usability. `only` restricts to a set of ids (for a non-administrator).
|
||||
pub fn relation_views(&self, active_only: bool, only: Option<&[String]>, now: i64) -> Result<Vec<RelationView>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare(&format!(
|
||||
"SELECT {RELATION_COLUMNS} FROM orbit_relations WHERE (?1 = 0 OR active = 1)
|
||||
AND (?2 IS NULL OR id IN (SELECT value FROM json_each(?2))) ORDER BY created_at DESC, version DESC"
|
||||
))?;
|
||||
let restriction = only.map(serde_json::to_string).transpose()?;
|
||||
let relations: Vec<Relation> = stmt.query_map(params![active_only, restriction], read_relation)?.collect::<rusqlite::Result<_>>()?;
|
||||
drop(stmt);
|
||||
let mut out = Vec::new();
|
||||
for relation in relations {
|
||||
let name = |sql: &str, id: &str| -> rusqlite::Result<String> {
|
||||
Ok(conn.query_row(sql, params![id], |r| r.get::<_, String>(0)).optional()?.unwrap_or_default())
|
||||
};
|
||||
let environment = |sql: &str, id: &str| -> rusqlite::Result<Option<String>> {
|
||||
conn.query_row(sql, params![id], |r| r.get::<_, String>(0)).optional()
|
||||
};
|
||||
let reason = unusable(&conn, &relation, now)?;
|
||||
out.push(RelationView {
|
||||
source_name: name("SELECT name FROM orbits WHERE id=?1", &relation.source_orbit_id)?,
|
||||
source_environment: environment("SELECT environment FROM orbit_environments WHERE orbit_id=?1", &relation.source_orbit_id)?,
|
||||
target_name: serde_json::from_str::<serde_json::Value>(
|
||||
&name("SELECT profile FROM restore_targets WHERE id=?1", &relation.target_id)?,
|
||||
).ok().and_then(|p| p["name"].as_str().map(str::to_string)).unwrap_or_default(),
|
||||
target_environment: environment("SELECT environment FROM target_environments WHERE target_id=?1", &relation.target_id)?,
|
||||
usable: reason.is_none(),
|
||||
unusable_reason: reason,
|
||||
relation,
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn environments(&self) -> Result<(std::collections::HashMap<String, String>, std::collections::HashMap<String, String>)> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let read = |sql: &str| -> rusqlite::Result<std::collections::HashMap<String, String>> {
|
||||
let mut stmt = conn.prepare(sql)?;
|
||||
let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
|
||||
rows.collect()
|
||||
};
|
||||
Ok((read("SELECT orbit_id, environment FROM orbit_environments")?, read("SELECT target_id, environment FROM target_environments")?))
|
||||
}
|
||||
|
||||
/// Every registered restore target, with whether its Outpost can be used right now.
|
||||
pub fn all_restore_targets(&self, now: i64) -> Result<Vec<(RestoreTarget, bool)>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare("SELECT profile FROM restore_targets ORDER BY id")?;
|
||||
let profiles: Vec<String> = stmt.query_map([], |r| r.get(0))?.collect::<rusqlite::Result<_>>()?;
|
||||
drop(stmt);
|
||||
let mut out = Vec::new();
|
||||
for profile in profiles {
|
||||
if let Ok(target) = serde_json::from_str::<RestoreTarget>(&profile) {
|
||||
let active = outpost_active(&conn, &target.outpost_id.to_string(), now)?;
|
||||
out.push((target, active));
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn restore_target(&self, id: Uuid) -> Result<Option<RestoreTarget>> {
|
||||
let profile: Option<String> = self.conn.lock().unwrap()
|
||||
.query_row("SELECT profile FROM restore_targets WHERE id=?1", params![id.to_string()], |r| r.get(0))
|
||||
.optional()?;
|
||||
Ok(profile.and_then(|p| serde_json::from_str(&p).ok()))
|
||||
}
|
||||
|
||||
// ---- 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>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let active: bool = conn.query_row("SELECT EXISTS(SELECT 1 FROM orbit_relations WHERE id=?1 AND active=1)", params![relation], |r| r.get(0))?;
|
||||
if !active {
|
||||
return Ok(None);
|
||||
}
|
||||
let id = Uuid::new_v4().to_string();
|
||||
let inserted = conn.execute(
|
||||
"INSERT OR IGNORE INTO relation_grants(id,principal_type,principal,relation_id,expires_at,created_by,created_at) VALUES (?1,?2,?3,?4,?5,?6,?7)",
|
||||
params![id, principal_type, principal, relation, expires_at, created_by, now],
|
||||
)?;
|
||||
Ok((inserted == 1).then(|| RelationGrant {
|
||||
id, principal_type: principal_type.into(), principal: principal.into(), relation_id: relation.into(), expires_at, created_by: created_by.into(), created_at: now,
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn delete_relation_grant(&self, relation: &str, grant: &str) -> Result<bool> {
|
||||
Ok(self.conn.lock().unwrap().execute("DELETE FROM relation_grants WHERE id=?1 AND relation_id=?2", params![grant, relation])? == 1)
|
||||
}
|
||||
|
||||
pub fn relation_grants(&self, relation: &str) -> Result<Vec<RelationGrant>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare("SELECT id,principal_type,principal,relation_id,expires_at,created_by,created_at FROM relation_grants WHERE relation_id=?1 ORDER BY principal_type, principal")?;
|
||||
let rows = stmt.query_map(params![relation], |r| Ok(RelationGrant {
|
||||
id: r.get(0)?, principal_type: r.get(1)?, principal: r.get(2)?, relation_id: r.get(3)?, expires_at: r.get(4)?, created_by: r.get(5)?, created_at: r.get(6)?,
|
||||
}))?;
|
||||
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||
}
|
||||
|
||||
/// Ids of the active relations this subject may use. Read live on every request.
|
||||
pub fn granted_relations(&self, user: Option<&str>, groups: &[String], now: i64) -> Result<Vec<String>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT DISTINCT g.relation_id FROM relation_grants g JOIN orbit_relations r ON r.id = g.relation_id AND r.active = 1
|
||||
WHERE (g.expires_at IS NULL OR g.expires_at > ?1)
|
||||
AND ((g.principal_type='user' AND g.principal=?2) OR (g.principal_type='group' AND g.principal IN (SELECT value FROM json_each(?3))))",
|
||||
)?;
|
||||
let groups_json = serde_json::to_string(groups)?;
|
||||
let rows = stmt.query_map(params![now, user, groups_json], |r| r.get::<_, String>(0))?.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
Ok(rows)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tessera_core::job::{CaptureFormat, CaptureProfile};
|
||||
use tessera_core::restore::{DatabaseIdentity, RestoreTarget};
|
||||
|
||||
struct Fixture {
|
||||
db: Db,
|
||||
orbit: Uuid,
|
||||
application: Uuid,
|
||||
outpost: Uuid,
|
||||
target: Uuid,
|
||||
_dir: tempfile::TempDir,
|
||||
}
|
||||
|
||||
fn now() -> i64 {
|
||||
chrono::Utc::now().timestamp()
|
||||
}
|
||||
|
||||
async fn orbit(db: &Db, name: &str) -> Uuid {
|
||||
let id = Uuid::new_v4();
|
||||
db.upsert_orbit(&OrbitRow {
|
||||
id, name: name.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();
|
||||
id
|
||||
}
|
||||
|
||||
fn profile(db: &Db, orbit: Uuid, outpost: Uuid, format: CaptureFormat) -> Uuid {
|
||||
let application = Uuid::new_v4();
|
||||
let profile = CaptureProfile { application_id: application, orbit_id: orbit, outpost_id: outpost, format, schedule: None, retention: None };
|
||||
assert!(db.register_capture_profile(&profile, now()).unwrap());
|
||||
application
|
||||
}
|
||||
|
||||
fn target(db: &Db, application: Uuid, outpost: Uuid, engine: Engine, instance: &str, name: &str) -> Uuid {
|
||||
let target = RestoreTarget {
|
||||
id: Uuid::new_v4(), application_id: application, outpost_id: outpost, name: name.into(), engine,
|
||||
identity: DatabaseIdentity { instance: instance.into(), database: "app".into() },
|
||||
};
|
||||
assert!(db.register_restore_target(&target).unwrap());
|
||||
target.id
|
||||
}
|
||||
|
||||
async fn fixture() -> Fixture {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let db = Db::connect(&dir.path().join("t.db")).await.unwrap();
|
||||
db.migrate().await.unwrap();
|
||||
let outpost = Uuid::new_v4();
|
||||
db.insert_test_credential("token", &outpost.to_string(), "agent");
|
||||
let orbit = orbit(&db, "prod-db").await;
|
||||
let application = profile(&db, orbit, outpost, CaptureFormat::PostgresCustom);
|
||||
let target = target(&db, application, outpost, Engine::Postgres, "111", "staging-db");
|
||||
db.set_orbit_environment(orbit, "production", now()).unwrap();
|
||||
db.set_target_environment(target, "staging", now()).unwrap();
|
||||
Fixture { db, orbit, application, outpost, target, _dir: dir }
|
||||
}
|
||||
|
||||
fn make(f: &Fixture) -> std::result::Result<Relation, Reject> {
|
||||
f.db.create_relation(f.orbit, f.target, None, false, true, "admin", now()).unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_valid_relation_is_created_in_one_direction_and_only_once() {
|
||||
let f = fixture().await;
|
||||
let relation = make(&f).unwrap();
|
||||
assert_eq!((relation.version, relation.active, relation.engine.as_str()), (1, true, "postgres"));
|
||||
assert_eq!(relation.target_identity["instance"], "111");
|
||||
assert_eq!(make(&f).err(), Some(Reject::Duplicate), "one active relation per source and target");
|
||||
// not symmetric: the target is not a source, and a production-labelled database can never be a target
|
||||
let reverse_source = orbit(&f.db, "staging-orbit").await;
|
||||
assert_eq!(f.db.create_relation(reverse_source, f.target, None, false, true, "admin", now()).unwrap().err(), Some(Reject::SourceNotManaged));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn every_rule_has_its_own_refusal() {
|
||||
let f = fixture().await;
|
||||
let now = now();
|
||||
let try_with = |source: Uuid, target: Uuid, clash: bool| f.db.create_relation(source, target, None, clash, true, "admin", now).unwrap().err();
|
||||
assert_eq!(try_with(Uuid::new_v4(), f.target, false), Some(Reject::UnknownSource));
|
||||
assert_eq!(try_with(f.orbit, Uuid::new_v4(), false), Some(Reject::UnknownTarget));
|
||||
assert_eq!(try_with(f.orbit, f.target, true), Some(Reject::TargetMatchesSource), "the target is a production database under another label");
|
||||
|
||||
// a source that is not managed, or whose format cannot be restored
|
||||
let plain = orbit(&f.db, "plain").await;
|
||||
assert_eq!(try_with(plain, f.target, false), Some(Reject::SourceNotManaged));
|
||||
let files = orbit(&f.db, "files").await;
|
||||
profile(&f.db, files, f.outpost, CaptureFormat::Filesystem);
|
||||
f.db.set_orbit_environment(files, "production", now).unwrap();
|
||||
assert_eq!(try_with(files, f.target, false), Some(Reject::SourceNotRestoreReady));
|
||||
|
||||
// environments are never assumed
|
||||
let unset = orbit(&f.db, "unset").await;
|
||||
let unset_app = profile(&f.db, unset, f.outpost, CaptureFormat::PostgresSql);
|
||||
let unset_target = target(&f.db, unset_app, f.outpost, Engine::Postgres, "222", "other");
|
||||
assert_eq!(try_with(unset, unset_target, false), Some(Reject::SourceEnvironmentUnset));
|
||||
f.db.set_orbit_environment(unset, "production", now).unwrap();
|
||||
assert_eq!(try_with(unset, unset_target, false), Some(Reject::TargetEnvironmentUnset), "an unlabelled target fails closed");
|
||||
f.db.set_target_environment(unset_target, "production", now).unwrap();
|
||||
assert_eq!(try_with(unset, unset_target, false), Some(Reject::TargetIsProduction));
|
||||
|
||||
// a target belongs to the application it was registered for, and the engines must agree
|
||||
let wrong_app = target(&f.db, unset_app, f.outpost, Engine::Postgres, "333", "for-another-app");
|
||||
f.db.set_target_environment(wrong_app, "staging", now).unwrap();
|
||||
assert_eq!(try_with(f.orbit, wrong_app, false), Some(Reject::ApplicationMismatch));
|
||||
let mysql = target(&f.db, f.application, f.outpost, Engine::Mysql, &Uuid::new_v4().to_string(), "mysql-staging");
|
||||
f.db.set_target_environment(mysql, "staging", now).unwrap();
|
||||
assert_eq!(try_with(f.orbit, mysql, false), Some(Reject::EngineMismatch));
|
||||
assert!(f.db.relation_views(false, None, now).unwrap().is_empty(), "no refused request stored anything");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_expired_or_revoked_outpost_is_refused() {
|
||||
let f = fixture().await;
|
||||
let far = now() + crate::db::credentials::lifetime_secs() + 10;
|
||||
assert_eq!(f.db.create_relation(f.orbit, f.target, None, false, true, "admin", far).unwrap().err(), Some(Reject::OutpostInactive), "credential expired");
|
||||
assert!(f.db.revoke_outpost(&f.outpost.to_string(), now()).unwrap());
|
||||
assert_eq!(make(&f).err(), Some(Reject::OutpostInactive), "credential revoked");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn retargeting_makes_a_new_version_and_grants_do_not_follow() {
|
||||
let f = fixture().await;
|
||||
let first = make(&f).unwrap();
|
||||
f.db.add_relation_grant("user", "qa-user", &first.id, None, "admin", now()).unwrap().unwrap();
|
||||
assert_eq!(f.db.granted_relations(Some("qa-user"), &[], now()).unwrap(), [first.id.clone()]);
|
||||
let other = target(&f.db, f.application, f.outpost, Engine::Postgres, "444", "second-staging");
|
||||
f.db.set_target_environment(other, "development", now()).unwrap();
|
||||
let second = f.db.create_relation(f.orbit, other, Some(&first.id), false, true, "admin", now()).unwrap().unwrap();
|
||||
assert_eq!((second.version, second.lineage.as_str()), (2, first.lineage.as_str()));
|
||||
assert_ne!(second.id, first.id);
|
||||
let old = f.db.relation(&first.id).unwrap().unwrap();
|
||||
assert_eq!((old.active, old.deactivated_reason.as_deref()), (false, Some("replaced")));
|
||||
assert!(f.db.granted_relations(Some("qa-user"), &[], now()).unwrap().is_empty(), "the new database starts with no access");
|
||||
assert!(f.db.add_relation_grant("user", "qa-user", &first.id, None, "admin", now()).unwrap().is_none(), "no grants on a deactivated relation");
|
||||
// retargeting something that is not an active relation of this source changes nothing
|
||||
assert!(f.db.create_relation(f.orbit, other, Some(&first.id), false, true, "admin", now()).unwrap().is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn relabelling_the_target_as_production_ends_its_relations_at_once() {
|
||||
let f = fixture().await;
|
||||
let relation = make(&f).unwrap();
|
||||
f.db.add_relation_grant("user", "qa-user", &relation.id, None, "admin", now()).unwrap().unwrap();
|
||||
assert!(f.db.relation_views(true, None, now()).unwrap()[0].usable);
|
||||
let ended = f.db.set_target_environment(f.target, "production", now()).unwrap().unwrap();
|
||||
assert_eq!(ended, [relation.id.clone()]);
|
||||
let stored = f.db.relation(&relation.id).unwrap().unwrap();
|
||||
assert_eq!((stored.active, stored.deactivated_reason.as_deref()), (false, Some("target_relabelled")));
|
||||
assert!(f.db.granted_relations(Some("qa-user"), &[], now()).unwrap().is_empty());
|
||||
assert_eq!(make(&f).err(), Some(Reject::TargetIsProduction));
|
||||
assert!(f.db.set_target_environment(Uuid::new_v4(), "staging", now()).unwrap().is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn revoking_an_outpost_ends_relations_through_it_and_a_lapsed_credential_makes_one_unusable() {
|
||||
let f = fixture().await;
|
||||
let relation = make(&f).unwrap();
|
||||
let view = &f.db.relation_views(true, None, now()).unwrap()[0];
|
||||
assert!(view.usable && view.source_name == "prod-db" && view.target_name == "staging-db");
|
||||
assert_eq!((view.source_environment.as_deref(), view.target_environment.as_deref()), (Some("production"), Some("staging")));
|
||||
// the credential simply expires: still "active" in the table, but not usable
|
||||
let late = now() + crate::db::credentials::lifetime_secs() + 10;
|
||||
let stale = &f.db.relation_views(true, None, late).unwrap()[0];
|
||||
assert_eq!((stale.usable, stale.unusable_reason), (false, Some("outpost_inactive")));
|
||||
assert!(f.db.revoke_outpost(&f.outpost.to_string(), now()).unwrap());
|
||||
let stored = f.db.relation(&relation.id).unwrap().unwrap();
|
||||
assert_eq!((stored.active, stored.deactivated_reason.as_deref()), (false, Some("outpost_revoked")));
|
||||
assert!(f.db.relation_views(true, None, now()).unwrap().is_empty());
|
||||
assert_eq!(f.db.relation_views(false, None, now()).unwrap()[0].unusable_reason, Some("deactivated"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn relation_grants_apply_to_people_and_groups_until_they_expire_or_are_removed() {
|
||||
let f = fixture().await;
|
||||
let relation = make(&f).unwrap();
|
||||
let user = f.db.add_relation_grant("user", "u1", &relation.id, Some(100), "admin", 10).unwrap().unwrap();
|
||||
f.db.add_relation_grant("group", "qa", &relation.id, None, "admin", 10).unwrap().unwrap();
|
||||
assert!(f.db.add_relation_grant("user", "u1", &relation.id, None, "admin", 10).unwrap().is_none(), "duplicate");
|
||||
assert_eq!(f.db.granted_relations(Some("u1"), &[], 99).unwrap().len(), 1);
|
||||
assert!(f.db.granted_relations(Some("u1"), &[], 100).unwrap().is_empty(), "expiry is exclusive");
|
||||
assert_eq!(f.db.granted_relations(Some("someone"), &["qa".to_string()], 100).unwrap().len(), 1, "group member");
|
||||
assert!(f.db.granted_relations(Some("someone"), &[], 100).unwrap().is_empty(), "a missing groups claim grants nothing");
|
||||
assert!(f.db.delete_relation_grant(&relation.id, &user.id).unwrap());
|
||||
assert!(!f.db.delete_relation_grant("other-relation", &user.id).unwrap(), "a grant is only removed through its own relation");
|
||||
assert_eq!(f.db.relation_grants(&relation.id).unwrap().len(), 1);
|
||||
let only = f.db.relation_views(true, Some(&["nope".to_string()]), now()).unwrap();
|
||||
assert!(only.is_empty(), "restricting to other ids returns nothing");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn migration_is_additive_and_repeatable() {
|
||||
let f = fixture().await;
|
||||
make(&f).unwrap();
|
||||
f.db.migrate().await.unwrap();
|
||||
f.db.migrate().await.unwrap();
|
||||
assert_eq!(f.db.relation_views(true, None, now()).unwrap().len(), 1, "existing data survives a re-run");
|
||||
}
|
||||
}
|
||||
@@ -319,3 +319,28 @@ The snapshot's recorded size is added to that margin; if a producer did not reco
|
||||
The audit log records `export.requested`, `export.ready` and then `export.finished` or `export.disconnected` for each
|
||||
download. "Finished" means the body was handed to the connection, not that a file reached the person's disk.
|
||||
|
||||
## Refresh relations (staging from production)
|
||||
|
||||
A *relation* says that one source orbit may overwrite one restore target (a staging or development database),
|
||||
in that direction only. Administrators set it up in the Relations console (or `/api/v1/relations`). Nothing is assumed:
|
||||
|
||||
1. Give each **source orbit** and each **restore target** an environment: `production`, `staging` or `development`.
|
||||
An orbit or target that is not labelled is never used. A target labelled `production` is refused.
|
||||
2. A source must be a managed Outpost database backup (a capture profile with a restorable PostgreSQL or MySQL format).
|
||||
Filesystem backups are not databases and cannot be a source.
|
||||
3. A target is registered for one application, so it can only be connected to that application's orbit, with the same engine.
|
||||
4. Connect them. The hub refuses a target whose database identity matches a database captured as production (or never
|
||||
classified) in any snapshot, which catches a production database labelled staging. A staging or development orbit that
|
||||
backs up the target itself does not count. If the source has no snapshot yet, the relation is created as *not yet
|
||||
compared* and the refresh checks again before it applies anything. Each refusal names the rule that stopped it.
|
||||
|
||||
Relations are versioned. Pointing one at another target creates a new relation (new id, next version) and ends the old one.
|
||||
Who may start a refresh is granted **per relation id** (`refresh.run`, to a person or an identity-provider group, with an
|
||||
optional end date), so a new version starts with nobody allowed. These grants are separate from orbit access and never
|
||||
include `orbit.read`, `snapshot.download` or `capture.run`. A person holding only a relation grant sees its name and
|
||||
environments and never where the database is (no identity, host, Outpost or application id).
|
||||
|
||||
A relation stops being usable at once when its target is relabelled `production`, when either Outpost on its path is
|
||||
revoked, or (when read) when an Outpost credential has expired. Existing administrator restores (`POST /restore-jobs`)
|
||||
are unchanged. Running the refresh itself comes with the next step; this step only prepares and guards it.
|
||||
|
||||
|
||||
@@ -29,6 +29,13 @@ admin/browser. Semua status/data job hanya di scope owner/admin yang berizin.
|
||||
| /api/v1/access/users/:id | PUT | human | access.manage | admin | tidak ada; menonaktifkan juga memutus semua sesi; tidak untuk diri sendiri/akun darurat |
|
||||
| /api/v1/access/users/:id/revoke-sessions | POST | human | access.manage | admin | tidak ada; semua sesi user berakhir |
|
||||
| /api/v1/me/preferences | GET,PUT | human | session.self | current account | pilihan tampilan sendiri (look: window atau radar); no-store; CSRF pada PUT; token/dev tanpa akun: GET kosong, PUT 404 |
|
||||
| /api/v1/orbits/:id/environment | PUT | human | orbit.manage | admin | tidak ada; menandai sumber (production/staging/development); diaudit |
|
||||
| /api/v1/restore-targets/:id/environment | PUT | human | relation.manage | admin | relasi aktif ke target yang diberi label production berakhir seketika; diaudit |
|
||||
| /api/v1/relations | GET,POST | human | relation.manage | admin | daftar relasi, orbit dan target untuk wizard (dengan identity); POST membuat relasi atau menyebut aturan yang menolak |
|
||||
| /api/v1/relations/:id | PUT,DELETE | human | relation.manage | admin | PUT = versi baru (id baru, grant tidak ikut); DELETE menonaktifkan; diaudit |
|
||||
| /api/v1/relations/:id/access | GET,POST | human | relation.manage | admin | grant refresh.run per relasi (user atau grup, expiry); diaudit |
|
||||
| /api/v1/relations/:id/access/:grant | DELETE | human | relation.manage | admin | berlaku pada request berikutnya; diaudit |
|
||||
| /api/v1/refresh-relations | GET | human | refresh.run | relasi yang di-grant | nama dan environment saja; tanpa identity, host, Outpost, application id; 403 bila tanpa grant |
|
||||
| /api/v1/operator/login | POST | public | — | emergency account | cookie opaque dan CSRF; limiter, no-store |
|
||||
| /api/v1/snapshots | GET | human | snapshot.read | orbit | metadata aman terfilter |
|
||||
| /api/v1/snapshots/:id | DELETE | human | snapshot.delete | snapshot→orbit | tidak ada; cek pin |
|
||||
|
||||
@@ -89,12 +89,17 @@ Hasil: `GET /snapshots/:id/download` mengirim arsip yang memang terkompresi, buk
|
||||
Bukti: `cargo test --workspace` hijau (hub 94 tes). Tes: tiap jenis snapshot dengan hasil dekompresi sama persis dengan byte asli, header, 24 MiB dialirkan dalam frame di bawah 256 KiB, audit dan pembersihan untuk unduhan selesai dan ditinggalkan, batas satu slot (ditolak seketika, slot kembali), disk tidak cukup (507), HEAD, pemanggil tanpa izin tidak memakai slot, sweep hanya menyentuh milik sendiri; tiga mutasi sengaja tertangkap (Content-Length pada gzip, PGDMP dikompres ganda, unduhan ditinggalkan tercatat selesai). Proses nyata dengan producer asli (orbit filesystem via restic): `.tar.gz`, `gunzip -t` ok, hasil ekstrak identik dengan file asli (termasuk 24 MiB acak); curl dibatasi lajunya lalu dibunuh di tengah: direktori ekspor hilang dan tercatat `export.disconnected`; stale dir dibersihkan saat restart tanpa menyentuh folder lain; HEAD 405. `cargo audit`/`deny` tidak berubah (async-compression 0.4.36, rustix 1.1.6, tanpa duplikat baru).
|
||||
Batas: snapshot yang tersimpan sebagai chunk vault dibaca utuh ke memori saat diekspor (hanya yang berbasis restic dan tahap kompresi yang terbatas); SQL asli dari PostgreSQL/MySQL baru diuji lewat fixture, rehearsal dengan database sungguhan ada di M6d; tidak ada checksum arsip hasil kompresi karena streaming; sisa `.tmp*` dari kode lama tidak disapu.
|
||||
|
||||
### M6b — Environment dan relasi production → staging (admin)
|
||||
Hasil: DevOps menyatakan "target staging X boleh ditimpa dari orbit production Y", dan QA dapat diberi hak memakainya.
|
||||
- Orbit punya `environment` (production/staging/development). Tabel `orbit_relations` berarah (sumber orbit managed → restore target), berversi, tidak simetris/transitif; sumber dan target tidak boleh alias identitas database yang sama; target production ditolak; Outpost sumber dan tujuan harus aktif; sumber harus capture profile managed yang restore-ready. Mengubah tujuan membuat versi baru dan menonaktifkan yang lama.
|
||||
- Hak baru: `relation.manage` (admin-only) dan `refresh.run` (dapat diberikan, scope = satu relasi). Scope grant bertambah dari global/orbit menjadi global/orbit/relasi; `refresh.run` tidak memberi `snapshot.download` atau `capture.run` bebas.
|
||||
- Wizard admin (UI) dan API; QA tidak melihat host/DSN.
|
||||
Selesai bila: tes aturan (relasi terbalik, target production, alias sumber, versi usang, Outpost nonaktif), matriks akses diperluas, migrasi aditif pada salinan DB.
|
||||
### M6b — Environment dan relasi production → staging (selesai di working tree, belum di-commit, 14 November 2026)
|
||||
Hasil: DevOps menyatakan "sumber X boleh menimpa target Y", dan hak memakainya bisa diberikan per relasi.
|
||||
- Environment (production/staging/development) di orbit sumber dan di restore target (bukan orbit placeholder, supaya staging tidak muncul di galaksi, scheduler, retensi, dan binding Outpost lama). Belum dilabeli = ditolak; target berlabel production ditolak.
|
||||
- `orbit_relations` berarah (sumber orbit managed ke restore target), berversi (retarget membuat id baru, versi berikutnya, yang lama `replaced`), tidak simetris/transitif, satu relasi aktif per pasangan (indeks unik parsial). Aturan dengan kode penolakan: sumber tidak dikenal atau belum dilabeli, bukan capture profile managed, format tidak restore-ready, target tidak dikenal atau belum dilabeli atau production, aplikasi target berbeda, engine berbeda, target cocok dengan database yang di-capture sebagai production/belum diklasifikasi (dibaca dari `source_identity` snapshot semua orbit; backup staging/development milik target sendiri tidak dihitung), Outpost tidak aktif, duplikat. Fakta yang ada di DB diperiksa ulang di dalam transaksi; sumber tanpa snapshot ditandai `verified=false` agar M6c memeriksa ulang sebelum apply.
|
||||
- Relasi mati di transaksi yang sama saat target di-relabel production atau Outpost dicabut, dan `usable` dihitung ulang saat dibaca (kredensial kedaluwarsa); diaudit.
|
||||
- Hak `refresh.run` per id relasi di tabel sendiri `relation_grants` (user atau grup, expiry), tanpa global dan tanpa ikut ke versi baru (fail-safe); `refresh.run` bukan permission `access_grants` sehingga `scoped` dan `visible` tidak pernah menerimanya; gerbang relasi sendiri (`gate::relation`, `visible_relations`).
|
||||
- API (admin, `relation.manage`): `/orbits/:id/environment`, `/restore-targets/:id/environment`, `/relations` (GET untuk wizard dengan identity, POST), `/relations/:id` (PUT retarget, DELETE), `/relations/:id/access` (+ `/:grant`). Orang dengan grant relasi hanya melihat `GET /refresh-relations`: nama dan environment, tanpa identity, host, Outpost, atau application id. `POST /restore-jobs` admin tidak diubah.
|
||||
- UI: konsol Relations (admin) dengan `Select` yang sama: label environment, form hubungkan sumber ke target (hanya target yang cocok ditawarkan), retarget, akhiri, dan siapa yang boleh refresh.
|
||||
Bukti: `cargo test --workspace` hijau (hub 106 tes; 12 tes baru: 9 store, 5 HTTP termasuk matriks yang diperluas dengan jenis `RelationList`, fixture relasi di dua orbit, dan pemanggil yang hanya punya grant relasi). Tes: setiap aturan punya penolakannya sendiri, arah, versi, grant tidak ikut retarget, relabel production dan revoke Outpost mematikan relasi seketika, kredensial kedaluwarsa membuatnya tidak usable, database production berlabel staging tertangkap lewat snapshot, grant per user dan grup dengan expiry, tampilan refresher tanpa identity/host. Empat mutasi sengaja tertangkap (daftar refresher menampilkan semua, retarget tanpa gerbang admin, target production diterima, relabel tidak mematikan relasi). Rehearsal browser dengan hub asli (data sintetis): label environment lewat Select, hanya sumber yang siap dan target yang cocok ditawarkan, relasi dibuat (version 1, "not yet compared"), grup diberi akses, retarget menjadi version 2 dengan akses kosong, relabel target production mengakhiri relasi dan UI menampilkan pemberitahuan.
|
||||
Catatan untuk M6d: pengguna yang hanya punya grant relasi belum dianggap `authorized` oleh status sesi dan vault UI memanggil `/orbits` dan `/snapshots` saat load (403); UI QA harus menangani itu (hitung grant relasi atau wajibkan viewer pada orbit sumber).
|
||||
Belum ada / batas: relasi belum menjalankan apa pun (M6c); sumber yang di-capture tidak di-cek terhadap target yang sama bila snapshot-nya belum ada (ditandai belum dibandingkan); pendaftaran restore target masih lewat Orbits console dan memerlukan Outpost aktif; ekstra: form login tanpa SSO tidak lagi menampilkan label "Details" dan memakai gaya field yang sama.
|
||||
|
||||
### M6c — Refresh run durable (backend)
|
||||
Hasil: satu permintaan "refresh staging" menjalankan capture baru lalu restore snapshot hasil capture itu, tanpa persetujuan DevOps per eksekusi.
|
||||
|
||||
@@ -7,8 +7,9 @@ import {
|
||||
} from "./api";
|
||||
import { OrbitInspector, OrbitRegister, TelemetryStrip } from "./components/hud/DiegeticHUD";
|
||||
import { HUDPanel } from "./components/hud/HUDPanel";
|
||||
import { accessItem, HUDRail, hudItems, type HUDMode } from "./components/hud/HUDRail";
|
||||
import { accessItem, HUDRail, hudItems, relationsItem, type HUDMode } from "./components/hud/HUDRail";
|
||||
import { AccessView } from "./components/access/AccessView";
|
||||
import { RelationsView } from "./components/relations/RelationsView";
|
||||
import { SearchIcon, VaultSearch } from "./components/hud/VaultSearch";
|
||||
import { OperatorGate, type Caps } from "./components/operator/OperatorGate";
|
||||
import { OrbitsView } from "./components/orbits/OrbitsView";
|
||||
@@ -35,6 +36,7 @@ const panelTitles: Record<HUDMode, string> = {
|
||||
wormhole: "Wormhole uplink",
|
||||
activity: "Activity",
|
||||
access: "Access",
|
||||
relations: "Refresh relations",
|
||||
reconstitute: "Restore snapshot",
|
||||
snapshot: "Snapshot detail",
|
||||
};
|
||||
@@ -44,10 +46,11 @@ const panelLabels: Record<HUDMode, string> = {
|
||||
wormhole: "Console 03 · Outposts",
|
||||
activity: "Console 04 · Activity",
|
||||
access: "Console 05 · Access",
|
||||
relations: "Console 06 · Relations",
|
||||
reconstitute: "Restore from a snapshot",
|
||||
snapshot: "Recovery point",
|
||||
};
|
||||
const panelWidths: Record<HUDMode, number> = { scene: 640, orbits: 1120, wormhole: 760, activity: 1120, access: 1120, reconstitute: 760, snapshot: 640 };
|
||||
const panelWidths: Record<HUDMode, number> = { scene: 640, orbits: 1120, wormhole: 760, activity: 1120, access: 1120, relations: 1120, reconstitute: 760, snapshot: 640 };
|
||||
|
||||
const LOOK_KEY = "tessera.look";
|
||||
|
||||
@@ -237,7 +240,7 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () =>
|
||||
const activity = useActivity(snaps.data, orbits.data, caps.admin);
|
||||
// Consoles a non-administrator never sees: managing orbits and Outposts, restores, and access.
|
||||
const railItems = useMemo(
|
||||
() => (caps.admin ? [...hudItems, accessItem] : hudItems.filter((item) => item.id === "scene" || item.id === "activity")),
|
||||
() => (caps.admin ? [...hudItems, relationsItem, accessItem] : hudItems.filter((item) => item.id === "scene" || item.id === "activity")),
|
||||
[caps.admin],
|
||||
);
|
||||
const failedCount = sceneOrbits.filter(({ last_status }) => last_status === "failed").length;
|
||||
@@ -429,6 +432,9 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () =>
|
||||
{mode === "wormhole" && caps.admin && (
|
||||
<SpringPane key="wormhole"><WormholeView pairing={pairing} onPaired={setPairing} /></SpringPane>
|
||||
)}
|
||||
{mode === "relations" && caps.admin && (
|
||||
<SpringPane key="relations"><RelationsView /></SpringPane>
|
||||
)}
|
||||
{mode === "access" && caps.admin && (
|
||||
<SpringPane key="access"><AccessView orbits={orbits.data ?? []} /></SpringPane>
|
||||
)}
|
||||
|
||||
@@ -75,6 +75,56 @@ export async function fetchMe(signal?: AbortSignal): Promise<Me> {
|
||||
return api<Me>("/api/v1/me", { signal });
|
||||
}
|
||||
|
||||
export type Environment = "production" | "staging" | "development";
|
||||
export type RelationView = {
|
||||
id: string;
|
||||
version: number;
|
||||
source_orbit_id: string;
|
||||
target_id: string;
|
||||
engine: string;
|
||||
verified: boolean;
|
||||
active: boolean;
|
||||
deactivated_reason: string | null;
|
||||
source_name: string;
|
||||
source_environment: Environment | null;
|
||||
target_name: string;
|
||||
target_environment: Environment | null;
|
||||
usable: boolean;
|
||||
unusable_reason: string | null;
|
||||
};
|
||||
export type OrbitSetup = {
|
||||
id: string; name: string; environment: Environment | null; application_id: string | null;
|
||||
engine: string | null; ready: boolean; reason: string | null;
|
||||
};
|
||||
export type TargetSetup = {
|
||||
id: string; name: string; engine: string; identity: { instance: string; database: string };
|
||||
application_id: string; environment: Environment | null; outpost_active: boolean;
|
||||
};
|
||||
export type RelationOverview = { relations: RelationView[]; orbits: OrbitSetup[]; targets: TargetSetup[] };
|
||||
export type RelationGrant = { id: string; principal_type: "user" | "group"; principal: string; expires_at: number | null; created_at: number };
|
||||
|
||||
/** The rule a refused relation request names (`{"reason": "..."}`), if the error carries one. */
|
||||
export function refusalReason(error: unknown): string | undefined {
|
||||
try {
|
||||
return JSON.parse((error as Error).message).reason;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
const json = (method: string, body: unknown) => ({ method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
|
||||
export const fetchRelations = () => api<RelationOverview>("/api/v1/relations");
|
||||
export const setOrbitEnvironment = (id: string, environment: Environment) => api<void>(`/api/v1/orbits/${id}/environment`, json("PUT", { environment }));
|
||||
export const setTargetEnvironment = (id: string, environment: Environment) =>
|
||||
api<{ ended_relations: string[] }>(`/api/v1/restore-targets/${id}/environment`, json("PUT", { environment }));
|
||||
export const createRelation = (source_orbit_id: string, target_id: string) => api<RelationView>("/api/v1/relations", json("POST", { source_orbit_id, target_id }));
|
||||
export const retargetRelation = (id: string, target_id: string) => api<RelationView>(`/api/v1/relations/${id}`, json("PUT", { target_id }));
|
||||
export const endRelation = (id: string) => api<void>(`/api/v1/relations/${id}`, { method: "DELETE" });
|
||||
export const fetchRelationAccess = (id: string) => api<RelationGrant[]>(`/api/v1/relations/${id}/access`);
|
||||
export const grantRelationAccess = (id: string, grant: { principal_type: "user" | "group"; principal: string; expires_at?: string }) =>
|
||||
api<RelationGrant>(`/api/v1/relations/${id}/access`, json("POST", grant));
|
||||
export const revokeRelationAccess = (id: string, grant: string) => api<void>(`/api/v1/relations/${id}/access/${grant}`, { method: "DELETE" });
|
||||
|
||||
export type Look = "window" | "radar";
|
||||
|
||||
/** The account's saved display choices. A hub without this endpoint, or an account without one, yields `{}`. */
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useCallback, useId, useLayoutEffect, useRef, type PointerEvent } from "
|
||||
import { useScreenTransition } from "../../hooks/useScreenTransition";
|
||||
import { uiSpring } from "../../lib/motion";
|
||||
|
||||
export type HUDMode = "scene" | "orbits" | "wormhole" | "activity" | "access" | "reconstitute" | "snapshot";
|
||||
export type HUDMode = "scene" | "orbits" | "wormhole" | "activity" | "access" | "relations" | "reconstitute" | "snapshot";
|
||||
|
||||
export const hudItems = [
|
||||
{ id: "scene", label: "Vault", icon: "M4 9l8-4 8 4v6l-8 4-8-4z M4 9l8 4 8-4 M12 13v6" },
|
||||
@@ -20,6 +20,12 @@ export const accessItem: HUDItem = {
|
||||
icon: "M12 3l7 3v5c0 4.5-3 8-7 10-4-2-7-5.5-7-10V6z M9.5 12l2 2 3.5-4",
|
||||
};
|
||||
|
||||
/** Only for administrators: which source may overwrite which target. */
|
||||
export const relationsItem: HUDItem = {
|
||||
id: "relations", label: "Relations",
|
||||
icon: "M6 6.5a2.5 2.5 0 1 0 0 .01z M18 17.5a2.5 2.5 0 1 0 0 .01z M8.5 6.5h5a4 4 0 0 1 4 4v4.5 M15 13l2.5 2.5L20 13",
|
||||
};
|
||||
|
||||
type Slot = { center: number; width: number };
|
||||
type Gesture = { pointer: number; x: number; y: number; origin?: number };
|
||||
|
||||
|
||||
@@ -124,22 +124,34 @@ export function OperatorGate({
|
||||
</a>
|
||||
)}
|
||||
{session.data.login_enabled && (
|
||||
<details open={!session.data.oidc_enabled} className="group">
|
||||
{session.data.oidc_enabled && (
|
||||
session.data.oidc_enabled ? (
|
||||
<details className="group">
|
||||
<summary className="cursor-pointer text-sm text-star-300">Emergency operator sign-in</summary>
|
||||
)}
|
||||
<form onSubmit={submit} className="mt-3 space-y-4">
|
||||
<form onSubmit={submit} className="mt-3 space-y-4">
|
||||
<label className="block text-sm text-star-300">
|
||||
Operator password
|
||||
<input type="password" name="password" autoComplete="current-password" required
|
||||
maxLength={1024} className="mt-1 block w-full rounded-xl border border-space-700 bg-space-950 px-3 py-2 text-star-100" />
|
||||
maxLength={1024} className="field" />
|
||||
</label>
|
||||
{error && <p role="alert" className="text-sm text-orbit-red">{error}</p>}
|
||||
<Button type="submit" variant="primary" className="w-full" disabled={pending}>
|
||||
{pending ? "Signing in…" : "Sign in"}
|
||||
</Button>
|
||||
</form>
|
||||
</details>
|
||||
</details>
|
||||
) : (
|
||||
<form onSubmit={submit} className="mt-3 space-y-4">
|
||||
<label className="block text-sm text-star-300">
|
||||
Operator password
|
||||
<input type="password" name="password" autoComplete="current-password" required
|
||||
maxLength={1024} className="field" />
|
||||
</label>
|
||||
{error && <p role="alert" className="text-sm text-orbit-red">{error}</p>}
|
||||
<Button type="submit" variant="primary" className="w-full" disabled={pending}>
|
||||
{pending ? "Signing in…" : "Sign in"}
|
||||
</Button>
|
||||
</form>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
) : <p className="mt-4 text-star-300">Browser sign-in is disabled on this hub.</p>}
|
||||
|
||||
290
web/src/components/relations/RelationsView.tsx
Normal file
290
web/src/components/relations/RelationsView.tsx
Normal file
@@ -0,0 +1,290 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
createRelation, endRelation, fetchAccessUsers, fetchRelationAccess, fetchRelations, grantRelationAccess, refusalReason,
|
||||
retargetRelation, revokeRelationAccess, setOrbitEnvironment, setTargetEnvironment,
|
||||
type AccessUser, type Environment, type OrbitSetup, type RelationOverview, type RelationView, type TargetSetup,
|
||||
} from "../../api";
|
||||
import { Button } from "../ui/Button";
|
||||
import { Select } from "../ui/Select";
|
||||
|
||||
const ENVIRONMENTS: Environment[] = ["production", "staging", "development"];
|
||||
|
||||
const REFUSALS: Record<string, string> = {
|
||||
unknown_source: "That source orbit no longer exists.",
|
||||
unknown_target: "That target no longer exists.",
|
||||
source_environment_unset: "Set the source orbit's environment first.",
|
||||
source_not_managed: "The source is not a managed Outpost backup; only managed capture profiles can be refreshed from.",
|
||||
source_not_restore_ready: "The source's backup format cannot be restored (filesystem backups are not databases).",
|
||||
target_environment_unset: "Set the target's environment first. An unlabelled target is never used.",
|
||||
target_is_production: "A production database can never be overwritten.",
|
||||
application_mismatch: "That target was registered for a different application.",
|
||||
engine_mismatch: "The target uses a different database engine than the source.",
|
||||
target_matches_a_production_source: "The target looks like a database that is backed up as production. Check its environment and identity.",
|
||||
outpost_inactive: "An Outpost on this path is no longer paired or its token has expired.",
|
||||
relation_exists: "That relation already exists.",
|
||||
};
|
||||
|
||||
const ENDED: Record<string, string> = {
|
||||
deactivated_by_admin: "ended by an administrator",
|
||||
replaced: "replaced by a newer version",
|
||||
target_relabelled: "target was relabelled",
|
||||
outpost_revoked: "an Outpost was revoked",
|
||||
deactivated: "ended",
|
||||
target_environment: "target environment changed",
|
||||
outpost_inactive: "an Outpost is not available",
|
||||
};
|
||||
|
||||
const reasonText = (error: unknown) => REFUSALS[refusalReason(error) ?? ""] ?? "That change was refused.";
|
||||
const notSet = "Not set";
|
||||
const label = (value: string | null) => (value ? value : notSet);
|
||||
|
||||
/** Which source may overwrite which target, and who may start it. Administrators only. */
|
||||
export function RelationsView() {
|
||||
const qc = useQueryClient();
|
||||
const overview = useQuery({ queryKey: ["relations"], queryFn: fetchRelations, refetchInterval: 10_000 });
|
||||
const data: RelationOverview | undefined =
|
||||
overview.data && Array.isArray(overview.data.relations) && Array.isArray(overview.data.orbits) && Array.isArray(overview.data.targets)
|
||||
? overview.data : undefined;
|
||||
const refresh = () => void qc.invalidateQueries({ queryKey: ["relations"] });
|
||||
const orbitEnv = useMutation({ mutationFn: (v: { id: string; environment: Environment }) => setOrbitEnvironment(v.id, v.environment), onSuccess: refresh });
|
||||
const targetEnv = useMutation({ mutationFn: (v: { id: string; environment: Environment }) => setTargetEnvironment(v.id, v.environment), onSuccess: refresh });
|
||||
const create = useMutation({ mutationFn: (v: { source: string; target: string }) => createRelation(v.source, v.target), onSuccess: refresh });
|
||||
const end = useMutation({ mutationFn: endRelation, onSuccess: refresh });
|
||||
const [source, setSource] = useState("");
|
||||
|
||||
if (overview.isPending) return <p role="status" className="p-6 text-star-300">Loading…</p>;
|
||||
if (overview.isError || !data) {
|
||||
return <p role="alert" className="p-6 text-star-300">Could not load relations. This hub may not support them.</p>;
|
||||
}
|
||||
|
||||
const sources = data.orbits.filter((o) => o.ready);
|
||||
const chosen = data.orbits.find((o) => o.id === source);
|
||||
const targetsFor = (orbit?: OrbitSetup) =>
|
||||
data.targets.filter((t) => t.environment === "staging" || t.environment === "development")
|
||||
.filter((t) => !orbit || (t.application_id === orbit.application_id && t.engine === orbit.engine));
|
||||
const active = data.relations.filter((r) => r.active);
|
||||
const ended = data.relations.filter((r) => !r.active).slice(0, 8);
|
||||
|
||||
function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
const form = new FormData(event.currentTarget);
|
||||
create.mutate({ source: String(form.get("source") ?? ""), target: String(form.get("target") ?? "") });
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-10 p-6">
|
||||
<section aria-labelledby="rel-intro">
|
||||
<h3 id="rel-intro" className="text-lg font-semibold text-star-100">What a relation is</h3>
|
||||
<p className="mt-1 text-sm text-star-300">
|
||||
A relation says that one source orbit may overwrite one staging or development database, in that direction only.
|
||||
Nothing is assumed: label each source and target below, then connect them. A production database can never be a target.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section aria-labelledby="rel-env">
|
||||
<h3 id="rel-env" className="text-lg font-semibold text-star-100">Environments</h3>
|
||||
<div className="mt-3 grid gap-6 lg:grid-cols-2">
|
||||
<div className="overflow-x-auto">
|
||||
<h4 className="text-sm font-medium text-star-200">Source orbits</h4>
|
||||
<table className="mt-2 w-full text-left text-sm">
|
||||
<thead className="text-star-300"><tr><th className="py-2 pr-3">Orbit</th><th className="pr-3">Environment</th><th>Can be a source</th></tr></thead>
|
||||
<tbody>
|
||||
{data.orbits.map((o) => (
|
||||
<tr key={o.id} className="border-t border-space-700 text-star-100">
|
||||
<td className="py-2 pr-3">{o.name}</td>
|
||||
<td className="pr-3" style={{ minWidth: 160 }}>
|
||||
<Select aria-label={`Environment of ${o.name}`} value={o.environment ?? ""} onChange={(e) => orbitEnv.mutate({ id: o.id, environment: e.target.value as Environment })}>
|
||||
<option value="" disabled>{notSet}</option>
|
||||
{ENVIRONMENTS.map((env) => <option key={env} value={env}>{env}</option>)}
|
||||
</Select>
|
||||
</td>
|
||||
<td className="text-star-300">{o.ready ? `Yes (${o.engine})` : o.reason === "not_managed" ? "No: not a managed Outpost backup" : o.reason === "not_restore_ready" ? "No: format cannot be restored" : "Set the environment"}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div className="overflow-x-auto">
|
||||
<h4 className="text-sm font-medium text-star-200">Restore targets</h4>
|
||||
{data.targets.length === 0 ? <p className="mt-2 text-sm text-star-300">No restore targets are registered yet. Register one from the Orbits console.</p> : (
|
||||
<table className="mt-2 w-full text-left text-sm">
|
||||
<thead className="text-star-300"><tr><th className="py-2 pr-3">Target</th><th className="pr-3">Database</th><th className="pr-3">Environment</th><th>Outpost</th></tr></thead>
|
||||
<tbody>
|
||||
{data.targets.map((t: TargetSetup) => (
|
||||
<tr key={t.id} className="border-t border-space-700 text-star-100">
|
||||
<td className="py-2 pr-3">{t.name}</td>
|
||||
<td className="pr-3 text-star-300">{t.engine} · {t.identity.database}</td>
|
||||
<td className="pr-3" style={{ minWidth: 160 }}>
|
||||
<Select aria-label={`Environment of ${t.name}`} value={t.environment ?? ""} onChange={(e) => targetEnv.mutate({ id: t.id, environment: e.target.value as Environment })}>
|
||||
<option value="" disabled>{notSet}</option>
|
||||
{ENVIRONMENTS.map((env) => <option key={env} value={env}>{env}</option>)}
|
||||
</Select>
|
||||
</td>
|
||||
<td className="text-star-300">{t.outpost_active ? "Paired" : "Not available"}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{targetEnv.data && targetEnv.data.ended_relations.length > 0 && (
|
||||
<p role="status" className="mt-3 text-sm text-orbit-red">Relabelling that target ended {targetEnv.data.ended_relations.length} relation(s) into it.</p>
|
||||
)}
|
||||
{(orbitEnv.isError || targetEnv.isError) && <p role="alert" className="mt-3 text-sm text-orbit-red">That change was refused.</p>}
|
||||
</section>
|
||||
|
||||
<section aria-labelledby="rel-new">
|
||||
<h3 id="rel-new" className="text-lg font-semibold text-star-100">Connect a source to a target</h3>
|
||||
{sources.length === 0 ? (
|
||||
<p className="mt-2 text-sm text-star-300">No orbit can be a source yet. A source must be a managed Outpost database backup with an environment.</p>
|
||||
) : (
|
||||
<form onSubmit={submit} className="mt-3 grid gap-4 sm:grid-cols-2">
|
||||
<label className="text-sm text-star-300">
|
||||
Source orbit
|
||||
<Select name="source" required value={source} onChange={(e) => setSource(e.target.value)}>
|
||||
<option value="" disabled>Choose…</option>
|
||||
{sources.map((o) => <option key={o.id} value={o.id}>{o.name} ({o.environment})</option>)}
|
||||
</Select>
|
||||
</label>
|
||||
<label className="text-sm text-star-300">
|
||||
Target database
|
||||
<Select name="target" required key={source}>
|
||||
<option value="" disabled>{chosen ? "Choose…" : "Pick a source first"}</option>
|
||||
{targetsFor(chosen).map((t) => <option key={t.id} value={t.id}>{t.name} ({t.environment})</option>)}
|
||||
</Select>
|
||||
</label>
|
||||
<div className="sm:col-span-2 flex items-center gap-4">
|
||||
<Button type="submit" variant="primary" disabled={create.isPending}>{create.isPending ? "Connecting…" : "Create relation"}</Button>
|
||||
<p className="text-xs text-star-300">Only staging and development targets registered for the same application and engine are offered.</p>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
{create.isError && <p role="alert" className="mt-3 text-sm text-orbit-red">{reasonText(create.error)}</p>}
|
||||
{create.isSuccess && !create.data.verified && (
|
||||
<p role="status" className="mt-3 text-sm text-star-300">Created. The source has no backup yet, so the target could not be compared with it; that check repeats before a refresh runs.</p>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section aria-labelledby="rel-list">
|
||||
<h3 id="rel-list" className="text-lg font-semibold text-star-100">Relations</h3>
|
||||
{active.length === 0 ? <p className="mt-2 text-sm text-star-300">No active relations.</p> : (
|
||||
<div className="mt-3 space-y-4">
|
||||
{active.map((relation) => (
|
||||
<RelationCard key={relation.id} relation={relation} targets={targetsFor({ id: relation.source_orbit_id, name: relation.source_name, application_id: data.targets.find((t) => t.id === relation.target_id)?.application_id ?? null, engine: relation.engine, environment: relation.source_environment, ready: true, reason: null })}
|
||||
onEnd={() => end.mutate(relation.id)} ending={end.isPending} onChanged={refresh} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{ended.length > 0 && (
|
||||
<details className="mt-4 text-sm text-star-300">
|
||||
<summary className="cursor-pointer">Ended relations</summary>
|
||||
<ul className="mt-2 space-y-1">
|
||||
{ended.map((r) => <li key={r.id}>{r.source_name} → {r.target_name} (version {r.version}): {ENDED[r.deactivated_reason ?? ""] ?? "ended"}</li>)}
|
||||
</ul>
|
||||
</details>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RelationCard({ relation, targets, onEnd, ending, onChanged }: {
|
||||
relation: RelationView; targets: TargetSetup[]; onEnd: () => void; ending: boolean; onChanged: () => void;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const retarget = useMutation({ mutationFn: (target: string) => retargetRelation(relation.id, target), onSuccess: onChanged });
|
||||
const others = targets.filter((t) => t.id !== relation.target_id);
|
||||
return (
|
||||
<div className="rounded-xl border border-space-700 p-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<p className="text-star-100">
|
||||
<strong>{relation.source_name}</strong> <span className="text-star-300">({label(relation.source_environment)})</span>
|
||||
<span aria-hidden="true"> → </span><span className="sr-only"> may overwrite </span>
|
||||
<strong>{relation.target_name}</strong> <span className="text-star-300">({label(relation.target_environment)})</span>
|
||||
</p>
|
||||
<p className="text-sm text-star-300">
|
||||
Version {relation.version} · {relation.usable ? "Ready" : `Not usable: ${ENDED[relation.unusable_reason ?? ""] ?? "unavailable"}`}
|
||||
{!relation.verified && " · not yet compared with the source"}
|
||||
</p>
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap items-end gap-3">
|
||||
{others.length > 0 && (
|
||||
<form className="flex items-end gap-2" onSubmit={(e) => { e.preventDefault(); const t = String(new FormData(e.currentTarget).get("target") ?? ""); if (t) retarget.mutate(t); }}>
|
||||
<label className="text-sm text-star-300">
|
||||
Point at another target
|
||||
<Select name="target" key={relation.id}>
|
||||
<option value="" disabled>Choose…</option>
|
||||
{others.map((t) => <option key={t.id} value={t.id}>{t.name}</option>)}
|
||||
</Select>
|
||||
</label>
|
||||
<Button type="submit" disabled={retarget.isPending}>Retarget</Button>
|
||||
</form>
|
||||
)}
|
||||
<Button disabled={ending} onClick={onEnd}>End relation</Button>
|
||||
</div>
|
||||
{retarget.isError && <p role="alert" className="mt-2 text-sm text-orbit-red">{reasonText(retarget.error)}</p>}
|
||||
{retarget.isSuccess && <p role="status" className="mt-2 text-sm text-star-300">A new version was created. It starts with nobody allowed to use it; grant access again.</p>}
|
||||
<RelationAccess relationId={relation.id} onChange={() => void qc.invalidateQueries({ queryKey: ["relation-access", relation.id] })} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Who may start a refresh through this one relation. Access never carries over to a new version. */
|
||||
function RelationAccess({ relationId, onChange }: { relationId: string; onChange: () => void }) {
|
||||
const qc = useQueryClient();
|
||||
const grants = useQuery({ queryKey: ["relation-access", relationId], queryFn: () => fetchRelationAccess(relationId) });
|
||||
const users = useQuery({ queryKey: ["access-users"], queryFn: fetchAccessUsers });
|
||||
const [kind, setKind] = useState<"user" | "group">("user");
|
||||
const list = Array.isArray(grants.data) ? grants.data : [];
|
||||
const people: AccessUser[] = Array.isArray(users.data) ? users.data : [];
|
||||
const nameOf = (id: string) => people.find((u) => u.id === id)?.display_name ?? id;
|
||||
const refresh = () => { onChange(); void qc.invalidateQueries({ queryKey: ["relation-access", relationId] }); };
|
||||
const add = useMutation({ mutationFn: (v: { principal_type: "user" | "group"; principal: string }) => grantRelationAccess(relationId, v), onSuccess: refresh });
|
||||
const remove = useMutation({ mutationFn: (grant: string) => revokeRelationAccess(relationId, grant), onSuccess: refresh });
|
||||
return (
|
||||
<div className="mt-4 border-t border-space-700 pt-3">
|
||||
<h5 className="text-sm font-medium text-star-200">Who may refresh through this relation</h5>
|
||||
{list.length === 0 ? <p className="mt-1 text-sm text-star-300">Nobody yet.</p> : (
|
||||
<ul className="mt-1 space-y-1 text-sm text-star-100">
|
||||
{list.map((g) => (
|
||||
<li key={g.id} className="flex items-center justify-between gap-3">
|
||||
<span>{g.principal_type === "group" ? `Group ${g.principal}` : nameOf(g.principal)}</span>
|
||||
<Button disabled={remove.isPending} onClick={() => remove.mutate(g.id)} aria-label={`Remove access for ${g.principal_type === "group" ? g.principal : nameOf(g.principal)}`}>Remove</Button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<form className="mt-3 flex flex-wrap items-end gap-2" onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const principal = String(new FormData(e.currentTarget).get("principal") ?? "").trim();
|
||||
if (principal) add.mutate({ principal_type: kind, principal });
|
||||
}}>
|
||||
<label className="text-sm text-star-300">
|
||||
Add
|
||||
<Select value={kind} onChange={(e) => setKind(e.target.value as "user" | "group")}>
|
||||
<option value="user">A person</option>
|
||||
<option value="group">A group</option>
|
||||
</Select>
|
||||
</label>
|
||||
{kind === "user" ? (
|
||||
<label className="text-sm text-star-300">
|
||||
Person
|
||||
<Select name="principal" key="user">
|
||||
<option value="" disabled>Choose…</option>
|
||||
{people.filter((u) => !u.is_emergency && u.active).map((u) => <option key={u.id} value={u.id}>{u.display_name}</option>)}
|
||||
</Select>
|
||||
</label>
|
||||
) : (
|
||||
<label className="text-sm text-star-300">
|
||||
Group name
|
||||
<input name="principal" required maxLength={128} className="field" autoComplete="off" />
|
||||
</label>
|
||||
)}
|
||||
<Button type="submit" disabled={add.isPending}>Allow</Button>
|
||||
</form>
|
||||
{add.isError && <p role="alert" className="mt-2 text-sm text-orbit-red">Could not add that. It may already be allowed.</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user