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:
@@ -236,10 +236,15 @@ pub struct BrowserSession {
|
|||||||
pub auth_method: String,
|
pub auth_method: String,
|
||||||
/// May use the management API. A signed-in user without a grant is `false`.
|
/// May use the management API. A signed-in user without a grant is `false`.
|
||||||
pub admin: bool,
|
pub admin: bool,
|
||||||
|
pub groups: Vec<String>,
|
||||||
pub expires_at: i64,
|
pub expires_at: i64,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl BrowserSession {
|
impl BrowserSession {
|
||||||
|
pub fn subject(&self) -> crate::auth::Subject {
|
||||||
|
crate::auth::Subject { user_id: Some(self.user_id.clone()), groups: self.groups.clone(), admin: self.admin }
|
||||||
|
}
|
||||||
|
|
||||||
/// Audit identity. Never derived from IdP-supplied names: OIDC users are
|
/// Audit identity. Never derived from IdP-supplied names: OIDC users are
|
||||||
/// identified by their stable user id, so a username of "operator" cannot
|
/// identified by their stable user id, so a username of "operator" cannot
|
||||||
/// be mistaken for the emergency account.
|
/// be mistaken for the emergency account.
|
||||||
@@ -335,6 +340,7 @@ impl SessionGate {
|
|||||||
user_id: stored.user_id,
|
user_id: stored.user_id,
|
||||||
auth_method: stored.auth_method,
|
auth_method: stored.auth_method,
|
||||||
admin: stored.admin,
|
admin: stored.admin,
|
||||||
|
groups: stored.groups,
|
||||||
expires_at: stored.expires_at,
|
expires_at: stored.expires_at,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -363,7 +369,7 @@ impl SessionGate {
|
|||||||
let id = uuid::Uuid::new_v4();
|
let id = uuid::Uuid::new_v4();
|
||||||
let created = self
|
let created = self
|
||||||
.db
|
.db
|
||||||
.create_session(&id.to_string(), &user_id, "password", Some(&config.fingerprint), true, now)
|
.create_session(&id.to_string(), &user_id, "password", Some(&config.fingerprint), true, &[], now)
|
||||||
.map_err(internal)?;
|
.map_err(internal)?;
|
||||||
if !created {
|
if !created {
|
||||||
// Inactive user row: the break-glass account has been disabled.
|
// Inactive user row: the break-glass account has been disabled.
|
||||||
@@ -376,6 +382,7 @@ impl SessionGate {
|
|||||||
user_id,
|
user_id,
|
||||||
auth_method: "password".into(),
|
auth_method: "password".into(),
|
||||||
admin: true,
|
admin: true,
|
||||||
|
groups: vec![],
|
||||||
expires_at: now + crate::db::sessions::ABSOLUTE_SECS,
|
expires_at: now + crate::db::sessions::ABSOLUTE_SECS,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -387,12 +394,13 @@ impl SessionGate {
|
|||||||
user_id: &str,
|
user_id: &str,
|
||||||
display_name: &str,
|
display_name: &str,
|
||||||
admin: bool,
|
admin: bool,
|
||||||
|
groups: &[String],
|
||||||
now: i64,
|
now: i64,
|
||||||
) -> anyhow::Result<BrowserSession> {
|
) -> anyhow::Result<BrowserSession> {
|
||||||
let fp = self.oidc_fp.as_deref().ok_or_else(|| anyhow::anyhow!("OIDC is not configured"))?;
|
let fp = self.oidc_fp.as_deref().ok_or_else(|| anyhow::anyhow!("OIDC is not configured"))?;
|
||||||
let id = uuid::Uuid::new_v4();
|
let id = uuid::Uuid::new_v4();
|
||||||
anyhow::ensure!(
|
anyhow::ensure!(
|
||||||
self.db.create_session(&id.to_string(), user_id, "oidc", Some(fp), admin, now)?,
|
self.db.create_session(&id.to_string(), user_id, "oidc", Some(fp), admin, groups, now)?,
|
||||||
"user is disabled"
|
"user is disabled"
|
||||||
);
|
);
|
||||||
Ok(BrowserSession {
|
Ok(BrowserSession {
|
||||||
@@ -402,6 +410,7 @@ impl SessionGate {
|
|||||||
user_id: user_id.to_string(),
|
user_id: user_id.to_string(),
|
||||||
auth_method: "oidc".into(),
|
auth_method: "oidc".into(),
|
||||||
admin,
|
admin,
|
||||||
|
groups: groups.to_vec(),
|
||||||
expires_at: now + crate::db::sessions::ABSOLUTE_SECS,
|
expires_at: now + crate::db::sessions::ABSOLUTE_SECS,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -570,7 +579,7 @@ mod session_gate_tests {
|
|||||||
let (_dir, db) = db().await;
|
let (_dir, db) = db().await;
|
||||||
let user = db.upsert_user("https://idp.example", "alice", "Alice", unix_now()).unwrap();
|
let user = db.upsert_user("https://idp.example", "alice", "Alice", unix_now()).unwrap();
|
||||||
let gate = SessionGate::without_operator(db.clone()).with_oidc("fp-a");
|
let gate = SessionGate::without_operator(db.clone()).with_oidc("fp-a");
|
||||||
let session = gate.create_oidc(&user, "Alice", true, unix_now()).unwrap();
|
let session = gate.create_oidc(&user, "Alice", true, &[], unix_now()).unwrap();
|
||||||
assert_eq!(session.principal().fields().0, format!("oidc:{user}"));
|
assert_eq!(session.principal().fields().0, format!("oidc:{user}"));
|
||||||
assert!(gate.active(&cookie(&session)).is_some());
|
assert!(gate.active(&cookie(&session)).is_some());
|
||||||
// admin mapping changed (different fingerprint) or OIDC switched off: dead
|
// admin mapping changed (different fingerprint) or OIDC switched off: dead
|
||||||
@@ -584,7 +593,7 @@ mod session_gate_tests {
|
|||||||
async fn an_oidc_display_name_never_becomes_the_emergency_principal() {
|
async fn an_oidc_display_name_never_becomes_the_emergency_principal() {
|
||||||
let (_dir, db) = db().await;
|
let (_dir, db) = db().await;
|
||||||
let user = db.upsert_user("https://idp.example", "mallory", "operator", unix_now()).unwrap();
|
let user = db.upsert_user("https://idp.example", "mallory", "operator", unix_now()).unwrap();
|
||||||
let session = SessionGate::without_operator(db).with_oidc("fp").create_oidc(&user, "operator", false, unix_now()).unwrap();
|
let session = SessionGate::without_operator(db).with_oidc("fp").create_oidc(&user, "operator", false, &[], unix_now()).unwrap();
|
||||||
let (id, kind, method) = session.principal().fields();
|
let (id, kind, method) = session.principal().fields();
|
||||||
assert_eq!((kind, method), ("user", "oidc"));
|
assert_eq!((kind, method), ("user", "oidc"));
|
||||||
assert!(id.starts_with("oidc:") && !id.contains("emergency"));
|
assert!(id.starts_with("oidc:") && !id.contains("emergency"));
|
||||||
|
|||||||
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)
|
||||||
|
}
|
||||||
573
crates/tessera-hub/src/api/access_tests.rs
Normal file
573
crates/tessera-hub/src/api/access_tests.rs
Normal file
@@ -0,0 +1,573 @@
|
|||||||
|
//! Authorization matrix, generated from `tasks/auth-endpoint-contract.md`.
|
||||||
|
//!
|
||||||
|
//! Every `human` route in the contract is exercised against real resources in two
|
||||||
|
//! orbits with six kinds of caller. A route added to the contract without a
|
||||||
|
//! request recipe here fails the test, so nothing ships ungated by accident.
|
||||||
|
use crate::admin::SessionGate;
|
||||||
|
use crate::auth::{role, Permission};
|
||||||
|
use crate::db::access::NewGrant;
|
||||||
|
use crate::state::HubState;
|
||||||
|
use axum::body::{to_bytes, Body};
|
||||||
|
use axum::extract::ConnectInfo;
|
||||||
|
use axum::http::{header, Method, Request, StatusCode};
|
||||||
|
use serde_json::{json, Value};
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use tessera_core::job::{CaptureFormat, CaptureProfile};
|
||||||
|
use tessera_core::manifest::SnapshotManifest;
|
||||||
|
use tessera_core::restore::{DatabaseIdentity, Engine, RestoreTarget};
|
||||||
|
use tower::ServiceExt;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
const CONTRACT: &str = include_str!("../../../../tasks/auth-endpoint-contract.md");
|
||||||
|
const ISSUER: &str = "https://idp.example";
|
||||||
|
|
||||||
|
struct Fixture {
|
||||||
|
orbit: Uuid,
|
||||||
|
application: Uuid,
|
||||||
|
outpost: Uuid,
|
||||||
|
snapshot: Uuid,
|
||||||
|
job: Uuid,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Caller {
|
||||||
|
name: &'static str,
|
||||||
|
cookie: Option<String>,
|
||||||
|
csrf: Option<String>,
|
||||||
|
user_id: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct World {
|
||||||
|
app: axum::Router,
|
||||||
|
state: HubState,
|
||||||
|
a: Fixture,
|
||||||
|
b: Fixture,
|
||||||
|
_dir: tempfile::TempDir,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn now() -> i64 {
|
||||||
|
chrono::Utc::now().timestamp()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fixture(state: &HubState, name: &str) -> Fixture {
|
||||||
|
let orbit = Uuid::new_v4();
|
||||||
|
state
|
||||||
|
.db
|
||||||
|
.upsert_orbit(&crate::db::OrbitRow {
|
||||||
|
id: orbit,
|
||||||
|
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();
|
||||||
|
let outpost = Uuid::new_v4();
|
||||||
|
state.db.insert_test_credential(&format!("token-{name}"), &outpost.to_string(), name);
|
||||||
|
let application = Uuid::new_v4();
|
||||||
|
let profile = CaptureProfile { application_id: application, orbit_id: orbit, outpost_id: outpost, format: CaptureFormat::PostgresCustom, schedule: None, retention: None };
|
||||||
|
assert!(state.db.register_capture_profile(&profile, now()).unwrap());
|
||||||
|
let job = state.db.enqueue_capture(application, "seed", now()).unwrap().unwrap().id;
|
||||||
|
let snapshot = Uuid::new_v4();
|
||||||
|
let manifest = SnapshotManifest {
|
||||||
|
snapshot_id: snapshot,
|
||||||
|
orbit_id: orbit,
|
||||||
|
orbit_name: name.into(),
|
||||||
|
labels: vec![],
|
||||||
|
provider: "filesystem".into(),
|
||||||
|
paths: vec![],
|
||||||
|
restore_hints: Value::Null,
|
||||||
|
};
|
||||||
|
state.vault.write().await.snapshot(manifest, b"synthetic payload", false).unwrap();
|
||||||
|
let target = RestoreTarget {
|
||||||
|
id: Uuid::new_v4(),
|
||||||
|
application_id: application,
|
||||||
|
outpost_id: outpost,
|
||||||
|
name: format!("{name}-staging"),
|
||||||
|
engine: Engine::Postgres,
|
||||||
|
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 }
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn world() -> World {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault").await.unwrap();
|
||||||
|
state.sessions = SessionGate::without_operator(state.db.clone()).with_oidc("matrix-fp");
|
||||||
|
let a = fixture(&state, "orbit-a").await;
|
||||||
|
let b = fixture(&state, "orbit-b").await;
|
||||||
|
let app = crate::api::router(state.clone());
|
||||||
|
World { app, state, a, b, _dir: dir }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl World {
|
||||||
|
fn caller(&self, name: &'static str, admin: bool, groups: &[&str]) -> Caller {
|
||||||
|
let groups: Vec<String> = groups.iter().map(|g| g.to_string()).collect();
|
||||||
|
let user = self.state.db.upsert_user(ISSUER, name, name, now()).unwrap();
|
||||||
|
let session = self.state.sessions.create_oidc(&user, name, admin, &groups, now()).unwrap();
|
||||||
|
Caller { name, cookie: Some(format!("__Host-tessera-session={}", session.id)), csrf: Some(session.csrf), user_id: Some(user) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn grant_role(&self, user: &str, role_name: &str, orbit: Option<Uuid>) {
|
||||||
|
self.grant("user", user, role_name, orbit);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn grant(&self, kind: &str, principal: &str, role_name: &str, orbit: Option<Uuid>) {
|
||||||
|
let orbit = orbit.map(|o| o.to_string());
|
||||||
|
for permission in role(role_name).unwrap() {
|
||||||
|
self.state
|
||||||
|
.db
|
||||||
|
.add_grant(
|
||||||
|
&NewGrant { principal_type: kind, principal, permission: permission.as_str(), orbit: orbit.as_deref(), expires_at: None, created_by: "test" },
|
||||||
|
now(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn send(&self, caller: &Caller, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
|
||||||
|
let mut request = Request::builder()
|
||||||
|
.method(Method::from_bytes(method.as_bytes()).unwrap())
|
||||||
|
.uri(uri)
|
||||||
|
.extension(ConnectInfo("127.0.0.1:4000".parse::<SocketAddr>().unwrap()));
|
||||||
|
if let Some(cookie) = &caller.cookie {
|
||||||
|
request = request.header(header::COOKIE, cookie);
|
||||||
|
}
|
||||||
|
if method != "GET" {
|
||||||
|
if let Some(csrf) = &caller.csrf {
|
||||||
|
request = request.header("x-tessera-csrf", csrf);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let request = match body {
|
||||||
|
Some(json) => request.header(header::CONTENT_TYPE, "application/json").body(Body::from(json.to_string())).unwrap(),
|
||||||
|
None => request.body(Body::empty()).unwrap(),
|
||||||
|
};
|
||||||
|
let response = self.app.clone().oneshot(request).await.unwrap();
|
||||||
|
let status = response.status();
|
||||||
|
let bytes = to_bytes(response.into_body(), 1 << 22).await.unwrap();
|
||||||
|
(status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn anonymous() -> Caller {
|
||||||
|
Caller { name: "anonymous", cookie: None, csrf: None, user_id: None }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, PartialEq, Debug)]
|
||||||
|
enum Kind {
|
||||||
|
SelfOnly,
|
||||||
|
AdminOnly,
|
||||||
|
List(Permission),
|
||||||
|
Resource(Permission),
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Row {
|
||||||
|
method: String,
|
||||||
|
template: String,
|
||||||
|
kind: Kind,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every method of every `human` row of the contract.
|
||||||
|
fn rows() -> Vec<Row> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for line in CONTRACT.lines().filter(|l| l.starts_with("| /")) {
|
||||||
|
let f: Vec<_> = line.split('|').map(str::trim).collect();
|
||||||
|
if f[3] != "human" {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let kind = if f[4] == "session.self" {
|
||||||
|
Kind::SelfOnly
|
||||||
|
} else {
|
||||||
|
let permission = Permission::parse(f[4]).unwrap_or_else(|| panic!("unknown permission {} in the contract", f[4]));
|
||||||
|
if !permission.grantable() {
|
||||||
|
Kind::AdminOnly
|
||||||
|
} else if f[1].contains(":id") {
|
||||||
|
Kind::Resource(permission)
|
||||||
|
} else {
|
||||||
|
Kind::List(permission)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for method in f[2].split(',') {
|
||||||
|
out.push(Row { method: method.trim().to_string(), template: f[1].to_string(), kind });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A concrete request for a contract row, aimed at orbit A's resources.
|
||||||
|
fn recipe(w: &World, row: &Row) -> (String, Option<Value>) {
|
||||||
|
let a = &w.a;
|
||||||
|
let unknown = Uuid::new_v4();
|
||||||
|
let id = match row.template.as_str() {
|
||||||
|
"/api/v1/snapshots/:id" | "/api/v1/snapshots/:id/download" | "/api/v1/snapshots/:id/restore-targets" | "/api/v1/snapshots/:id/restore-jobs" => a.snapshot,
|
||||||
|
"/api/v1/orbits/:id/retention" | "/api/v1/orbits/:id/run" | "/api/v1/orbits/:id/outpost" => a.orbit,
|
||||||
|
"/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,
|
||||||
|
_ => unknown,
|
||||||
|
};
|
||||||
|
let uri = row.template.replace(":id", &id.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() },
|
||||||
|
};
|
||||||
|
let body = match (row.method.as_str(), row.template.as_str()) {
|
||||||
|
("POST", "/api/v1/orbits") => Some(json!({"name": "created", "provider": "filesystem", "source": "filesystem", "provider_config": {"path": "/nonexistent"}})),
|
||||||
|
("PUT", "/api/v1/orbits/:id/retention") => Some(json!({"decay_preset": "week-of-dailies"})),
|
||||||
|
("PUT", "/api/v1/orbits/:id/outpost") => Some(json!({"outpost_id": a.outpost})),
|
||||||
|
("POST", "/api/v1/reconstitute") => Some(json!({"snapshot_id": a.snapshot, "target_path": "out"})),
|
||||||
|
("POST", "/api/v1/capture-profiles") => Some(serde_json::to_value(CaptureProfile { application_id: Uuid::new_v4(), orbit_id: a.orbit, outpost_id: a.outpost, format: CaptureFormat::PostgresCustom, schedule: None, retention: None }).unwrap()),
|
||||||
|
("POST", "/api/v1/restore-targets") => Some(serde_json::to_value(target).unwrap()),
|
||||||
|
("POST", "/api/v1/restore-jobs") => Some(json!({"snapshot_id": a.snapshot, "target_id": unknown, "confirmation": "x"})),
|
||||||
|
("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})),
|
||||||
|
("POST" | "PUT" | "DELETE" | "GET", _) => None,
|
||||||
|
other => panic!("no request recipe for {other:?}"),
|
||||||
|
};
|
||||||
|
(uri, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The orbit ids a list response contains, per list route.
|
||||||
|
fn orbits_in(template: &str, body: &Value) -> Vec<String> {
|
||||||
|
let pick = |path: &[&str]| -> Vec<String> {
|
||||||
|
body.as_array().unwrap_or(&vec![]).iter().filter_map(|item| {
|
||||||
|
let mut v = item;
|
||||||
|
for key in path {
|
||||||
|
v = v.get(key)?;
|
||||||
|
}
|
||||||
|
v.as_str().map(str::to_string)
|
||||||
|
}).collect()
|
||||||
|
};
|
||||||
|
match template {
|
||||||
|
"/api/v1/orbits" => pick(&["id"]),
|
||||||
|
"/api/v1/snapshots" | "/api/v1/capture-profiles" => pick(&["orbit_id"]),
|
||||||
|
"/api/v1/capture-jobs" => pick(&["profile", "orbit_id"]),
|
||||||
|
other => panic!("no list reader for {other}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn denied(status: StatusCode) -> bool {
|
||||||
|
matches!(status, StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN | StatusCode::NOT_FOUND)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn every_human_route_enforces_the_matrix_for_every_kind_of_caller() {
|
||||||
|
let w = world().await;
|
||||||
|
let nogrant = w.caller("nogrant", false, &[]);
|
||||||
|
let viewer_b = w.caller("viewer-b", false, &[]);
|
||||||
|
let viewer_a = w.caller("viewer-a", false, &[]);
|
||||||
|
let capturer_a = w.caller("capturer-a", false, &[]);
|
||||||
|
let downloader_a = w.caller("downloader-a", false, &[]);
|
||||||
|
let group_a = w.caller("group-a", false, &["qa"]);
|
||||||
|
let admin = w.caller("admin", true, &[]);
|
||||||
|
w.grant_role(viewer_b.user_id.as_ref().unwrap(), "viewer", Some(w.b.orbit));
|
||||||
|
w.grant_role(viewer_a.user_id.as_ref().unwrap(), "viewer", Some(w.a.orbit));
|
||||||
|
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));
|
||||||
|
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
|
||||||
|
let mut rows = rows();
|
||||||
|
rows.sort_by_key(|row| matches!(row.kind, Kind::AdminOnly));
|
||||||
|
let mut covered = 0;
|
||||||
|
for row in &rows {
|
||||||
|
if row.kind == Kind::SelfOnly {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
covered += 1;
|
||||||
|
let (uri, body) = recipe(&w, row);
|
||||||
|
let label = format!("{} {}", row.method, row.template);
|
||||||
|
|
||||||
|
// no credential: always 401
|
||||||
|
let (status, _) = w.send(&anonymous(), &row.method, &uri, body.clone()).await;
|
||||||
|
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] {
|
||||||
|
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 held: &[Permission] = match caller.name {
|
||||||
|
"viewer-a" | "viewer-b" | "group-a" => role("viewer").unwrap(),
|
||||||
|
"capturer-a" => role("capturer").unwrap(),
|
||||||
|
"downloader-a" => role("downloader").unwrap(),
|
||||||
|
_ => &[],
|
||||||
|
};
|
||||||
|
let who = format!("{label} as {}", caller.name);
|
||||||
|
match row.kind {
|
||||||
|
Kind::AdminOnly => assert_eq!(status, StatusCode::FORBIDDEN, "{who}"),
|
||||||
|
Kind::Resource(permission) => {
|
||||||
|
let expected = if !on_a {
|
||||||
|
StatusCode::NOT_FOUND
|
||||||
|
} else if held.contains(&permission) {
|
||||||
|
// allowed: whatever the handler says, but never a gate answer
|
||||||
|
assert!(!denied(status), "{who}: {status}");
|
||||||
|
continue;
|
||||||
|
} else {
|
||||||
|
StatusCode::FORBIDDEN
|
||||||
|
};
|
||||||
|
assert_eq!(status, expected, "{who}");
|
||||||
|
}
|
||||||
|
Kind::List(_) => {
|
||||||
|
if caller.name == "nogrant" {
|
||||||
|
assert_eq!(status, StatusCode::FORBIDDEN, "{who}");
|
||||||
|
} else if row.method == "GET" {
|
||||||
|
assert_eq!(status, StatusCode::OK, "{who}");
|
||||||
|
let seen = orbits_in(&row.template, &body_out);
|
||||||
|
let own = if caller.name == "viewer-b" { &b } else { &a };
|
||||||
|
assert!(!seen.is_empty() && seen.iter().all(|id| id == own), "{who} sees only its own orbit: {seen:?}");
|
||||||
|
} else {
|
||||||
|
assert!(!denied(status), "{who}: {status}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// the administrator is never turned away by the gate
|
||||||
|
let (status, body_out) = w.send(&admin, &row.method, &uri, body.clone()).await;
|
||||||
|
assert!(status != StatusCode::UNAUTHORIZED && status != StatusCode::FORBIDDEN, "{label} as admin: {status}");
|
||||||
|
if let (Kind::List(_), "GET") = (row.kind, row.method.as_str()) {
|
||||||
|
let seen = orbits_in(&row.template, &body_out);
|
||||||
|
assert!(seen.contains(&a) && seen.contains(&b), "{label}: the administrator sees every orbit");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!(covered >= 25, "the matrix covered {covered} routes");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn permissions_are_separate_capture_does_not_imply_download_and_the_reverse() {
|
||||||
|
let w = world().await;
|
||||||
|
let capturer = w.caller("capturer", false, &[]);
|
||||||
|
let downloader = w.caller("downloader", false, &[]);
|
||||||
|
w.grant_role(capturer.user_id.as_ref().unwrap(), "capturer", Some(w.a.orbit));
|
||||||
|
w.grant_role(downloader.user_id.as_ref().unwrap(), "downloader", Some(w.a.orbit));
|
||||||
|
let download = format!("/api/v1/snapshots/{}/download", w.a.snapshot);
|
||||||
|
let enqueue = format!("/api/v1/capture-profiles/{}/jobs", w.a.application);
|
||||||
|
assert_eq!(w.send(&capturer, "POST", &enqueue, None).await.0, StatusCode::ACCEPTED);
|
||||||
|
assert_eq!(w.send(&capturer, "GET", &download, None).await.0, StatusCode::FORBIDDEN);
|
||||||
|
assert_eq!(w.send(&downloader, "GET", &download, None).await.0, StatusCode::OK);
|
||||||
|
assert_eq!(w.send(&downloader, "POST", &enqueue, None).await.0, StatusCode::FORBIDDEN);
|
||||||
|
// download on the other orbit stays invisible for both
|
||||||
|
let other = format!("/api/v1/snapshots/{}/download", w.b.snapshot);
|
||||||
|
assert_eq!(w.send(&downloader, "GET", &other, None).await.0, StatusCode::NOT_FOUND);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_revoked_or_expired_grant_is_refused_on_the_next_request_and_groups_follow_the_login() {
|
||||||
|
let w = world().await;
|
||||||
|
let user = w.caller("temp", false, &[]);
|
||||||
|
let id = user.user_id.clone().unwrap();
|
||||||
|
let uri = "/api/v1/orbits";
|
||||||
|
assert_eq!(w.send(&user, "GET", uri, None).await.0, StatusCode::FORBIDDEN, "no grant yet");
|
||||||
|
w.grant_role(&id, "viewer", Some(w.a.orbit));
|
||||||
|
assert_eq!(w.send(&user, "GET", uri, None).await.0, StatusCode::OK, "effective at once");
|
||||||
|
let grants = w.state.db.list_grants().unwrap();
|
||||||
|
for grant in grants.iter().filter(|g| g.principal == id) {
|
||||||
|
assert!(w.state.db.delete_grant(&grant.id).unwrap());
|
||||||
|
}
|
||||||
|
assert_eq!(w.send(&user, "GET", uri, None).await.0, StatusCode::FORBIDDEN, "revoked at once");
|
||||||
|
// an expiry in the past is ignored even though the row is still there
|
||||||
|
w.state
|
||||||
|
.db
|
||||||
|
.add_grant(&NewGrant { principal_type: "user", principal: &id, permission: "orbit.read", orbit: None, expires_at: Some(now() - 5), created_by: "test" }, now() - 100)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(w.send(&user, "GET", uri, None).await.0, StatusCode::FORBIDDEN, "expired");
|
||||||
|
// a group grant applies to the groups of the session, not to a later claim
|
||||||
|
w.grant("group", "qa", "viewer", None);
|
||||||
|
let in_group = w.caller("member", false, &["qa"]);
|
||||||
|
let no_claim = w.caller("no-claim", false, &[]);
|
||||||
|
assert_eq!(w.send(&in_group, "GET", uri, None).await.0, StatusCode::OK);
|
||||||
|
assert_eq!(w.send(&no_claim, "GET", uri, None).await.0, StatusCode::FORBIDDEN, "a missing groups claim grants nothing");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_restricted_caller_still_gets_a_full_page_of_their_own_jobs() {
|
||||||
|
let w = world().await;
|
||||||
|
// orbit B has one job; orbit A gets many newer ones that would fill a page
|
||||||
|
for _ in 0..5 {
|
||||||
|
w.state.db.enqueue_capture(w.a.application, "seed", now() + 10).unwrap();
|
||||||
|
}
|
||||||
|
let viewer = w.caller("viewer-b", false, &[]);
|
||||||
|
w.grant_role(viewer.user_id.as_ref().unwrap(), "viewer", Some(w.b.orbit));
|
||||||
|
let (status, body) = w.send(&viewer, "GET", "/api/v1/capture-jobs?limit=1", None).await;
|
||||||
|
assert_eq!(status, StatusCode::OK);
|
||||||
|
assert_eq!(body.as_array().unwrap().len(), 1, "filtered before the limit");
|
||||||
|
assert_eq!(body[0]["profile"]["orbit_id"], w.b.orbit.to_string());
|
||||||
|
// asking for the other orbit's application by id is a 404, not an empty list
|
||||||
|
let uri = format!("/api/v1/capture-jobs?application_id={}", w.a.application);
|
||||||
|
assert_eq!(w.send(&viewer, "GET", &uri, None).await.0, StatusCode::NOT_FOUND);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn jobs_are_attributed_to_the_stable_principal_never_to_an_idp_display_name() {
|
||||||
|
let w = world().await;
|
||||||
|
// an IdP user who calls themselves "scheduler" must not look like the scheduler
|
||||||
|
let user = w.caller("scheduler", false, &[]);
|
||||||
|
let id = user.user_id.clone().unwrap();
|
||||||
|
w.grant_role(&id, "capturer", Some(w.a.orbit));
|
||||||
|
let enqueue = format!("/api/v1/capture-profiles/{}/jobs", w.a.application);
|
||||||
|
let (status, job) = w.send(&user, "POST", &enqueue, None).await;
|
||||||
|
assert_eq!(status, StatusCode::ACCEPTED);
|
||||||
|
assert_eq!(job["actor"], format!("oidc:{id}"));
|
||||||
|
assert_ne!(job["actor"], "scheduler");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn the_grant_api_validates_audits_and_is_for_administrators_only() {
|
||||||
|
let w = world().await;
|
||||||
|
let admin = w.caller("admin", true, &[]);
|
||||||
|
let plain = w.caller("plain", false, &[]);
|
||||||
|
let target = w.caller("target", false, &[]);
|
||||||
|
let uid = target.user_id.clone().unwrap();
|
||||||
|
let grants = "/api/v1/access/grants";
|
||||||
|
let user_grant = |extra: Value| {
|
||||||
|
let mut base = json!({"principal_type": "user", "principal": uid, "role": "viewer", "orbit_id": w.a.orbit});
|
||||||
|
base.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||||
|
base
|
||||||
|
};
|
||||||
|
|
||||||
|
// not for non-admins, not even for someone who holds grants
|
||||||
|
w.grant_role(plain.user_id.as_ref().unwrap(), "viewer", None);
|
||||||
|
assert_eq!(w.send(&plain, "POST", grants, Some(user_grant(json!({})))).await.0, StatusCode::FORBIDDEN);
|
||||||
|
assert_eq!(w.send(&plain, "GET", grants, None).await.0, StatusCode::FORBIDDEN);
|
||||||
|
|
||||||
|
// validation: each of these must be refused
|
||||||
|
for (what, body, expected) in [
|
||||||
|
("unknown permission", user_grant(json!({"role": null, "permission": "orbit.reader"})), StatusCode::BAD_REQUEST),
|
||||||
|
("prefix of a permission", user_grant(json!({"role": null, "permission": "orbit"})), StatusCode::BAD_REQUEST),
|
||||||
|
("ungrantable permission", user_grant(json!({"role": null, "permission": "orbit.manage"})), StatusCode::BAD_REQUEST),
|
||||||
|
("access.manage is never delegated", user_grant(json!({"role": null, "permission": "access.manage"})), StatusCode::BAD_REQUEST),
|
||||||
|
("unknown role", user_grant(json!({"role": "root"})), StatusCode::BAD_REQUEST),
|
||||||
|
("role and permission together", user_grant(json!({"permission": "orbit.read"})), StatusCode::BAD_REQUEST),
|
||||||
|
("neither role nor permission", user_grant(json!({"role": null})), StatusCode::BAD_REQUEST),
|
||||||
|
("unknown principal type", user_grant(json!({"principal_type": "service"})), StatusCode::BAD_REQUEST),
|
||||||
|
("unknown user", user_grant(json!({"principal": Uuid::new_v4()})), StatusCode::UNPROCESSABLE_ENTITY),
|
||||||
|
("unknown orbit", user_grant(json!({"orbit_id": Uuid::new_v4()})), StatusCode::UNPROCESSABLE_ENTITY),
|
||||||
|
("expiry in the past", user_grant(json!({"expires_at": "2020-01-01T00:00:00Z"})), StatusCode::BAD_REQUEST),
|
||||||
|
("expiry far in the future", user_grant(json!({"expires_at": "2099-01-01T00:00:00Z"})), StatusCode::BAD_REQUEST),
|
||||||
|
("malformed expiry", user_grant(json!({"expires_at": "tomorrow"})), StatusCode::BAD_REQUEST),
|
||||||
|
("oversized group", json!({"principal_type": "group", "principal": "g".repeat(200), "role": "viewer"}), StatusCode::BAD_REQUEST),
|
||||||
|
] {
|
||||||
|
assert_eq!(w.send(&admin, "POST", grants, Some(body)).await.0, expected, "{what}");
|
||||||
|
}
|
||||||
|
assert_eq!(w.state.db.list_grants().unwrap().iter().filter(|g| g.principal == uid).count(), 0, "nothing was stored by the rejected requests");
|
||||||
|
|
||||||
|
// a valid grant takes effect on the very next request, and removing it ends that
|
||||||
|
let (status, created) = w.send(&admin, "POST", grants, Some(user_grant(json!({"expires_at": (chrono::Utc::now() + chrono::Duration::days(30)).to_rfc3339()})))).await;
|
||||||
|
assert_eq!(status, StatusCode::CREATED);
|
||||||
|
assert_eq!(created.as_array().unwrap().len(), 2, "the viewer role expands to orbit.read and snapshot.read");
|
||||||
|
assert_eq!(w.send(&target, "GET", "/api/v1/orbits", None).await.0, StatusCode::OK);
|
||||||
|
assert_eq!(w.send(&admin, "POST", grants, Some(user_grant(json!({})))).await.0, StatusCode::CONFLICT, "duplicates are refused");
|
||||||
|
for grant in created.as_array().unwrap() {
|
||||||
|
let uri = format!("/api/v1/access/grants/{}", grant["id"].as_str().unwrap());
|
||||||
|
assert_eq!(w.send(&admin, "DELETE", &uri, None).await.0, StatusCode::NO_CONTENT);
|
||||||
|
}
|
||||||
|
assert_eq!(w.send(&target, "GET", "/api/v1/orbits", None).await.0, StatusCode::FORBIDDEN);
|
||||||
|
|
||||||
|
// listing: roles and the grantable permissions come from the server
|
||||||
|
let (status, listing) = w.send(&admin, "GET", grants, None).await;
|
||||||
|
assert_eq!(status, StatusCode::OK);
|
||||||
|
assert_eq!(listing["grantable"].as_array().unwrap().len(), 4);
|
||||||
|
assert!(listing["roles"].as_array().unwrap().iter().any(|r| r["name"] == "downloader"));
|
||||||
|
|
||||||
|
// every change is audited by id, attributed to the administrator
|
||||||
|
let conn = rusqlite::Connection::open(w._dir.path().join("tessera.db")).unwrap();
|
||||||
|
let created_rows: i64 = conn
|
||||||
|
.query_row("SELECT COUNT(*) FROM audit_events WHERE action='access.grant_create' AND outcome='succeeded' AND resource_type='grant' AND actor_id LIKE 'oidc:%'", [], |r| r.get(0))
|
||||||
|
.unwrap();
|
||||||
|
let deleted_rows: i64 = conn.query_row("SELECT COUNT(*) FROM audit_events WHERE action='access.grant_delete' AND outcome='succeeded'", [], |r| r.get(0)).unwrap();
|
||||||
|
assert_eq!((created_rows, deleted_rows), (2, 2));
|
||||||
|
let denied_actor: String = conn
|
||||||
|
.query_row("SELECT actor_id FROM audit_events WHERE action='authorization.check' AND outcome='denied' ORDER BY id LIMIT 1", [], |r| r.get(0))
|
||||||
|
.unwrap();
|
||||||
|
assert!(denied_actor.starts_with("oidc:"), "{denied_actor}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn disabling_a_user_ends_their_access_at_once_and_cannot_lock_out_the_caller() {
|
||||||
|
let w = world().await;
|
||||||
|
let admin = w.caller("admin", true, &[]);
|
||||||
|
let user = w.caller("leaver", false, &[]);
|
||||||
|
let id = user.user_id.clone().unwrap();
|
||||||
|
w.grant_role(&id, "viewer", None);
|
||||||
|
assert_eq!(w.send(&user, "GET", "/api/v1/orbits", None).await.0, StatusCode::OK);
|
||||||
|
let uri = format!("/api/v1/access/users/{id}");
|
||||||
|
assert_eq!(w.send(&admin, "PUT", &uri, Some(json!({"active": false}))).await.0, StatusCode::NO_CONTENT);
|
||||||
|
assert_eq!(w.send(&user, "GET", "/api/v1/orbits", None).await.0, StatusCode::UNAUTHORIZED, "the session is gone");
|
||||||
|
// an administrator cannot disable themselves
|
||||||
|
let own = format!("/api/v1/access/users/{}", admin.user_id.as_ref().unwrap());
|
||||||
|
assert_eq!(w.send(&admin, "PUT", &own, Some(json!({"active": false}))).await.0, StatusCode::CONFLICT);
|
||||||
|
// revoking sessions leaves the user able to sign in again
|
||||||
|
let again = w.caller("returner", false, &[]);
|
||||||
|
let rid = again.user_id.clone().unwrap();
|
||||||
|
w.grant_role(&rid, "viewer", None);
|
||||||
|
let revoke = format!("/api/v1/access/users/{rid}/revoke-sessions");
|
||||||
|
assert_eq!(w.send(&admin, "POST", &revoke, None).await.0, StatusCode::NO_CONTENT);
|
||||||
|
assert_eq!(w.send(&again, "GET", "/api/v1/orbits", None).await.0, StatusCode::UNAUTHORIZED);
|
||||||
|
let users = w.send(&admin, "GET", "/api/v1/access/users", None).await.1;
|
||||||
|
assert!(users.as_array().unwrap().iter().any(|u| u["id"] == id && u["active"] == false));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn me_and_the_session_status_describe_what_the_caller_can_use() {
|
||||||
|
let w = world().await;
|
||||||
|
let user = w.caller("viewer", false, &[]);
|
||||||
|
let id = user.user_id.clone().unwrap();
|
||||||
|
let none = w.send(&user, "GET", "/api/v1/operator/session", None).await.1;
|
||||||
|
assert_eq!((none["authorized"].clone(), none["admin"].clone()), (json!(false), json!(false)), "no grant: the app stays closed");
|
||||||
|
w.grant_role(&id, "downloader", Some(w.a.orbit));
|
||||||
|
let status = w.send(&user, "GET", "/api/v1/operator/session", None).await.1;
|
||||||
|
assert_eq!((status["authorized"].clone(), status["admin"].clone()), (json!(true), json!(false)));
|
||||||
|
let me = w.send(&user, "GET", "/api/v1/me", None).await.1;
|
||||||
|
assert_eq!(me["admin"], false);
|
||||||
|
assert!(me["capabilities"].as_array().unwrap().iter().any(|c| c == "snapshot.download"));
|
||||||
|
assert!(me["grants"].as_array().unwrap().iter().all(|g| g["orbit_id"] == w.a.orbit.to_string()));
|
||||||
|
assert!(!me.to_string().contains("csrf"));
|
||||||
|
let admin = w.caller("admin", true, &[]);
|
||||||
|
let me = w.send(&admin, "GET", "/api/v1/me", None).await.1;
|
||||||
|
assert_eq!((me["admin"].clone(), me["capabilities"][0].clone()), (json!(true), json!("admin")));
|
||||||
|
assert!(me["id"].as_str().unwrap().starts_with("oidc:"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn display_preferences_stick_to_the_account_and_are_validated() {
|
||||||
|
let w = world().await;
|
||||||
|
let ann = w.caller("ann", false, &[]);
|
||||||
|
let ben = w.caller("ben", false, &[]);
|
||||||
|
let prefs = "/api/v1/me/preferences";
|
||||||
|
assert_eq!(w.send(&anonymous(), "GET", prefs, None).await.0, StatusCode::UNAUTHORIZED);
|
||||||
|
assert_eq!(w.send(&anonymous(), "PUT", prefs, Some(json!({"look": "radar"}))).await.0, StatusCode::UNAUTHORIZED);
|
||||||
|
// nothing stored yet; works for a user who holds no grant at all
|
||||||
|
let (status, body) = w.send(&ann, "GET", prefs, None).await;
|
||||||
|
assert_eq!((status, body["look"].clone()), (StatusCode::OK, Value::Null));
|
||||||
|
assert_eq!(w.send(&ann, "PUT", prefs, Some(json!({"look": "radar"}))).await.0, StatusCode::NO_CONTENT);
|
||||||
|
assert_eq!(w.send(&ann, "GET", prefs, None).await.1["look"], "radar");
|
||||||
|
// another account is unaffected; invalid values and unknown keys are refused
|
||||||
|
assert_eq!(w.send(&ben, "GET", prefs, None).await.1["look"], Value::Null);
|
||||||
|
assert_eq!(w.send(&ann, "PUT", prefs, Some(json!({"look": "neon"}))).await.0, StatusCode::BAD_REQUEST);
|
||||||
|
assert_eq!(w.send(&ann, "PUT", prefs, Some(json!({"theme": "x"}))).await.0, StatusCode::UNPROCESSABLE_ENTITY);
|
||||||
|
assert_eq!(w.send(&ann, "GET", prefs, None).await.1["look"], "radar", "a refused change leaves the choice alone");
|
||||||
|
// it follows the account, not the session: a fresh sign-in sees it
|
||||||
|
let again = w.caller("ann", false, &[]);
|
||||||
|
assert_eq!(w.send(&again, "GET", prefs, None).await.1["look"], "radar");
|
||||||
|
// the legacy admin token has no account: empty, and nothing to write to
|
||||||
|
let mut request = Request::builder().method("PUT").uri(prefs)
|
||||||
|
.extension(ConnectInfo("127.0.0.1:4000".parse::<SocketAddr>().unwrap()))
|
||||||
|
.header(header::CONTENT_TYPE, "application/json").header("x-tessera-admin-token", "legacy-token")
|
||||||
|
.body(Body::from(json!({"look": "window"}).to_string())).unwrap();
|
||||||
|
let mut state = w.state.clone();
|
||||||
|
state.admin.token = Some("legacy-token".into());
|
||||||
|
let app = crate::api::router(state);
|
||||||
|
*request.uri_mut() = prefs.parse().unwrap();
|
||||||
|
assert_eq!(app.oneshot(request).await.unwrap().status(), StatusCode::NOT_FOUND);
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
use super::routes::{require_admin, require_admin_mutation};
|
use super::routes::{admin_write, authenticate};
|
||||||
|
use crate::auth::Permission;
|
||||||
use crate::state::HubState;
|
use crate::state::HubState;
|
||||||
use axum::{
|
use axum::{
|
||||||
body::Body,
|
body::Body,
|
||||||
@@ -24,7 +25,7 @@ async fn download(
|
|||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
Path(id): Path<Uuid>,
|
Path(id): Path<Uuid>,
|
||||||
) -> Result<Response, StatusCode> {
|
) -> Result<Response, StatusCode> {
|
||||||
require_admin(&state, peer, &headers)?;
|
let actor = authenticate(&state, peer, &headers, false)?;
|
||||||
let snapshot = state
|
let snapshot = state
|
||||||
.vault
|
.vault
|
||||||
.read()
|
.read()
|
||||||
@@ -33,6 +34,7 @@ async fn download(
|
|||||||
.map_err(internal)?
|
.map_err(internal)?
|
||||||
.filter(|snapshot| snapshot.manifest.provider != "legacy-history")
|
.filter(|snapshot| snapshot.manifest.provider != "legacy-history")
|
||||||
.ok_or(StatusCode::NOT_FOUND)?;
|
.ok_or(StatusCode::NOT_FOUND)?;
|
||||||
|
super::gate::scoped(&state, &actor, Permission::SnapshotDownload, snapshot.manifest.orbit_id)?;
|
||||||
let staging = tempfile::tempdir_in(&state.data_dir).map_err(internal)?;
|
let staging = tempfile::tempdir_in(&state.data_dir).map_err(internal)?;
|
||||||
let path = staging.path().join("download");
|
let path = staging.path().join("download");
|
||||||
let size = state
|
let size = state
|
||||||
@@ -73,7 +75,7 @@ async fn delete(
|
|||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
Path(id): Path<Uuid>,
|
Path(id): Path<Uuid>,
|
||||||
) -> Result<StatusCode, StatusCode> {
|
) -> Result<StatusCode, StatusCode> {
|
||||||
let actor = require_admin_mutation(&state, peer, &headers)?;
|
let actor = admin_write(&state, peer, &headers)?;
|
||||||
let mut vault = state.vault.clone().write_owned().await;
|
let mut vault = state.vault.clone().write_owned().await;
|
||||||
if state.db.snapshot_in_restore(id).map_err(internal)?
|
if state.db.snapshot_in_restore(id).map_err(internal)?
|
||||||
|| state.db.offsite_pending(id).map_err(internal)? || state.active_exports().await.contains(&id)
|
|| state.db.offsite_pending(id).map_err(internal)? || state.active_exports().await.contains(&id)
|
||||||
|
|||||||
124
crates/tessera-hub/src/api/gate.rs
Normal file
124
crates/tessera-hub/src/api/gate.rs
Normal file
@@ -0,0 +1,124 @@
|
|||||||
|
//! The one place that decides what an authenticated caller may do.
|
||||||
|
//!
|
||||||
|
//! Order everywhere: authenticate (401 / CSRF 403), resolve the resource, then
|
||||||
|
//! the gate. A resource the caller cannot see answers 404 (it is not confirmed to
|
||||||
|
//! exist); one they can see but may not use answers 403. Grants are read from the
|
||||||
|
//! database on every call, so a revoke is effective on the next request.
|
||||||
|
use super::routes::OperatorActor;
|
||||||
|
use crate::auth::{AuditAction, AuditOutcome, AuditResource, Permission};
|
||||||
|
use crate::state::HubState;
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use std::collections::HashSet;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
fn now() -> i64 {
|
||||||
|
chrono::Utc::now().timestamp()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn audit(state: &HubState, actor: &OperatorActor, resource: AuditResource, allowed: bool) -> Result<(), StatusCode> {
|
||||||
|
state
|
||||||
|
.db
|
||||||
|
.audit_event(
|
||||||
|
&actor.principal,
|
||||||
|
AuditAction::Authorization,
|
||||||
|
resource,
|
||||||
|
if allowed { AuditOutcome::Allowed } else { AuditOutcome::Denied },
|
||||||
|
actor.request_id,
|
||||||
|
)
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn internal(error: impl std::fmt::Display) -> StatusCode {
|
||||||
|
tracing::error!("authorization lookup failed: {error}");
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Management actions are never delegated: anyone who is not a configured
|
||||||
|
/// administrator gets 403 without any lookup, so this also reveals nothing about resources.
|
||||||
|
pub(super) fn admin_only(state: &HubState, actor: &OperatorActor) -> Result<(), StatusCode> {
|
||||||
|
let allowed = actor.subject.admin;
|
||||||
|
audit(state, actor, AuditResource::Api, allowed)?;
|
||||||
|
if allowed { Ok(()) } else { Err(StatusCode::FORBIDDEN) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Use `permission` on one orbit. Not visible (no `orbit.read`) is 404, visible
|
||||||
|
/// but not permitted is 403. A permission that cannot be granted is admin-only.
|
||||||
|
pub(super) fn scoped(state: &HubState, actor: &OperatorActor, permission: Permission, orbit: Uuid) -> Result<(), StatusCode> {
|
||||||
|
let resource = AuditResource::Orbit(orbit);
|
||||||
|
if actor.subject.admin {
|
||||||
|
return audit(state, actor, resource, true);
|
||||||
|
}
|
||||||
|
let held = |permission: Permission| -> Result<bool, StatusCode> {
|
||||||
|
permission.grantable().then(|| {
|
||||||
|
state
|
||||||
|
.db
|
||||||
|
.has_permission(actor.subject.user_id.as_deref(), &actor.subject.groups, permission.as_str(), &orbit.to_string(), now())
|
||||||
|
.map_err(internal)
|
||||||
|
})
|
||||||
|
.unwrap_or(Ok(false))
|
||||||
|
};
|
||||||
|
if !held(Permission::OrbitRead)? {
|
||||||
|
audit(state, actor, resource, false)?;
|
||||||
|
return Err(StatusCode::NOT_FOUND);
|
||||||
|
}
|
||||||
|
let allowed = held(permission)?;
|
||||||
|
audit(state, actor, resource, allowed)?;
|
||||||
|
if allowed { Ok(()) } else { Err(StatusCode::FORBIDDEN) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Which orbits a list may show.
|
||||||
|
pub(super) enum Visible {
|
||||||
|
All,
|
||||||
|
Only(HashSet<Uuid>),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Visible {
|
||||||
|
pub(super) fn contains(&self, orbit: Uuid) -> bool {
|
||||||
|
match self {
|
||||||
|
Self::All => true,
|
||||||
|
Self::Only(set) => set.contains(&orbit),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// SQL-friendly form: `None` = no restriction.
|
||||||
|
pub(super) fn restriction(&self) -> Option<Vec<String>> {
|
||||||
|
match self {
|
||||||
|
Self::All => None,
|
||||||
|
Self::Only(set) => Some(set.iter().map(Uuid::to_string).collect()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Orbits where the caller holds both `orbit.read` and `permission`. A caller
|
||||||
|
/// with nothing to see gets 403 rather than an empty list.
|
||||||
|
pub(super) fn visible(state: &HubState, actor: &OperatorActor, permission: Permission) -> Result<Visible, StatusCode> {
|
||||||
|
if actor.subject.admin {
|
||||||
|
audit(state, actor, AuditResource::Api, true)?;
|
||||||
|
return Ok(Visible::All);
|
||||||
|
}
|
||||||
|
let fetch = |permission: Permission| {
|
||||||
|
if !permission.grantable() {
|
||||||
|
return Ok(Default::default());
|
||||||
|
}
|
||||||
|
state
|
||||||
|
.db
|
||||||
|
.permitted_orbits(actor.subject.user_id.as_deref(), &actor.subject.groups, permission.as_str(), now())
|
||||||
|
.map_err(internal)
|
||||||
|
};
|
||||||
|
let read = fetch(Permission::OrbitRead)?;
|
||||||
|
let wanted = if permission == Permission::OrbitRead { None } else { Some(fetch(permission)?) };
|
||||||
|
let parse = |set: &HashSet<String>| -> HashSet<Uuid> { set.iter().filter_map(|id| Uuid::parse_str(id).ok()).collect() };
|
||||||
|
let result = match wanted {
|
||||||
|
None if read.everywhere => Visible::All,
|
||||||
|
None => Visible::Only(parse(&read.orbits)),
|
||||||
|
Some(w) => match (read.everywhere, w.everywhere) {
|
||||||
|
(true, true) => Visible::All,
|
||||||
|
(true, false) => Visible::Only(parse(&w.orbits)),
|
||||||
|
(false, true) => Visible::Only(parse(&read.orbits)),
|
||||||
|
(false, false) => Visible::Only(parse(&read.orbits).intersection(&parse(&w.orbits)).copied().collect()),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
let nothing = matches!(&result, Visible::Only(set) if set.is_empty());
|
||||||
|
audit(state, actor, AuditResource::Api, !nothing)?;
|
||||||
|
if nothing { Err(StatusCode::FORBIDDEN) } else { Ok(result) }
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
use super::routes::{require_admin, require_admin_mutation, upload_token};
|
use super::routes::{admin_write, authenticate, upload_token};
|
||||||
|
use crate::auth::Permission;
|
||||||
use crate::state::HubState;
|
use crate::state::HubState;
|
||||||
use axum::{
|
use axum::{
|
||||||
body::{Body, HttpBody},
|
body::{Body, HttpBody},
|
||||||
@@ -38,8 +39,10 @@ async fn profiles(
|
|||||||
State(state): State<HubState>,
|
State(state): State<HubState>,
|
||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
) -> Result<Json<Vec<CaptureProfile>>, StatusCode> {
|
) -> Result<Json<Vec<CaptureProfile>>, StatusCode> {
|
||||||
require_admin(&state, peer, &headers)?;
|
let actor = authenticate(&state, peer, &headers, false)?;
|
||||||
state.db.capture_profiles().map(Json).map_err(internal)
|
let visible = super::gate::visible(&state, &actor, Permission::OrbitRead)?;
|
||||||
|
let profiles = state.db.capture_profiles().map_err(internal)?;
|
||||||
|
Ok(Json(profiles.into_iter().filter(|profile| visible.contains(profile.orbit_id)).collect()))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn register_profile(
|
async fn register_profile(
|
||||||
@@ -48,7 +51,7 @@ async fn register_profile(
|
|||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
Json(profile): Json<CaptureProfile>,
|
Json(profile): Json<CaptureProfile>,
|
||||||
) -> Result<(StatusCode, Json<CaptureProfile>), StatusCode> {
|
) -> Result<(StatusCode, Json<CaptureProfile>), StatusCode> {
|
||||||
let actor = require_admin_mutation(&state, peer, &headers)?;
|
let actor = admin_write(&state, peer, &headers)?;
|
||||||
if profile
|
if profile
|
||||||
.retention
|
.retention
|
||||||
.is_some_and(|retention| !retention.is_valid())
|
.is_some_and(|retention| !retention.is_valid())
|
||||||
@@ -83,10 +86,19 @@ async fn enqueue(
|
|||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
Path(id): Path<Uuid>,
|
Path(id): Path<Uuid>,
|
||||||
) -> Result<(StatusCode, Json<CaptureJob>), StatusCode> {
|
) -> Result<(StatusCode, Json<CaptureJob>), StatusCode> {
|
||||||
let actor = require_admin_mutation(&state, peer, &headers)?;
|
let actor = authenticate(&state, peer, &headers, true)?;
|
||||||
|
let orbit = state.db.orbit_of_application(id).map_err(internal)?;
|
||||||
|
match orbit {
|
||||||
|
Some(orbit) => super::gate::scoped(&state, &actor, Permission::CaptureRun, orbit)?,
|
||||||
|
// no such application: administrators learn that, everyone else cannot tell it from "not visible"
|
||||||
|
None => {
|
||||||
|
super::gate::admin_only(&state, &actor).map_err(|_| StatusCode::NOT_FOUND)?;
|
||||||
|
return Err(StatusCode::NOT_FOUND);
|
||||||
|
}
|
||||||
|
}
|
||||||
let job = state
|
let job = state
|
||||||
.db
|
.db
|
||||||
.enqueue_capture(id, &actor.name, now())
|
.enqueue_capture(id, &actor.id(), now())
|
||||||
.map_err(internal)?
|
.map_err(internal)?
|
||||||
.ok_or(StatusCode::NOT_FOUND)?;
|
.ok_or(StatusCode::NOT_FOUND)?;
|
||||||
Ok((StatusCode::ACCEPTED, Json(job)))
|
Ok((StatusCode::ACCEPTED, Json(job)))
|
||||||
@@ -105,7 +117,14 @@ async fn history(
|
|||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
Query(filter): Query<JobFilter>,
|
Query(filter): Query<JobFilter>,
|
||||||
) -> Result<Json<Vec<CaptureJob>>, StatusCode> {
|
) -> Result<Json<Vec<CaptureJob>>, StatusCode> {
|
||||||
require_admin(&state, peer, &headers)?;
|
let actor = authenticate(&state, peer, &headers, false)?;
|
||||||
|
let visible = super::gate::visible(&state, &actor, Permission::OrbitRead)?;
|
||||||
|
if let Some(application) = filter.application_id {
|
||||||
|
let orbit = state.db.orbit_of_application(application).map_err(internal)?;
|
||||||
|
if !orbit.is_some_and(|orbit| visible.contains(orbit)) {
|
||||||
|
return Err(StatusCode::NOT_FOUND);
|
||||||
|
}
|
||||||
|
}
|
||||||
if filter
|
if filter
|
||||||
.status
|
.status
|
||||||
.as_deref()
|
.as_deref()
|
||||||
@@ -119,24 +138,36 @@ async fn history(
|
|||||||
filter.application_id,
|
filter.application_id,
|
||||||
filter.status.as_deref(),
|
filter.status.as_deref(),
|
||||||
filter.limit.unwrap_or(50).clamp(1, 200),
|
filter.limit.unwrap_or(50).clamp(1, 200),
|
||||||
|
visible.restriction().as_deref(),
|
||||||
)
|
)
|
||||||
.map(Json)
|
.map(Json)
|
||||||
.map_err(internal)
|
.map_err(internal)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A capture job, if the caller may read its orbit; otherwise 404.
|
||||||
|
fn job_in_scope(state: &HubState, actor: &super::routes::OperatorActor, id: Uuid) -> Result<CaptureJob, StatusCode> {
|
||||||
|
let job = state.db.capture_job(id).map_err(internal)?;
|
||||||
|
match job {
|
||||||
|
Some(job) => {
|
||||||
|
super::gate::scoped(state, actor, Permission::OrbitRead, job.profile.orbit_id)?;
|
||||||
|
Ok(job)
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
super::gate::admin_only(state, actor).map_err(|_| StatusCode::NOT_FOUND)?;
|
||||||
|
Err(StatusCode::NOT_FOUND)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async fn events(
|
async fn events(
|
||||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||||
State(state): State<HubState>,
|
State(state): State<HubState>,
|
||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
Path(id): Path<Uuid>,
|
Path(id): Path<Uuid>,
|
||||||
) -> Result<Json<Vec<CaptureEvent>>, StatusCode> {
|
) -> Result<Json<Vec<CaptureEvent>>, StatusCode> {
|
||||||
require_admin(&state, peer, &headers)?;
|
let actor = authenticate(&state, peer, &headers, false)?;
|
||||||
state
|
let job = job_in_scope(&state, &actor, id)?;
|
||||||
.db
|
state.db.capture_events(job.id).map(Json).map_err(internal)
|
||||||
.capture_job(id)
|
|
||||||
.map_err(internal)?
|
|
||||||
.ok_or(StatusCode::NOT_FOUND)?;
|
|
||||||
state.db.capture_events(id).map(Json).map_err(internal)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn job(
|
async fn job(
|
||||||
@@ -145,13 +176,8 @@ async fn job(
|
|||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
Path(id): Path<Uuid>,
|
Path(id): Path<Uuid>,
|
||||||
) -> Result<Json<CaptureJob>, StatusCode> {
|
) -> Result<Json<CaptureJob>, StatusCode> {
|
||||||
require_admin(&state, peer, &headers)?;
|
let actor = authenticate(&state, peer, &headers, false)?;
|
||||||
state
|
job_in_scope(&state, &actor, id).map(Json)
|
||||||
.db
|
|
||||||
.capture_job(id)
|
|
||||||
.map_err(internal)?
|
|
||||||
.map(Json)
|
|
||||||
.ok_or(StatusCode::NOT_FOUND)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn claim(
|
async fn claim(
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
|
mod access;
|
||||||
mod catalog;
|
mod catalog;
|
||||||
|
mod gate;
|
||||||
mod jobs;
|
mod jobs;
|
||||||
mod oidc;
|
mod oidc;
|
||||||
mod orbit;
|
mod orbit;
|
||||||
@@ -11,6 +13,8 @@ mod auth_contract;
|
|||||||
mod oidc_tests;
|
mod oidc_tests;
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod credentials_tests;
|
mod credentials_tests;
|
||||||
|
#[cfg(test)]
|
||||||
|
mod access_tests;
|
||||||
|
|
||||||
pub use orbit::run_orbit_internal;
|
pub use orbit::run_orbit_internal;
|
||||||
pub use routes::router;
|
pub use routes::router;
|
||||||
|
|||||||
@@ -147,12 +147,14 @@ async fn complete(
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
let admin = oidc.config.is_admin(&identity);
|
let admin = oidc.config.is_admin(&identity);
|
||||||
|
// Bounded, so a hostile or huge claim cannot bloat the session row.
|
||||||
|
let groups: Vec<String> = identity.groups.iter().filter(|g| !g.is_empty() && g.len() <= 128).take(64).cloned().collect();
|
||||||
let now = now();
|
let now = now();
|
||||||
let session = state
|
let session = state
|
||||||
.db
|
.db
|
||||||
.upsert_user(&identity.issuer, &identity.subject, &identity.display_name, now)
|
.upsert_user(&identity.issuer, &identity.subject, &identity.display_name, now)
|
||||||
.map_err(anyhow::Error::from)
|
.map_err(anyhow::Error::from)
|
||||||
.and_then(|user_id| state.sessions.create_oidc(&user_id, &identity.display_name, admin, now));
|
.and_then(|user_id| state.sessions.create_oidc(&user_id, &identity.display_name, admin, &groups, now));
|
||||||
match session {
|
match session {
|
||||||
Ok(session) => {
|
Ok(session) => {
|
||||||
audit(&session.principal(), AuditOutcome::Succeeded);
|
audit(&session.principal(), AuditOutcome::Succeeded);
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use super::{
|
use super::{
|
||||||
jobs::{header_value, internal, now, outpost, receive_payload},
|
jobs::{header_value, internal, now, outpost, receive_payload},
|
||||||
routes::{require_admin, require_admin_mutation},
|
routes::{admin_read, admin_write},
|
||||||
};
|
};
|
||||||
use crate::state::HubState;
|
use crate::state::HubState;
|
||||||
use axum::{
|
use axum::{
|
||||||
@@ -46,7 +46,7 @@ async fn register(
|
|||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
Json(target): Json<RestoreTarget>,
|
Json(target): Json<RestoreTarget>,
|
||||||
) -> Result<(StatusCode, Json<RestoreTarget>), StatusCode> {
|
) -> Result<(StatusCode, Json<RestoreTarget>), StatusCode> {
|
||||||
let actor = require_admin_mutation(&state, peer, &headers)?;
|
let actor = admin_write(&state, peer, &headers)?;
|
||||||
if target.name.trim().is_empty()
|
if target.name.trim().is_empty()
|
||||||
|| target.name.len() > 128
|
|| target.name.len() > 128
|
||||||
|| target.name.chars().any(char::is_control)
|
|| target.name.chars().any(char::is_control)
|
||||||
@@ -84,7 +84,7 @@ async fn targets(
|
|||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
Path(application): Path<Uuid>,
|
Path(application): Path<Uuid>,
|
||||||
) -> Result<Json<Vec<RestoreTarget>>, StatusCode> {
|
) -> Result<Json<Vec<RestoreTarget>>, StatusCode> {
|
||||||
require_admin(&state, peer, &headers)?;
|
admin_read(&state, peer, &headers)?;
|
||||||
state
|
state
|
||||||
.db
|
.db
|
||||||
.restore_targets(application)
|
.restore_targets(application)
|
||||||
@@ -105,7 +105,7 @@ async fn snapshot_targets(
|
|||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
Path(snapshot): Path<Uuid>,
|
Path(snapshot): Path<Uuid>,
|
||||||
) -> Result<Json<Vec<SnapshotTarget>>, StatusCode> {
|
) -> Result<Json<Vec<SnapshotTarget>>, StatusCode> {
|
||||||
require_admin(&state, peer, &headers)?;
|
admin_read(&state, peer, &headers)?;
|
||||||
let vault = state.vault.read().await;
|
let vault = state.vault.read().await;
|
||||||
let snap = vault
|
let snap = vault
|
||||||
.get_snapshot(snapshot)
|
.get_snapshot(snapshot)
|
||||||
@@ -137,7 +137,7 @@ async fn enqueue(
|
|||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
Json(request): Json<RestoreRequest>,
|
Json(request): Json<RestoreRequest>,
|
||||||
) -> Result<(StatusCode, Json<RestoreJob>), StatusCode> {
|
) -> Result<(StatusCode, Json<RestoreJob>), StatusCode> {
|
||||||
let actor = require_admin_mutation(&state, peer, &headers)?;
|
let actor = admin_write(&state, peer, &headers)?;
|
||||||
if request.confirmation != RestoreRequest::confirmation(request.snapshot_id, request.target_id)
|
if request.confirmation != RestoreRequest::confirmation(request.snapshot_id, request.target_id)
|
||||||
{
|
{
|
||||||
return Err(StatusCode::BAD_REQUEST);
|
return Err(StatusCode::BAD_REQUEST);
|
||||||
@@ -156,7 +156,7 @@ async fn enqueue(
|
|||||||
request.snapshot_id,
|
request.snapshot_id,
|
||||||
application,
|
application,
|
||||||
request.target_id,
|
request.target_id,
|
||||||
&actor.name,
|
&actor.id(),
|
||||||
&artifact,
|
&artifact,
|
||||||
now(),
|
now(),
|
||||||
)
|
)
|
||||||
@@ -199,7 +199,7 @@ async fn job(
|
|||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
Path(id): Path<Uuid>,
|
Path(id): Path<Uuid>,
|
||||||
) -> Result<Json<RestoreJob>, StatusCode> {
|
) -> Result<Json<RestoreJob>, StatusCode> {
|
||||||
require_admin(&state, peer, &headers)?;
|
admin_read(&state, peer, &headers)?;
|
||||||
state
|
state
|
||||||
.db
|
.db
|
||||||
.restore_job(id, now())
|
.restore_job(id, now())
|
||||||
@@ -214,7 +214,7 @@ async fn history(
|
|||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
Path(snapshot): Path<Uuid>,
|
Path(snapshot): Path<Uuid>,
|
||||||
) -> Result<Json<Vec<RestoreJob>>, StatusCode> {
|
) -> Result<Json<Vec<RestoreJob>>, StatusCode> {
|
||||||
require_admin(&state, peer, &headers)?;
|
admin_read(&state, peer, &headers)?;
|
||||||
state
|
state
|
||||||
.db
|
.db
|
||||||
.restore_history(snapshot, now())
|
.restore_history(snapshot, now())
|
||||||
@@ -234,7 +234,7 @@ async fn recent(
|
|||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
Query(query): Query<Recent>,
|
Query(query): Query<Recent>,
|
||||||
) -> Result<Json<Vec<RestoreJob>>, StatusCode> {
|
) -> Result<Json<Vec<RestoreJob>>, StatusCode> {
|
||||||
require_admin(&state, peer, &headers)?;
|
admin_read(&state, peer, &headers)?;
|
||||||
state
|
state
|
||||||
.db
|
.db
|
||||||
.restore_recent(query.limit.unwrap_or(50).clamp(1, 200), now())
|
.restore_recent(query.limit.unwrap_or(50).clamp(1, 200), now())
|
||||||
@@ -248,10 +248,10 @@ async fn cancel(
|
|||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
Path(id): Path<Uuid>,
|
Path(id): Path<Uuid>,
|
||||||
) -> Result<StatusCode, StatusCode> {
|
) -> Result<StatusCode, StatusCode> {
|
||||||
let actor = require_admin_mutation(&state, peer, &headers)?;
|
let actor = admin_write(&state, peer, &headers)?;
|
||||||
if !state
|
if !state
|
||||||
.db
|
.db
|
||||||
.cancel_restore(id, &actor.name, now())
|
.cancel_restore(id, &actor.id(), now())
|
||||||
.map_err(internal)?
|
.map_err(internal)?
|
||||||
{
|
{
|
||||||
return Err(StatusCode::CONFLICT);
|
return Err(StatusCode::CONFLICT);
|
||||||
@@ -271,13 +271,13 @@ async fn reconcile(
|
|||||||
Path(id): Path<Uuid>,
|
Path(id): Path<Uuid>,
|
||||||
Json(body): Json<Reconcile>,
|
Json(body): Json<Reconcile>,
|
||||||
) -> Result<StatusCode, StatusCode> {
|
) -> Result<StatusCode, StatusCode> {
|
||||||
let actor = require_admin_mutation(&state, peer, &headers)?;
|
let actor = admin_write(&state, peer, &headers)?;
|
||||||
if body.confirmation != format!("RECONCILE {id}") {
|
if body.confirmation != format!("RECONCILE {id}") {
|
||||||
return Err(StatusCode::BAD_REQUEST);
|
return Err(StatusCode::BAD_REQUEST);
|
||||||
}
|
}
|
||||||
if !state
|
if !state
|
||||||
.db
|
.db
|
||||||
.reconcile_restore(id, &actor.name, now())
|
.reconcile_restore(id, &actor.id(), now())
|
||||||
.map_err(internal)?
|
.map_err(internal)?
|
||||||
{
|
{
|
||||||
return Err(StatusCode::CONFLICT);
|
return Err(StatusCode::CONFLICT);
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use crate::db::OrbitRow;
|
use crate::db::OrbitRow;
|
||||||
use crate::auth::{AuditAction, AuditOutcome, AuditResource, Principal};
|
use crate::auth::{AuditAction, AuditOutcome, AuditResource, Permission, Principal, Subject};
|
||||||
use crate::state::{HubState, ManagedRetention};
|
use crate::state::{HubState, ManagedRetention};
|
||||||
use crate::upload::write_at;
|
use crate::upload::write_at;
|
||||||
use axum::{
|
use axum::{
|
||||||
@@ -238,35 +238,32 @@ struct ReconstituteStartResponse {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(super) struct OperatorActor {
|
pub(super) struct OperatorActor {
|
||||||
|
/// Display only. Never record this as "who did it": an IdP can call a user anything.
|
||||||
pub(super) name: String,
|
pub(super) name: String,
|
||||||
browser: bool,
|
pub(super) browser: bool,
|
||||||
pub(super) principal: Principal,
|
pub(super) principal: Principal,
|
||||||
request_id: Uuid,
|
pub(super) subject: Subject,
|
||||||
|
pub(super) request_id: Uuid,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OperatorActor {
|
||||||
|
/// Stable identity for job attribution and audit details (`oidc:<users.id>`, ...).
|
||||||
|
pub(super) fn id(&self) -> String {
|
||||||
|
self.principal.fields().0
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::fmt::Display for OperatorActor {
|
impl std::fmt::Display for OperatorActor {
|
||||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
self.name.fmt(formatter)
|
self.id().fmt(formatter)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn require_admin(
|
/// Who is calling, and nothing more: no permission is checked here. A request
|
||||||
state: &HubState,
|
/// with no or a wrong credential is 401, a mutation without CSRF is 403. Every
|
||||||
peer: SocketAddr,
|
/// handler must then choose a gate from `gate.rs` (`admin_only`, `scoped`,
|
||||||
headers: &HeaderMap,
|
/// `visible`); there is deliberately no "signed in is enough" path.
|
||||||
) -> Result<(), StatusCode> {
|
pub(super) fn authenticate(
|
||||||
authorize_operator(state, peer, headers, false).map(|_| ())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn require_admin_mutation(
|
|
||||||
state: &HubState,
|
|
||||||
peer: SocketAddr,
|
|
||||||
headers: &HeaderMap,
|
|
||||||
) -> Result<OperatorActor, StatusCode> {
|
|
||||||
authorize_operator(state, peer, headers, true)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn authorize_operator(
|
|
||||||
state: &HubState,
|
state: &HubState,
|
||||||
peer: SocketAddr,
|
peer: SocketAddr,
|
||||||
headers: &HeaderMap,
|
headers: &HeaderMap,
|
||||||
@@ -275,43 +272,53 @@ pub(super) fn authorize_operator(
|
|||||||
let request_id = Uuid::new_v4();
|
let request_id = Uuid::new_v4();
|
||||||
// Resolve the session once: each lookup is a DB query and may slide the idle window.
|
// Resolve the session once: each lookup is a DB query and may slide the idle window.
|
||||||
let session = state.sessions.active(headers);
|
let session = state.sessions.active(headers);
|
||||||
let attempted_actor = session.as_ref()
|
let attempted = session.as_ref().map(|s| s.principal()).unwrap_or(Principal::Anonymous);
|
||||||
.map(|session| session.principal()).unwrap_or(Principal::Anonymous);
|
let result = authenticate_inner(state, peer, headers, mutation, request_id, session);
|
||||||
let result = authorize_operator_inner(state, peer, headers, mutation, request_id, session);
|
if result.is_err() {
|
||||||
let actor = result.as_ref().map(|actor| &actor.principal).unwrap_or(&attempted_actor);
|
state.db.audit_event(&attempted, AuditAction::Authentication, AuditResource::Api, AuditOutcome::Denied, request_id)
|
||||||
state.db.audit_event(actor, AuditAction::Authorization, AuditResource::Api,
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
if result.is_ok() { AuditOutcome::Allowed } else { AuditOutcome::Denied }, request_id)
|
}
|
||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
fn authorize_operator_inner(
|
fn authenticate_inner(
|
||||||
state: &HubState, peer: SocketAddr, headers: &HeaderMap, mutation: bool, request_id: Uuid,
|
state: &HubState, peer: SocketAddr, headers: &HeaderMap, mutation: bool, request_id: Uuid,
|
||||||
session: Option<crate::admin::BrowserSession>,
|
session: Option<crate::admin::BrowserSession>,
|
||||||
) -> Result<OperatorActor, StatusCode> {
|
) -> Result<OperatorActor, StatusCode> {
|
||||||
|
let configured_admin = |name: &str, principal: Principal| OperatorActor {
|
||||||
|
name: name.into(), browser: false, principal,
|
||||||
|
subject: Subject { user_id: None, groups: vec![], admin: true }, request_id,
|
||||||
|
};
|
||||||
if state.admin.token.is_some() && state.admin.authorize(peer, headers).is_ok() {
|
if state.admin.token.is_some() && state.admin.authorize(peer, headers).is_ok() {
|
||||||
return Ok(OperatorActor { name: "api-token".into(), browser: false,
|
return Ok(configured_admin("api-token", Principal::Service("legacy-admin-token")));
|
||||||
principal: Principal::Service("legacy-admin-token"), request_id });
|
|
||||||
}
|
}
|
||||||
if let Some(session) = session {
|
if let Some(session) = session {
|
||||||
// Signed in is not the same as allowed: a user without a grant gets 403.
|
|
||||||
if !session.admin {
|
|
||||||
return Err(StatusCode::FORBIDDEN);
|
|
||||||
}
|
|
||||||
if mutation {
|
if mutation {
|
||||||
super::session::require_csrf(headers, &session.csrf.to_string())?;
|
super::session::require_csrf(headers, &session.csrf.to_string())?;
|
||||||
}
|
}
|
||||||
return Ok(OperatorActor { principal: session.principal(),
|
return Ok(OperatorActor { principal: session.principal(), subject: session.subject(),
|
||||||
name: session.actor, browser: true, request_id });
|
name: session.actor, browser: true, request_id });
|
||||||
}
|
}
|
||||||
if !state.sessions.enabled() {
|
if !state.sessions.enabled() {
|
||||||
state.admin.authorize(peer, headers)?;
|
state.admin.authorize(peer, headers)?;
|
||||||
return Ok(OperatorActor { name: "local-development".into(), browser: false,
|
return Ok(configured_admin("local-development", Principal::LocalDevelopment));
|
||||||
principal: Principal::LocalDevelopment, request_id });
|
|
||||||
}
|
}
|
||||||
Err(StatusCode::UNAUTHORIZED)
|
Err(StatusCode::UNAUTHORIZED)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Management endpoints that only a configured administrator may use.
|
||||||
|
pub(super) fn admin_read(state: &HubState, peer: SocketAddr, headers: &HeaderMap) -> Result<OperatorActor, StatusCode> {
|
||||||
|
let actor = authenticate(state, peer, headers, false)?;
|
||||||
|
super::gate::admin_only(state, &actor)?;
|
||||||
|
Ok(actor)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn admin_write(state: &HubState, peer: SocketAddr, headers: &HeaderMap) -> Result<OperatorActor, StatusCode> {
|
||||||
|
let actor = authenticate(state, peer, headers, true)?;
|
||||||
|
super::gate::admin_only(state, &actor)?;
|
||||||
|
Ok(actor)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn router(state: HubState) -> Router {
|
pub fn router(state: HubState) -> Router {
|
||||||
let api = Router::new()
|
let api = Router::new()
|
||||||
.route("/health", get(health))
|
.route("/health", get(health))
|
||||||
@@ -340,6 +347,7 @@ pub fn router(state: HubState) -> Router {
|
|||||||
.merge(super::catalog::routes())
|
.merge(super::catalog::routes())
|
||||||
.merge(super::session::routes())
|
.merge(super::session::routes())
|
||||||
.merge(super::oidc::routes())
|
.merge(super::oidc::routes())
|
||||||
|
.merge(super::access::routes())
|
||||||
.merge(super::restore::routes())
|
.merge(super::restore::routes())
|
||||||
.with_state(state);
|
.with_state(state);
|
||||||
|
|
||||||
@@ -363,12 +371,14 @@ async fn list_snapshots(
|
|||||||
State(state): State<HubState>,
|
State(state): State<HubState>,
|
||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
) -> Result<Json<Vec<SnapshotSummary>>, StatusCode> {
|
) -> Result<Json<Vec<SnapshotSummary>>, StatusCode> {
|
||||||
require_admin(&state, peer, &headers)?;
|
let actor = authenticate(&state, peer, &headers, false)?;
|
||||||
|
let visible = super::gate::visible(&state, &actor, Permission::SnapshotRead)?;
|
||||||
let vault = state.vault.read().await;
|
let vault = state.vault.read().await;
|
||||||
let snaps = vault.list_snapshots().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
let snaps = vault.list_snapshots().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
let out = snaps
|
let out = snaps
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter(|s| s.manifest.provider != "legacy-history")
|
.filter(|s| s.manifest.provider != "legacy-history")
|
||||||
|
.filter(|s| visible.contains(s.manifest.orbit_id))
|
||||||
.map(|s| SnapshotSummary {
|
.map(|s| SnapshotSummary {
|
||||||
id: s.id,
|
id: s.id,
|
||||||
orbit_id: s.manifest.orbit_id,
|
orbit_id: s.manifest.orbit_id,
|
||||||
@@ -389,7 +399,8 @@ async fn list_orbits(
|
|||||||
State(state): State<HubState>,
|
State(state): State<HubState>,
|
||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
) -> Result<Json<Vec<OrbitResponse>>, StatusCode> {
|
) -> Result<Json<Vec<OrbitResponse>>, StatusCode> {
|
||||||
require_admin(&state, peer, &headers)?;
|
let actor = authenticate(&state, peer, &headers, false)?;
|
||||||
|
let visible = super::gate::visible(&state, &actor, Permission::OrbitRead)?;
|
||||||
let profiles: std::collections::HashMap<_, _> = state
|
let profiles: std::collections::HashMap<_, _> = state
|
||||||
.db
|
.db
|
||||||
.capture_profiles()
|
.capture_profiles()
|
||||||
@@ -400,6 +411,7 @@ async fn list_orbits(
|
|||||||
let rows = state.db.list_orbits().await.map_err(super::jobs::internal)?;
|
let rows = state.db.list_orbits().await.map_err(super::jobs::internal)?;
|
||||||
let responses = rows
|
let responses = rows
|
||||||
.into_iter()
|
.into_iter()
|
||||||
|
.filter(|row| visible.contains(row.id))
|
||||||
.map(|row| {
|
.map(|row| {
|
||||||
let mut response = OrbitResponse::from(row);
|
let mut response = OrbitResponse::from(row);
|
||||||
if let Some(profile) = profiles.get(&response.id) {
|
if let Some(profile) = profiles.get(&response.id) {
|
||||||
@@ -430,7 +442,7 @@ async fn create_orbit(
|
|||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
Json(req): Json<CreateOrbitRequest>,
|
Json(req): Json<CreateOrbitRequest>,
|
||||||
) -> Result<Json<OrbitResponse>, (StatusCode, &'static str)> {
|
) -> Result<Json<OrbitResponse>, (StatusCode, &'static str)> {
|
||||||
require_admin_mutation(&state, peer, &headers).map_err(|status| (status, "unauthorized"))?;
|
admin_write(&state, peer, &headers).map_err(|status| (status, "unauthorized"))?;
|
||||||
if req.name.trim().is_empty() {
|
if req.name.trim().is_empty() {
|
||||||
return Err((StatusCode::BAD_REQUEST, "orbit name is required"));
|
return Err((StatusCode::BAD_REQUEST, "orbit name is required"));
|
||||||
}
|
}
|
||||||
@@ -523,7 +535,7 @@ async fn update_orbit_retention(
|
|||||||
Path(id): Path<Uuid>,
|
Path(id): Path<Uuid>,
|
||||||
Json(req): Json<RetentionUpdate>,
|
Json(req): Json<RetentionUpdate>,
|
||||||
) -> Result<StatusCode, (StatusCode, &'static str)> {
|
) -> Result<StatusCode, (StatusCode, &'static str)> {
|
||||||
require_admin_mutation(&state, peer, &headers).map_err(|status| (status, "unauthorized"))?;
|
admin_write(&state, peer, &headers).map_err(|status| (status, "unauthorized"))?;
|
||||||
if req.decay_preset.is_none() && req.retention.is_none() {
|
if req.decay_preset.is_none() && req.retention.is_none() {
|
||||||
return Err((
|
return Err((
|
||||||
StatusCode::BAD_REQUEST,
|
StatusCode::BAD_REQUEST,
|
||||||
@@ -553,12 +565,14 @@ async fn trigger_orbit(
|
|||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
Path(id): Path<Uuid>,
|
Path(id): Path<Uuid>,
|
||||||
) -> Result<(StatusCode, HeaderMap), (StatusCode, String)> {
|
) -> Result<(StatusCode, HeaderMap), (StatusCode, String)> {
|
||||||
require_admin_mutation(&state, peer, &headers).map_err(|status| (status, "unauthorized".into()))?;
|
let actor = authenticate(&state, peer, &headers, true).map_err(|status| (status, "unauthorized".into()))?;
|
||||||
let orbit = state.db.list_orbits().await
|
let orbit = state.db.list_orbits().await
|
||||||
.map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "could not read orbits".into()))?
|
.map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "could not read orbits".into()))?
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.find(|orbit| orbit.id == id)
|
.find(|orbit| orbit.id == id);
|
||||||
.ok_or((StatusCode::NOT_FOUND, "orbit not found".into()))?;
|
// Gate on the id first: unknown and not-visible look the same to a caller without access.
|
||||||
|
super::gate::scoped(&state, &actor, Permission::CaptureRun, id).map_err(|status| (status, "not permitted".into()))?;
|
||||||
|
let orbit = orbit.ok_or((StatusCode::NOT_FOUND, "orbit not found".into()))?;
|
||||||
if orbit.provider == "wormhole" {
|
if orbit.provider == "wormhole" {
|
||||||
return Err((StatusCode::CONFLICT, "queue the capture through its Outpost profile or run the legacy agent".into()));
|
return Err((StatusCode::CONFLICT, "queue the capture through its Outpost profile or run the legacy agent".into()));
|
||||||
}
|
}
|
||||||
@@ -588,7 +602,7 @@ async fn start_reconstitute(
|
|||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
Json(req): Json<ReconstituteRequest>,
|
Json(req): Json<ReconstituteRequest>,
|
||||||
) -> Result<Json<ReconstituteStartResponse>, StatusCode> {
|
) -> Result<Json<ReconstituteStartResponse>, StatusCode> {
|
||||||
let actor = require_admin_mutation(&state, peer, &headers)?;
|
let actor = admin_write(&state, peer, &headers)?;
|
||||||
let destination = if actor.browser {
|
let destination = if actor.browser {
|
||||||
browser_export_path(&state, &req.target_path)?
|
browser_export_path(&state, &req.target_path)?
|
||||||
} else {
|
} else {
|
||||||
@@ -695,7 +709,7 @@ async fn reconstitute_status(
|
|||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
Path(id): Path<Uuid>,
|
Path(id): Path<Uuid>,
|
||||||
) -> Result<Json<ReconstituteSession>, StatusCode> {
|
) -> Result<Json<ReconstituteSession>, StatusCode> {
|
||||||
require_admin(&state, peer, &headers)?;
|
admin_read(&state, peer, &headers)?;
|
||||||
let map = state.reconstitute_sessions.read().await;
|
let map = state.reconstitute_sessions.read().await;
|
||||||
map.get(&id).cloned().map(Json).ok_or(StatusCode::NOT_FOUND)
|
map.get(&id).cloned().map(Json).ok_or(StatusCode::NOT_FOUND)
|
||||||
}
|
}
|
||||||
@@ -706,7 +720,7 @@ async fn abort_reconstitute(
|
|||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
Path(id): Path<Uuid>,
|
Path(id): Path<Uuid>,
|
||||||
) -> Result<StatusCode, StatusCode> {
|
) -> Result<StatusCode, StatusCode> {
|
||||||
require_admin_mutation(&state, peer, &headers)?;
|
admin_write(&state, peer, &headers)?;
|
||||||
let mut map = state.reconstitute_sessions.write().await;
|
let mut map = state.reconstitute_sessions.write().await;
|
||||||
if let Some(s) = map.get_mut(&id) {
|
if let Some(s) = map.get_mut(&id) {
|
||||||
if matches!(
|
if matches!(
|
||||||
@@ -725,7 +739,7 @@ async fn outposts(
|
|||||||
State(state): State<HubState>,
|
State(state): State<HubState>,
|
||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
) -> Result<Json<Vec<OutpostSummary>>, StatusCode> {
|
) -> Result<Json<Vec<OutpostSummary>>, StatusCode> {
|
||||||
require_admin(&state, peer, &headers)?;
|
admin_read(&state, peer, &headers)?;
|
||||||
state.db.list_outposts().map(Json).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
|
state.db.list_outposts().map(Json).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -735,7 +749,7 @@ async fn pairing_start(
|
|||||||
State(state): State<HubState>,
|
State(state): State<HubState>,
|
||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
) -> Result<Json<PairingResponse>, StatusCode> {
|
) -> Result<Json<PairingResponse>, StatusCode> {
|
||||||
require_admin_mutation(&state, peer, &headers)?;
|
admin_write(&state, peer, &headers)?;
|
||||||
const ALPHABET: &[u8] = b"23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
|
const ALPHABET: &[u8] = b"23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
|
||||||
let code: String = {
|
let code: String = {
|
||||||
let mut random = rand::thread_rng();
|
let mut random = rand::thread_rng();
|
||||||
@@ -832,7 +846,7 @@ async fn rotate_outpost_token(
|
|||||||
Path(id): Path<Uuid>,
|
Path(id): Path<Uuid>,
|
||||||
axum::extract::Query(query): axum::extract::Query<RotateQuery>,
|
axum::extract::Query(query): axum::extract::Query<RotateQuery>,
|
||||||
) -> Result<(HeaderMap, Json<RotateResponse>), StatusCode> {
|
) -> Result<(HeaderMap, Json<RotateResponse>), StatusCode> {
|
||||||
let actor = require_admin_mutation(&state, peer, &headers)?;
|
let actor = admin_write(&state, peer, &headers)?;
|
||||||
let grace = query.grace_minutes.unwrap_or(60);
|
let grace = query.grace_minutes.unwrap_or(60);
|
||||||
if !(0..=1440).contains(&grace) {
|
if !(0..=1440).contains(&grace) {
|
||||||
return Err(StatusCode::BAD_REQUEST);
|
return Err(StatusCode::BAD_REQUEST);
|
||||||
@@ -872,7 +886,7 @@ async fn revoke_outpost(
|
|||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
Path(id): Path<Uuid>,
|
Path(id): Path<Uuid>,
|
||||||
) -> Result<StatusCode, StatusCode> {
|
) -> Result<StatusCode, StatusCode> {
|
||||||
let actor = require_admin_mutation(&state, peer, &headers)?;
|
let actor = admin_write(&state, peer, &headers)?;
|
||||||
let known = state
|
let known = state
|
||||||
.db
|
.db
|
||||||
.revoke_outpost(&id.to_string(), chrono::Utc::now().timestamp())
|
.revoke_outpost(&id.to_string(), chrono::Utc::now().timestamp())
|
||||||
@@ -901,7 +915,7 @@ async fn bind_outpost(
|
|||||||
Path(orbit): Path<Uuid>,
|
Path(orbit): Path<Uuid>,
|
||||||
Json(binding): Json<OutpostBinding>,
|
Json(binding): Json<OutpostBinding>,
|
||||||
) -> Result<StatusCode, StatusCode> {
|
) -> Result<StatusCode, StatusCode> {
|
||||||
let actor = require_admin_mutation(&state, peer, &headers)?;
|
let actor = admin_write(&state, peer, &headers)?;
|
||||||
let _vault = state.vault.write().await;
|
let _vault = state.vault.write().await;
|
||||||
if !state.db.bind_legacy_outpost(orbit, binding.outpost_id)
|
if !state.db.bind_legacy_outpost(orbit, binding.outpost_id)
|
||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? {
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? {
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ struct Status {
|
|||||||
login_enabled: bool,
|
login_enabled: bool,
|
||||||
oidc_enabled: bool,
|
oidc_enabled: bool,
|
||||||
authorized: bool,
|
authorized: bool,
|
||||||
|
admin: bool,
|
||||||
actor: Option<String>,
|
actor: Option<String>,
|
||||||
csrf: Option<String>,
|
csrf: Option<String>,
|
||||||
expires_at: Option<i64>,
|
expires_at: Option<i64>,
|
||||||
@@ -31,6 +32,7 @@ pub(super) fn routes() -> Router<HubState> {
|
|||||||
.route("/api/v1/operator/session", get(status).delete(logout))
|
.route("/api/v1/operator/session", get(status).delete(logout))
|
||||||
.route("/api/v1/operator/login", post(login))
|
.route("/api/v1/operator/login", post(login))
|
||||||
.route("/api/v1/me", get(me))
|
.route("/api/v1/me", get(me))
|
||||||
|
.route("/api/v1/me/preferences", get(preferences).put(set_preferences))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn status(
|
async fn status(
|
||||||
@@ -39,7 +41,15 @@ async fn status(
|
|||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
) -> (HeaderMap, Json<Status>) {
|
) -> (HeaderMap, Json<Status>) {
|
||||||
let browser = state.sessions.active(&headers);
|
let browser = state.sessions.active(&headers);
|
||||||
let authorized = browser.as_ref().is_some_and(|session| session.admin)
|
// The app opens for an administrator or for anyone holding a live grant that lets them read an orbit.
|
||||||
|
let reads_something = browser.as_ref().is_some_and(|session| {
|
||||||
|
!session.admin
|
||||||
|
&& state
|
||||||
|
.db
|
||||||
|
.permitted_orbits(Some(&session.user_id), &session.groups, "orbit.read", chrono::Utc::now().timestamp())
|
||||||
|
.is_ok_and(|p| p.everywhere || !p.orbits.is_empty())
|
||||||
|
});
|
||||||
|
let authorized = browser.as_ref().is_some_and(|session| session.admin) || reads_something
|
||||||
|| (browser.is_none() && !state.sessions.enabled() && state.admin.token.is_none()
|
|| (browser.is_none() && !state.sessions.enabled() && state.admin.token.is_none()
|
||||||
&& state.admin.authorize(peer, &headers).is_ok());
|
&& state.admin.authorize(peer, &headers).is_ok());
|
||||||
(
|
(
|
||||||
@@ -48,6 +58,7 @@ async fn status(
|
|||||||
login_enabled: state.sessions.password_enabled(),
|
login_enabled: state.sessions.password_enabled(),
|
||||||
oidc_enabled: state.oidc.is_some(),
|
oidc_enabled: state.oidc.is_some(),
|
||||||
authorized,
|
authorized,
|
||||||
|
admin: browser.as_ref().map_or(authorized, |session| session.admin),
|
||||||
actor: browser.as_ref().map(|session| session.actor.clone()),
|
actor: browser.as_ref().map(|session| session.actor.clone()),
|
||||||
expires_at: browser.as_ref().map(|session| session.expires_at),
|
expires_at: browser.as_ref().map(|session| session.expires_at),
|
||||||
csrf: browser.map(|session| session.csrf.to_string()),
|
csrf: browser.map(|session| session.csrf.to_string()),
|
||||||
@@ -55,13 +66,22 @@ async fn status(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
struct MyGrant {
|
||||||
|
permission: String,
|
||||||
|
/// `None` = every orbit.
|
||||||
|
orbit_id: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
struct Me {
|
struct Me {
|
||||||
id: String,
|
id: String,
|
||||||
kind: &'static str,
|
kind: &'static str,
|
||||||
auth_method: &'static str,
|
auth_method: &'static str,
|
||||||
display_name: String,
|
display_name: String,
|
||||||
capabilities: Vec<&'static str>,
|
admin: bool,
|
||||||
|
capabilities: Vec<String>,
|
||||||
|
grants: Vec<MyGrant>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The caller's own identity. Every authenticated principal is an administrator
|
/// The caller's own identity. Every authenticated principal is an administrator
|
||||||
@@ -71,20 +91,81 @@ async fn me(
|
|||||||
State(state): State<HubState>,
|
State(state): State<HubState>,
|
||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
) -> Result<(HeaderMap, Json<Me>), StatusCode> {
|
) -> Result<(HeaderMap, Json<Me>), StatusCode> {
|
||||||
// A signed-in user without a grant still gets their identity (capabilities empty).
|
// Identity only, no gate: a signed-in user without any grant still gets this (empty grants).
|
||||||
if let Some(session) = state.sessions.active(&headers) {
|
let actor = super::routes::authenticate(&state, peer, &headers, false)?;
|
||||||
let (id, kind, auth_method) = session.principal().fields();
|
|
||||||
let capabilities = if session.admin { vec!["admin"] } else { vec![] };
|
|
||||||
return Ok((no_store(), Json(Me { id, kind, auth_method, display_name: session.actor, capabilities })));
|
|
||||||
}
|
|
||||||
let actor = super::routes::authorize_operator(&state, peer, &headers, false)?;
|
|
||||||
let (id, kind, auth_method) = actor.principal.fields();
|
let (id, kind, auth_method) = actor.principal.fields();
|
||||||
|
let grants: Vec<MyGrant> = if actor.subject.admin {
|
||||||
|
vec![]
|
||||||
|
} else {
|
||||||
|
state
|
||||||
|
.db
|
||||||
|
.grants_of(actor.subject.user_id.as_deref(), &actor.subject.groups, chrono::Utc::now().timestamp())
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||||
|
.into_iter()
|
||||||
|
.map(|(permission, orbit_id)| MyGrant { permission, orbit_id })
|
||||||
|
.collect()
|
||||||
|
};
|
||||||
|
let mut capabilities: Vec<String> = if actor.subject.admin {
|
||||||
|
vec!["admin".into()]
|
||||||
|
} else {
|
||||||
|
let mut names: Vec<String> = grants.iter().map(|g| g.permission.clone()).collect();
|
||||||
|
names.dedup();
|
||||||
|
names
|
||||||
|
};
|
||||||
|
capabilities.sort();
|
||||||
Ok((
|
Ok((
|
||||||
no_store(),
|
no_store(),
|
||||||
Json(Me { id, kind, auth_method, display_name: actor.name.clone(), capabilities: vec!["admin"] }),
|
Json(Me { id, kind, auth_method, display_name: actor.name.clone(), admin: actor.subject.admin, capabilities, grants }),
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Display choices an account keeps across browsers. Every key has a closed set of values.
|
||||||
|
const LOOKS: [&str; 2] = ["window", "radar"];
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
struct Preferences {
|
||||||
|
look: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The caller's own preferences. A caller without an account (the legacy token, local
|
||||||
|
/// development) simply has none.
|
||||||
|
async fn preferences(
|
||||||
|
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||||
|
State(state): State<HubState>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
) -> Result<(HeaderMap, Json<Preferences>), StatusCode> {
|
||||||
|
let actor = super::routes::authenticate(&state, peer, &headers, false)?;
|
||||||
|
let stored = match actor.subject.user_id.as_deref() {
|
||||||
|
Some(user) => state.db.preferences(user).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
|
||||||
|
None => Default::default(),
|
||||||
|
};
|
||||||
|
let look = stored.get("look").filter(|value| LOOKS.contains(&value.as_str())).cloned();
|
||||||
|
Ok((no_store(), Json(Preferences { look })))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct SetPreferences {
|
||||||
|
look: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn set_preferences(
|
||||||
|
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||||
|
State(state): State<HubState>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Json(body): Json<SetPreferences>,
|
||||||
|
) -> Result<StatusCode, StatusCode> {
|
||||||
|
let actor = super::routes::authenticate(&state, peer, &headers, true)?;
|
||||||
|
let user = actor.subject.user_id.as_deref().ok_or(StatusCode::NOT_FOUND)?;
|
||||||
|
if let Some(look) = body.look {
|
||||||
|
if !LOOKS.contains(&look.as_str()) {
|
||||||
|
return Err(StatusCode::BAD_REQUEST);
|
||||||
|
}
|
||||||
|
state.db.set_preference(user, "look", &look, chrono::Utc::now().timestamp()).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
|
}
|
||||||
|
Ok(StatusCode::NO_CONTENT)
|
||||||
|
}
|
||||||
|
|
||||||
async fn login(
|
async fn login(
|
||||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||||
State(state): State<HubState>,
|
State(state): State<HubState>,
|
||||||
@@ -133,6 +214,7 @@ async fn login(
|
|||||||
login_enabled: true,
|
login_enabled: true,
|
||||||
oidc_enabled: state.oidc.is_some(),
|
oidc_enabled: state.oidc.is_some(),
|
||||||
authorized: true,
|
authorized: true,
|
||||||
|
admin: true,
|
||||||
actor: Some(session.actor),
|
actor: Some(session.actor),
|
||||||
expires_at: Some(session.expires_at),
|
expires_at: Some(session.expires_at),
|
||||||
csrf: Some(session.csrf.to_string()),
|
csrf: Some(session.csrf.to_string()),
|
||||||
|
|||||||
@@ -34,6 +34,10 @@ pub enum AuditAction {
|
|||||||
OutpostPair,
|
OutpostPair,
|
||||||
CredentialRotate,
|
CredentialRotate,
|
||||||
CredentialRevoke,
|
CredentialRevoke,
|
||||||
|
GrantCreate,
|
||||||
|
GrantDelete,
|
||||||
|
UserState,
|
||||||
|
SessionsRevoke,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AuditAction {
|
impl AuditAction {
|
||||||
@@ -47,6 +51,10 @@ impl AuditAction {
|
|||||||
Self::OutpostPair => "outpost.pair",
|
Self::OutpostPair => "outpost.pair",
|
||||||
Self::CredentialRotate => "outpost.credential_rotate",
|
Self::CredentialRotate => "outpost.credential_rotate",
|
||||||
Self::CredentialRevoke => "outpost.credential_revoke",
|
Self::CredentialRevoke => "outpost.credential_revoke",
|
||||||
|
Self::GrantCreate => "access.grant_create",
|
||||||
|
Self::GrantDelete => "access.grant_delete",
|
||||||
|
Self::UserState => "access.user_state",
|
||||||
|
Self::SessionsRevoke => "access.sessions_revoke",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -75,6 +83,8 @@ pub enum AuditResource {
|
|||||||
Orbit(Uuid),
|
Orbit(Uuid),
|
||||||
Outpost(Uuid),
|
Outpost(Uuid),
|
||||||
UploadSession(Uuid),
|
UploadSession(Uuid),
|
||||||
|
Grant(Uuid),
|
||||||
|
User(Uuid),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AuditResource {
|
impl AuditResource {
|
||||||
@@ -85,6 +95,82 @@ impl AuditResource {
|
|||||||
Self::Orbit(id) => ("orbit", Some(id.to_string())),
|
Self::Orbit(id) => ("orbit", Some(id.to_string())),
|
||||||
Self::Outpost(id) => ("outpost", Some(id.to_string())),
|
Self::Outpost(id) => ("outpost", Some(id.to_string())),
|
||||||
Self::UploadSession(id) => ("upload_session", Some(id.to_string())),
|
Self::UploadSession(id) => ("upload_session", Some(id.to_string())),
|
||||||
|
Self::Grant(id) => ("grant", Some(id.to_string())),
|
||||||
|
Self::User(id) => ("user", Some(id.to_string())),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What a signed-in user may do. Only the first four can be granted to a
|
||||||
|
/// non-administrator; everything else belongs to the configured administrators
|
||||||
|
/// (SSO admin mapping, the emergency operator, the legacy admin token). Names are
|
||||||
|
/// matched exactly, never by prefix.
|
||||||
|
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub enum Permission {
|
||||||
|
OrbitRead,
|
||||||
|
SnapshotRead,
|
||||||
|
CaptureRun,
|
||||||
|
SnapshotDownload,
|
||||||
|
OrbitManage,
|
||||||
|
OutpostManage,
|
||||||
|
RetentionManage,
|
||||||
|
SnapshotDelete,
|
||||||
|
RecoveryManage,
|
||||||
|
AccessManage,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Permission {
|
||||||
|
pub fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::OrbitRead => "orbit.read",
|
||||||
|
Self::SnapshotRead => "snapshot.read",
|
||||||
|
Self::CaptureRun => "capture.run",
|
||||||
|
Self::SnapshotDownload => "snapshot.download",
|
||||||
|
Self::OrbitManage => "orbit.manage",
|
||||||
|
Self::OutpostManage => "outpost.manage",
|
||||||
|
Self::RetentionManage => "retention.manage",
|
||||||
|
Self::SnapshotDelete => "snapshot.delete",
|
||||||
|
Self::RecoveryManage => "recovery.manage",
|
||||||
|
Self::AccessManage => "access.manage",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.find(|permission| permission.as_str() == text)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// May be given to a non-administrator through a grant.
|
||||||
|
pub fn grantable(self) -> bool {
|
||||||
|
matches!(self, Self::OrbitRead | Self::SnapshotRead | Self::CaptureRun | Self::SnapshotDownload)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Named bundles that expand into individual grants. Every bundle includes
|
||||||
|
/// `orbit.read`: without it a resource is invisible and answers 404.
|
||||||
|
pub fn role(name: &str) -> Option<&'static [Permission]> {
|
||||||
|
use Permission::*;
|
||||||
|
match name {
|
||||||
|
"viewer" => Some(&[OrbitRead, SnapshotRead]),
|
||||||
|
"capturer" => Some(&[OrbitRead, SnapshotRead, CaptureRun]),
|
||||||
|
"downloader" => Some(&[OrbitRead, SnapshotRead, SnapshotDownload]),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const ROLE_NAMES: [&str; 3] = ["viewer", "capturer", "downloader"];
|
||||||
|
|
||||||
|
/// Who is asking, as far as authorization is concerned.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct Subject {
|
||||||
|
/// `users.id` for signed-in users; `None` for the legacy token and local development.
|
||||||
|
pub user_id: Option<String>,
|
||||||
|
/// Groups verified at sign-in. Changes at the IdP apply at the next sign-in.
|
||||||
|
pub groups: Vec<String>,
|
||||||
|
/// Configured administrator: holds every permission everywhere.
|
||||||
|
pub admin: bool,
|
||||||
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ mod audit;
|
|||||||
pub mod sessions;
|
pub mod sessions;
|
||||||
pub(crate) mod oidc_login;
|
pub(crate) mod oidc_login;
|
||||||
pub(crate) mod credentials;
|
pub(crate) mod credentials;
|
||||||
|
pub(crate) mod access;
|
||||||
pub(crate) use restore::restore_target_mismatch;
|
pub(crate) use restore::restore_target_mismatch;
|
||||||
|
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
@@ -97,6 +98,7 @@ impl Db {
|
|||||||
audit::migrate(&conn)?;
|
audit::migrate(&conn)?;
|
||||||
sessions::migrate(&conn)?;
|
sessions::migrate(&conn)?;
|
||||||
oidc_login::migrate(&conn)?;
|
oidc_login::migrate(&conn)?;
|
||||||
|
access::migrate(&conn)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
329
crates/tessera-hub/src/db/access.rs
Normal file
329
crates/tessera-hub/src/db/access.rs
Normal file
@@ -0,0 +1,329 @@
|
|||||||
|
//! Grants: which permission a user (or an IdP group) holds, globally or on one orbit.
|
||||||
|
//!
|
||||||
|
//! Grants are read live on every request, never cached, so a revoke or an expiry
|
||||||
|
//! is effective on the very next request. Anything stored that does not parse as a
|
||||||
|
//! known permission or scope is ignored by the gate.
|
||||||
|
use super::*;
|
||||||
|
use std::collections::HashSet;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, serde::Serialize)]
|
||||||
|
pub struct Grant {
|
||||||
|
pub id: String,
|
||||||
|
pub principal_type: String,
|
||||||
|
pub principal: String,
|
||||||
|
pub permission: String,
|
||||||
|
pub scope_type: String,
|
||||||
|
pub scope_id: Option<String>,
|
||||||
|
pub expires_at: Option<i64>,
|
||||||
|
pub created_by: String,
|
||||||
|
pub created_at: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct NewGrant<'a> {
|
||||||
|
pub principal_type: &'a str,
|
||||||
|
pub principal: &'a str,
|
||||||
|
pub permission: &'a str,
|
||||||
|
pub orbit: Option<&'a str>,
|
||||||
|
pub expires_at: Option<i64>,
|
||||||
|
pub created_by: &'a str,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Orbits a subject may use for one permission.
|
||||||
|
#[derive(Debug, Default, PartialEq, Eq)]
|
||||||
|
pub struct Permitted {
|
||||||
|
pub everywhere: bool,
|
||||||
|
pub orbits: HashSet<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, serde::Serialize)]
|
||||||
|
pub struct UserRow {
|
||||||
|
pub id: String,
|
||||||
|
pub issuer: String,
|
||||||
|
pub display_name: String,
|
||||||
|
pub active: bool,
|
||||||
|
pub created_at: i64,
|
||||||
|
pub last_login_at: Option<i64>,
|
||||||
|
pub is_emergency: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn migrate(conn: &Connection) -> Result<()> {
|
||||||
|
conn.execute_batch(
|
||||||
|
"CREATE TABLE IF NOT EXISTS access_grants (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
principal_type TEXT NOT NULL CHECK(principal_type IN ('user','group')),
|
||||||
|
principal TEXT NOT NULL,
|
||||||
|
permission TEXT NOT NULL,
|
||||||
|
scope_type TEXT NOT NULL CHECK(scope_type IN ('global','orbit')),
|
||||||
|
scope_id TEXT NOT NULL DEFAULT '',
|
||||||
|
expires_at INTEGER,
|
||||||
|
created_by TEXT NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
UNIQUE(principal_type, principal, permission, scope_type, scope_id)
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS access_grants_principal ON access_grants(principal_type, principal);
|
||||||
|
CREATE TABLE IF NOT EXISTS user_preferences (
|
||||||
|
user_id TEXT NOT NULL,
|
||||||
|
key TEXT NOT NULL,
|
||||||
|
value TEXT NOT NULL,
|
||||||
|
updated_at INTEGER NOT NULL,
|
||||||
|
PRIMARY KEY(user_id, key)
|
||||||
|
);",
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
const LIVE: &str = "(expires_at IS NULL OR expires_at > ?2)
|
||||||
|
AND ((principal_type='user' AND principal=?3) OR (principal_type='group' AND principal IN (SELECT value FROM json_each(?4))))";
|
||||||
|
|
||||||
|
fn groups_json(groups: &[String]) -> String {
|
||||||
|
serde_json::to_string(groups).unwrap_or_else(|_| "[]".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Db {
|
||||||
|
/// Insert one grant; `None` when an identical grant already exists.
|
||||||
|
pub fn add_grant(&self, grant: &NewGrant<'_>, now: i64) -> Result<Option<Grant>> {
|
||||||
|
let conn = self.conn.lock().unwrap();
|
||||||
|
let id = Uuid::new_v4().to_string();
|
||||||
|
let (scope_type, scope_id) = match grant.orbit {
|
||||||
|
Some(orbit) => ("orbit", orbit),
|
||||||
|
None => ("global", ""),
|
||||||
|
};
|
||||||
|
let inserted = conn.execute(
|
||||||
|
"INSERT OR IGNORE INTO access_grants(id,principal_type,principal,permission,scope_type,scope_id,expires_at,created_by,created_at)
|
||||||
|
VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9)",
|
||||||
|
params![id, grant.principal_type, grant.principal, grant.permission, scope_type, scope_id, grant.expires_at, grant.created_by, now],
|
||||||
|
)?;
|
||||||
|
Ok((inserted == 1).then(|| Grant {
|
||||||
|
id,
|
||||||
|
principal_type: grant.principal_type.into(),
|
||||||
|
principal: grant.principal.into(),
|
||||||
|
permission: grant.permission.into(),
|
||||||
|
scope_type: scope_type.into(),
|
||||||
|
scope_id: grant.orbit.map(str::to_string),
|
||||||
|
expires_at: grant.expires_at,
|
||||||
|
created_by: grant.created_by.into(),
|
||||||
|
created_at: now,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn delete_grant(&self, id: &str) -> Result<bool> {
|
||||||
|
Ok(self.conn.lock().unwrap().execute("DELETE FROM access_grants WHERE id=?1", params![id])? == 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn list_grants(&self) -> Result<Vec<Grant>> {
|
||||||
|
let conn = self.conn.lock().unwrap();
|
||||||
|
let mut stmt = conn.prepare(
|
||||||
|
"SELECT id,principal_type,principal,permission,scope_type,scope_id,expires_at,created_by,created_at
|
||||||
|
FROM access_grants ORDER BY principal_type, principal, scope_type, scope_id, permission",
|
||||||
|
)?;
|
||||||
|
let rows = stmt.query_map([], |r| {
|
||||||
|
let scope_type: String = r.get(4)?;
|
||||||
|
let scope_id: String = r.get(5)?;
|
||||||
|
Ok(Grant {
|
||||||
|
id: r.get(0)?,
|
||||||
|
principal_type: r.get(1)?,
|
||||||
|
principal: r.get(2)?,
|
||||||
|
permission: r.get(3)?,
|
||||||
|
scope_id: (scope_type == "orbit").then_some(scope_id),
|
||||||
|
scope_type,
|
||||||
|
expires_at: r.get(6)?,
|
||||||
|
created_by: r.get(7)?,
|
||||||
|
created_at: r.get(8)?,
|
||||||
|
})
|
||||||
|
})?;
|
||||||
|
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Does the subject hold `permission` on `orbit` (a global grant counts)?
|
||||||
|
pub fn has_permission(&self, user: Option<&str>, groups: &[String], permission: &str, orbit: &str, now: i64) -> Result<bool> {
|
||||||
|
let conn = self.conn.lock().unwrap();
|
||||||
|
Ok(conn.query_row(
|
||||||
|
&format!(
|
||||||
|
"SELECT EXISTS(SELECT 1 FROM access_grants WHERE permission=?1 AND {LIVE}
|
||||||
|
AND (scope_type='global' OR (scope_type='orbit' AND scope_id=?5)))"
|
||||||
|
),
|
||||||
|
params![permission, now, user, groups_json(groups), orbit],
|
||||||
|
|r| r.get(0),
|
||||||
|
)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn permitted_orbits(&self, user: Option<&str>, groups: &[String], permission: &str, now: i64) -> Result<Permitted> {
|
||||||
|
let conn = self.conn.lock().unwrap();
|
||||||
|
let mut stmt = conn.prepare(&format!(
|
||||||
|
"SELECT scope_type, scope_id FROM access_grants WHERE permission=?1 AND {LIVE}"
|
||||||
|
))?;
|
||||||
|
let rows = stmt.query_map(params![permission, now, user, groups_json(groups)], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
|
||||||
|
let mut out = Permitted::default();
|
||||||
|
for row in rows {
|
||||||
|
let (scope, id) = row?;
|
||||||
|
if scope == "global" {
|
||||||
|
out.everywhere = true;
|
||||||
|
} else {
|
||||||
|
out.orbits.insert(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Live grants of one subject, for `/me`.
|
||||||
|
pub fn grants_of(&self, user: Option<&str>, groups: &[String], now: i64) -> Result<Vec<(String, Option<String>)>> {
|
||||||
|
let conn = self.conn.lock().unwrap();
|
||||||
|
let mut stmt = conn.prepare(&format!(
|
||||||
|
"SELECT permission, scope_type, scope_id FROM access_grants WHERE (expires_at IS NULL OR expires_at > ?1)
|
||||||
|
AND ((principal_type='user' AND principal=?2) OR (principal_type='group' AND principal IN (SELECT value FROM json_each(?3))))
|
||||||
|
ORDER BY permission, scope_id"
|
||||||
|
).replace("?1", "?1"))?;
|
||||||
|
let rows = stmt.query_map(params![now, user, groups_json(groups)], |r| {
|
||||||
|
let scope_type: String = r.get(1)?;
|
||||||
|
let scope_id: String = r.get(2)?;
|
||||||
|
Ok((r.get::<_, String>(0)?, (scope_type == "orbit").then_some(scope_id)))
|
||||||
|
})?;
|
||||||
|
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn list_users(&self) -> Result<Vec<UserRow>> {
|
||||||
|
let conn = self.conn.lock().unwrap();
|
||||||
|
let mut stmt = conn.prepare("SELECT id,issuer,display_name,active,created_at,last_login_at FROM users ORDER BY display_name, id")?;
|
||||||
|
let rows = stmt.query_map([], |r| {
|
||||||
|
let issuer: String = r.get(1)?;
|
||||||
|
Ok(UserRow {
|
||||||
|
id: r.get(0)?,
|
||||||
|
is_emergency: issuer == crate::admin::EMERGENCY_ISSUER,
|
||||||
|
issuer,
|
||||||
|
display_name: r.get(2)?,
|
||||||
|
active: r.get::<_, i64>(3)? == 1,
|
||||||
|
created_at: r.get(4)?,
|
||||||
|
last_login_at: r.get(5)?,
|
||||||
|
})
|
||||||
|
})?;
|
||||||
|
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn user_exists(&self, id: &str) -> Result<bool> {
|
||||||
|
Ok(self.conn.lock().unwrap().query_row("SELECT EXISTS(SELECT 1 FROM users WHERE id=?1)", params![id], |r| r.get(0))?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Enable or disable a user. Disabling also ends every session at once.
|
||||||
|
pub fn set_user_active(&self, id: &str, active: bool) -> Result<bool> {
|
||||||
|
let mut conn = self.conn.lock().unwrap();
|
||||||
|
let tx = conn.transaction()?;
|
||||||
|
let changed = tx.execute("UPDATE users SET active=?2, generation=generation+1 WHERE id=?1", params![id, active])? == 1;
|
||||||
|
if changed && !active {
|
||||||
|
tx.execute("DELETE FROM sessions WHERE user_id=?1", params![id])?;
|
||||||
|
}
|
||||||
|
tx.commit()?;
|
||||||
|
Ok(changed)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Per-account display preferences (for example the Window/Radar view).
|
||||||
|
pub fn preferences(&self, user: &str) -> Result<std::collections::BTreeMap<String, String>> {
|
||||||
|
let conn = self.conn.lock().unwrap();
|
||||||
|
let mut stmt = conn.prepare("SELECT key, value FROM user_preferences WHERE user_id=?1")?;
|
||||||
|
let rows = stmt.query_map(params![user], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
|
||||||
|
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_preference(&self, user: &str, key: &str, value: &str, now: i64) -> Result<()> {
|
||||||
|
self.conn.lock().unwrap().execute(
|
||||||
|
"INSERT INTO user_preferences(user_id,key,value,updated_at) VALUES (?1,?2,?3,?4)
|
||||||
|
ON CONFLICT(user_id,key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at",
|
||||||
|
params![user, key, value, now],
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn orbit_exists(&self, id: &str) -> Result<bool> {
|
||||||
|
Ok(self.conn.lock().unwrap().query_row("SELECT EXISTS(SELECT 1 FROM orbits WHERE id=?1)", params![id], |r| r.get(0))?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The orbit an application (capture profile) belongs to.
|
||||||
|
pub fn orbit_of_application(&self, application: Uuid) -> Result<Option<Uuid>> {
|
||||||
|
let conn = self.conn.lock().unwrap();
|
||||||
|
let orbit: Option<String> = conn
|
||||||
|
.query_row("SELECT orbit_id FROM capture_profiles WHERE application_id=?1", params![application.to_string()], |r| r.get(0))
|
||||||
|
.optional()?;
|
||||||
|
Ok(orbit.and_then(|id| Uuid::parse_str(&id).ok()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
async fn db() -> (tempfile::TempDir, Db) {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let db = Db::connect(&dir.path().join("t.db")).await.unwrap();
|
||||||
|
db.migrate().await.unwrap();
|
||||||
|
(dir, db)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn grant<'a>(kind: &'a str, who: &'a str, permission: &'a str, orbit: Option<&'a str>, expires: Option<i64>) -> NewGrant<'a> {
|
||||||
|
NewGrant { principal_type: kind, principal: who, permission, orbit, expires_at: expires, created_by: "test" }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_grant_applies_to_its_user_scope_and_permission_only() {
|
||||||
|
let (_d, db) = db().await;
|
||||||
|
db.add_grant(&grant("user", "u1", "orbit.read", Some("orbit-a"), None), 10).unwrap().unwrap();
|
||||||
|
let has = |user: &str, perm: &str, orbit: &str| db.has_permission(Some(user), &[], perm, orbit, 20).unwrap();
|
||||||
|
assert!(has("u1", "orbit.read", "orbit-a"));
|
||||||
|
assert!(!has("u1", "orbit.read", "orbit-b"), "other orbit");
|
||||||
|
assert!(!has("u1", "snapshot.read", "orbit-a"), "other permission");
|
||||||
|
assert!(!has("u2", "orbit.read", "orbit-a"), "other user");
|
||||||
|
assert!(!has("u1", "orbit.", "orbit-a") && !has("u1", "orbit", "orbit-a"), "never by prefix");
|
||||||
|
assert!(!db.has_permission(None, &[], "orbit.read", "orbit-a", 20).unwrap(), "no user, no groups");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_global_grant_covers_every_orbit_and_a_group_grant_covers_its_members() {
|
||||||
|
let (_d, db) = db().await;
|
||||||
|
db.add_grant(&grant("group", "qa", "capture.run", None, None), 10).unwrap().unwrap();
|
||||||
|
let qa = vec!["qa".to_string()];
|
||||||
|
assert!(db.has_permission(Some("anyone"), &qa, "capture.run", "any-orbit", 11).unwrap());
|
||||||
|
assert!(!db.has_permission(Some("anyone"), &["devs".to_string()], "capture.run", "any-orbit", 11).unwrap());
|
||||||
|
assert!(!db.has_permission(Some("anyone"), &[], "capture.run", "any-orbit", 11).unwrap(), "claim missing = no groups");
|
||||||
|
let p = db.permitted_orbits(Some("anyone"), &qa, "capture.run", 11).unwrap();
|
||||||
|
assert!(p.everywhere && p.orbits.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn expired_and_deleted_grants_stop_applying_on_the_next_check() {
|
||||||
|
let (_d, db) = db().await;
|
||||||
|
let timed = db.add_grant(&grant("user", "u1", "orbit.read", Some("o"), Some(100)), 10).unwrap().unwrap();
|
||||||
|
assert!(db.has_permission(Some("u1"), &[], "orbit.read", "o", 99).unwrap());
|
||||||
|
assert!(!db.has_permission(Some("u1"), &[], "orbit.read", "o", 100).unwrap(), "expiry is exclusive");
|
||||||
|
let forever = db.add_grant(&grant("user", "u1", "snapshot.read", Some("o"), None), 10).unwrap().unwrap();
|
||||||
|
assert!(db.has_permission(Some("u1"), &[], "snapshot.read", "o", 1_000_000).unwrap());
|
||||||
|
assert!(db.delete_grant(&forever.id).unwrap());
|
||||||
|
assert!(!db.has_permission(Some("u1"), &[], "snapshot.read", "o", 11).unwrap(), "revoked at once");
|
||||||
|
assert!(!db.delete_grant(&forever.id).unwrap());
|
||||||
|
let _ = timed;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn duplicates_are_ignored_and_the_list_filters_by_permission() {
|
||||||
|
let (_d, db) = db().await;
|
||||||
|
assert!(db.add_grant(&grant("user", "u1", "orbit.read", Some("a"), None), 1).unwrap().is_some());
|
||||||
|
assert!(db.add_grant(&grant("user", "u1", "orbit.read", Some("a"), None), 2).unwrap().is_none());
|
||||||
|
db.add_grant(&grant("user", "u1", "orbit.read", Some("b"), None), 1).unwrap();
|
||||||
|
db.add_grant(&grant("user", "u1", "capture.run", Some("c"), None), 1).unwrap();
|
||||||
|
let p = db.permitted_orbits(Some("u1"), &[], "orbit.read", 5).unwrap();
|
||||||
|
assert!(!p.everywhere);
|
||||||
|
assert_eq!(p.orbits, ["a".to_string(), "b".to_string()].into_iter().collect());
|
||||||
|
assert_eq!(db.list_grants().unwrap().len(), 3);
|
||||||
|
assert_eq!(db.grants_of(Some("u1"), &[], 5).unwrap().len(), 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn disabling_a_user_ends_their_sessions_and_blocks_new_ones() {
|
||||||
|
let (_d, db) = db().await;
|
||||||
|
let user = db.upsert_user("https://idp.example", "sub", "Sam", 1).unwrap();
|
||||||
|
db.create_session("s1", &user, "oidc", None, false, &[], 1).unwrap();
|
||||||
|
assert!(db.set_user_active(&user, false).unwrap());
|
||||||
|
assert!(db.lookup_session("s1", 2).unwrap().is_none());
|
||||||
|
assert!(!db.create_session("s2", &user, "oidc", None, false, &[], 2).unwrap());
|
||||||
|
assert!(db.set_user_active(&user, true).unwrap());
|
||||||
|
assert!(db.create_session("s3", &user, "oidc", None, false, &[], 3).unwrap());
|
||||||
|
assert!(!db.set_user_active("missing", false).unwrap());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -176,14 +176,20 @@ impl Db {
|
|||||||
application: Option<Uuid>,
|
application: Option<Uuid>,
|
||||||
status: Option<&str>,
|
status: Option<&str>,
|
||||||
limit: u16,
|
limit: u16,
|
||||||
|
orbits: Option<&[String]>,
|
||||||
) -> Result<Vec<CaptureJob>> {
|
) -> Result<Vec<CaptureJob>> {
|
||||||
let conn = self.conn.lock().unwrap();
|
let conn = self.conn.lock().unwrap();
|
||||||
|
// The orbit restriction is part of the query, before LIMIT, so a restricted
|
||||||
|
// caller still gets a full page of their own jobs.
|
||||||
let mut stmt = conn.prepare(&format!(
|
let mut stmt = conn.prepare(&format!(
|
||||||
"{JOB_VIEW} WHERE (?1 IS NULL OR j.application_id = ?1) AND (?2 IS NULL OR j.status = ?2)
|
"{JOB_VIEW} WHERE (?1 IS NULL OR j.application_id = ?1) AND (?2 IS NULL OR j.status = ?2)
|
||||||
|
AND (?4 IS NULL OR j.application_id IN (
|
||||||
|
SELECT application_id FROM capture_profiles WHERE orbit_id IN (SELECT value FROM json_each(?4))))
|
||||||
ORDER BY j.created_at DESC, j.rowid DESC LIMIT ?3"
|
ORDER BY j.created_at DESC, j.rowid DESC LIMIT ?3"
|
||||||
))?;
|
))?;
|
||||||
|
let restriction = orbits.map(|ids| serde_json::to_string(ids)).transpose()?;
|
||||||
let rows = stmt.query_map(
|
let rows = stmt.query_map(
|
||||||
params![application.map(|id| id.to_string()), status, limit],
|
params![application.map(|id| id.to_string()), status, limit, restriction],
|
||||||
read_job,
|
read_job,
|
||||||
)?;
|
)?;
|
||||||
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||||
@@ -633,17 +639,17 @@ mod tests {
|
|||||||
}
|
}
|
||||||
let tick = crate::scheduler::tick_capture_schedules;
|
let tick = crate::scheduler::tick_capture_schedules;
|
||||||
tick(&db, registered).unwrap();
|
tick(&db, registered).unwrap();
|
||||||
assert!(db.capture_jobs(None, None, 100).unwrap().is_empty());
|
assert!(db.capture_jobs(None, None, 100, None).unwrap().is_empty());
|
||||||
let now = Utc.with_ymd_and_hms(2026, 11, 8, 19, 5, 0).unwrap();
|
let now = Utc.with_ymd_and_hms(2026, 11, 8, 19, 5, 0).unwrap();
|
||||||
tick(&db, now).unwrap();
|
tick(&db, now).unwrap();
|
||||||
drop(db);
|
drop(db);
|
||||||
let db = Db::connect(&path).await.unwrap();
|
let db = Db::connect(&path).await.unwrap();
|
||||||
db.migrate().await.unwrap();
|
db.migrate().await.unwrap();
|
||||||
tick(&db, now).unwrap();
|
tick(&db, now).unwrap();
|
||||||
let all = db.capture_jobs(None, Some("queued"), 100).unwrap();
|
let all = db.capture_jobs(None, Some("queued"), 100, None).unwrap();
|
||||||
assert_eq!(all.len(), 4);
|
assert_eq!(all.len(), 4);
|
||||||
let history = db
|
let history = db
|
||||||
.capture_jobs(Some(a.application_id), Some("queued"), 100)
|
.capture_jobs(Some(a.application_id), Some("queued"), 100, None)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(history.len(), 2);
|
assert_eq!(history.len(), 2);
|
||||||
assert!(history.iter().all(|job| job.actor == "scheduler"));
|
assert!(history.iter().all(|job| job.actor == "scheduler"));
|
||||||
@@ -669,7 +675,7 @@ mod tests {
|
|||||||
.unwrap());
|
.unwrap());
|
||||||
}
|
}
|
||||||
let failed = db
|
let failed = db
|
||||||
.capture_jobs(Some(a.application_id), Some("failed"), 100)
|
.capture_jobs(Some(a.application_id), Some("failed"), 100, None)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(failed.len(), 1);
|
assert_eq!(failed.len(), 1);
|
||||||
let events = db.capture_events(first.job_id).unwrap();
|
let events = db.capture_events(first.job_id).unwrap();
|
||||||
|
|||||||
@@ -28,6 +28,8 @@ pub struct StoredSession {
|
|||||||
pub auth_method: String,
|
pub auth_method: String,
|
||||||
pub credential_fp: Option<String>,
|
pub credential_fp: Option<String>,
|
||||||
pub admin: bool,
|
pub admin: bool,
|
||||||
|
/// Groups verified at sign-in (JSON in the table).
|
||||||
|
pub groups: Vec<String>,
|
||||||
pub expires_at: i64,
|
pub expires_at: i64,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,6 +62,7 @@ pub(super) fn migrate(conn: &Connection) -> Result<()> {
|
|||||||
)?;
|
)?;
|
||||||
// Added after the first M2 build; default 0 keeps old rows without admin rights.
|
// Added after the first M2 build; default 0 keeps old rows without admin rights.
|
||||||
super::ensure_column(conn, "sessions", "admin", "INTEGER NOT NULL DEFAULT 0")?;
|
super::ensure_column(conn, "sessions", "admin", "INTEGER NOT NULL DEFAULT 0")?;
|
||||||
|
super::ensure_column(conn, "sessions", "groups", "TEXT NOT NULL DEFAULT '[]'")?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,14 +92,15 @@ impl Db {
|
|||||||
auth_method: &str,
|
auth_method: &str,
|
||||||
credential_fp: Option<&str>,
|
credential_fp: Option<&str>,
|
||||||
admin: bool,
|
admin: bool,
|
||||||
|
groups: &[String],
|
||||||
now: i64,
|
now: i64,
|
||||||
) -> Result<bool> {
|
) -> Result<bool> {
|
||||||
let conn = self.conn.lock().unwrap();
|
let conn = self.conn.lock().unwrap();
|
||||||
conn.execute("DELETE FROM sessions WHERE expires_at <= ?1 OR last_seen + ?2 <= ?1", params![now, IDLE_SECS])?;
|
conn.execute("DELETE FROM sessions WHERE expires_at <= ?1 OR last_seen + ?2 <= ?1", params![now, IDLE_SECS])?;
|
||||||
let inserted = conn.execute(
|
let inserted = conn.execute(
|
||||||
"INSERT INTO sessions(token_digest,user_id,generation,auth_method,credential_fp,auth_time,created_at,last_seen,expires_at,admin)
|
"INSERT INTO sessions(token_digest,user_id,generation,auth_method,credential_fp,auth_time,created_at,last_seen,expires_at,admin,groups)
|
||||||
SELECT ?1, id, generation, ?3, ?4, ?5, ?5, ?5, ?6, ?7 FROM users WHERE id=?2 AND active=1",
|
SELECT ?1, id, generation, ?3, ?4, ?5, ?5, ?5, ?6, ?7, ?8 FROM users WHERE id=?2 AND active=1",
|
||||||
params![session_digest(id), user_id, auth_method, credential_fp, now, now + ABSOLUTE_SECS, admin],
|
params![session_digest(id), user_id, auth_method, credential_fp, now, now + ABSOLUTE_SECS, admin, serde_json::to_string(groups)?],
|
||||||
)?;
|
)?;
|
||||||
Ok(inserted == 1)
|
Ok(inserted == 1)
|
||||||
}
|
}
|
||||||
@@ -109,7 +113,7 @@ impl Db {
|
|||||||
let conn = self.conn.lock().unwrap();
|
let conn = self.conn.lock().unwrap();
|
||||||
let found: Option<(StoredSession, i64)> = conn
|
let found: Option<(StoredSession, i64)> = conn
|
||||||
.query_row(
|
.query_row(
|
||||||
"SELECT s.user_id,u.display_name,s.auth_method,s.credential_fp,s.expires_at,s.last_seen,s.admin
|
"SELECT s.user_id,u.display_name,s.auth_method,s.credential_fp,s.expires_at,s.last_seen,s.admin,s.groups
|
||||||
FROM sessions s JOIN users u ON u.id=s.user_id
|
FROM sessions s JOIN users u ON u.id=s.user_id
|
||||||
WHERE s.token_digest=?1 AND u.active=1 AND s.generation=u.generation
|
WHERE s.token_digest=?1 AND u.active=1 AND s.generation=u.generation
|
||||||
AND s.expires_at>?2 AND s.last_seen+?3>?2",
|
AND s.expires_at>?2 AND s.last_seen+?3>?2",
|
||||||
@@ -123,6 +127,7 @@ impl Db {
|
|||||||
credential_fp: row.get(3)?,
|
credential_fp: row.get(3)?,
|
||||||
expires_at: row.get(4)?,
|
expires_at: row.get(4)?,
|
||||||
admin: row.get(6)?,
|
admin: row.get(6)?,
|
||||||
|
groups: serde_json::from_str(&row.get::<_, String>(7)?).unwrap_or_default(),
|
||||||
},
|
},
|
||||||
row.get(5)?,
|
row.get(5)?,
|
||||||
))
|
))
|
||||||
@@ -141,8 +146,6 @@ impl Db {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Used by the per-user revoke endpoint planned for M5 (admin).
|
|
||||||
#[allow(dead_code)]
|
|
||||||
/// Invalidate every session of a user, including any created concurrently
|
/// Invalidate every session of a user, including any created concurrently
|
||||||
/// from the previous generation. Returns the number of rows removed.
|
/// from the previous generation. Returns the number of rows removed.
|
||||||
pub fn revoke_user_sessions(&self, user_id: &str) -> Result<usize> {
|
pub fn revoke_user_sessions(&self, user_id: &str) -> Result<usize> {
|
||||||
@@ -180,13 +183,13 @@ mod tests {
|
|||||||
async fn idle_and_absolute_deadlines_use_the_supplied_clock() {
|
async fn idle_and_absolute_deadlines_use_the_supplied_clock() {
|
||||||
let (_dir, db) = db().await;
|
let (_dir, db) = db().await;
|
||||||
let user = db.upsert_user("local:emergency", "ops", "ops", 1000).unwrap();
|
let user = db.upsert_user("local:emergency", "ops", "ops", 1000).unwrap();
|
||||||
assert!(db.create_session("a", &user, "password", Some("fp"), true, 1000).unwrap());
|
assert!(db.create_session("a", &user, "password", Some("fp"), true, &[], 1000).unwrap());
|
||||||
assert!(db.lookup_session("a", 1000 + IDLE_SECS - 1).unwrap().is_some());
|
assert!(db.lookup_session("a", 1000 + IDLE_SECS - 1).unwrap().is_some());
|
||||||
// sliding: the touch above moved last_seen, so a request just inside the
|
// sliding: the touch above moved last_seen, so a request just inside the
|
||||||
// new idle window is still fine, one beyond it is not
|
// new idle window is still fine, one beyond it is not
|
||||||
assert!(db.lookup_session("a", 1000 + 2 * IDLE_SECS - 2).unwrap().is_some());
|
assert!(db.lookup_session("a", 1000 + 2 * IDLE_SECS - 2).unwrap().is_some());
|
||||||
assert!(db.lookup_session("a", 1000 + 3 * IDLE_SECS).unwrap().is_none());
|
assert!(db.lookup_session("a", 1000 + 3 * IDLE_SECS).unwrap().is_none());
|
||||||
assert!(db.create_session("b", &user, "password", None, true, 5000).unwrap());
|
assert!(db.create_session("b", &user, "password", None, true, &[], 5000).unwrap());
|
||||||
let mut now = 5000;
|
let mut now = 5000;
|
||||||
while now + IDLE_SECS - 10 < 5000 + ABSOLUTE_SECS {
|
while now + IDLE_SECS - 10 < 5000 + ABSOLUTE_SECS {
|
||||||
now += IDLE_SECS - 10;
|
now += IDLE_SECS - 10;
|
||||||
@@ -200,7 +203,7 @@ mod tests {
|
|||||||
async fn only_a_digest_is_stored_and_csrf_is_not_the_key() {
|
async fn only_a_digest_is_stored_and_csrf_is_not_the_key() {
|
||||||
let (_dir, db) = db().await;
|
let (_dir, db) = db().await;
|
||||||
let user = db.upsert_user("local:emergency", "ops", "ops", 1).unwrap();
|
let user = db.upsert_user("local:emergency", "ops", "ops", 1).unwrap();
|
||||||
db.create_session("raw-session-id", &user, "password", None, true, 1).unwrap();
|
db.create_session("raw-session-id", &user, "password", None, true, &[], 1).unwrap();
|
||||||
let conn = db.conn.lock().unwrap();
|
let conn = db.conn.lock().unwrap();
|
||||||
let key: String = conn.query_row("SELECT token_digest FROM sessions", [], |r| r.get(0)).unwrap();
|
let key: String = conn.query_row("SELECT token_digest FROM sessions", [], |r| r.get(0)).unwrap();
|
||||||
assert_ne!(key, "raw-session-id");
|
assert_ne!(key, "raw-session-id");
|
||||||
@@ -216,7 +219,7 @@ mod tests {
|
|||||||
async fn revoked_sessions_cannot_be_resurrected_by_a_late_touch() {
|
async fn revoked_sessions_cannot_be_resurrected_by_a_late_touch() {
|
||||||
let (_dir, db) = db().await;
|
let (_dir, db) = db().await;
|
||||||
let user = db.upsert_user("local:emergency", "ops", "ops", 1000).unwrap();
|
let user = db.upsert_user("local:emergency", "ops", "ops", 1000).unwrap();
|
||||||
db.create_session("a", &user, "password", None, true, 1000).unwrap();
|
db.create_session("a", &user, "password", None, true, &[], 1000).unwrap();
|
||||||
db.revoke_session("a").unwrap();
|
db.revoke_session("a").unwrap();
|
||||||
assert!(db.lookup_session("a", 1000 + 2 * TOUCH_AFTER_SECS).unwrap().is_none());
|
assert!(db.lookup_session("a", 1000 + 2 * TOUCH_AFTER_SECS).unwrap().is_none());
|
||||||
assert_eq!(db.session_rows(), 0);
|
assert_eq!(db.session_rows(), 0);
|
||||||
@@ -228,14 +231,14 @@ mod tests {
|
|||||||
let one = db.upsert_user("https://idp.example", "alice", "Alice", 10).unwrap();
|
let one = db.upsert_user("https://idp.example", "alice", "Alice", 10).unwrap();
|
||||||
let two = db.upsert_user("https://idp.example", "bob", "Bob", 10).unwrap();
|
let two = db.upsert_user("https://idp.example", "bob", "Bob", 10).unwrap();
|
||||||
for id in ["a1", "a2"] {
|
for id in ["a1", "a2"] {
|
||||||
db.create_session(id, &one, "oidc", None, true, 10).unwrap();
|
db.create_session(id, &one, "oidc", None, true, &[], 10).unwrap();
|
||||||
}
|
}
|
||||||
db.create_session("b1", &two, "oidc", None, true, 10).unwrap();
|
db.create_session("b1", &two, "oidc", None, true, &[], 10).unwrap();
|
||||||
assert_eq!(db.revoke_user_sessions(&one).unwrap(), 2);
|
assert_eq!(db.revoke_user_sessions(&one).unwrap(), 2);
|
||||||
assert!(db.lookup_session("a1", 11).unwrap().is_none());
|
assert!(db.lookup_session("a1", 11).unwrap().is_none());
|
||||||
assert!(db.lookup_session("a2", 11).unwrap().is_none());
|
assert!(db.lookup_session("a2", 11).unwrap().is_none());
|
||||||
assert!(db.lookup_session("b1", 11).unwrap().is_some());
|
assert!(db.lookup_session("b1", 11).unwrap().is_some());
|
||||||
assert!(db.create_session("a3", &one, "oidc", None, true, 12).unwrap());
|
assert!(db.create_session("a3", &one, "oidc", None, true, &[], 12).unwrap());
|
||||||
assert!(db.lookup_session("a3", 13).unwrap().is_some());
|
assert!(db.lookup_session("a3", 13).unwrap().is_some());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -243,11 +246,11 @@ mod tests {
|
|||||||
async fn inactive_users_have_no_valid_or_new_sessions() {
|
async fn inactive_users_have_no_valid_or_new_sessions() {
|
||||||
let (_dir, db) = db().await;
|
let (_dir, db) = db().await;
|
||||||
let user = db.upsert_user("https://idp.example", "carol", "Carol", 10).unwrap();
|
let user = db.upsert_user("https://idp.example", "carol", "Carol", 10).unwrap();
|
||||||
db.create_session("c1", &user, "oidc", None, true, 10).unwrap();
|
db.create_session("c1", &user, "oidc", None, true, &[], 10).unwrap();
|
||||||
db.conn.lock().unwrap().execute("UPDATE users SET active=0 WHERE id=?1", params![user]).unwrap();
|
db.conn.lock().unwrap().execute("UPDATE users SET active=0 WHERE id=?1", params![user]).unwrap();
|
||||||
assert!(db.lookup_session("c1", 11).unwrap().is_none());
|
assert!(db.lookup_session("c1", 11).unwrap().is_none());
|
||||||
assert!(!db.create_session("c2", &user, "oidc", None, true, 11).unwrap());
|
assert!(!db.create_session("c2", &user, "oidc", None, true, &[], 11).unwrap());
|
||||||
assert!(!db.create_session("c3", "no-such-user", "oidc", None, true, 11).unwrap());
|
assert!(!db.create_session("c3", "no-such-user", "oidc", None, true, &[], 11).unwrap());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
@@ -270,8 +273,8 @@ mod tests {
|
|||||||
let db = Db::connect(&path).await.unwrap();
|
let db = Db::connect(&path).await.unwrap();
|
||||||
db.migrate().await.unwrap();
|
db.migrate().await.unwrap();
|
||||||
let user = db.upsert_user("local:emergency", "ops", "ops", 1000).unwrap();
|
let user = db.upsert_user("local:emergency", "ops", "ops", 1000).unwrap();
|
||||||
db.create_session("live", &user, "password", Some("fp"), true, 1000).unwrap();
|
db.create_session("live", &user, "password", Some("fp"), true, &[], 1000).unwrap();
|
||||||
db.create_session("old", &user, "password", Some("fp"), true, 1000).unwrap();
|
db.create_session("old", &user, "password", Some("fp"), true, &[], 1000).unwrap();
|
||||||
}
|
}
|
||||||
let db = Db::connect(&path).await.unwrap();
|
let db = Db::connect(&path).await.unwrap();
|
||||||
db.migrate().await.unwrap();
|
db.migrate().await.unwrap();
|
||||||
|
|||||||
@@ -259,3 +259,34 @@ immediately. A denial is written to the audit log at most once a minute per sour
|
|||||||
timestamp) and the hub refuses the token after that time. Without it the hub logs a
|
timestamp) and the hub refuses the token after that time. Without it the hub logs a
|
||||||
warning at start. Every use is audited as the `legacy-admin-token` service principal.
|
warning at start. Every use is audited as the `legacy-admin-token` service principal.
|
||||||
|
|
||||||
|
## Who may do what (access grants)
|
||||||
|
|
||||||
|
Administrators are the people named by the SSO admin mapping (`TESSERA_OIDC_ADMIN_SUBJECTS` /
|
||||||
|
`TESSERA_OIDC_ADMIN_GROUPS`), the emergency operator and the shared admin token. They can
|
||||||
|
do everything. Everyone else gets **nothing** until an administrator grants it in the
|
||||||
|
Access console (or through `/api/v1/access/*`). A grant names a person (a user who has signed
|
||||||
|
in) or an identity-provider group, a permission, an orbit (or all orbits) and optionally an end date.
|
||||||
|
|
||||||
|
Permissions that can be granted: `orbit.read`, `snapshot.read`, `capture.run`,
|
||||||
|
`snapshot.download`. They are separate: running a backup does not allow downloading it, and
|
||||||
|
the reverse. The roles `viewer`, `capturer` and `downloader` are shortcuts that expand into
|
||||||
|
these permissions, each including `orbit.read`. Everything else (creating or changing orbits,
|
||||||
|
profiles, Outposts, retention, deleting snapshots, restores, and access itself) stays with
|
||||||
|
administrators and cannot be delegated.
|
||||||
|
|
||||||
|
- An orbit a user has no `orbit.read` on is invisible: by id it answers `404`, in lists it is
|
||||||
|
left out. A visible orbit without the needed permission answers `403`. A user with no grant at
|
||||||
|
all gets `403` on lists and sees "No access yet" in the app.
|
||||||
|
- Grants are read on every request. Removing a grant, an expiry, disabling a user or
|
||||||
|
"Sign out everywhere" take effect on that user's next request. A change to a user's groups at
|
||||||
|
the identity provider applies at their next sign-in (at most 8 hours later), because groups
|
||||||
|
are taken from the sign-in token.
|
||||||
|
- A group grant applies to people whose token carries that group; a missing groups claim grants nothing.
|
||||||
|
- Jobs and audit entries record the stable user id (`oidc:<id>`), never the name the IdP reports.
|
||||||
|
- Until the self-service refresh arrives, restore targets and restore history are shown to
|
||||||
|
administrators only, because they describe the destination database.
|
||||||
|
- The administrator who disables a user cannot disable themselves or the emergency operator.
|
||||||
|
- Display choices (currently the Window/Radar view) are stored per account (`/api/v1/me/preferences`), so they follow
|
||||||
|
a person to another browser. Accounts without a user row (the shared admin token, local development) keep the
|
||||||
|
choice in the browser only.
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ Inventaris A01, 11 November 2026. Gate saat ini masih admin global; kolom
|
|||||||
permission/scope adalah kontrak yang harus diterapkan A11–A12, bukan klaim RBAC
|
permission/scope adalah kontrak yang harus diterapkan A11–A12, bukan klaim RBAC
|
||||||
sudah tersedia. A02 menutup isolasi upload legacy; A03 menghapus fallback loopback.
|
sudah tersedia. A02 menutup isolasi upload legacy; A03 menghapus fallback loopback.
|
||||||
|
|
||||||
|
Gate (M5): `authenticate` lalu resolve resource lalu gate. Permission yang dapat diberikan ke non-admin hanya `orbit.read`, `snapshot.read`, `capture.run`, `snapshot.download`; semua permission lain hanya dimiliki administrator terkonfigurasi (403 tanpa lookup resource). Resource di luar scope = 404, terlihat tapi tanpa izin = 403, daftar tanpa satu pun akses = 403. Tes `access_tests` membangkitkan matriks dari tabel ini.
|
||||||
|
|
||||||
Human = sesi user aktif atau service token dengan grant; token Outpost ditolak.
|
Human = sesi user aktif atau service token dengan grant; token Outpost ditolak.
|
||||||
Mutasi cookie memerlukan CSRF. Anonymous/token salah: 401; resource di luar scope:
|
Mutasi cookie memerlukan CSRF. Anonymous/token salah: 401; resource di luar scope:
|
||||||
404; aksi tanpa permission pada resource terlihat: 403. Parsing request invalid
|
404; aksi tanpa permission pada resource terlihat: 403. Parsing request invalid
|
||||||
@@ -20,6 +22,13 @@ admin/browser. Semua status/data job hanya di scope owner/admin yang berizin.
|
|||||||
| /api/v1/me | GET | human | session.self | current principal | id, kind, auth method, display name, capabilities; no-store |
|
| /api/v1/me | GET | human | session.self | current principal | id, kind, auth method, display name, capabilities; no-store |
|
||||||
| /api/v1/auth/oidc/login | GET | public | — | OIDC configured | redirect to the IdP; sets one-time Lax correlation cookie; 404 when OIDC is off |
|
| /api/v1/auth/oidc/login | GET | public | — | OIDC configured | redirect to the IdP; sets one-time Lax correlation cookie; 404 when OIDC is off |
|
||||||
| /api/v1/auth/oidc/callback | GET | public | — | login transaction + correlation cookie | redirect to `/`; session cookie only on success, fixed error code otherwise; no tokens |
|
| /api/v1/auth/oidc/callback | GET | public | — | login transaction + correlation cookie | redirect to `/`; session cookie only on success, fixed error code otherwise; no tokens |
|
||||||
|
| /api/v1/access/grants | GET | human | access.manage | admin | daftar grant, role, permission yang dapat diberikan; no-store |
|
||||||
|
| /api/v1/access/grants | POST | human | access.manage | admin | grant baru (role atau permission, scope global/orbit, expiry); diaudit per id |
|
||||||
|
| /api/v1/access/grants/:id | DELETE | human | access.manage | admin | tidak ada; berlaku pada request berikutnya; diaudit |
|
||||||
|
| /api/v1/access/users | GET | human | access.manage | admin | daftar user (tanpa kredensial); no-store |
|
||||||
|
| /api/v1/access/users/:id | PUT | human | access.manage | admin | tidak ada; menonaktifkan juga memutus semua sesi; tidak untuk diri sendiri/akun darurat |
|
||||||
|
| /api/v1/access/users/:id/revoke-sessions | POST | human | access.manage | admin | tidak ada; semua sesi user berakhir |
|
||||||
|
| /api/v1/me/preferences | GET,PUT | human | session.self | current account | pilihan tampilan sendiri (look: window atau radar); no-store; CSRF pada PUT; token/dev tanpa akun: GET kosong, PUT 404 |
|
||||||
| /api/v1/operator/login | POST | public | — | emergency account | cookie opaque dan CSRF; limiter, no-store |
|
| /api/v1/operator/login | POST | public | — | emergency account | cookie opaque dan CSRF; limiter, no-store |
|
||||||
| /api/v1/snapshots | GET | human | snapshot.read | orbit | metadata aman terfilter |
|
| /api/v1/snapshots | GET | human | snapshot.read | orbit | metadata aman terfilter |
|
||||||
| /api/v1/snapshots/:id | DELETE | human | snapshot.delete | snapshot→orbit | tidak ada; cek pin |
|
| /api/v1/snapshots/:id | DELETE | human | snapshot.delete | snapshot→orbit | tidak ada; cek pin |
|
||||||
@@ -50,10 +59,10 @@ admin/browser. Semua status/data job hanya di scope owner/admin yang berizin.
|
|||||||
| /api/v1/wormhole/capture/:id/payload | POST | outpost | capture.assigned | job owner + lease | tidak ada |
|
| /api/v1/wormhole/capture/:id/payload | POST | outpost | capture.assigned | job owner + lease | tidak ada |
|
||||||
| /api/v1/wormhole/capture/:id/restic | POST | outpost | capture.assigned | job owner + lease + repository | commit owner |
|
| /api/v1/wormhole/capture/:id/restic | POST | outpost | capture.assigned | job owner + lease + repository | commit owner |
|
||||||
| /api/v1/restore-targets | POST | human | orbit.manage | target→orbit | identity terverifikasi admin; tanpa kredensial |
|
| /api/v1/restore-targets | POST | human | orbit.manage | target→orbit | identity terverifikasi admin; tanpa kredensial |
|
||||||
| /api/v1/capture-profiles/:id/restore-targets | GET | human | orbit.read | profile→orbit | target aman terfilter |
|
| /api/v1/capture-profiles/:id/restore-targets | GET | human | recovery.manage | admin | identity target (instance/database) hanya untuk admin sampai self-service M6; tanpa kredensial |
|
||||||
| /api/v1/snapshots/:id/restore-targets | GET | human | snapshot.read | snapshot→orbit | target aman terfilter |
|
| /api/v1/snapshots/:id/restore-targets | GET | human | recovery.manage | admin | identity target hanya untuk admin sampai self-service M6; tanpa kredensial |
|
||||||
| /api/v1/restore-jobs | POST | human | recovery.manage | snapshot + target | restore administratif; refresh.run lewat relasi terpisah |
|
| /api/v1/restore-jobs | GET,POST | human | recovery.manage | admin | restore administratif dan daftar terbaru; refresh.run lewat relasi terpisah (M6) |
|
||||||
| /api/v1/snapshots/:id/restore-jobs | GET | human | snapshot.read | snapshot→orbit | histori aman terfilter |
|
| /api/v1/snapshots/:id/restore-jobs | GET | human | recovery.manage | admin | histori restore memuat target dan aktor; admin saja sampai M6 |
|
||||||
| /api/v1/restore-jobs/:id | GET,DELETE | human | recovery.manage | job→snapshot + target | status aman; cancel sebelum apply |
|
| /api/v1/restore-jobs/:id | GET,DELETE | human | recovery.manage | job→snapshot + target | status aman; cancel sebelum apply |
|
||||||
| /api/v1/restore-jobs/:id/reconcile | POST | human | recovery.manage | job→target | status recovery admin |
|
| /api/v1/restore-jobs/:id/reconcile | POST | human | recovery.manage | job→target | status recovery admin |
|
||||||
| /api/v1/wormhole/restore-targets/:id/claim | POST | outpost | restore.assigned | target owner | lease + artifact metadata |
|
| /api/v1/wormhole/restore-targets/:id/claim | POST | outpost | restore.assigned | target owner | lease + artifact metadata |
|
||||||
|
|||||||
@@ -61,13 +61,20 @@ Hasil: tidak ada rahasia aktif yang tersimpan mentah dan endpoint publik tidak b
|
|||||||
Bukti: `cargo test --workspace` hijau (hub 70 tes), `cargo audit` hanya `proc-macro-error`, `cargo deny` ok. Tes: tidak ada token/kode mentah di file DB (termasuk `-wal`/`-journal`, dengan sanity check bahwa scan benar-benar membaca file), klaim sekali pakai, expiry/revoke/rotasi dengan clock injeksi, migrasi legacy (token aktif dengan expiry lama tetap jalan, scrub, idempoten), pairing→claim lewat HTTP nyata, revoke → 401 di endpoint upload dan endpoint lease, flood satu sumber tidak menghabiskan kuota sumber lain dan header palsu tidak membantu, audit penolakan sekali per menit, Argon2 terbatas dan permit dilepas, token admin kedaluwarsa, tes lewat listener mTLS sungguhan (gagal 500 bila penyisipan peer dilepas). Proses nyata pada DB bergaya lama dengan token sintetis: migrasi, token lama tetap 200, tidak ada teks mentah di file DB, pairing/rotate/revoke via HTTP, audit sesuai, tidak ada token di DB maupun log.
|
Bukti: `cargo test --workspace` hijau (hub 70 tes), `cargo audit` hanya `proc-macro-error`, `cargo deny` ok. Tes: tidak ada token/kode mentah di file DB (termasuk `-wal`/`-journal`, dengan sanity check bahwa scan benar-benar membaca file), klaim sekali pakai, expiry/revoke/rotasi dengan clock injeksi, migrasi legacy (token aktif dengan expiry lama tetap jalan, scrub, idempoten), pairing→claim lewat HTTP nyata, revoke → 401 di endpoint upload dan endpoint lease, flood satu sumber tidak menghabiskan kuota sumber lain dan header palsu tidak membantu, audit penolakan sekali per menit, Argon2 terbatas dan permit dilepas, token admin kedaluwarsa, tes lewat listener mTLS sungguhan (gagal 500 bila penyisipan peer dilepas). Proses nyata pada DB bergaya lama dengan token sintetis: migrasi, token lama tetap 200, tidak ada teks mentah di file DB, pairing/rotate/revoke via HTTP, audit sesuai, tidak ada token di DB maupun log.
|
||||||
Belum ada / batas: rotasi oleh agen sendiri (operator yang mengantar token baru; grace window jadi jembatannya), tanggal akhir token admin sengaja tetap opsional (keputusan Sen, 14 November 2026; peringatan saat start bila `TESSERA_ADMIN_TOKEN_EXPIRES` tidak diset, jadi token bisa tetap permanen sampai tanggal itu dipasang), limiter di memori (reset saat restart, tidak dibagi antar proses), tidak ada `Retry-After` di respons 429, endpoint list Outpost belum menampilkan status/expiry kredensial, tidak ada UI untuk rotate/revoke, backup DB lama masih memuat token mentah sehingga rotasi setelah upgrade wajib. Migrasi hanya diuji pada salinan; belum dijalankan pada hub produksi.
|
Belum ada / batas: rotasi oleh agen sendiri (operator yang mengantar token baru; grace window jadi jembatannya), tanggal akhir token admin sengaja tetap opsional (keputusan Sen, 14 November 2026; peringatan saat start bila `TESSERA_ADMIN_TOKEN_EXPIRES` tidak diset, jadi token bisa tetap permanen sampai tanggal itu dipasang), limiter di memori (reset saat restart, tidak dibagi antar proses), tidak ada `Retry-After` di respons 429, endpoint list Outpost belum menampilkan status/expiry kredensial, tidak ada UI untuk rotate/revoke, backup DB lama masih memuat token mentah sehingga rotasi setelah upgrade wajib. Migrasi hanya diuji pada salinan; belum dijalankan pada hub produksi.
|
||||||
|
|
||||||
## M5 — Hak akses per scope
|
## M5 — Hak akses per scope (selesai di working tree, belum di-commit, 14 November 2026)
|
||||||
|
|
||||||
Hasil: QA, developer, dan DevOps punya hak berbeda per orbit.
|
Hasil: user biasa hanya melihat dan memakai orbit yang diberikan; administrator tetap memegang semuanya.
|
||||||
- Permission bertipe dan tabel `access_grants` (principal user/group/service, permission, scope, expiry). Tanpa Casbin.
|
- Model: permission bertipe (`auth.rs`) dan tabel `access_grants` (user atau grup IdP, permission, global atau satu orbit, expiry, pembuat). Tanpa Casbin. Hanya `orbit.read`, `snapshot.read`, `capture.run`, `snapshot.download` yang dapat diberikan ke non-admin; semua permission lain (kelola orbit/profil/Outpost/retensi, hapus snapshot, restore, akses) hanya dimiliki administrator terkonfigurasi dan tidak dapat didelegasikan. Role `viewer`, `capturer`, `downloader` hanya jalan pintas yang diperluas menjadi permission (selalu termasuk `orbit.read`).
|
||||||
- Satu gate terpusat dipakai semua handler; scope di luar akses = 404, tanpa izin pada resource terlihat = 403. List dan akses UUID langsung ikut difilter.
|
- Satu gate (`api/gate.rs`): `authenticate` (401 atau CSRF 403), resolve resource, lalu `admin_only` / `scoped` / `visible`. Orbit tanpa `orbit.read` = 404, terlihat tapi tanpa izin = 403, daftar tanpa akses sama sekali = 403, route admin-only = 403 tanpa lookup resource. `require_admin*` dihapus agar compiler memaksa tiap handler memilih gate. Grant dibaca dari DB di setiap request (tidak ada cache), jadi cabut grant, expiry, nonaktifkan user, dan "sign out everywhere" berlaku di request berikutnya.
|
||||||
- Admin UI untuk grant dan mapping grup; perubahan berlaku di request berikutnya.
|
- Filter sebelum LIMIT untuk riwayat capture job (`json_each` di SQL), daftar snapshot/orbit/profil terfilter, grup diambil dari token saat sign-in dan disimpan di sesi (batas 64 grup x 128 karakter).
|
||||||
Selesai bila: tes tabel seluruh matriks di kontrak endpoint lulus, grant dicabut langsung menolak, unknown permission ditolak.
|
- Atribusi memakai identitas stabil (`oidc:<users.id>`, `emergency:<nama>`, `legacy-admin-token`), tidak pernah nama dari IdP; pekerjaan baru tidak bisa menyamar sebagai `scheduler`. (Baris lama di DB tetap memuat nama lama.)
|
||||||
|
- API admin: `/api/v1/access/grants` (GET/POST/DELETE), `/access/users` (GET, PUT aktif/nonaktif, revoke-sessions). Validasi: permission tidak dikenal atau bukan prefix, tidak dapat diberikan, role tidak dikenal, role dan permission bersamaan, user/orbit tidak ada, expiry lampau atau lebih dari 2 tahun, grup terlalu panjang, duplikat 409; admin tidak bisa menonaktifkan diri sendiri atau akun darurat. Semua perubahan diaudit per id.
|
||||||
|
- UI: tab Access (admin) untuk memberi dan mencabut akses, daftar orang yang sudah sign in; non-admin hanya melihat Vault dan Activity, tombol capture/download/hapus/restore sesuai grant, dan tidak memanggil endpoint admin. `/me` mengembalikan `admin`, `capabilities`, `grants`.
|
||||||
|
- Kontrak endpoint diperbarui: tiga endpoint restore (`restore-targets` dua rute dan `snapshots/:id/restore-jobs`) dan `restore-jobs` GET kini admin-only (identity database tujuan; lihat plan bagian 7) sampai self-service M6.
|
||||||
|
Bukti: `cargo test --workspace` hijau (hub 83 tes, 12 tes baru). Matriks dibangkitkan dari file kontrak dengan resource nyata di dua orbit untuk enam jenis pemanggil (anonim, tanpa grant, viewer orbit lain, viewer, capturer, downloader, anggota grup, admin): route baru yang tidak ada resepnya membuat tes gagal, user tanpa grant tidak pernah mendapat 2xx, dan tiga mutasi sengaja (download hanya butuh `orbit.read`, reconcile tanpa gate admin, daftar job tanpa filter) semuanya tertangkap. Rehearsal browser nyata dengan Keycloak 26.1: Bob "No access yet" -> Alice memberi viewer pada `wiki` lewat tab Access -> Bob melihat 1 orbit dan 14 snapshot (admin 12 orbit dan 185), hanya tab Vault dan Activity, semua request 200 tanpa 403/404 dan tanpa `restore-jobs`/`access` -> grant dicabut -> UI Bob kembali ke "No access yet" pada siklus polling berikutnya.
|
||||||
|
UI Access memakai komponen yang sama dengan form lain (`Select` bertema dan `DatePicker` kustom dengan navigasi keyboard). Pilihan tampilan Window/Radar disimpan per akun (`/api/v1/me/preferences`, tabel `user_preferences`), bukan hanya di browser.
|
||||||
|
Keputusan Sen (14 November 2026): admin tetap boleh mengunduh semua snapshot tanpa grant eksplisit (rencana awal meminta grant untuk data sensitif; kebijakan data mentah per orbit dipertimbangkan lagi di M6).
|
||||||
|
Belum ada / batas: principal `service` bergrant (hanya user dan grup; token admin lama = admin), grant atas nama grup berlaku dari token saat sign-in, UI tidak menyembunyikan satu per satu aksi untuk orbit tanpa izin di semua panel (backend tetap menolak), tidak ada pra-otorisasi user yang belum pernah sign in, tidak ada UI per-orbit untuk melihat siapa saja yang punya akses, pencarian vault masih menampilkan konsol admin untuk non-admin (navigasi diabaikan).
|
||||||
|
|
||||||
## M6 — Self-service data
|
## M6 — Self-service data
|
||||||
|
|
||||||
|
|||||||
@@ -2,20 +2,22 @@ import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
|||||||
import { AnimatePresence, useMotionValue } from "motion/react";
|
import { AnimatePresence, useMotionValue } from "motion/react";
|
||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import {
|
import {
|
||||||
abortReconstitute, fetchCaptureJobs, fetchHealth, fetchOrbits, fetchSnapshots, pollReconstitute,
|
abortReconstitute, fetchCaptureJobs, fetchHealth, fetchOrbits, fetchPreferences, fetchSnapshots, pollReconstitute, savePreferences,
|
||||||
enqueueCapture, runOrbit, startReconstitute, type Orbit,
|
enqueueCapture, runOrbit, startReconstitute, type Orbit,
|
||||||
} from "./api";
|
} from "./api";
|
||||||
import { OrbitInspector, OrbitRegister, TelemetryStrip } from "./components/hud/DiegeticHUD";
|
import { OrbitInspector, OrbitRegister, TelemetryStrip } from "./components/hud/DiegeticHUD";
|
||||||
import { HUDPanel } from "./components/hud/HUDPanel";
|
import { HUDPanel } from "./components/hud/HUDPanel";
|
||||||
import { HUDRail, type HUDMode } from "./components/hud/HUDRail";
|
import { accessItem, HUDRail, hudItems, type HUDMode } from "./components/hud/HUDRail";
|
||||||
|
import { AccessView } from "./components/access/AccessView";
|
||||||
import { SearchIcon, VaultSearch } from "./components/hud/VaultSearch";
|
import { SearchIcon, VaultSearch } from "./components/hud/VaultSearch";
|
||||||
import { OperatorGate } from "./components/operator/OperatorGate";
|
import { OperatorGate, type Caps } from "./components/operator/OperatorGate";
|
||||||
import { OrbitsView } from "./components/orbits/OrbitsView";
|
import { OrbitsView } from "./components/orbits/OrbitsView";
|
||||||
import { WormholeView } from "./components/outposts/WormholeView";
|
import { WormholeView } from "./components/outposts/WormholeView";
|
||||||
import { ActivityView } from "./components/activity/ActivityView";
|
import { ActivityView } from "./components/activity/ActivityView";
|
||||||
import { ReconstituteWizard } from "./components/reconstitute/ReconstituteWizard";
|
import { ReconstituteWizard } from "./components/reconstitute/ReconstituteWizard";
|
||||||
import { VaultScene } from "./components/scene/VaultScene";
|
import { VaultScene } from "./components/scene/VaultScene";
|
||||||
import { EmptyState } from "./components/ui/EmptyState";
|
import { EmptyState } from "./components/ui/EmptyState";
|
||||||
|
import { PanelBoundary } from "./components/ui/PanelBoundary";
|
||||||
import { QueryGate } from "./components/ui/QueryGate";
|
import { QueryGate } from "./components/ui/QueryGate";
|
||||||
import { SpringPane } from "./components/ui/SpringPane";
|
import { SpringPane } from "./components/ui/SpringPane";
|
||||||
import { SnapshotSheet } from "./components/vault/SnapshotSheet";
|
import { SnapshotSheet } from "./components/vault/SnapshotSheet";
|
||||||
@@ -31,6 +33,7 @@ const panelTitles: Record<HUDMode, string> = {
|
|||||||
orbits: "Orbits",
|
orbits: "Orbits",
|
||||||
wormhole: "Wormhole uplink",
|
wormhole: "Wormhole uplink",
|
||||||
activity: "Activity",
|
activity: "Activity",
|
||||||
|
access: "Access",
|
||||||
reconstitute: "Restore snapshot",
|
reconstitute: "Restore snapshot",
|
||||||
snapshot: "Snapshot detail",
|
snapshot: "Snapshot detail",
|
||||||
};
|
};
|
||||||
@@ -39,10 +42,11 @@ const panelLabels: Record<HUDMode, string> = {
|
|||||||
orbits: "Console 02 · Orbit management",
|
orbits: "Console 02 · Orbit management",
|
||||||
wormhole: "Console 03 · Outposts",
|
wormhole: "Console 03 · Outposts",
|
||||||
activity: "Console 04 · Activity",
|
activity: "Console 04 · Activity",
|
||||||
|
access: "Console 05 · Access",
|
||||||
reconstitute: "Restore from a snapshot",
|
reconstitute: "Restore from a snapshot",
|
||||||
snapshot: "Recovery point",
|
snapshot: "Recovery point",
|
||||||
};
|
};
|
||||||
const panelWidths: Record<HUDMode, number> = { scene: 640, orbits: 1120, wormhole: 760, activity: 1120, reconstitute: 760, snapshot: 640 };
|
const panelWidths: Record<HUDMode, number> = { scene: 640, orbits: 1120, wormhole: 760, activity: 1120, access: 1120, reconstitute: 760, snapshot: 640 };
|
||||||
|
|
||||||
const LOOK_KEY = "tessera.look";
|
const LOOK_KEY = "tessera.look";
|
||||||
|
|
||||||
@@ -64,11 +68,15 @@ export default function App() {
|
|||||||
return <OperatorGate>{(operator) => <VaultApp {...operator} />}</OperatorGate>;
|
return <OperatorGate>{(operator) => <VaultApp {...operator} />}</OperatorGate>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promise<void> }) {
|
function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () => Promise<void>; caps: Caps }) {
|
||||||
const [logoutError, setLogoutError] = useState(false);
|
const [logoutError, setLogoutError] = useState(false);
|
||||||
const workspaceScroll = useRef<number>(undefined);
|
const workspaceScroll = useRef<number>(undefined);
|
||||||
const [bigScreen, setBigScreen] = useState(false);
|
const [bigScreen, setBigScreen] = useState(false);
|
||||||
const [radar, setRadar] = useState(readRadar);
|
const [radar, setRadar] = useState(readRadar);
|
||||||
|
// The look follows the account: the server's saved choice wins once, and a choice made before this existed is
|
||||||
|
// carried over. The browser copy stays as the instant first paint and as the fallback when there is no account.
|
||||||
|
const preferences = useQuery({ queryKey: ["preferences"], queryFn: ({ signal }) => fetchPreferences(signal), retry: false, staleTime: Infinity });
|
||||||
|
const adoptedLook = useRef(false);
|
||||||
const [mode, setMode] = useState<HUDMode>("scene");
|
const [mode, setMode] = useState<HUDMode>("scene");
|
||||||
const [searchOpen, setSearchOpen] = useState(false);
|
const [searchOpen, setSearchOpen] = useState(false);
|
||||||
const searchTrigger = useRef<HTMLButtonElement>(null);
|
const searchTrigger = useRef<HTMLButtonElement>(null);
|
||||||
@@ -83,6 +91,21 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis
|
|||||||
const reducedMotion = useReducedMotion();
|
const reducedMotion = useReducedMotion();
|
||||||
const qc = useQueryClient();
|
const qc = useQueryClient();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (adoptedLook.current || !preferences.isSuccess) return;
|
||||||
|
adoptedLook.current = true;
|
||||||
|
const saved = preferences.data.look;
|
||||||
|
if (saved) {
|
||||||
|
setRadar(saved === "radar");
|
||||||
|
try {
|
||||||
|
window.localStorage.setItem(LOOK_KEY, saved === "radar" ? "radar" : "realistic");
|
||||||
|
} catch {
|
||||||
|
// Not remembered in this browser; the account copy still applies.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (radar) void savePreferences({ look: "radar" }).catch(() => undefined);
|
||||||
|
}, [preferences.isSuccess, preferences.data, radar]);
|
||||||
|
|
||||||
useLayoutEffect(() => {
|
useLayoutEffect(() => {
|
||||||
function searchKeys(event: KeyboardEvent) {
|
function searchKeys(event: KeyboardEvent) {
|
||||||
const composing = event.isComposing || event.keyCode === 229;
|
const composing = event.isComposing || event.keyCode === 229;
|
||||||
@@ -137,6 +160,7 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis
|
|||||||
function toggleRadar() {
|
function toggleRadar() {
|
||||||
const next = !radar;
|
const next = !radar;
|
||||||
setRadar(next);
|
setRadar(next);
|
||||||
|
void savePreferences({ look: next ? "radar" : "window" }).catch(() => undefined);
|
||||||
try {
|
try {
|
||||||
window.localStorage.setItem(LOOK_KEY, next ? "radar" : "realistic");
|
window.localStorage.setItem(LOOK_KEY, next ? "radar" : "realistic");
|
||||||
} catch {
|
} catch {
|
||||||
@@ -207,7 +231,12 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis
|
|||||||
? { orbitId: captureOrbitId, key: capture.submittedAt, snapshotId: capture.data ?? undefined }
|
? { orbitId: captureOrbitId, key: capture.submittedAt, snapshotId: capture.data ?? undefined }
|
||||||
: undefined, [captureOrbitId, capture.submittedAt, capture.isError, capture.data]);
|
: undefined, [captureOrbitId, capture.submittedAt, capture.isError, capture.data]);
|
||||||
const captureReady = !!captureEffect?.snapshotId && !!snaps.data?.some(({ id }) => id === captureEffect.snapshotId);
|
const captureReady = !!captureEffect?.snapshotId && !!snaps.data?.some(({ id }) => id === captureEffect.snapshotId);
|
||||||
const activity = useActivity(snaps.data, orbits.data);
|
const activity = useActivity(snaps.data, orbits.data, caps.admin);
|
||||||
|
// Consoles a non-administrator never sees: managing orbits and Outposts, restores, and access.
|
||||||
|
const railItems = useMemo(
|
||||||
|
() => (caps.admin ? [...hudItems, accessItem] : hudItems.filter((item) => item.id === "scene" || item.id === "activity")),
|
||||||
|
[caps.admin],
|
||||||
|
);
|
||||||
const failedCount = sceneOrbits.filter(({ last_status }) => last_status === "failed").length;
|
const failedCount = sceneOrbits.filter(({ last_status }) => last_status === "failed").length;
|
||||||
|
|
||||||
const orbitMessage = orbits.isPending ? "Receiving orbit telemetry…" : orbits.isError
|
const orbitMessage = orbits.isPending ? "Receiving orbit telemetry…" : orbits.isError
|
||||||
@@ -246,6 +275,7 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis
|
|||||||
}
|
}
|
||||||
|
|
||||||
function openConsole(next: HUDMode, target: string | null = null) {
|
function openConsole(next: HUDMode, target: string | null = null) {
|
||||||
|
if (!caps.admin && next !== "scene" && next !== "activity" && next !== "snapshot") return;
|
||||||
if (next === "reconstitute" && !restoreBusy &&
|
if (next === "reconstitute" && !restoreBusy &&
|
||||||
(!restoreTarget || (target !== null && target !== restoreTarget.id))) {
|
(!restoreTarget || (target !== null && target !== restoreTarget.id))) {
|
||||||
setRestoreTarget({ id: target });
|
setRestoreTarget({ id: target });
|
||||||
@@ -283,7 +313,7 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis
|
|||||||
</svg>
|
</svg>
|
||||||
<div><strong>Tessera</strong><span>Flight deck · Backup control</span></div>
|
<div><strong>Tessera</strong><span>Flight deck · Backup control</span></div>
|
||||||
</div>
|
</div>
|
||||||
<HUDRail active={mode === "snapshot" || mode === "reconstitute" ? "scene" : mode} alerts={{ activity: activity.counts.needs > 0 }} floating={bigScreen} panelOpen={panelOpen} reducedMotion={reducedMotion} onSelect={openConsole} />
|
<HUDRail active={mode === "snapshot" || mode === "reconstitute" ? "scene" : mode} items={railItems} alerts={{ activity: activity.counts.needs > 0 }} floating={bigScreen} panelOpen={panelOpen} reducedMotion={reducedMotion} onSelect={openConsole} />
|
||||||
<div className="vault-topbar-tools">
|
<div className="vault-topbar-tools">
|
||||||
<p className="hub-link" role="status">
|
<p className="hub-link" role="status">
|
||||||
<span className={`register-signal signal-${online ? "green" : "grey"}`} />
|
<span className={`register-signal signal-${online ? "green" : "grey"}`} />
|
||||||
@@ -329,7 +359,7 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis
|
|||||||
/>
|
/>
|
||||||
<OrbitRegister
|
<OrbitRegister
|
||||||
orbits={register} selected={selected?.id} message={orbitMessage} bigScreen={bigScreen}
|
orbits={register} selected={selected?.id} message={orbitMessage} bigScreen={bigScreen}
|
||||||
onSelect={selectOrbit} onManage={() => setMode("orbits")}
|
onSelect={selectOrbit} onManage={() => openConsole("orbits")}
|
||||||
/>
|
/>
|
||||||
<OrbitInspector
|
<OrbitInspector
|
||||||
orbit={selected} snapshots={history} snapshotMessage={snapshotMessage}
|
orbit={selected} snapshots={history} snapshotMessage={snapshotMessage}
|
||||||
@@ -337,7 +367,7 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis
|
|||||||
onSelectSnapshot={openSnapshot}
|
onSelectSnapshot={openSnapshot}
|
||||||
capture={selected && (
|
capture={selected && (
|
||||||
<>
|
<>
|
||||||
<button
|
{caps.can("capture.run", selected.id) && <button
|
||||||
type="button" className="console-control capture-button"
|
type="button" className="console-control capture-button"
|
||||||
onClick={() => runCapture(selected)}
|
onClick={() => runCapture(selected)}
|
||||||
disabled={!online || capture.isPending || orbitStatus(selected.last_status).busy ||
|
disabled={!online || capture.isPending || orbitStatus(selected.last_status).busy ||
|
||||||
@@ -345,7 +375,7 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis
|
|||||||
>
|
>
|
||||||
<span aria-hidden="true">↘</span>
|
<span aria-hidden="true">↘</span>
|
||||||
<span>{selected.application_id ? "Queue backup for" : selected.dry_run ? "Rehearse" : "Capture"} {selected.name}</span>
|
<span>{selected.application_id ? "Queue backup for" : selected.dry_run ? "Rehearse" : "Capture"} {selected.name}</span>
|
||||||
</button>
|
</button>}
|
||||||
{noticeInInspector && mode !== "orbits" && captureNotice}
|
{noticeInInspector && mode !== "orbits" && captureNotice}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
@@ -369,8 +399,9 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis
|
|||||||
subtitle={mode === "reconstitute" ? "Review the destination before starting the restore." : undefined}
|
subtitle={mode === "reconstitute" ? "Review the destination before starting the restore." : undefined}
|
||||||
onClose={() => setMode("scene")}
|
onClose={() => setMode("scene")}
|
||||||
>
|
>
|
||||||
|
<PanelBoundary key={mode}>
|
||||||
<AnimatePresence initial={false}>
|
<AnimatePresence initial={false}>
|
||||||
{mode === "orbits" && (
|
{mode === "orbits" && caps.admin && (
|
||||||
<SpringPane key="orbits">
|
<SpringPane key="orbits">
|
||||||
<QueryGate query={orbits}>
|
<QueryGate query={orbits}>
|
||||||
{() => <OrbitsView snapshots={snaps.isSuccess ? snaps.data : undefined} orbits={sceneOrbits} onRun={runCapture} onOpenSnapshot={openSnapshot} captureDisabled={!online || capture.isPending} notice={captureNotice} />}
|
{() => <OrbitsView snapshots={snaps.isSuccess ? snaps.data : undefined} orbits={sceneOrbits} onRun={runCapture} onOpenSnapshot={openSnapshot} captureDisabled={!online || capture.isPending} notice={captureNotice} />}
|
||||||
@@ -392,13 +423,16 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis
|
|||||||
/>
|
/>
|
||||||
</SpringPane>
|
</SpringPane>
|
||||||
)}
|
)}
|
||||||
{mode === "wormhole" && (
|
{mode === "wormhole" && caps.admin && (
|
||||||
<SpringPane key="wormhole"><WormholeView pairing={pairing} onPaired={setPairing} /></SpringPane>
|
<SpringPane key="wormhole"><WormholeView pairing={pairing} onPaired={setPairing} /></SpringPane>
|
||||||
)}
|
)}
|
||||||
|
{mode === "access" && caps.admin && (
|
||||||
|
<SpringPane key="access"><AccessView orbits={orbits.data ?? []} /></SpringPane>
|
||||||
|
)}
|
||||||
{mode === "snapshot" && (
|
{mode === "snapshot" && (
|
||||||
<SpringPane key="snapshot">
|
<SpringPane key="snapshot">
|
||||||
{snapshot
|
{snapshot
|
||||||
? <SnapshotSheet snap={snapshot} siblings={snapshotSiblings} onDeleted={() => openConsole("scene")} onReconstitute={() => openConsole("reconstitute", snapshot.id)} />
|
? <SnapshotSheet snap={snapshot} siblings={snapshotSiblings} canManage={caps.admin} canDownload={caps.can("snapshot.download", snapshot.orbit_id)} onDeleted={() => openConsole("scene")} onReconstitute={() => openConsole("reconstitute", snapshot.id)} />
|
||||||
: <EmptyState title="Snapshot unavailable" body="It may have expired under the retention policy." />}
|
: <EmptyState title="Snapshot unavailable" body="It may have expired under the retention policy." />}
|
||||||
</SpringPane>
|
</SpringPane>
|
||||||
)}
|
)}
|
||||||
@@ -416,6 +450,7 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis
|
|||||||
</QueryGate>
|
</QueryGate>
|
||||||
))}
|
))}
|
||||||
</SpringPane>
|
</SpringPane>
|
||||||
|
</PanelBoundary>
|
||||||
</HUDPanel>
|
</HUDPanel>
|
||||||
<VaultSearch
|
<VaultSearch
|
||||||
open={searchOpen} reducedMotion={reducedMotion}
|
open={searchOpen} reducedMotion={reducedMotion}
|
||||||
|
|||||||
@@ -54,11 +54,77 @@ export type OperatorSession = {
|
|||||||
login_enabled: boolean;
|
login_enabled: boolean;
|
||||||
oidc_enabled: boolean;
|
oidc_enabled: boolean;
|
||||||
authorized: boolean;
|
authorized: boolean;
|
||||||
|
admin: boolean;
|
||||||
actor: string | null;
|
actor: string | null;
|
||||||
csrf: string | null;
|
csrf: string | null;
|
||||||
expires_at: number | null;
|
expires_at: number | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type MyGrant = { permission: string; orbit_id: string | null };
|
||||||
|
export type Me = {
|
||||||
|
id: string;
|
||||||
|
kind: string;
|
||||||
|
auth_method: string;
|
||||||
|
display_name: string;
|
||||||
|
admin: boolean;
|
||||||
|
capabilities: string[];
|
||||||
|
grants: MyGrant[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function fetchMe(signal?: AbortSignal): Promise<Me> {
|
||||||
|
return api<Me>("/api/v1/me", { signal });
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Look = "window" | "radar";
|
||||||
|
|
||||||
|
/** The account's saved display choices. A hub without this endpoint, or an account without one, yields `{}`. */
|
||||||
|
export async function fetchPreferences(signal?: AbortSignal): Promise<{ look?: Look }> {
|
||||||
|
const data = await api<unknown>("/api/v1/me/preferences", { signal }).catch(() => undefined);
|
||||||
|
const look = (data as { look?: unknown } | undefined)?.look;
|
||||||
|
return look === "window" || look === "radar" ? { look } : {};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const savePreferences = (preferences: { look?: Look }) =>
|
||||||
|
api<void>("/api/v1/me/preferences", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(preferences) });
|
||||||
|
|
||||||
|
export type Grant = {
|
||||||
|
id: string;
|
||||||
|
principal_type: "user" | "group";
|
||||||
|
principal: string;
|
||||||
|
permission: string;
|
||||||
|
scope_type: "global" | "orbit";
|
||||||
|
scope_id: string | null;
|
||||||
|
expires_at: number | null;
|
||||||
|
created_by: string;
|
||||||
|
created_at: number;
|
||||||
|
};
|
||||||
|
export type GrantList = { grants: Grant[]; roles: { name: string; permissions: string[] }[]; grantable: string[] };
|
||||||
|
export type AccessUser = {
|
||||||
|
id: string;
|
||||||
|
issuer: string;
|
||||||
|
display_name: string;
|
||||||
|
active: boolean;
|
||||||
|
created_at: number;
|
||||||
|
last_login_at: number | null;
|
||||||
|
is_emergency: boolean;
|
||||||
|
};
|
||||||
|
export type NewGrant = {
|
||||||
|
principal_type: "user" | "group";
|
||||||
|
principal: string;
|
||||||
|
role?: string;
|
||||||
|
orbit_id?: string;
|
||||||
|
expires_at?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const fetchGrants = () => api<GrantList>("/api/v1/access/grants");
|
||||||
|
export const fetchAccessUsers = () => api<AccessUser[]>("/api/v1/access/users");
|
||||||
|
export const createGrant = (grant: NewGrant) =>
|
||||||
|
api<Grant[]>("/api/v1/access/grants", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(grant) });
|
||||||
|
export const deleteGrant = (id: string) => api<void>(`/api/v1/access/grants/${id}`, { method: "DELETE" });
|
||||||
|
export const setUserActive = (id: string, active: boolean) =>
|
||||||
|
api<void>(`/api/v1/access/users/${id}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ active }) });
|
||||||
|
export const revokeUserSessions = (id: string) => api<void>(`/api/v1/access/users/${id}/revoke-sessions`, { method: "POST" });
|
||||||
|
|
||||||
let csrf: string | null = null;
|
let csrf: string | null = null;
|
||||||
|
|
||||||
export async function fetchOperatorSession(signal?: AbortSignal): Promise<OperatorSession> {
|
export async function fetchOperatorSession(signal?: AbortSignal): Promise<OperatorSession> {
|
||||||
|
|||||||
189
web/src/components/access/AccessView.tsx
Normal file
189
web/src/components/access/AccessView.tsx
Normal file
@@ -0,0 +1,189 @@
|
|||||||
|
import { useState, type FormEvent } from "react";
|
||||||
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import {
|
||||||
|
createGrant, deleteGrant, fetchAccessUsers, fetchGrants, fetchMe, revokeUserSessions, setUserActive,
|
||||||
|
type Grant, type NewGrant, type Orbit,
|
||||||
|
} from "../../api";
|
||||||
|
import { Button } from "../ui/Button";
|
||||||
|
import { DatePicker } from "../ui/DatePicker";
|
||||||
|
import { Select } from "../ui/Select";
|
||||||
|
|
||||||
|
const field = "field";
|
||||||
|
|
||||||
|
/** Today as `YYYY-MM-DD` in the viewer's own calendar (not UTC). */
|
||||||
|
function localToday() {
|
||||||
|
const now = new Date();
|
||||||
|
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function when(seconds: number | null) {
|
||||||
|
return seconds ? new Date(seconds * 1000).toLocaleString() : "never";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Who may see and do what. Everything here is administrator-only and takes effect on the user's next request. */
|
||||||
|
export function AccessView({ orbits }: { orbits: Orbit[] }) {
|
||||||
|
const qc = useQueryClient();
|
||||||
|
const grants = useQuery({ queryKey: ["access-grants"], queryFn: fetchGrants, refetchInterval: 10_000 });
|
||||||
|
const users = useQuery({ queryKey: ["access-users"], queryFn: fetchAccessUsers, refetchInterval: 10_000 });
|
||||||
|
const me = useQuery({ queryKey: ["me"], queryFn: ({ signal }) => fetchMe(signal) });
|
||||||
|
const refresh = () => {
|
||||||
|
void qc.invalidateQueries({ queryKey: ["access-grants"] });
|
||||||
|
void qc.invalidateQueries({ queryKey: ["access-users"] });
|
||||||
|
};
|
||||||
|
const add = useMutation({ mutationFn: (grant: NewGrant) => createGrant(grant), onSuccess: refresh });
|
||||||
|
const remove = useMutation({ mutationFn: deleteGrant, onSuccess: refresh });
|
||||||
|
const toggle = useMutation({ mutationFn: (v: { id: string; active: boolean }) => setUserActive(v.id, v.active), onSuccess: refresh });
|
||||||
|
const signOut = useMutation({ mutationFn: revokeUserSessions, onSuccess: refresh });
|
||||||
|
const [kind, setKind] = useState<"user" | "group">("user");
|
||||||
|
|
||||||
|
// Only trust a response that has the expected shape; an older hub or a mock may send something else.
|
||||||
|
const grantList = grants.data && Array.isArray(grants.data.grants) && Array.isArray(grants.data.roles) ? grants.data : undefined;
|
||||||
|
const userList = Array.isArray(users.data) ? users.data : undefined;
|
||||||
|
const userName = (id: string) => userList?.find((u) => u.id === id)?.display_name ?? id;
|
||||||
|
const orbitName = (id: string | null) => (id ? orbits.find((o) => o.id === id)?.name ?? id : "All orbits");
|
||||||
|
|
||||||
|
function submit(event: FormEvent<HTMLFormElement>) {
|
||||||
|
event.preventDefault();
|
||||||
|
const data = new FormData(event.currentTarget);
|
||||||
|
const text = (name: string) => String(data.get(name) ?? "").trim();
|
||||||
|
const expiry = text("expires");
|
||||||
|
add.mutate({
|
||||||
|
principal_type: kind,
|
||||||
|
principal: text("principal"),
|
||||||
|
role: text("role"),
|
||||||
|
...(text("orbit") ? { orbit_id: text("orbit") } : {}),
|
||||||
|
...(expiry ? { expires_at: new Date(`${expiry}T23:59:59`).toISOString() } : {}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Administrators hold every permission without grants, so only people other than you are worth listing here.
|
||||||
|
const pendingUsers = (userList ?? []).filter(
|
||||||
|
(u) => !u.is_emergency && `oidc:${u.id}` !== me.data?.id &&
|
||||||
|
!(grantList?.grants ?? []).some((g) => g.principal_type === "user" && g.principal === u.id),
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-8 p-6">
|
||||||
|
<section aria-labelledby="grant-heading">
|
||||||
|
<h3 id="grant-heading" className="text-lg font-semibold text-star-100">Give access</h3>
|
||||||
|
<p className="mt-1 text-sm text-star-300">
|
||||||
|
Administrators come from the SSO configuration. Everyone else sees only the orbits you grant here.
|
||||||
|
Group names are the values in the sign-in token's groups claim.
|
||||||
|
</p>
|
||||||
|
<form onSubmit={submit} className="mt-4 grid gap-4 sm:grid-cols-2">
|
||||||
|
<label className="text-sm text-star-300">
|
||||||
|
Grant to
|
||||||
|
<Select value={kind} onChange={(e) => setKind(e.target.value as "user" | "group")}>
|
||||||
|
<option value="user">A person who has signed in</option>
|
||||||
|
<option value="group">An identity-provider group</option>
|
||||||
|
</Select>
|
||||||
|
</label>
|
||||||
|
{kind === "user" ? (
|
||||||
|
<label className="text-sm text-star-300">
|
||||||
|
Person
|
||||||
|
<Select name="principal" required>
|
||||||
|
<option value="" disabled>Choose…</option>
|
||||||
|
{(userList ?? []).filter((u) => !u.is_emergency && u.active).map((u) => (
|
||||||
|
<option key={u.id} value={u.id}>{u.display_name}</option>
|
||||||
|
))}
|
||||||
|
</Select>
|
||||||
|
</label>
|
||||||
|
) : (
|
||||||
|
<label className="text-sm text-star-300">
|
||||||
|
Group name
|
||||||
|
<input name="principal" required maxLength={128} className={field} autoComplete="off" />
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
<label className="text-sm text-star-300">
|
||||||
|
Access
|
||||||
|
<Select name="role" required defaultValue="viewer">
|
||||||
|
{(grantList?.roles ?? []).map((r) => (
|
||||||
|
<option key={r.name} value={r.name}>{r.name} — {r.permissions.join(", ")}</option>
|
||||||
|
))}
|
||||||
|
</Select>
|
||||||
|
</label>
|
||||||
|
<label className="text-sm text-star-300">
|
||||||
|
Orbit
|
||||||
|
<Select name="orbit">
|
||||||
|
<option value="">All orbits</option>
|
||||||
|
{orbits.map((o) => <option key={o.id} value={o.id}>{o.name}</option>)}
|
||||||
|
</Select>
|
||||||
|
</label>
|
||||||
|
<label className="text-sm text-star-300">
|
||||||
|
Ends on (optional)
|
||||||
|
<DatePicker name="expires" aria-label="Ends on" placeholder="No end date" min={localToday()} />
|
||||||
|
</label>
|
||||||
|
<div className="flex items-end">
|
||||||
|
<Button type="submit" variant="primary" disabled={add.isPending}>{add.isPending ? "Saving…" : "Grant access"}</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
{add.isError && <p role="alert" className="mt-3 text-sm text-orbit-red">Could not grant access. Check the person, the orbit and the end date; an identical grant may already exist.</p>}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section aria-labelledby="grants-heading">
|
||||||
|
<h3 id="grants-heading" className="text-lg font-semibold text-star-100">Current access</h3>
|
||||||
|
{grants.isPending ? <p role="status" className="mt-2 text-star-300">Loading…</p>
|
||||||
|
: grants.isError || !grantList ? <p role="alert" className="mt-2 text-star-300">Could not load grants. This hub may not support access management.</p>
|
||||||
|
: grantList.grants.length === 0 ? <p className="mt-2 text-star-300">Nobody has been granted access yet.</p>
|
||||||
|
: (
|
||||||
|
<div className="mt-3 overflow-x-auto">
|
||||||
|
<table className="w-full text-left text-sm">
|
||||||
|
<thead className="text-star-300">
|
||||||
|
<tr><th className="py-2 pr-4">Who</th><th className="pr-4">Permission</th><th className="pr-4">Orbit</th><th className="pr-4">Ends</th><th /></tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{grantList.grants.map((g: Grant) => (
|
||||||
|
<tr key={g.id} className="border-t border-space-700 text-star-100">
|
||||||
|
<td className="py-2 pr-4">{g.principal_type === "group" ? `Group ${g.principal}` : userName(g.principal)}</td>
|
||||||
|
<td className="pr-4">{g.permission}</td>
|
||||||
|
<td className="pr-4">{orbitName(g.scope_id)}</td>
|
||||||
|
<td className="pr-4">{when(g.expires_at)}</td>
|
||||||
|
<td className="text-right">
|
||||||
|
<Button disabled={remove.isPending} onClick={() => remove.mutate(g.id)} aria-label={`Remove ${g.permission} from ${g.principal_type === "group" ? g.principal : userName(g.principal)}`}>Remove</Button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section aria-labelledby="users-heading">
|
||||||
|
<h3 id="users-heading" className="text-lg font-semibold text-star-100">People who have signed in</h3>
|
||||||
|
{pendingUsers.length > 0 && (
|
||||||
|
<p className="mt-1 text-sm text-star-300">
|
||||||
|
Signed in but not granted anything yet: {pendingUsers.map((u) => u.display_name).join(", ")}. Administrators from the SSO settings are not shown as waiting.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{userList && (
|
||||||
|
<div className="mt-3 overflow-x-auto">
|
||||||
|
<table className="w-full text-left text-sm">
|
||||||
|
<thead className="text-star-300"><tr><th className="py-2 pr-4">Name</th><th className="pr-4">Last sign-in</th><th className="pr-4">Status</th><th /></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{userList.map((u) => (
|
||||||
|
<tr key={u.id} className="border-t border-space-700 text-star-100">
|
||||||
|
<td className="py-2 pr-4">{u.display_name}{u.is_emergency ? " (emergency operator)" : ""}</td>
|
||||||
|
<td className="pr-4">{when(u.last_login_at)}</td>
|
||||||
|
<td className="pr-4">{u.active ? "Active" : "Disabled"}</td>
|
||||||
|
<td className="space-x-2 text-right">
|
||||||
|
{!u.is_emergency && (
|
||||||
|
<>
|
||||||
|
<Button disabled={signOut.isPending} onClick={() => signOut.mutate(u.id)}>Sign out everywhere</Button>
|
||||||
|
<Button disabled={toggle.isPending} onClick={() => toggle.mutate({ id: u.id, active: !u.active })}>
|
||||||
|
{u.active ? "Disable" : "Enable"}
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{(toggle.isError || signOut.isError) && <p role="alert" className="mt-3 text-sm text-orbit-red">That change was refused. You cannot disable yourself or the emergency operator.</p>}
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -3,7 +3,7 @@ import { useCallback, useId, useLayoutEffect, useRef, type PointerEvent } from "
|
|||||||
import { useScreenTransition } from "../../hooks/useScreenTransition";
|
import { useScreenTransition } from "../../hooks/useScreenTransition";
|
||||||
import { uiSpring } from "../../lib/motion";
|
import { uiSpring } from "../../lib/motion";
|
||||||
|
|
||||||
export type HUDMode = "scene" | "orbits" | "wormhole" | "activity" | "reconstitute" | "snapshot";
|
export type HUDMode = "scene" | "orbits" | "wormhole" | "activity" | "access" | "reconstitute" | "snapshot";
|
||||||
|
|
||||||
export const hudItems = [
|
export const hudItems = [
|
||||||
{ id: "scene", label: "Vault", icon: "M4 9l8-4 8 4v6l-8 4-8-4z M4 9l8 4 8-4 M12 13v6" },
|
{ id: "scene", label: "Vault", icon: "M4 9l8-4 8 4v6l-8 4-8-4z M4 9l8 4 8-4 M12 13v6" },
|
||||||
@@ -12,12 +12,22 @@ export const hudItems = [
|
|||||||
{ id: "activity", label: "Activity", icon: "M3 12h4l3-7 4 14 3-7h4" },
|
{ id: "activity", label: "Activity", icon: "M3 12h4l3-7 4 14 3-7h4" },
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
|
export type HUDItem = { id: HUDMode; label: string; icon: string };
|
||||||
|
|
||||||
|
/** Only for administrators: who may see and do what. */
|
||||||
|
export const accessItem: HUDItem = {
|
||||||
|
id: "access", label: "Access",
|
||||||
|
icon: "M12 3l7 3v5c0 4.5-3 8-7 10-4-2-7-5.5-7-10V6z M9.5 12l2 2 3.5-4",
|
||||||
|
};
|
||||||
|
|
||||||
type Slot = { center: number; width: number };
|
type Slot = { center: number; width: number };
|
||||||
type Gesture = { pointer: number; x: number; y: number; origin?: number };
|
type Gesture = { pointer: number; x: number; y: number; origin?: number };
|
||||||
|
|
||||||
export function HUDRail({
|
export function HUDRail({
|
||||||
active, floating, panelOpen, reducedMotion, alerts, onSelect,
|
active, floating, panelOpen, reducedMotion, alerts, items = hudItems, onSelect,
|
||||||
}: {
|
}: {
|
||||||
|
/** The systems this user may open. */
|
||||||
|
items?: readonly HUDItem[];
|
||||||
active: HUDMode;
|
active: HUDMode;
|
||||||
/** Tabs with something that needs a person: their lamp turns ember even when they are not the active tab. */
|
/** Tabs with something that needs a person: their lamp turns ember even when they are not the active tab. */
|
||||||
alerts?: Partial<Record<HUDMode, boolean>>;
|
alerts?: Partial<Record<HUDMode, boolean>>;
|
||||||
@@ -36,7 +46,7 @@ export function HUDRail({
|
|||||||
const velocity = useVelocity(center);
|
const velocity = useVelocity(center);
|
||||||
const tail = useTransform(() => center.get() - Math.max(-22, Math.min(22, velocity.get() * 0.032)));
|
const tail = useTransform(() => center.get() - Math.max(-22, Math.min(22, velocity.get() * 0.032)));
|
||||||
const id = useId();
|
const id = useId();
|
||||||
const activeIndex = Math.max(0, hudItems.findIndex(item => item.id === active));
|
const activeIndex = Math.max(0, items.findIndex(item => item.id === active));
|
||||||
|
|
||||||
const snap = useCallback((index: number, immediate = false) => {
|
const snap = useCallback((index: number, immediate = false) => {
|
||||||
const slot = slots.current[index];
|
const slot = slots.current[index];
|
||||||
@@ -117,7 +127,7 @@ export function HUDRail({
|
|||||||
Math.abs(slot.center - projected) < Math.abs(slots.current[nearest].center - projected) ? index : nearest,
|
Math.abs(slot.center - projected) < Math.abs(slots.current[nearest].center - projected) ? index : nearest,
|
||||||
0);
|
0);
|
||||||
if (next === activeIndex) snap(activeIndex);
|
if (next === activeIndex) snap(activeIndex);
|
||||||
else onSelect(hudItems[next].id);
|
else onSelect(items[next].id);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -166,7 +176,7 @@ export function HUDRail({
|
|||||||
<span aria-hidden="true" className="nav-text-dock" />
|
<span aria-hidden="true" className="nav-text-dock" />
|
||||||
<motion.span aria-hidden="true" className="nav-underline" style={{ x: center, width }}
|
<motion.span aria-hidden="true" className="nav-underline" style={{ x: center, width }}
|
||||||
initial={false} animate={{ opacity: floating ? 0 : 1 }} />
|
initial={false} animate={{ opacity: floating ? 0 : 1 }} />
|
||||||
{hudItems.map(({ id, label, icon }) => (
|
{items.map(({ id, label, icon }) => (
|
||||||
<button
|
<button
|
||||||
key={id}
|
key={id}
|
||||||
type="button"
|
type="button"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useEffect, useState, type FormEvent, type ReactNode } from "react";
|
import { useEffect, useState, type FormEvent, type ReactNode } from "react";
|
||||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import { fetchOperatorSession, loginOperator, logoutOperator } from "../../api";
|
import { fetchMe, fetchOperatorSession, loginOperator, logoutOperator, type Me } from "../../api";
|
||||||
import { Button } from "../ui/Button";
|
import { Button } from "../ui/Button";
|
||||||
|
|
||||||
const SSO_ERRORS: Record<string, string> = {
|
const SSO_ERRORS: Record<string, string> = {
|
||||||
@@ -20,10 +20,25 @@ function useSsoError() {
|
|||||||
return code ? SSO_ERRORS[code] ?? SSO_ERRORS.failed : undefined;
|
return code ? SSO_ERRORS[code] ?? SSO_ERRORS.failed : undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** What the signed-in user may do. The hub enforces it; this only decides what is worth showing. */
|
||||||
|
export type Caps = {
|
||||||
|
admin: boolean;
|
||||||
|
can: (permission: string, orbitId?: string) => boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function capsFrom(me: Me | undefined, admin: boolean): Caps {
|
||||||
|
return {
|
||||||
|
admin,
|
||||||
|
can: (permission, orbitId) =>
|
||||||
|
// A hub or mock that does not send grants simply grants nothing here; the server decides anyway.
|
||||||
|
admin || (Array.isArray(me?.grants) && me.grants.some((g) => g.permission === permission && (g.orbit_id === null || g.orbit_id === orbitId))),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export function OperatorGate({
|
export function OperatorGate({
|
||||||
children,
|
children,
|
||||||
}: {
|
}: {
|
||||||
children: (operator: { actor?: string; onLogout?: () => Promise<void> }) => ReactNode;
|
children: (operator: { actor?: string; onLogout?: () => Promise<void>; caps: Caps }) => ReactNode;
|
||||||
}) {
|
}) {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const session = useQuery({
|
const session = useQuery({
|
||||||
@@ -32,6 +47,8 @@ export function OperatorGate({
|
|||||||
refetchInterval: 15_000,
|
refetchInterval: 15_000,
|
||||||
retry: false,
|
retry: false,
|
||||||
});
|
});
|
||||||
|
const signedIn = session.isSuccess && session.data.authorized;
|
||||||
|
const me = useQuery({ queryKey: ["me"], queryFn: ({ signal }) => fetchMe(signal), enabled: signedIn, refetchInterval: 15_000, retry: false });
|
||||||
const [pending, setPending] = useState(false);
|
const [pending, setPending] = useState(false);
|
||||||
const [error, setError] = useState<string>();
|
const [error, setError] = useState<string>();
|
||||||
const ssoError = useSsoError();
|
const ssoError = useSsoError();
|
||||||
@@ -61,14 +78,20 @@ export function OperatorGate({
|
|||||||
await logoutOperator();
|
await logoutOperator();
|
||||||
queryClient.setQueryData(["operator-session"], {
|
queryClient.setQueryData(["operator-session"], {
|
||||||
login_enabled: session.data.login_enabled, oidc_enabled: session.data.oidc_enabled,
|
login_enabled: session.data.login_enabled, oidc_enabled: session.data.oidc_enabled,
|
||||||
authorized: false, actor: null, csrf: null, expires_at: null,
|
authorized: false, admin: false, actor: null, csrf: null, expires_at: null,
|
||||||
});
|
});
|
||||||
queryClient.removeQueries({ predicate: (query) => query.queryKey[0] !== "operator-session" });
|
queryClient.removeQueries({ predicate: (query) => query.queryKey[0] !== "operator-session" });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (session.isSuccess && session.data.authorized) {
|
if (session.isSuccess && session.data.authorized) {
|
||||||
const actor = session.data.actor ?? undefined;
|
const actor = session.data.actor ?? undefined;
|
||||||
return children({ actor, onLogout: actor ? signOut : undefined });
|
// Hold the app back for a moment so a viewer never fires an administrator-only request while permissions load.
|
||||||
|
// A hub older than the access model sends no `admin` flag and only ever had administrators.
|
||||||
|
const admin = session.data.admin ?? true;
|
||||||
|
if (!admin && !me.isSuccess) {
|
||||||
|
return <main className="vault-app flex min-h-screen items-center justify-center"><p role="status" className="text-star-300">Loading your access…</p></main>;
|
||||||
|
}
|
||||||
|
return children({ actor, onLogout: actor ? signOut : undefined, caps: capsFrom(me.data, admin) });
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
193
web/src/components/ui/DatePicker.tsx
Normal file
193
web/src/components/ui/DatePicker.tsx
Normal file
@@ -0,0 +1,193 @@
|
|||||||
|
import { useEffect, useId, useLayoutEffect, useRef, useState, type KeyboardEvent } from "react";
|
||||||
|
import { createPortal } from "react-dom";
|
||||||
|
import { motion } from "motion/react";
|
||||||
|
|
||||||
|
const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
|
||||||
|
const WEEKDAYS = ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"];
|
||||||
|
|
||||||
|
type Day = { y: number; m: number; d: number };
|
||||||
|
const pad = (n: number) => String(n).padStart(2, "0");
|
||||||
|
const iso = ({ y, m, d }: Day) => `${y}-${pad(m + 1)}-${pad(d)}`;
|
||||||
|
const sameDay = (a: Day, b: Day) => a.y === b.y && a.m === b.m && a.d === b.d;
|
||||||
|
const fromDate = (date: Date): Day => ({ y: date.getFullYear(), m: date.getMonth(), d: date.getDate() });
|
||||||
|
const toDate = ({ y, m, d }: Day) => new Date(y, m, d);
|
||||||
|
const shift = (day: Day, days: number): Day => fromDate(new Date(day.y, day.m, day.d + days));
|
||||||
|
const shiftMonth = (day: Day, months: number): Day => {
|
||||||
|
const target = new Date(day.y, day.m + months, 1);
|
||||||
|
const last = new Date(target.getFullYear(), target.getMonth() + 1, 0).getDate();
|
||||||
|
return { y: target.getFullYear(), m: target.getMonth(), d: Math.min(day.d, last) };
|
||||||
|
};
|
||||||
|
function parse(text: string): Day | undefined {
|
||||||
|
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text);
|
||||||
|
if (!match) return undefined;
|
||||||
|
const day = { y: +match[1], m: +match[2] - 1, d: +match[3] };
|
||||||
|
return iso(fromDate(toDate(day))) === text ? day : undefined;
|
||||||
|
}
|
||||||
|
const label = (day: Day) => toDate(day).toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" });
|
||||||
|
|
||||||
|
type Place = { left: number; top?: number; bottom?: number };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A themed date field in the same family as `Select`: a trigger styled like every other field, a calendar drawn in a
|
||||||
|
* portal so a console's scroll never clips it, and a hidden input that carries `YYYY-MM-DD` into forms. The grid is a
|
||||||
|
* roving-tabindex table driven by the arrow keys, PageUp/PageDown for months, Home/End for the week, Escape to close.
|
||||||
|
*/
|
||||||
|
export function DatePicker({
|
||||||
|
name, value, defaultValue = "", onChange, min, "aria-label": ariaLabel, placeholder = "Pick a date", clearable = true,
|
||||||
|
}: {
|
||||||
|
name?: string;
|
||||||
|
value?: string;
|
||||||
|
defaultValue?: string;
|
||||||
|
onChange?: (value: string) => void;
|
||||||
|
/** Earliest selectable day, `YYYY-MM-DD`. */
|
||||||
|
min?: string;
|
||||||
|
"aria-label"?: string;
|
||||||
|
placeholder?: string;
|
||||||
|
clearable?: boolean;
|
||||||
|
}) {
|
||||||
|
const [inner, setInner] = useState(defaultValue);
|
||||||
|
const current = value ?? inner;
|
||||||
|
const selected = parse(current);
|
||||||
|
const earliest = min ? parse(min) : undefined;
|
||||||
|
const today = fromDate(new Date());
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const [focus, setFocus] = useState<Day>(selected ?? today);
|
||||||
|
const [place, setPlace] = useState<Place>();
|
||||||
|
const trigger = useRef<HTMLButtonElement>(null);
|
||||||
|
const panel = useRef<HTMLDivElement>(null);
|
||||||
|
const id = useId();
|
||||||
|
|
||||||
|
const blocked = (day: Day) => !!earliest && toDate(day) < toDate(earliest);
|
||||||
|
|
||||||
|
function commit(day: Day | undefined) {
|
||||||
|
const next = day ? iso(day) : "";
|
||||||
|
setInner(next);
|
||||||
|
onChange?.(next);
|
||||||
|
setOpen(false);
|
||||||
|
trigger.current?.focus();
|
||||||
|
}
|
||||||
|
|
||||||
|
function show() {
|
||||||
|
const start = selected ?? (earliest && blocked(today) ? earliest : today);
|
||||||
|
setFocus(start);
|
||||||
|
setOpen(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
const rect = trigger.current!.getBoundingClientRect();
|
||||||
|
const height = 330;
|
||||||
|
const flip = window.innerHeight - rect.bottom < height + 12 && rect.top > window.innerHeight - rect.bottom;
|
||||||
|
setPlace({
|
||||||
|
left: Math.max(8, Math.min(rect.left, window.innerWidth - 300)),
|
||||||
|
...(flip ? { bottom: window.innerHeight - rect.top + 6 } : { top: rect.bottom + 6 }),
|
||||||
|
});
|
||||||
|
}, [open]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
const close = () => setOpen(false);
|
||||||
|
const outside = (event: PointerEvent) => {
|
||||||
|
const target = event.target as Node;
|
||||||
|
if (!panel.current?.contains(target) && !trigger.current?.contains(target)) setOpen(false);
|
||||||
|
};
|
||||||
|
window.addEventListener("pointerdown", outside, true);
|
||||||
|
window.addEventListener("resize", close);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener("pointerdown", outside, true);
|
||||||
|
window.removeEventListener("resize", close);
|
||||||
|
};
|
||||||
|
}, [open]);
|
||||||
|
|
||||||
|
// Keep keyboard focus on the day the arrows point at.
|
||||||
|
useEffect(() => {
|
||||||
|
if (open && place) panel.current?.querySelector<HTMLButtonElement>(`[data-day="${iso(focus)}"]`)?.focus();
|
||||||
|
}, [open, place, focus]);
|
||||||
|
|
||||||
|
function keys(event: KeyboardEvent<HTMLElement>) {
|
||||||
|
const moves: Record<string, () => Day> = {
|
||||||
|
ArrowLeft: () => shift(focus, -1),
|
||||||
|
ArrowRight: () => shift(focus, 1),
|
||||||
|
ArrowUp: () => shift(focus, -7),
|
||||||
|
ArrowDown: () => shift(focus, 7),
|
||||||
|
PageUp: () => shiftMonth(focus, -1),
|
||||||
|
PageDown: () => shiftMonth(focus, 1),
|
||||||
|
Home: () => shift(focus, -((toDate(focus).getDay() + 6) % 7)),
|
||||||
|
End: () => shift(focus, 6 - ((toDate(focus).getDay() + 6) % 7)),
|
||||||
|
};
|
||||||
|
if (event.key === "Escape") {
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
setOpen(false);
|
||||||
|
trigger.current?.focus();
|
||||||
|
} else if (moves[event.key]) {
|
||||||
|
event.preventDefault();
|
||||||
|
setFocus(moves[event.key]());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Six weeks starting on Monday, so the grid never changes height.
|
||||||
|
const first = new Date(focus.y, focus.m, 1);
|
||||||
|
const lead = (first.getDay() + 6) % 7;
|
||||||
|
const cells = Array.from({ length: 42 }, (_, i) => fromDate(new Date(focus.y, focus.m, 1 - lead + i)));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<button
|
||||||
|
ref={trigger} type="button" className="field select-trigger" aria-label={ariaLabel} aria-haspopup="dialog"
|
||||||
|
aria-expanded={open} aria-controls={open ? id : undefined}
|
||||||
|
onClick={() => (open ? setOpen(false) : show())}
|
||||||
|
onKeyDown={(event) => {
|
||||||
|
if (!open && (event.key === "ArrowDown" || event.key === "Enter" || event.key === " ")) {
|
||||||
|
event.preventDefault();
|
||||||
|
show();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span className="select-value" data-placeholder={!selected || undefined}>{selected ? label(selected) : placeholder}</span>
|
||||||
|
<svg viewBox="0 0 16 16" width="15" height="15" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"
|
||||||
|
strokeLinejoin="round" aria-hidden="true" className="select-chevron">
|
||||||
|
<rect x="2.5" y="3.5" width="11" height="10" rx="1.5" /><path d="M2.5 6.5h11M5.5 2v3M10.5 2v3" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
<input className="select-proxy" tabIndex={-1} aria-hidden="true" name={name} value={current} onChange={() => {}} />
|
||||||
|
{open && place && createPortal(
|
||||||
|
<motion.div
|
||||||
|
ref={panel} id={id} role="dialog" aria-label={`${ariaLabel ?? "Date"} calendar`} className="datepicker"
|
||||||
|
style={{ left: place.left, top: place.top, bottom: place.bottom }}
|
||||||
|
initial={{ opacity: 0, y: place.bottom === undefined ? -6 : 6 }} animate={{ opacity: 1, y: 0 }}
|
||||||
|
onKeyDown={keys}
|
||||||
|
>
|
||||||
|
<div className="datepicker-head">
|
||||||
|
<button type="button" aria-label="Previous month" onClick={() => setFocus(shiftMonth(focus, -1))}>‹</button>
|
||||||
|
<span aria-live="polite">{MONTHS[focus.m]} {focus.y}</span>
|
||||||
|
<button type="button" aria-label="Next month" onClick={() => setFocus(shiftMonth(focus, 1))}>›</button>
|
||||||
|
</div>
|
||||||
|
<div className="datepicker-grid" role="grid" aria-label={`${MONTHS[focus.m]} ${focus.y}`}>
|
||||||
|
{WEEKDAYS.map((day) => <span key={day} className="datepicker-weekday" role="columnheader">{day}</span>)}
|
||||||
|
{cells.map((day) => {
|
||||||
|
const outside = day.m !== focus.m;
|
||||||
|
const disabled = blocked(day);
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={iso(day)} type="button" role="gridcell" data-day={iso(day)} disabled={disabled}
|
||||||
|
tabIndex={sameDay(day, focus) ? 0 : -1}
|
||||||
|
data-outside={outside || undefined} data-today={sameDay(day, today) || undefined}
|
||||||
|
aria-selected={!!selected && sameDay(day, selected)} aria-current={sameDay(day, today) ? "date" : undefined}
|
||||||
|
onClick={() => commit(day)}
|
||||||
|
>
|
||||||
|
{day.d}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
<div className="datepicker-foot">
|
||||||
|
<button type="button" disabled={blocked(today)} onClick={() => commit(today)}>Today</button>
|
||||||
|
{clearable && <button type="button" disabled={!selected} onClick={() => commit(undefined)}>Clear</button>}
|
||||||
|
</div>
|
||||||
|
</motion.div>,
|
||||||
|
document.body,
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
24
web/src/components/ui/PanelBoundary.tsx
Normal file
24
web/src/components/ui/PanelBoundary.tsx
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
import { Component, type ReactNode } from "react";
|
||||||
|
|
||||||
|
/** One console failing to render must not blank the whole app. */
|
||||||
|
export class PanelBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {
|
||||||
|
state = { failed: false };
|
||||||
|
|
||||||
|
static getDerivedStateFromError() {
|
||||||
|
return { failed: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
componentDidCatch(error: unknown) {
|
||||||
|
console.error("console failed to render", error);
|
||||||
|
}
|
||||||
|
|
||||||
|
render() {
|
||||||
|
if (!this.state.failed) return this.props.children;
|
||||||
|
return (
|
||||||
|
<div role="alert" className="mx-auto max-w-sm px-4 py-12 text-center">
|
||||||
|
<h3 className="text-lg font-semibold text-star-100">This console could not be shown</h3>
|
||||||
|
<p className="mt-2 text-sm text-star-300">The hub sent something this version does not understand. Close the panel and try again.</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,12 +17,17 @@ export function SnapshotSheet({
|
|||||||
siblings = [],
|
siblings = [],
|
||||||
onReconstitute,
|
onReconstitute,
|
||||||
onDeleted,
|
onDeleted,
|
||||||
|
canManage = false,
|
||||||
|
canDownload = false,
|
||||||
}: {
|
}: {
|
||||||
snap: Snapshot;
|
snap: Snapshot;
|
||||||
/** Every snapshot of the same orbit, newest first, including this one. */
|
/** Every snapshot of the same orbit, newest first, including this one. */
|
||||||
siblings?: Snapshot[];
|
siblings?: Snapshot[];
|
||||||
onReconstitute: () => void;
|
onReconstitute: () => void;
|
||||||
onDeleted: () => void;
|
onDeleted: () => void;
|
||||||
|
/** Administrators only: restore and delete. */
|
||||||
|
canManage?: boolean;
|
||||||
|
canDownload?: boolean;
|
||||||
}) {
|
}) {
|
||||||
const [confirmDelete, setConfirmDelete] = useState(false);
|
const [confirmDelete, setConfirmDelete] = useState(false);
|
||||||
const [copied, setCopied] = useState(false);
|
const [copied, setCopied] = useState(false);
|
||||||
@@ -99,17 +104,17 @@ export function SnapshotSheet({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="sheet-actions">
|
<div className="sheet-actions">
|
||||||
<Button variant="primary" className="sheet-primary" onClick={onReconstitute}>
|
{canManage && <Button variant="primary" className="sheet-primary" onClick={onReconstitute}>
|
||||||
{database ? "Database recovery options" : "Export file on hub"}
|
{database ? "Database recovery options" : "Export file on hub"}
|
||||||
<span aria-hidden="true">→</span>
|
<span aria-hidden="true">→</span>
|
||||||
</Button>
|
</Button>}
|
||||||
<a href={`/api/v1/snapshots/${snap.id}/download`} download className="console-control sheet-link">
|
{canDownload && <a href={`/api/v1/snapshots/${snap.id}/download`} download className="console-control sheet-link">
|
||||||
Download snapshot
|
Download snapshot
|
||||||
<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
|
<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
|
||||||
<path d="M8 2v8M4.5 7 8 10.5 11.5 7M3 13.5h10" />
|
<path d="M8 2v8M4.5 7 8 10.5 11.5 7M3 13.5h10" />
|
||||||
</svg>
|
</svg>
|
||||||
</a>
|
</a>}
|
||||||
{confirmDelete ? (
|
{canManage && (confirmDelete ? (
|
||||||
<div className="sheet-confirm" role="alertdialog" aria-label="Confirm deletion">
|
<div className="sheet-confirm" role="alertdialog" aria-label="Confirm deletion">
|
||||||
<p>Remove this recovery point from the hub catalogue? This cannot be undone.</p>
|
<p>Remove this recovery point from the hub catalogue? This cannot be undone.</p>
|
||||||
{deletion.isError && <p role="alert" className="text-orbit-red">Snapshot could not be removed. It may be in use.</p>}
|
{deletion.isError && <p role="alert" className="text-orbit-red">Snapshot could not be removed. It may be in use.</p>}
|
||||||
@@ -122,7 +127,7 @@ export function SnapshotSheet({
|
|||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<button type="button" className="sheet-delete" onClick={() => setConfirmDelete(true)}>Delete snapshot</button>
|
<button type="button" className="sheet-delete" onClick={() => setConfirmDelete(true)}>Delete snapshot</button>
|
||||||
)}
|
))}
|
||||||
</div>
|
</div>
|
||||||
<TelemetryPanel label="Snapshot record">{JSON.stringify(snap, null, 2)}</TelemetryPanel>
|
<TelemetryPanel label="Snapshot record">{JSON.stringify(snap, null, 2)}</TelemetryPanel>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -4,8 +4,9 @@ import { fetchCaptureJobs, fetchRecentRestoreJobs, type Orbit, type Snapshot } f
|
|||||||
import { activityCounts, buildActivity } from "../lib/activity";
|
import { activityCounts, buildActivity } from "../lib/activity";
|
||||||
|
|
||||||
/** Everything the hub reports as backups and restores, folded into one log. Polling shares keys with the Orbits console. */
|
/** Everything the hub reports as backups and restores, folded into one log. Polling shares keys with the Orbits console. */
|
||||||
export function useActivity(snapshots?: Snapshot[], orbits?: Orbit[]) {
|
export function useActivity(snapshots?: Snapshot[], orbits?: Orbit[], canSeeRestores = true) {
|
||||||
const restores = useQuery({ queryKey: ["restore-jobs-recent"], queryFn: () => fetchRecentRestoreJobs(100), refetchInterval: 5_000, retry: false });
|
// Restore history is administrator-only; asking would only produce a 403.
|
||||||
|
const restores = useQuery({ queryKey: ["restore-jobs-recent"], queryFn: () => fetchRecentRestoreJobs(100), refetchInterval: 5_000, retry: false, enabled: canSeeRestores });
|
||||||
const captures = useQuery({ queryKey: ["capture-jobs", "", ""], queryFn: () => fetchCaptureJobs("", ""), refetchInterval: 5_000, retry: 1 });
|
const captures = useQuery({ queryKey: ["capture-jobs", "", ""], queryFn: () => fetchCaptureJobs("", ""), refetchInterval: 5_000, retry: 1 });
|
||||||
const restoreData = restores.data;
|
const restoreData = restores.data;
|
||||||
const captureData = captures.data;
|
const captureData = captures.data;
|
||||||
@@ -19,7 +20,7 @@ export function useActivity(snapshots?: Snapshot[], orbits?: Orbit[]) {
|
|||||||
return {
|
return {
|
||||||
entries,
|
entries,
|
||||||
counts: activityCounts(entries),
|
counts: activityCounts(entries),
|
||||||
restoresUnavailable: restores.isError,
|
restoresUnavailable: canSeeRestores && restores.isError,
|
||||||
capturesUnavailable: captures.isError,
|
capturesUnavailable: captures.isError,
|
||||||
updatedAt: Math.max(restores.dataUpdatedAt, captures.dataUpdatedAt),
|
updatedAt: Math.max(restores.dataUpdatedAt, captures.dataUpdatedAt),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1025,3 +1025,31 @@ button.act-row[data-group="needs"]:hover { background: #20161a; }
|
|||||||
.act-state { grid-column: 3; grid-row: 1; flex-direction: row; align-items: center; gap: 8px; }
|
.act-state { grid-column: 3; grid-row: 1; flex-direction: row; align-items: center; gap: 8px; }
|
||||||
.act-open { grid-column: 1 / -1; grid-row: 3; justify-self: start; }
|
.act-open { grid-column: 1 / -1; grid-row: 3; justify-self: start; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Date field: the calendar shares the select list's surface so every popover on a console looks alike. */
|
||||||
|
.select-value[data-placeholder] { color: var(--quiet); }
|
||||||
|
.datepicker {
|
||||||
|
position: fixed; z-index: 80; width: 284px; box-sizing: border-box; padding: 10px;
|
||||||
|
background: #111418; border: 1px solid #3a3f46; border-radius: 9px;
|
||||||
|
box-shadow: 0 18px 50px #000c, inset 0 1px 0 #ffffff10;
|
||||||
|
}
|
||||||
|
.datepicker-head { display: flex; align-items: center; justify-content: space-between; padding: 2px 2px 8px; font: 500 13px var(--font-sans); color: var(--color-star-100); }
|
||||||
|
.datepicker-head button, .datepicker-foot button {
|
||||||
|
min-width: 32px; height: 32px; padding: 0 10px; border: 1px solid #2f343b; border-radius: 6px; background: #14171b;
|
||||||
|
color: var(--color-star-200); font: 13px var(--font-sans); cursor: pointer;
|
||||||
|
}
|
||||||
|
.datepicker-head button:hover:not(:disabled), .datepicker-foot button:hover:not(:disabled) { border-color: #5a6068; color: var(--color-star-100); }
|
||||||
|
.datepicker-grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 2px; }
|
||||||
|
.datepicker-weekday { padding: 4px 0; text-align: center; font: 500 9.5px/1.4 var(--font-mono); letter-spacing: .1em; text-transform: uppercase; color: var(--quiet); }
|
||||||
|
.datepicker-grid button {
|
||||||
|
height: 34px; border: 0; border-radius: 6px; background: transparent; color: var(--color-star-200);
|
||||||
|
font: 13px var(--font-sans); cursor: pointer;
|
||||||
|
}
|
||||||
|
.datepicker-grid button[data-outside] { color: #5d636c; }
|
||||||
|
.datepicker-grid button[data-today] { box-shadow: inset 0 0 0 1px #4a4f57; }
|
||||||
|
.datepicker-grid button:hover:not(:disabled) { background: #1e1c20; color: var(--color-star-100); }
|
||||||
|
.datepicker-grid button:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
|
||||||
|
.datepicker-grid button[aria-selected="true"] { background: #2a2118; color: #ffd0a9; box-shadow: inset 0 0 0 1px var(--accent); }
|
||||||
|
.datepicker-grid button:disabled { opacity: .35; cursor: default; }
|
||||||
|
.datepicker-foot { display: flex; justify-content: space-between; padding-top: 8px; }
|
||||||
|
.datepicker-foot button:disabled { opacity: .4; cursor: default; }
|
||||||
|
|||||||
Reference in New Issue
Block a user