feat: per-orbit access grants and an Access console (auth M5)
Authorization - one gate for every human endpoint: authenticate, resolve the resource, then admin_only / scoped / visible; require_admin* removed so each handler must choose - grants (user or IdP group; global or one orbit; optional end date) read live on every request; only orbit.read, snapshot.read, capture.run and snapshot.download can be granted, everything else stays with configured administrators - an orbit without orbit.read is 404, a visible one without the permission is 403, a caller with nothing to see gets 403 on lists; job history is filtered before LIMIT - jobs and audit record the stable principal id, not the IdP display name - restore targets and restore history are admin-only until self-service (M6) - sessions keep the groups verified at sign-in Administration - /api/v1/access grants and users (enable, disable, sign out everywhere), validated and audited by id; admins cannot disable themselves or the emergency operator - Access console with the shared Select and a themed DatePicker; non-administrators only see Vault and Activity and never call administrator endpoints - the Window/Radar view is stored per account (/api/v1/me/preferences) - UI tolerates older hubs and mocks (missing admin/grants) and a console that fails to render no longer blanks the app Tests: a matrix generated from the endpoint contract exercises every human route against real resources in two orbits for each kind of caller. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
232
crates/tessera-hub/src/api/access.rs
Normal file
232
crates/tessera-hub/src/api/access.rs
Normal file
@@ -0,0 +1,232 @@
|
||||
//! Administration of access: who holds which permission on which orbit.
|
||||
//! Administrators only (`access.manage` is never delegated). Every change is
|
||||
//! audited by id and effective on the very next request of the affected user.
|
||||
use super::routes::{admin_read, admin_write};
|
||||
use crate::auth::{role, AuditAction, AuditOutcome, AuditResource, Permission, ROLE_NAMES};
|
||||
use crate::db::access::NewGrant;
|
||||
use crate::state::HubState;
|
||||
use axum::{
|
||||
extract::{ConnectInfo, Path, State},
|
||||
http::{header, HeaderMap, HeaderValue, StatusCode},
|
||||
routing::{get, post, put},
|
||||
Json, Router,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::net::SocketAddr;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub(super) fn routes() -> Router<HubState> {
|
||||
Router::new()
|
||||
.route("/api/v1/access/grants", get(list).post(create))
|
||||
.route("/api/v1/access/grants/:id", axum::routing::delete(remove))
|
||||
.route("/api/v1/access/users", get(users))
|
||||
.route("/api/v1/access/users/:id", put(set_user))
|
||||
.route("/api/v1/access/users/:id/revoke-sessions", post(revoke_sessions))
|
||||
}
|
||||
|
||||
fn no_store() -> HeaderMap {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
|
||||
headers
|
||||
}
|
||||
|
||||
fn now() -> i64 {
|
||||
chrono::Utc::now().timestamp()
|
||||
}
|
||||
|
||||
fn internal(error: impl std::fmt::Display) -> StatusCode {
|
||||
tracing::error!("access administration failed: {error:#}");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct RoleInfo {
|
||||
name: &'static str,
|
||||
permissions: Vec<&'static str>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct GrantList {
|
||||
grants: Vec<crate::db::access::Grant>,
|
||||
roles: Vec<RoleInfo>,
|
||||
/// Permissions that can be granted; all others belong to administrators.
|
||||
grantable: Vec<&'static str>,
|
||||
}
|
||||
|
||||
async fn list(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<(HeaderMap, Json<GrantList>), StatusCode> {
|
||||
admin_read(&state, peer, &headers)?;
|
||||
let roles = ROLE_NAMES
|
||||
.iter()
|
||||
.map(|name| RoleInfo { name, permissions: role(name).unwrap_or(&[]).iter().map(|p| p.as_str()).collect() })
|
||||
.collect();
|
||||
Ok((
|
||||
no_store(),
|
||||
Json(GrantList {
|
||||
grants: state.db.list_grants().map_err(internal)?,
|
||||
roles,
|
||||
grantable: [Permission::OrbitRead, Permission::SnapshotRead, Permission::CaptureRun, Permission::SnapshotDownload]
|
||||
.iter()
|
||||
.map(|p| p.as_str())
|
||||
.collect(),
|
||||
}),
|
||||
))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct CreateGrant {
|
||||
/// `user` (a `users.id`) or `group` (an IdP group name).
|
||||
principal_type: String,
|
||||
principal: String,
|
||||
/// Exactly one of `role` and `permission`.
|
||||
role: Option<String>,
|
||||
permission: Option<String>,
|
||||
/// Absent = every orbit.
|
||||
orbit_id: Option<Uuid>,
|
||||
/// RFC 3339; absent = no expiry.
|
||||
expires_at: Option<String>,
|
||||
}
|
||||
|
||||
async fn create(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Json(body): Json<CreateGrant>,
|
||||
) -> Result<(StatusCode, HeaderMap, Json<Vec<crate::db::access::Grant>>), StatusCode> {
|
||||
let actor = admin_write(&state, peer, &headers)?;
|
||||
let now = now();
|
||||
let permissions: Vec<Permission> = match (&body.role, &body.permission) {
|
||||
(Some(name), None) => role(name).ok_or(StatusCode::BAD_REQUEST)?.to_vec(),
|
||||
(None, Some(name)) => vec![Permission::parse(name).filter(|p| p.grantable()).ok_or(StatusCode::BAD_REQUEST)?],
|
||||
_ => return Err(StatusCode::BAD_REQUEST),
|
||||
};
|
||||
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),
|
||||
}
|
||||
if let Some(orbit) = body.orbit_id {
|
||||
if !state.db.orbit_exists(&orbit.to_string()).map_err(internal)? {
|
||||
return Err(StatusCode::UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
let orbit = body.orbit_id.map(|id| id.to_string());
|
||||
let created_by = actor.id();
|
||||
let mut created = Vec::new();
|
||||
for permission in permissions {
|
||||
let grant = NewGrant {
|
||||
principal_type: &body.principal_type,
|
||||
principal: &body.principal,
|
||||
permission: permission.as_str(),
|
||||
orbit: orbit.as_deref(),
|
||||
expires_at,
|
||||
created_by: &created_by,
|
||||
};
|
||||
if let Some(grant) = state.db.add_grant(&grant, now).map_err(internal)? {
|
||||
let id = Uuid::parse_str(&grant.id).map_err(internal)?;
|
||||
state
|
||||
.db
|
||||
.audit_event(&actor.principal, AuditAction::GrantCreate, AuditResource::Grant(id), AuditOutcome::Succeeded, actor.request_id)
|
||||
.map_err(internal)?;
|
||||
created.push(grant);
|
||||
}
|
||||
}
|
||||
if created.is_empty() {
|
||||
return Err(StatusCode::CONFLICT);
|
||||
}
|
||||
Ok((StatusCode::CREATED, no_store(), Json(created)))
|
||||
}
|
||||
|
||||
async fn remove(
|
||||
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 removed = state.db.delete_grant(&id.to_string()).map_err(internal)?;
|
||||
state
|
||||
.db
|
||||
.audit_event(&actor.principal, AuditAction::GrantDelete, AuditResource::Grant(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) }
|
||||
}
|
||||
|
||||
async fn users(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<(HeaderMap, Json<Vec<crate::db::access::UserRow>>), StatusCode> {
|
||||
admin_read(&state, peer, &headers)?;
|
||||
Ok((no_store(), Json(state.db.list_users().map_err(internal)?)))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct UserState {
|
||||
active: bool,
|
||||
}
|
||||
|
||||
/// Look up the target user and refuse the two changes that would lock everyone out.
|
||||
fn target_user(state: &HubState, actor: &super::routes::OperatorActor, id: Uuid) -> Result<crate::db::access::UserRow, StatusCode> {
|
||||
let user = state.db.list_users().map_err(internal)?.into_iter().find(|u| u.id == id.to_string()).ok_or(StatusCode::NOT_FOUND)?;
|
||||
if actor.subject.user_id.as_deref() == Some(user.id.as_str()) || user.is_emergency {
|
||||
return Err(StatusCode::CONFLICT);
|
||||
}
|
||||
Ok(user)
|
||||
}
|
||||
|
||||
async fn set_user(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(body): Json<UserState>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
let actor = admin_write(&state, peer, &headers)?;
|
||||
let user = target_user(&state, &actor, id)?;
|
||||
state.db.set_user_active(&user.id, body.active).map_err(internal)?;
|
||||
state
|
||||
.db
|
||||
.audit_event(&actor.principal, AuditAction::UserState, AuditResource::User(id), AuditOutcome::Succeeded, actor.request_id)
|
||||
.map_err(internal)?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
async fn revoke_sessions(
|
||||
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 user = state.db.list_users().map_err(internal)?.into_iter().find(|u| u.id == id.to_string()).ok_or(StatusCode::NOT_FOUND)?;
|
||||
state.db.revoke_user_sessions(&user.id).map_err(internal)?;
|
||||
state
|
||||
.db
|
||||
.audit_event(&actor.principal, AuditAction::SessionsRevoke, AuditResource::User(id), AuditOutcome::Succeeded, actor.request_id)
|
||||
.map_err(internal)?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
Reference in New Issue
Block a user