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

View File

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

View File

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

View File

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

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