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:
2026-11-14 17:46:08 +07:00
parent e72b72111d
commit 5c4e0bf4a9
17 changed files with 1776 additions and 24 deletions

View File

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