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:
413
crates/tessera-hub/src/api/relations.rs
Normal file
413
crates/tessera-hub/src/api/relations.rs
Normal file
@@ -0,0 +1,413 @@
|
||||
//! Environments, relations and who may use them.
|
||||
//!
|
||||
//! Administrators configure everything here. The one endpoint a refresher sees is
|
||||
//! `GET /api/v1/refresh-relations`, which lists only the relations they hold a grant on and
|
||||
//! never shows where the database is (no identity, host, Outpost or application id).
|
||||
use super::routes::{admin_read, admin_write, authenticate};
|
||||
use crate::auth::{AuditAction, AuditOutcome, AuditResource};
|
||||
use crate::db::relations::{Reject, ENVIRONMENTS};
|
||||
use crate::state::HubState;
|
||||
use axum::{
|
||||
extract::{ConnectInfo, Path, State},
|
||||
http::{header, HeaderMap, HeaderValue, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
routing::{get, put},
|
||||
Json, Router,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::net::SocketAddr;
|
||||
use tessera_core::restore::{DatabaseIdentity, Engine};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub(super) fn routes() -> Router<HubState> {
|
||||
Router::new()
|
||||
.route("/api/v1/orbits/:id/environment", put(set_orbit_environment))
|
||||
.route("/api/v1/restore-targets/:id/environment", put(set_target_environment))
|
||||
.route("/api/v1/relations", get(list).post(create))
|
||||
.route("/api/v1/relations/:id", put(retarget).delete(deactivate))
|
||||
.route("/api/v1/relations/:id/access", get(list_access).post(grant_access))
|
||||
.route("/api/v1/relations/:id/access/:grant", axum::routing::delete(revoke_access))
|
||||
.route("/api/v1/refresh-relations", get(mine))
|
||||
}
|
||||
|
||||
fn now() -> i64 {
|
||||
chrono::Utc::now().timestamp()
|
||||
}
|
||||
|
||||
fn no_store() -> HeaderMap {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
|
||||
headers
|
||||
}
|
||||
|
||||
fn internal(error: impl std::fmt::Display) -> StatusCode {
|
||||
tracing::error!("relations: {error:#}");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
}
|
||||
|
||||
/// A refused request names the rule that refused it, so an administrator can fix the setup.
|
||||
fn refused(reject: Reject) -> Response {
|
||||
let status = match reject {
|
||||
Reject::UnknownSource | Reject::UnknownTarget => StatusCode::NOT_FOUND,
|
||||
Reject::Duplicate => StatusCode::CONFLICT,
|
||||
_ => StatusCode::UNPROCESSABLE_ENTITY,
|
||||
};
|
||||
(status, Json(serde_json::json!({ "reason": reject.code() }))).into_response()
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct SetEnvironment {
|
||||
environment: String,
|
||||
}
|
||||
|
||||
fn valid_environment(value: &str) -> bool {
|
||||
ENVIRONMENTS.contains(&value)
|
||||
}
|
||||
|
||||
async fn set_orbit_environment(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(body): Json<SetEnvironment>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
let actor = admin_write(&state, peer, &headers)?;
|
||||
if !valid_environment(&body.environment) {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
if !state.db.set_orbit_environment(id, &body.environment, now()).map_err(internal)? {
|
||||
return Err(StatusCode::NOT_FOUND);
|
||||
}
|
||||
state.db.audit_event(&actor.principal, AuditAction::EnvironmentSet, AuditResource::Orbit(id), AuditOutcome::Succeeded, actor.request_id).map_err(internal)?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct EnvironmentChange {
|
||||
/// Relations that stopped working because of this change.
|
||||
ended_relations: Vec<String>,
|
||||
}
|
||||
|
||||
async fn set_target_environment(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(body): Json<SetEnvironment>,
|
||||
) -> Result<Json<EnvironmentChange>, StatusCode> {
|
||||
let actor = admin_write(&state, peer, &headers)?;
|
||||
if !valid_environment(&body.environment) {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
let ended = state.db.set_target_environment(id, &body.environment, now()).map_err(internal)?.ok_or(StatusCode::NOT_FOUND)?;
|
||||
state.db.audit_event(&actor.principal, AuditAction::EnvironmentSet, AuditResource::RestoreTarget(id), AuditOutcome::Succeeded, actor.request_id).map_err(internal)?;
|
||||
for relation in &ended {
|
||||
if let Ok(relation) = Uuid::parse_str(relation) {
|
||||
state.db.audit_event(&actor.principal, AuditAction::RelationDeactivate, AuditResource::Relation(relation), AuditOutcome::Succeeded, actor.request_id).map_err(internal)?;
|
||||
}
|
||||
}
|
||||
Ok(Json(EnvironmentChange { ended_relations: ended }))
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct OrbitSetup {
|
||||
id: String,
|
||||
name: String,
|
||||
environment: Option<String>,
|
||||
application_id: Option<String>,
|
||||
engine: Option<&'static str>,
|
||||
/// Can this orbit be the source of a relation, and if not, why not.
|
||||
ready: bool,
|
||||
reason: Option<&'static str>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct TargetSetup {
|
||||
id: String,
|
||||
name: String,
|
||||
engine: &'static str,
|
||||
identity: DatabaseIdentity,
|
||||
application_id: String,
|
||||
environment: Option<String>,
|
||||
outpost_active: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Overview {
|
||||
relations: Vec<crate::db::relations::RelationView>,
|
||||
orbits: Vec<OrbitSetup>,
|
||||
targets: Vec<TargetSetup>,
|
||||
}
|
||||
|
||||
fn engine_name(engine: Engine) -> &'static str {
|
||||
match engine {
|
||||
Engine::Postgres => "postgres",
|
||||
Engine::Mysql => "mysql",
|
||||
}
|
||||
}
|
||||
|
||||
async fn list(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<(HeaderMap, Json<Overview>), StatusCode> {
|
||||
admin_read(&state, peer, &headers)?;
|
||||
let (orbit_env, target_env) = state.db.environments().map_err(internal)?;
|
||||
let profiles: std::collections::HashMap<_, _> =
|
||||
state.db.capture_profiles().map_err(internal)?.into_iter().map(|p| (p.orbit_id, p)).collect();
|
||||
let orbits = state
|
||||
.db
|
||||
.list_orbits()
|
||||
.await
|
||||
.map_err(internal)?
|
||||
.into_iter()
|
||||
.map(|orbit| {
|
||||
let profile = profiles.get(&orbit.id);
|
||||
let engine = profile.and_then(|p| p.format.engine());
|
||||
let environment = orbit_env.get(&orbit.id.to_string()).cloned();
|
||||
let reason = if profile.is_none() {
|
||||
Some("not_managed")
|
||||
} else if engine.is_none() {
|
||||
Some("not_restore_ready")
|
||||
} else if environment.is_none() {
|
||||
Some("environment_unset")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
OrbitSetup {
|
||||
id: orbit.id.to_string(),
|
||||
name: orbit.name,
|
||||
environment,
|
||||
application_id: profile.map(|p| p.application_id.to_string()),
|
||||
engine: engine.map(engine_name),
|
||||
ready: reason.is_none(),
|
||||
reason,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let targets = state
|
||||
.db
|
||||
.all_restore_targets(now())
|
||||
.map_err(internal)?
|
||||
.into_iter()
|
||||
.map(|(target, outpost_active)| TargetSetup {
|
||||
environment: target_env.get(&target.id.to_string()).cloned(),
|
||||
id: target.id.to_string(),
|
||||
name: target.name,
|
||||
engine: engine_name(target.engine),
|
||||
identity: target.identity,
|
||||
application_id: target.application_id.to_string(),
|
||||
outpost_active,
|
||||
})
|
||||
.collect();
|
||||
let relations = state.db.relation_views(false, None, now()).map_err(internal)?;
|
||||
Ok((no_store(), Json(Overview { relations, orbits, targets })))
|
||||
}
|
||||
|
||||
/// What the snapshots say about a target: does its identity match a database that is captured as a
|
||||
/// production (or unlabelled) source, and has the source itself been seen at all?
|
||||
async fn identity_facts(state: &HubState, source: Uuid, target: &DatabaseIdentity) -> Result<(bool, bool), StatusCode> {
|
||||
let (orbit_env, _) = state.db.environments().map_err(internal)?;
|
||||
let vault = state.vault.read().await;
|
||||
let snapshots = vault.list_snapshots().map_err(internal)?;
|
||||
let (mut clash, mut verified) = (false, false);
|
||||
for snapshot in snapshots {
|
||||
let Some(identity) = snapshot.manifest.restore_hints.get("source_identity").cloned() else { continue };
|
||||
let Ok(identity) = serde_json::from_value::<DatabaseIdentity>(identity) else { continue };
|
||||
let from = snapshot.manifest.orbit_id;
|
||||
if from == source {
|
||||
verified = true;
|
||||
}
|
||||
if &identity == target {
|
||||
// A staging or development orbit that backs up the target itself is fine; anything else is
|
||||
// a database captured as production (or never classified) under a staging label.
|
||||
let own_backup = from != source && matches!(orbit_env.get(&from.to_string()).map(String::as_str), Some("staging" | "development"));
|
||||
if !own_backup {
|
||||
clash = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok((clash, verified))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct NewRelation {
|
||||
source_orbit_id: Uuid,
|
||||
target_id: Uuid,
|
||||
}
|
||||
|
||||
async fn create(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Json(body): Json<NewRelation>,
|
||||
) -> Result<Response, StatusCode> {
|
||||
let actor = admin_write(&state, peer, &headers)?;
|
||||
let Some(target) = state.db.restore_target(body.target_id).map_err(internal)? else {
|
||||
return Ok(refused(Reject::UnknownTarget));
|
||||
};
|
||||
let (clash, verified) = identity_facts(&state, body.source_orbit_id, &target.identity).await?;
|
||||
match state.db.create_relation(body.source_orbit_id, body.target_id, None, clash, verified, &actor.id(), now()).map_err(internal)? {
|
||||
Ok(relation) => {
|
||||
let id = Uuid::parse_str(&relation.id).map_err(internal)?;
|
||||
state.db.audit_event(&actor.principal, AuditAction::RelationCreate, AuditResource::Relation(id), AuditOutcome::Succeeded, actor.request_id).map_err(internal)?;
|
||||
Ok((StatusCode::CREATED, no_store(), Json(relation)).into_response())
|
||||
}
|
||||
Err(reject) => Ok(refused(reject)),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Retarget {
|
||||
target_id: Uuid,
|
||||
}
|
||||
|
||||
async fn retarget(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(body): Json<Retarget>,
|
||||
) -> Result<Response, StatusCode> {
|
||||
let actor = admin_write(&state, peer, &headers)?;
|
||||
let old = state.db.relation(&id.to_string()).map_err(internal)?.filter(|r| r.active).ok_or(StatusCode::NOT_FOUND)?;
|
||||
let source = Uuid::parse_str(&old.source_orbit_id).map_err(internal)?;
|
||||
let Some(target) = state.db.restore_target(body.target_id).map_err(internal)? else {
|
||||
return Ok(refused(Reject::UnknownTarget));
|
||||
};
|
||||
let (clash, verified) = identity_facts(&state, source, &target.identity).await?;
|
||||
match state.db.create_relation(source, body.target_id, Some(&old.id), clash, verified, &actor.id(), now()).map_err(internal)? {
|
||||
Ok(relation) => {
|
||||
let new_id = Uuid::parse_str(&relation.id).map_err(internal)?;
|
||||
state.db.audit_event(&actor.principal, AuditAction::RelationRetarget, AuditResource::Relation(new_id), AuditOutcome::Succeeded, actor.request_id).map_err(internal)?;
|
||||
Ok((StatusCode::CREATED, no_store(), Json(relation)).into_response())
|
||||
}
|
||||
Err(reject) => Ok(refused(reject)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn deactivate(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
let actor = admin_write(&state, peer, &headers)?;
|
||||
let done = state.db.deactivate_relation(&id.to_string(), "deactivated_by_admin", now()).map_err(internal)?;
|
||||
state.db.audit_event(&actor.principal, AuditAction::RelationDeactivate, AuditResource::Relation(id),
|
||||
if done { AuditOutcome::Succeeded } else { AuditOutcome::Failed }, actor.request_id).map_err(internal)?;
|
||||
if done { Ok(StatusCode::NO_CONTENT) } else { Err(StatusCode::NOT_FOUND) }
|
||||
}
|
||||
|
||||
async fn list_access(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<(HeaderMap, Json<Vec<crate::db::relations::RelationGrant>>), StatusCode> {
|
||||
admin_read(&state, peer, &headers)?;
|
||||
state.db.relation(&id.to_string()).map_err(internal)?.ok_or(StatusCode::NOT_FOUND)?;
|
||||
Ok((no_store(), Json(state.db.relation_grants(&id.to_string()).map_err(internal)?)))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct NewAccess {
|
||||
principal_type: String,
|
||||
principal: String,
|
||||
expires_at: Option<String>,
|
||||
}
|
||||
|
||||
async fn grant_access(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(body): Json<NewAccess>,
|
||||
) -> Result<(StatusCode, HeaderMap, Json<crate::db::relations::RelationGrant>), StatusCode> {
|
||||
let actor = admin_write(&state, peer, &headers)?;
|
||||
let now = now();
|
||||
match body.principal_type.as_str() {
|
||||
"user" => {
|
||||
Uuid::parse_str(&body.principal).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
if !state.db.user_exists(&body.principal).map_err(internal)? {
|
||||
return Err(StatusCode::UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
}
|
||||
"group" => {
|
||||
if body.principal.is_empty() || body.principal.len() > 128 || body.principal.chars().any(char::is_control) {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
_ => return Err(StatusCode::BAD_REQUEST),
|
||||
}
|
||||
let expires_at = body
|
||||
.expires_at
|
||||
.as_deref()
|
||||
.map(|text| chrono::DateTime::parse_from_rfc3339(text).map(|t| t.timestamp()).map_err(|_| StatusCode::BAD_REQUEST))
|
||||
.transpose()?;
|
||||
if expires_at.is_some_and(|end| end <= now || end > now + 2 * 366 * 86_400) {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
state.db.relation(&id.to_string()).map_err(internal)?.filter(|r| r.active).ok_or(StatusCode::NOT_FOUND)?;
|
||||
let grant = state
|
||||
.db
|
||||
.add_relation_grant(&body.principal_type, &body.principal, &id.to_string(), expires_at, &actor.id(), now)
|
||||
.map_err(internal)?
|
||||
.ok_or(StatusCode::CONFLICT)?;
|
||||
state.db.audit_event(&actor.principal, AuditAction::RelationGrantCreate, AuditResource::Relation(id), AuditOutcome::Succeeded, actor.request_id).map_err(internal)?;
|
||||
Ok((StatusCode::CREATED, no_store(), Json(grant)))
|
||||
}
|
||||
|
||||
async fn revoke_access(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path((id, grant)): Path<(Uuid, Uuid)>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
let actor = admin_write(&state, peer, &headers)?;
|
||||
let removed = state.db.delete_relation_grant(&id.to_string(), &grant.to_string()).map_err(internal)?;
|
||||
state.db.audit_event(&actor.principal, AuditAction::RelationGrantDelete, AuditResource::Relation(id),
|
||||
if removed { AuditOutcome::Succeeded } else { AuditOutcome::Failed }, actor.request_id).map_err(internal)?;
|
||||
if removed { Ok(StatusCode::NO_CONTENT) } else { Err(StatusCode::NOT_FOUND) }
|
||||
}
|
||||
|
||||
/// A relation as a refresher sees it: names and environments, never where the database is.
|
||||
#[derive(Serialize)]
|
||||
struct MyRelation {
|
||||
id: String,
|
||||
version: i64,
|
||||
source_name: String,
|
||||
source_environment: Option<String>,
|
||||
target_name: String,
|
||||
target_environment: Option<String>,
|
||||
usable: bool,
|
||||
unusable_reason: Option<&'static str>,
|
||||
}
|
||||
|
||||
async fn mine(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<(HeaderMap, Json<Vec<MyRelation>>), StatusCode> {
|
||||
let actor = authenticate(&state, peer, &headers, false)?;
|
||||
let granted = super::gate::visible_relations(&state, &actor)?;
|
||||
let views = state.db.relation_views(true, granted.as_deref(), now()).map_err(internal)?;
|
||||
let list = views
|
||||
.into_iter()
|
||||
.map(|view| MyRelation {
|
||||
id: view.relation.id,
|
||||
version: view.relation.version,
|
||||
source_name: view.source_name,
|
||||
source_environment: view.source_environment,
|
||||
target_name: view.target_name,
|
||||
target_environment: view.target_environment,
|
||||
usable: view.usable,
|
||||
unusable_reason: view.unusable_reason,
|
||||
})
|
||||
.collect();
|
||||
Ok((no_store(), Json(list)))
|
||||
}
|
||||
Reference in New Issue
Block a user