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

View File

@@ -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,

View File

@@ -3,6 +3,7 @@ mod catalog;
mod gate;
mod jobs;
mod oidc;
mod relations;
mod orbit;
mod restore;
mod routes;

View 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)))
}

View File

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