feat: access console with a permission tree, grouped grants and effective access
Backend: grants accept a list of permissions; PUT /access/grants edits or renews a set atomically; refusals carry a reason; the grant list includes refresh grants per relation and the administrator-only permissions; users keep their last groups and admin flag; the emergency operator cannot hold grants. Frontend: the Access screen shows the grantable permissions as a checkbox tree with dependencies, rows grouped by person or group, orbit and end date, expiry and no-effect states, and what each person can do right now. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,9 @@
|
||||
//! 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.
|
||||
// Refusals are whole responses (`{"reason"}`); they are built once per request, not carried around.
|
||||
#![allow(clippy::result_large_err)]
|
||||
|
||||
use super::routes::{admin_read, admin_write};
|
||||
use crate::auth::{role, AuditAction, AuditOutcome, AuditResource, Permission, ROLE_NAMES};
|
||||
use crate::db::access::NewGrant;
|
||||
@@ -8,6 +11,7 @@ use crate::state::HubState;
|
||||
use axum::{
|
||||
extract::{ConnectInfo, Path, State},
|
||||
http::{header, HeaderMap, HeaderValue, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
routing::{get, post, put},
|
||||
Json, Router,
|
||||
};
|
||||
@@ -17,7 +21,7 @@ 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", get(list).post(create).put(replace))
|
||||
.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))
|
||||
@@ -51,9 +55,26 @@ struct RoleInfo {
|
||||
#[derive(Serialize)]
|
||||
struct GrantList {
|
||||
grants: Vec<crate::db::access::Grant>,
|
||||
/// Refresh grants, one per relation: the `refresh.run` permission is never in `grants`.
|
||||
relation_grants: Vec<crate::db::relations::RelationGrantRow>,
|
||||
roles: Vec<RoleInfo>,
|
||||
/// Permissions that can be granted; all others belong to administrators.
|
||||
grantable: Vec<&'static str>,
|
||||
/// Permissions only administrators hold, for the screen to show as locked.
|
||||
admin_only: Vec<&'static str>,
|
||||
}
|
||||
|
||||
fn names(keep: impl Fn(Permission) -> bool) -> Vec<&'static str> {
|
||||
Permission::ALL
|
||||
.into_iter()
|
||||
.filter(|p| keep(*p))
|
||||
.map(Permission::as_str)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A refusal that says which rule applied (`{"reason": "..."}`), so the screen can say it too.
|
||||
fn refuse(status: StatusCode, reason: &'static str) -> Response {
|
||||
(status, Json(serde_json::json!({ "reason": reason }))).into_response()
|
||||
}
|
||||
|
||||
async fn list(
|
||||
@@ -77,16 +98,10 @@ async fn list(
|
||||
no_store(),
|
||||
Json(GrantList {
|
||||
grants: state.db.list_grants().map_err(internal)?,
|
||||
relation_grants: state.db.list_relation_grants().map_err(internal)?,
|
||||
roles,
|
||||
grantable: [
|
||||
Permission::OrbitRead,
|
||||
Permission::SnapshotRead,
|
||||
Permission::CaptureRun,
|
||||
Permission::SnapshotDownload,
|
||||
]
|
||||
.iter()
|
||||
.map(|p| p.as_str())
|
||||
.collect(),
|
||||
grantable: names(Permission::grantable),
|
||||
admin_only: names(Permission::admin_only),
|
||||
}),
|
||||
))
|
||||
}
|
||||
@@ -97,35 +112,64 @@ struct CreateGrant {
|
||||
/// `user` (a `users.id`) or `group` (an IdP group name).
|
||||
principal_type: String,
|
||||
principal: String,
|
||||
/// Exactly one of `role` and `permission`.
|
||||
/// Exactly one of `role`, `permission` and `permissions`.
|
||||
role: Option<String>,
|
||||
permission: Option<String>,
|
||||
permissions: Option<Vec<String>>,
|
||||
/// Absent = every orbit.
|
||||
orbit_id: Option<Uuid>,
|
||||
/// RFC 3339; absent = no expiry.
|
||||
expires_at: Option<String>,
|
||||
/// Only for `PUT`: grants of the same person or group and orbit that this request replaces.
|
||||
#[serde(default)]
|
||||
replaces: Vec<Uuid>,
|
||||
}
|
||||
|
||||
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)
|
||||
/// A request that passed every rule: what to write, and for whom.
|
||||
struct Valid {
|
||||
permissions: Vec<Permission>,
|
||||
orbit: Option<String>,
|
||||
expires_at: Option<i64>,
|
||||
}
|
||||
|
||||
fn validate(state: &HubState, body: &CreateGrant, now: i64) -> Result<Valid, Response> {
|
||||
let bad = |reason| refuse(StatusCode::BAD_REQUEST, reason);
|
||||
let unprocessable = |reason| refuse(StatusCode::UNPROCESSABLE_ENTITY, reason);
|
||||
let mut permissions: Vec<Permission> = match (&body.role, &body.permission, &body.permissions) {
|
||||
(Some(name), None, None) => role(name).ok_or(bad("unknown_role"))?.to_vec(),
|
||||
(None, Some(name), None) => vec![Permission::parse(name)
|
||||
.filter(|p| p.grantable())
|
||||
.ok_or(StatusCode::BAD_REQUEST)?],
|
||||
_ => return Err(StatusCode::BAD_REQUEST),
|
||||
.ok_or(bad("unknown_permission"))?],
|
||||
(None, None, Some(names)) => names
|
||||
.iter()
|
||||
.map(|name| {
|
||||
Permission::parse(name)
|
||||
.filter(|p| p.grantable())
|
||||
.ok_or(bad("unknown_permission"))
|
||||
})
|
||||
.collect::<Result<_, _>>()?,
|
||||
_ => return Err(bad("choose_one")),
|
||||
};
|
||||
permissions.dedup();
|
||||
let mut seen = Vec::new();
|
||||
permissions.retain(|p| {
|
||||
let new = !seen.contains(p);
|
||||
seen.push(*p);
|
||||
new
|
||||
});
|
||||
if permissions.is_empty() {
|
||||
return Err(bad("nothing_selected"));
|
||||
}
|
||||
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);
|
||||
Uuid::parse_str(&body.principal).map_err(|_| bad("bad_person"))?;
|
||||
let user = state
|
||||
.db
|
||||
.user_row(&body.principal)
|
||||
.map_err(|e| internal(e).into_response())?
|
||||
.ok_or(unprocessable("unknown_user"))?;
|
||||
if user.is_emergency {
|
||||
return Err(unprocessable("emergency_operator"));
|
||||
}
|
||||
}
|
||||
"group" => {
|
||||
@@ -133,18 +177,18 @@ async fn create(
|
||||
|| body.principal.len() > 128
|
||||
|| body.principal.chars().any(char::is_control)
|
||||
{
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
return Err(bad("bad_group"));
|
||||
}
|
||||
}
|
||||
_ => return Err(StatusCode::BAD_REQUEST),
|
||||
_ => return Err(bad("bad_principal_type")),
|
||||
}
|
||||
if let Some(orbit) = body.orbit_id {
|
||||
if !state
|
||||
.db
|
||||
.orbit_exists(&orbit.to_string())
|
||||
.map_err(internal)?
|
||||
.map_err(|e| internal(e).into_response())?
|
||||
{
|
||||
return Err(StatusCode::UNPROCESSABLE_ENTITY);
|
||||
return Err(unprocessable("unknown_orbit"));
|
||||
}
|
||||
}
|
||||
let expires_at = body
|
||||
@@ -153,26 +197,48 @@ async fn create(
|
||||
.map(|text| {
|
||||
chrono::DateTime::parse_from_rfc3339(text)
|
||||
.map(|t| t.timestamp())
|
||||
.map_err(|_| StatusCode::BAD_REQUEST)
|
||||
.map_err(|_| bad("bad_end_date"))
|
||||
})
|
||||
.transpose()?;
|
||||
if expires_at.is_some_and(|end| end <= now || end > now + 2 * 366 * 86_400) {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
return Err(bad("bad_end_date"));
|
||||
}
|
||||
let orbit = body.orbit_id.map(|id| id.to_string());
|
||||
Ok(Valid {
|
||||
permissions,
|
||||
orbit: body.orbit_id.map(|id| id.to_string()),
|
||||
expires_at,
|
||||
})
|
||||
}
|
||||
|
||||
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>>), Response> {
|
||||
let actor = admin_write(&state, peer, &headers).map_err(IntoResponse::into_response)?;
|
||||
let now = now();
|
||||
if !body.replaces.is_empty() {
|
||||
return Err(refuse(StatusCode::BAD_REQUEST, "replaces_needs_put"));
|
||||
}
|
||||
let valid = validate(&state, &body, now)?;
|
||||
let created_by = actor.id();
|
||||
let mut created = Vec::new();
|
||||
for permission in permissions {
|
||||
for permission in valid.permissions {
|
||||
let grant = NewGrant {
|
||||
principal_type: &body.principal_type,
|
||||
principal: &body.principal,
|
||||
permission: permission.as_str(),
|
||||
orbit: orbit.as_deref(),
|
||||
expires_at,
|
||||
orbit: valid.orbit.as_deref(),
|
||||
expires_at: valid.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)?;
|
||||
if let Some(grant) = state
|
||||
.db
|
||||
.add_grant(&grant, now)
|
||||
.map_err(|e| internal(e).into_response())?
|
||||
{
|
||||
let id = Uuid::parse_str(&grant.id).map_err(|e| internal(e).into_response())?;
|
||||
state
|
||||
.db
|
||||
.audit_event(
|
||||
@@ -182,16 +248,68 @@ async fn create(
|
||||
AuditOutcome::Succeeded,
|
||||
actor.request_id,
|
||||
)
|
||||
.map_err(internal)?;
|
||||
.map_err(|e| internal(e).into_response())?;
|
||||
created.push(grant);
|
||||
}
|
||||
}
|
||||
if created.is_empty() {
|
||||
return Err(StatusCode::CONFLICT);
|
||||
return Err(refuse(StatusCode::CONFLICT, "already_granted"));
|
||||
}
|
||||
Ok((StatusCode::CREATED, no_store(), Json(created)))
|
||||
}
|
||||
|
||||
/// Edit or renew: replace some grants of one person or group and orbit with a new set and end date,
|
||||
/// all or nothing. Anything that was already granted keeps working through the change.
|
||||
async fn replace(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Json(body): Json<CreateGrant>,
|
||||
) -> Result<(HeaderMap, Json<Vec<crate::db::access::Grant>>), Response> {
|
||||
let actor = admin_write(&state, peer, &headers).map_err(IntoResponse::into_response)?;
|
||||
let now = now();
|
||||
let valid = validate(&state, &body, now)?;
|
||||
let created_by = actor.id();
|
||||
let new: Vec<NewGrant> = valid
|
||||
.permissions
|
||||
.iter()
|
||||
.map(|permission| NewGrant {
|
||||
principal_type: &body.principal_type,
|
||||
principal: &body.principal,
|
||||
permission: permission.as_str(),
|
||||
orbit: valid.orbit.as_deref(),
|
||||
expires_at: valid.expires_at,
|
||||
created_by: &created_by,
|
||||
})
|
||||
.collect();
|
||||
let replaces: Vec<String> = body.replaces.iter().map(Uuid::to_string).collect();
|
||||
let outcome = state
|
||||
.db
|
||||
.replace_grants(&replaces, &new, now)
|
||||
.map_err(|e| internal(e).into_response())?;
|
||||
let crate::db::access::Replace::Done { removed, written } = outcome else {
|
||||
return Err(refuse(StatusCode::UNPROCESSABLE_ENTITY, "grant_mismatch"));
|
||||
};
|
||||
for (id, action) in removed
|
||||
.iter()
|
||||
.map(|id| (id, AuditAction::GrantDelete))
|
||||
.chain(written.iter().map(|g| (&g.id, AuditAction::GrantCreate)))
|
||||
{
|
||||
let id = Uuid::parse_str(id).map_err(|e| internal(e).into_response())?;
|
||||
state
|
||||
.db
|
||||
.audit_event(
|
||||
&actor.principal,
|
||||
action,
|
||||
AuditResource::Grant(id),
|
||||
AuditOutcome::Succeeded,
|
||||
actor.request_id,
|
||||
)
|
||||
.map_err(|e| internal(e).into_response())?;
|
||||
}
|
||||
Ok((no_store(), Json(written)))
|
||||
}
|
||||
|
||||
async fn remove(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
@@ -241,16 +359,17 @@ fn target_user(
|
||||
state: &HubState,
|
||||
actor: &super::routes::OperatorActor,
|
||||
id: Uuid,
|
||||
) -> Result<crate::db::access::UserRow, StatusCode> {
|
||||
) -> Result<crate::db::access::UserRow, Response> {
|
||||
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);
|
||||
.user_row(&id.to_string())
|
||||
.map_err(|e| internal(e).into_response())?
|
||||
.ok_or(StatusCode::NOT_FOUND.into_response())?;
|
||||
if actor.subject.user_id.as_deref() == Some(user.id.as_str()) {
|
||||
return Err(refuse(StatusCode::CONFLICT, "cannot_disable_self"));
|
||||
}
|
||||
if user.is_emergency {
|
||||
return Err(refuse(StatusCode::CONFLICT, "cannot_disable_emergency"));
|
||||
}
|
||||
Ok(user)
|
||||
}
|
||||
@@ -261,13 +380,13 @@ async fn set_user(
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(body): Json<UserState>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
let actor = admin_write(&state, peer, &headers)?;
|
||||
) -> Result<StatusCode, Response> {
|
||||
let actor = admin_write(&state, peer, &headers).map_err(IntoResponse::into_response)?;
|
||||
let user = target_user(&state, &actor, id)?;
|
||||
state
|
||||
.db
|
||||
.set_user_active(&user.id, body.active)
|
||||
.map_err(internal)?;
|
||||
.map_err(|e| internal(e).into_response())?;
|
||||
state
|
||||
.db
|
||||
.audit_event(
|
||||
@@ -277,7 +396,7 @@ async fn set_user(
|
||||
AuditOutcome::Succeeded,
|
||||
actor.request_id,
|
||||
)
|
||||
.map_err(internal)?;
|
||||
.map_err(|e| internal(e).into_response())?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
|
||||
@@ -403,6 +403,9 @@ fn recipe(w: &World, row: &Row) -> (String, Option<Value>) {
|
||||
("POST", "/api/v1/access/grants") => {
|
||||
Some(json!({"principal_type": "group", "principal": "matrix-group", "role": "viewer"}))
|
||||
}
|
||||
("PUT", "/api/v1/access/grants") => Some(
|
||||
json!({"principal_type": "group", "principal": "matrix-group", "permissions": ["orbit.read"]}),
|
||||
),
|
||||
("PUT", "/api/v1/access/users/:id") => Some(json!({"active": true})),
|
||||
("PUT", "/api/v1/orbits/:id/environment")
|
||||
| ("PUT", "/api/v1/restore-targets/:id/environment") => {
|
||||
@@ -1722,3 +1725,193 @@ async fn revoking_an_outpost_or_deleting_a_relation_takes_refreshers_off_immedia
|
||||
.unwrap();
|
||||
assert_eq!(b["active"], true);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_set_of_permissions_can_be_granted_edited_and_renewed_all_or_nothing() {
|
||||
let w = world().await;
|
||||
let admin = w.caller("admin", true, &[]);
|
||||
let target = w.caller("target", false, &["qa"]);
|
||||
let uid = target.user_id.clone().unwrap();
|
||||
let grants = "/api/v1/access/grants";
|
||||
let orbit = w.a.orbit;
|
||||
let end = |days: i64| (chrono::Utc::now() + chrono::Duration::days(days)).to_rfc3339();
|
||||
|
||||
// a list of single permissions, in one request; refusals say which rule applied
|
||||
let (status, created) = w
|
||||
.send(&admin, "POST", grants, Some(json!({"principal_type": "user", "principal": uid, "permissions": ["orbit.read", "snapshot.read", "capture.run"], "orbit_id": orbit})))
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::CREATED);
|
||||
assert_eq!(created.as_array().unwrap().len(), 3);
|
||||
let (status, body) = w
|
||||
.send(&admin, "POST", grants, Some(json!({"principal_type": "user", "principal": uid, "permissions": ["orbit.read"], "orbit_id": orbit})))
|
||||
.await;
|
||||
assert_eq!(
|
||||
(status, body["reason"].as_str()),
|
||||
(StatusCode::CONFLICT, Some("already_granted"))
|
||||
);
|
||||
for (what, body, reason) in [
|
||||
(
|
||||
"empty list",
|
||||
json!({"principal_type": "group", "principal": "g", "permissions": []}),
|
||||
"nothing_selected",
|
||||
),
|
||||
(
|
||||
"admin-only permission",
|
||||
json!({"principal_type": "group", "principal": "g", "permissions": ["orbit.manage"]}),
|
||||
"unknown_permission",
|
||||
),
|
||||
(
|
||||
"refresh is per relation",
|
||||
json!({"principal_type": "group", "principal": "g", "permissions": ["refresh.run"]}),
|
||||
"unknown_permission",
|
||||
),
|
||||
(
|
||||
"two ways at once",
|
||||
json!({"principal_type": "group", "principal": "g", "role": "viewer", "permissions": ["orbit.read"]}),
|
||||
"choose_one",
|
||||
),
|
||||
(
|
||||
"replaces belongs to PUT",
|
||||
json!({"principal_type": "group", "principal": "g", "role": "viewer", "replaces": [Uuid::new_v4()]}),
|
||||
"replaces_needs_put",
|
||||
),
|
||||
(
|
||||
"bad end date",
|
||||
json!({"principal_type": "group", "principal": "g", "role": "viewer", "expires_at": "2020-01-01T00:00:00Z"}),
|
||||
"bad_end_date",
|
||||
),
|
||||
(
|
||||
"unknown orbit",
|
||||
json!({"principal_type": "group", "principal": "g", "role": "viewer", "orbit_id": Uuid::new_v4()}),
|
||||
"unknown_orbit",
|
||||
),
|
||||
] {
|
||||
let (status, body) = w.send(&admin, "POST", grants, Some(body)).await;
|
||||
assert!(status.is_client_error(), "{what}");
|
||||
assert_eq!(body["reason"], reason, "{what}");
|
||||
}
|
||||
|
||||
// the emergency operator is an administrator and never holds grants
|
||||
let emergency = w
|
||||
.state
|
||||
.db
|
||||
.list_users()
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.find(|u| u.is_emergency);
|
||||
if let Some(emergency) = emergency {
|
||||
let (status, body) = w
|
||||
.send(
|
||||
&admin,
|
||||
"POST",
|
||||
grants,
|
||||
Some(
|
||||
json!({"principal_type": "user", "principal": emergency.id, "role": "viewer"}),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
(status, body["reason"].as_str()),
|
||||
(StatusCode::UNPROCESSABLE_ENTITY, Some("emergency_operator"))
|
||||
);
|
||||
}
|
||||
|
||||
// renew: the same set with a new end date replaces the old rows; nothing is ever missing in between
|
||||
let ids: Vec<Value> = created
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|g| g["id"].clone())
|
||||
.collect();
|
||||
let (status, renewed) = w
|
||||
.send(&admin, "PUT", grants, Some(json!({"principal_type": "user", "principal": uid, "permissions": ["orbit.read", "snapshot.read", "capture.run"], "orbit_id": orbit, "expires_at": end(30), "replaces": ids})))
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(renewed.as_array().unwrap().len(), 3);
|
||||
let stored = w.state.db.list_grants().unwrap();
|
||||
let mine: Vec<_> = stored.iter().filter(|g| g.principal == uid).collect();
|
||||
assert_eq!(mine.len(), 3, "renewing does not duplicate");
|
||||
assert!(mine.iter().all(|g| g.expires_at.is_some()));
|
||||
|
||||
// edit: dropping a permission removes just that one
|
||||
let ids: Vec<Value> = mine.iter().map(|g| json!(g.id)).collect();
|
||||
let (status, _) = w
|
||||
.send(&admin, "PUT", grants, Some(json!({"principal_type": "user", "principal": uid, "permissions": ["orbit.read", "snapshot.read"], "orbit_id": orbit, "replaces": ids})))
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
let after: Vec<String> = w
|
||||
.state
|
||||
.db
|
||||
.list_grants()
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.filter(|g| g.principal == uid)
|
||||
.map(|g| g.permission)
|
||||
.collect();
|
||||
assert_eq!(after.len(), 2);
|
||||
assert!(!after.contains(&"capture.run".to_string()));
|
||||
|
||||
// a grant of someone else cannot be swept into the replacement, and nothing changes when it is refused
|
||||
let other = w
|
||||
.state
|
||||
.db
|
||||
.add_grant(
|
||||
&NewGrant {
|
||||
principal_type: "group",
|
||||
principal: "elsewhere",
|
||||
permission: "orbit.read",
|
||||
orbit: None,
|
||||
expires_at: None,
|
||||
created_by: "test",
|
||||
},
|
||||
now(),
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let before = w.state.db.list_grants().unwrap().len();
|
||||
let (status, body) = w
|
||||
.send(&admin, "PUT", grants, Some(json!({"principal_type": "user", "principal": uid, "permissions": ["orbit.read"], "orbit_id": orbit, "replaces": [other.id]})))
|
||||
.await;
|
||||
assert_eq!(
|
||||
(status, body["reason"].as_str()),
|
||||
(StatusCode::UNPROCESSABLE_ENTITY, Some("grant_mismatch"))
|
||||
);
|
||||
assert_eq!(w.state.db.list_grants().unwrap().len(), before);
|
||||
|
||||
// the listing carries refresh grants and the administrator-only permissions
|
||||
let (status, listing) = w.send(&admin, "GET", grants, None).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert!(listing["relation_grants"].is_array());
|
||||
let admin_only: Vec<&str> = listing["admin_only"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.collect();
|
||||
assert!(
|
||||
admin_only.contains(&"access.manage")
|
||||
&& !admin_only.contains(&"refresh.run")
|
||||
&& !admin_only.contains(&"orbit.read")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_user_list_keeps_what_the_identity_provider_said_at_the_last_sign_in() {
|
||||
let w = world().await;
|
||||
let admin = w.caller("admin", true, &[]);
|
||||
let _qa = w.caller("qa-person", false, &["qa", "developer"]);
|
||||
let (status, users) = w.send(&admin, "GET", "/api/v1/access/users", None).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
let find = |name: &str| {
|
||||
users
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|u| u["display_name"] == name)
|
||||
.cloned()
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(find("admin")["admin"], true);
|
||||
assert_eq!(find("qa-person")["admin"], false);
|
||||
assert_eq!(find("qa-person")["groups"], json!(["qa", "developer"]));
|
||||
}
|
||||
|
||||
@@ -100,7 +100,6 @@ pub(super) fn scoped(
|
||||
/// Use one relation. Administrators always; anyone else only through a live grant on that very relation
|
||||
/// (not on its orbit, not on an older version of it). Everything else answers 404, so a relation's
|
||||
/// existence is not confirmed to someone who cannot use it.
|
||||
#[allow(dead_code)] // used by the refresh run (M6c); the matrix already exercises the list built on the same grants
|
||||
pub(super) fn relation(
|
||||
state: &HubState,
|
||||
actor: &OperatorActor,
|
||||
|
||||
@@ -496,8 +496,10 @@ async fn grant_access(
|
||||
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);
|
||||
// The emergency operator is an administrator and never holds grants.
|
||||
match state.db.user_row(&body.principal).map_err(internal)? {
|
||||
Some(user) if !user.is_emergency => {}
|
||||
_ => return Err(StatusCode::UNPROCESSABLE_ENTITY),
|
||||
}
|
||||
}
|
||||
"group" => {
|
||||
|
||||
@@ -95,8 +95,7 @@ struct Me {
|
||||
refresh_relations: Vec<String>,
|
||||
}
|
||||
|
||||
/// The caller's own identity. Every authenticated principal is an administrator
|
||||
/// until scoped grants exist (M5), which is what `capabilities` reports.
|
||||
/// The caller's own identity and what it may use: `admin`, its live grants, and the relations it may refresh through.
|
||||
async fn me(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
|
||||
@@ -172,23 +172,31 @@ impl Permission {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every permission, in the order the administration screens list them.
|
||||
pub const ALL: [Permission; 12] = [
|
||||
Self::OrbitRead,
|
||||
Self::SnapshotRead,
|
||||
Self::CaptureRun,
|
||||
Self::SnapshotDownload,
|
||||
Self::OrbitManage,
|
||||
Self::OutpostManage,
|
||||
Self::RetentionManage,
|
||||
Self::SnapshotDelete,
|
||||
Self::RecoveryManage,
|
||||
Self::AccessManage,
|
||||
Self::RelationManage,
|
||||
Self::RefreshRun,
|
||||
];
|
||||
|
||||
pub fn parse(text: &str) -> Option<Self> {
|
||||
[
|
||||
Self::OrbitRead,
|
||||
Self::SnapshotRead,
|
||||
Self::CaptureRun,
|
||||
Self::SnapshotDownload,
|
||||
Self::OrbitManage,
|
||||
Self::OutpostManage,
|
||||
Self::RetentionManage,
|
||||
Self::SnapshotDelete,
|
||||
Self::RecoveryManage,
|
||||
Self::AccessManage,
|
||||
Self::RelationManage,
|
||||
Self::RefreshRun,
|
||||
]
|
||||
.into_iter()
|
||||
.find(|permission| permission.as_str() == text)
|
||||
Self::ALL
|
||||
.into_iter()
|
||||
.find(|permission| permission.as_str() == text)
|
||||
}
|
||||
|
||||
/// Held only by administrators (neither grantable nor the per-relation refresh).
|
||||
pub fn admin_only(self) -> bool {
|
||||
!self.grantable() && self != Self::RefreshRun
|
||||
}
|
||||
|
||||
/// May be given to a non-administrator through a grant.
|
||||
|
||||
@@ -28,6 +28,16 @@ pub struct NewGrant<'a> {
|
||||
pub created_by: &'a str,
|
||||
}
|
||||
|
||||
/// Outcome of [`Db::replace_grants`].
|
||||
pub enum Replace {
|
||||
Done {
|
||||
removed: Vec<String>,
|
||||
written: Vec<Grant>,
|
||||
},
|
||||
/// A grant to replace belongs to someone or somewhere else than the new set.
|
||||
Mismatch,
|
||||
}
|
||||
|
||||
/// Orbits a subject may use for one permission.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct Permitted {
|
||||
@@ -44,6 +54,10 @@ pub struct UserRow {
|
||||
pub created_at: i64,
|
||||
pub last_login_at: Option<i64>,
|
||||
pub is_emergency: bool,
|
||||
/// Administrator at the last sign-in (the SSO admin mapping; the emergency operator always is).
|
||||
pub admin: bool,
|
||||
/// Groups the identity provider reported at the last sign-in.
|
||||
pub groups: Vec<String>,
|
||||
}
|
||||
|
||||
pub(super) fn migrate(conn: &Connection) -> Result<()> {
|
||||
@@ -106,6 +120,76 @@ impl Db {
|
||||
}))
|
||||
}
|
||||
|
||||
/// Edit or renew a set of grants in one transaction: remove `replaces` (each must belong to the same
|
||||
/// principal and scope), then write `grants`, updating the end date of any that already exist.
|
||||
/// Returns the removed ids and the written grants. `Err(None)`-style conflicts are reported as `Replace::Mismatch`.
|
||||
pub fn replace_grants(
|
||||
&self,
|
||||
replaces: &[String],
|
||||
grants: &[NewGrant<'_>],
|
||||
now: i64,
|
||||
) -> Result<Replace> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction()?;
|
||||
let mut removed = Vec::new();
|
||||
for id in replaces {
|
||||
let row: Option<(String, String, String, String)> = tx
|
||||
.query_row(
|
||||
"SELECT principal_type,principal,scope_type,scope_id FROM access_grants WHERE id=?1",
|
||||
params![id],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
|
||||
)
|
||||
.optional()?;
|
||||
let Some((kind, who, scope_type, scope_id)) = row else {
|
||||
continue;
|
||||
};
|
||||
let same = grants.iter().all(|g| {
|
||||
g.principal_type == kind
|
||||
&& g.principal == who
|
||||
&& match g.orbit {
|
||||
Some(orbit) => scope_type == "orbit" && scope_id == orbit,
|
||||
None => scope_type == "global",
|
||||
}
|
||||
});
|
||||
if !same {
|
||||
return Ok(Replace::Mismatch);
|
||||
}
|
||||
tx.execute("DELETE FROM access_grants WHERE id=?1", params![id])?;
|
||||
removed.push(id.clone());
|
||||
}
|
||||
let mut written = Vec::new();
|
||||
for grant in grants {
|
||||
let (scope_type, scope_id) = match grant.orbit {
|
||||
Some(orbit) => ("orbit", orbit),
|
||||
None => ("global", ""),
|
||||
};
|
||||
tx.execute(
|
||||
"INSERT 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)
|
||||
ON CONFLICT(principal_type,principal,permission,scope_type,scope_id) DO UPDATE SET expires_at=excluded.expires_at",
|
||||
params![Uuid::new_v4().to_string(), grant.principal_type, grant.principal, grant.permission, scope_type, scope_id, grant.expires_at, grant.created_by, now],
|
||||
)?;
|
||||
let id: String = tx.query_row(
|
||||
"SELECT id FROM access_grants WHERE principal_type=?1 AND principal=?2 AND permission=?3 AND scope_type=?4 AND scope_id=?5",
|
||||
params![grant.principal_type, grant.principal, grant.permission, scope_type, scope_id],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
written.push(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,
|
||||
});
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(Replace::Done { removed, written })
|
||||
}
|
||||
|
||||
pub fn delete_grant(&self, id: &str) -> Result<bool> {
|
||||
Ok(self
|
||||
.conn
|
||||
@@ -209,28 +293,28 @@ impl Db {
|
||||
|
||||
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 mut stmt = conn.prepare("SELECT id,issuer,display_name,active,created_at,last_login_at,last_groups,last_admin FROM users ORDER BY display_name, id")?;
|
||||
let rows = stmt.query_map([], |r| {
|
||||
let issuer: String = r.get(1)?;
|
||||
let is_emergency = issuer == crate::admin::EMERGENCY_ISSUER;
|
||||
Ok(UserRow {
|
||||
id: r.get(0)?,
|
||||
is_emergency: issuer == crate::admin::EMERGENCY_ISSUER,
|
||||
is_emergency,
|
||||
issuer,
|
||||
display_name: r.get(2)?,
|
||||
active: r.get::<_, i64>(3)? == 1,
|
||||
created_at: r.get(4)?,
|
||||
last_login_at: r.get(5)?,
|
||||
groups: serde_json::from_str(&r.get::<_, String>(6)?).unwrap_or_default(),
|
||||
admin: is_emergency || r.get::<_, i64>(7)? == 1,
|
||||
})
|
||||
})?;
|
||||
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),
|
||||
)?)
|
||||
/// One user, or `None`.
|
||||
pub fn user_row(&self, id: &str) -> Result<Option<UserRow>> {
|
||||
Ok(self.list_users()?.into_iter().find(|u| u.id == id))
|
||||
}
|
||||
|
||||
/// Enable or disable a user. Disabling also ends every session at once.
|
||||
|
||||
@@ -91,6 +91,22 @@ pub struct RelationGrant {
|
||||
pub created_at: i64,
|
||||
}
|
||||
|
||||
/// A refresh grant with what it applies to, for the access screen.
|
||||
#[derive(Clone, Debug, serde::Serialize)]
|
||||
pub struct RelationGrantRow {
|
||||
pub id: String,
|
||||
pub principal_type: String,
|
||||
pub principal: String,
|
||||
pub relation_id: String,
|
||||
pub version: i64,
|
||||
/// An ended relation (or an older version of one) grants nothing.
|
||||
pub active: bool,
|
||||
pub source_name: String,
|
||||
pub target_name: String,
|
||||
pub expires_at: Option<i64>,
|
||||
pub created_at: i64,
|
||||
}
|
||||
|
||||
pub(super) fn migrate(conn: &Connection) -> Result<()> {
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE IF NOT EXISTS orbit_environments (
|
||||
@@ -616,6 +632,34 @@ impl Db {
|
||||
)? == 1)
|
||||
}
|
||||
|
||||
/// Every refresh grant with its relation's names, newest relations first.
|
||||
pub fn list_relation_grants(&self) -> Result<Vec<RelationGrantRow>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT g.id,g.principal_type,g.principal,g.relation_id,r.version,r.active,
|
||||
COALESCE((SELECT name FROM orbits WHERE id=r.source_orbit_id),''),
|
||||
COALESCE((SELECT json_extract(profile,'$.name') FROM restore_targets WHERE id=r.target_id),''),
|
||||
g.expires_at,g.created_at
|
||||
FROM relation_grants g JOIN orbit_relations r ON r.id=g.relation_id
|
||||
ORDER BY r.active DESC, g.principal_type, g.principal, g.created_at",
|
||||
)?;
|
||||
let rows = stmt.query_map([], |r| {
|
||||
Ok(RelationGrantRow {
|
||||
id: r.get(0)?,
|
||||
principal_type: r.get(1)?,
|
||||
principal: r.get(2)?,
|
||||
relation_id: r.get(3)?,
|
||||
version: r.get(4)?,
|
||||
active: r.get::<_, i64>(5)? == 1,
|
||||
source_name: r.get(6)?,
|
||||
target_name: r.get(7)?,
|
||||
expires_at: r.get(8)?,
|
||||
created_at: r.get(9)?,
|
||||
})
|
||||
})?;
|
||||
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||
}
|
||||
|
||||
pub fn relation_grants(&self, relation: &str) -> Result<Vec<RelationGrant>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare("SELECT id,principal_type,principal,relation_id,expires_at,created_by,created_at FROM relation_grants WHERE relation_id=?1 ORDER BY principal_type, principal")?;
|
||||
|
||||
@@ -63,6 +63,10 @@ pub(super) fn migrate(conn: &Connection) -> Result<()> {
|
||||
// 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", "groups", "TEXT NOT NULL DEFAULT '[]'")?;
|
||||
// What the identity provider said at the user's last sign-in, kept after the session ends so the
|
||||
// access screens can still say who is an administrator and which groups a person comes through.
|
||||
super::ensure_column(conn, "users", "last_groups", "TEXT NOT NULL DEFAULT '[]'")?;
|
||||
super::ensure_column(conn, "users", "last_admin", "INTEGER NOT NULL DEFAULT 0")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -112,6 +116,12 @@ impl Db {
|
||||
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, serde_json::to_string(groups)?],
|
||||
)?;
|
||||
if inserted == 1 {
|
||||
conn.execute(
|
||||
"UPDATE users SET last_groups=?2, last_admin=?3 WHERE id=?1",
|
||||
params![user_id, serde_json::to_string(groups)?, admin],
|
||||
)?;
|
||||
}
|
||||
Ok(inserted == 1)
|
||||
}
|
||||
|
||||
|
||||
@@ -22,8 +22,8 @@ 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/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/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 | GET | human | access.manage | admin | daftar grant, grant refresh per relasi, role, permission yang dapat diberikan dan yang khusus admin; no-store |
|
||||
| /api/v1/access/grants | POST,PUT | human | access.manage | admin | POST: grant baru (role, permission, atau daftar permission; scope global/orbit; expiry); PUT: ganti atau perpanjang sekumpulan grant orang/grup dan orbit yang sama secara atomik; alasan penolakan dalam `{"reason"}`; 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 |
|
||||
|
||||
109
web/scripts/access.test.mjs
Normal file
109
web/scripts/access.test.mjs
Normal file
@@ -0,0 +1,109 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
branchState, expiryState, groupGrants, hasNoEffect, neededBy, personAccess, reasonText, roleLabel, seenGroups, setMany, setPermission,
|
||||
} from "../src/lib/access.ts";
|
||||
|
||||
const roles = [
|
||||
{ name: "viewer", permissions: ["orbit.read", "snapshot.read"] },
|
||||
{ name: "capturer", permissions: ["orbit.read", "snapshot.read", "capture.run"] },
|
||||
{ name: "downloader", permissions: ["orbit.read", "snapshot.read", "snapshot.download"] },
|
||||
];
|
||||
const NOW = 1_000_000;
|
||||
const grant = (id, principal, permission, extra = {}) => ({
|
||||
id, principal_type: "user", principal, permission, scope_type: "global", scope_id: null, expires_at: null, created_by: "t", created_at: 1, ...extra,
|
||||
});
|
||||
|
||||
test("ticking a permission ticks what it needs; unticking removes what depends on it", () => {
|
||||
const download = setPermission(new Set(), "snapshot.download", true);
|
||||
assert.deepEqual([...download].sort(), ["orbit.read", "snapshot.download", "snapshot.read"]);
|
||||
const noList = setPermission(download, "snapshot.read", false);
|
||||
assert.deepEqual([...noList], ["orbit.read"], "download needs list, so it goes too");
|
||||
assert.deepEqual(neededBy(new Set(["orbit.read", "capture.run"]), "orbit.read"), ["capture.run"]);
|
||||
assert.deepEqual(neededBy(new Set(["orbit.read"]), "orbit.read"), []);
|
||||
});
|
||||
|
||||
test("a branch reports all, some or none and ticks as a whole", () => {
|
||||
const ids = ["snapshot.read", "snapshot.download"];
|
||||
assert.equal(branchState(new Set(), ids), "none");
|
||||
assert.equal(branchState(new Set(["snapshot.read"]), ids), "some");
|
||||
const all = setMany(new Set(), ids, true);
|
||||
assert.equal(branchState(all, ids), "all");
|
||||
assert.ok(all.has("orbit.read"));
|
||||
assert.equal(branchState(setMany(all, ids, false), ids), "none");
|
||||
});
|
||||
|
||||
test("names a set of permissions from the hub's roles, never inventing one", () => {
|
||||
assert.equal(roleLabel(["snapshot.read", "orbit.read"], roles), "Viewer");
|
||||
assert.equal(roleLabel(["orbit.read", "snapshot.read", "capture.run"], roles), "Capturer");
|
||||
assert.equal(roleLabel(["orbit.read", "snapshot.read", "capture.run", "snapshot.download"], roles), "Capturer + download");
|
||||
assert.equal(roleLabel(["capture.run"], roles), "Custom");
|
||||
assert.equal(roleLabel([], roles), "Custom");
|
||||
assert.equal(roleLabel(["orbit.read"], []), "Custom", "no roles known: always custom");
|
||||
});
|
||||
|
||||
test("one row per person, orbit and end date, with permissions in tree order", () => {
|
||||
const rows = groupGrants([
|
||||
grant("1", "u", "capture.run"), grant("2", "u", "orbit.read"), grant("3", "u", "snapshot.read"),
|
||||
grant("4", "u", "orbit.read", { scope_type: "orbit", scope_id: "o1" }),
|
||||
grant("5", "u", "snapshot.read", { expires_at: 5 }),
|
||||
grant("6", "dev", "orbit.read", { principal_type: "group" }),
|
||||
]);
|
||||
assert.equal(rows.length, 4);
|
||||
assert.deepEqual(rows[0].permissions, ["orbit.read", "snapshot.read", "capture.run"]);
|
||||
assert.deepEqual(rows[0].ids, ["1", "2", "3"]);
|
||||
});
|
||||
|
||||
test("expiry is none, soon (within two weeks) or expired", () => {
|
||||
assert.equal(expiryState(null, NOW), "none");
|
||||
assert.equal(expiryState(NOW, NOW), "expired", "expiry is exclusive, as on the hub");
|
||||
assert.equal(expiryState(NOW + 86_400, NOW), "soon");
|
||||
assert.equal(expiryState(NOW + 30 * 86_400, NOW), "none");
|
||||
});
|
||||
|
||||
test("a grant without orbit.read has no effect, unless another grant of theirs supplies it", () => {
|
||||
const all = [grant("1", "u", "capture.run", { scope_type: "orbit", scope_id: "o1" })];
|
||||
const [row] = groupGrants(all);
|
||||
assert.equal(hasNoEffect(row, all, [], NOW), true);
|
||||
const withGlobal = [...all, grant("2", "u", "orbit.read")];
|
||||
assert.equal(hasNoEffect(row, withGlobal, [], NOW), false, "a global orbit.read covers it");
|
||||
const otherOrbit = [...all, grant("3", "u", "orbit.read", { scope_type: "orbit", scope_id: "o2" })];
|
||||
assert.equal(hasNoEffect(row, otherOrbit, [], NOW), true, "another orbit does not");
|
||||
const viaGroup = [...all, grant("4", "qa", "orbit.read", { principal_type: "group" })];
|
||||
assert.equal(hasNoEffect(row, viaGroup, ["qa"], NOW), false, "a group of theirs supplies it");
|
||||
assert.equal(hasNoEffect(row, viaGroup, [], NOW), true, "a group they are not in does not");
|
||||
const expired = [grant("5", "u", "capture.run", { expires_at: NOW - 1 })];
|
||||
assert.equal(hasNoEffect(groupGrants(expired)[0], expired, [], NOW), false, "an expired grant is shown as expired instead");
|
||||
});
|
||||
|
||||
test("a person is an administrator, waiting, or described by everything that reaches them", () => {
|
||||
const user = (extra) => ({ id: "u", issuer: "i", display_name: "U", active: true, created_at: 1, last_login_at: 1, is_emergency: false, admin: false, groups: [], ...extra });
|
||||
assert.equal(personAccess(user({ admin: true }), [], [], roles, NOW).kind, "admin");
|
||||
assert.equal(personAccess(user(), [], [], roles, NOW).kind, "waiting");
|
||||
const viaGroup = personAccess(user({ groups: ["dev"] }), [grant("1", "dev", "orbit.read", { principal_type: "group" }), grant("2", "dev", "snapshot.read", { principal_type: "group" })], [], roles, NOW);
|
||||
assert.deepEqual([viaGroup.kind, viaGroup.label, viaGroup.via], ["granted", "Viewer", ["dev"]]);
|
||||
const refreshOnly = personAccess(
|
||||
user(), [],
|
||||
[{ id: "r", principal_type: "user", principal: "u", relation_id: "x", version: 1, active: true, source_name: "prod", target_name: "stg", expires_at: null, created_at: 1 }],
|
||||
roles, NOW,
|
||||
);
|
||||
assert.deepEqual([refreshOnly.kind, refreshOnly.refresh], ["granted", ["prod → stg"]]);
|
||||
const ended = personAccess(
|
||||
user(), [],
|
||||
[{ id: "r", principal_type: "user", principal: "u", relation_id: "x", version: 1, active: false, source_name: "prod", target_name: "stg", expires_at: null, created_at: 1 }],
|
||||
roles, NOW,
|
||||
);
|
||||
assert.equal(ended.kind, "waiting", "a grant on an ended relation gives nothing");
|
||||
assert.equal(personAccess(user(), [grant("1", "u", "capture.run")], [], roles, NOW).noEffect, true);
|
||||
});
|
||||
|
||||
test("seen groups are counted once per person and sorted by size", () => {
|
||||
const u = (groups) => ({ groups });
|
||||
assert.deepEqual(seenGroups([u(["dev", "qa"]), u(["dev", "dev"]), u(undefined)]), [{ name: "dev", people: 2 }, { name: "qa", people: 1 }]);
|
||||
});
|
||||
|
||||
test("refusal codes become sentences and unknown ones fall back", () => {
|
||||
assert.match(reasonText("already_granted", "x"), /Already granted/);
|
||||
assert.equal(reasonText("something_new", "fallback"), "fallback");
|
||||
assert.equal(reasonText(undefined, "fallback"), "fallback");
|
||||
});
|
||||
@@ -177,7 +177,28 @@ export type Grant = {
|
||||
created_by: string;
|
||||
created_at: number;
|
||||
};
|
||||
export type GrantList = { grants: Grant[]; roles: { name: string; permissions: string[] }[]; grantable: string[] };
|
||||
/** A refresh grant: one relation (a source orbit and the staging target it overwrites), not an orbit scope. */
|
||||
export type RelationGrantRow = {
|
||||
id: string;
|
||||
principal_type: "user" | "group";
|
||||
principal: string;
|
||||
relation_id: string;
|
||||
version: number;
|
||||
/** An ended relation grants nothing. */
|
||||
active: boolean;
|
||||
source_name: string;
|
||||
target_name: string;
|
||||
expires_at: number | null;
|
||||
created_at: number;
|
||||
};
|
||||
export type GrantList = {
|
||||
grants: Grant[];
|
||||
relation_grants?: RelationGrantRow[];
|
||||
roles: { name: string; permissions: string[] }[];
|
||||
grantable: string[];
|
||||
/** Permissions only administrators hold. */
|
||||
admin_only?: string[];
|
||||
};
|
||||
export type AccessUser = {
|
||||
id: string;
|
||||
issuer: string;
|
||||
@@ -186,11 +207,16 @@ export type AccessUser = {
|
||||
created_at: number;
|
||||
last_login_at: number | null;
|
||||
is_emergency: boolean;
|
||||
/** Administrator at the last sign-in. Absent on a hub older than this field. */
|
||||
admin?: boolean;
|
||||
/** Groups the identity provider reported at the last sign-in. */
|
||||
groups?: string[];
|
||||
};
|
||||
export type NewGrant = {
|
||||
principal_type: "user" | "group";
|
||||
principal: string;
|
||||
role?: string;
|
||||
permissions?: string[];
|
||||
orbit_id?: string;
|
||||
expires_at?: string;
|
||||
};
|
||||
@@ -199,6 +225,9 @@ 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) });
|
||||
/** Edit or renew in one step: `replaces` are the grants of the same person or group and orbit being swapped for the new set. */
|
||||
export const replaceGrants = (grant: NewGrant & { replaces: string[] }) =>
|
||||
api<Grant[]>("/api/v1/access/grants", { method: "PUT", 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 }) });
|
||||
|
||||
@@ -1,23 +1,59 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
createGrant, deleteGrant, fetchAccessUsers, fetchGrants, fetchMe, revokeUserSessions, setUserActive,
|
||||
type Grant, type NewGrant, type Orbit,
|
||||
createGrant, deleteGrant, fetchAccessUsers, fetchGrants, fetchMe, fetchRelations, grantRelationAccess, refusalReason, replaceGrants,
|
||||
revokeRelationAccess, revokeUserSessions, setUserActive, type AccessUser, type Orbit, type RelationGrantRow, type RelationView,
|
||||
} from "../../api";
|
||||
import {
|
||||
ADMIN_LABELS, TREE, branchState, expiryState, groupGrants, hasNoEffect, neededBy, personAccess, reasonText, roleLabel,
|
||||
seenGroups, setMany, setPermission, shortName, type AccessRow,
|
||||
} from "../../lib/access";
|
||||
import { Button } from "../ui/Button";
|
||||
import { DatePicker } from "../ui/DatePicker";
|
||||
import { Select } from "../ui/Select";
|
||||
|
||||
const field = "field";
|
||||
const pad = (n: number) => String(n).padStart(2, "0");
|
||||
const ymd = (date: Date) => `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
|
||||
/** Today plus `days`, as `YYYY-MM-DD` in the viewer's own calendar (not UTC). */
|
||||
const inDays = (days: number) => ymd(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + days));
|
||||
const day = (seconds: number) => new Date(seconds * 1000).toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" });
|
||||
const when = (seconds: number | null) => (seconds ? new Date(seconds * 1000).toLocaleString() : "never");
|
||||
const label = "text-[11px] font-mono uppercase tracking-[.14em] text-star-400";
|
||||
|
||||
/** 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")}`;
|
||||
type Report = { added: number; skipped: number; failures: string[] };
|
||||
type Who = "user" | "group";
|
||||
|
||||
/** A checkbox that can be fully, partly or not ticked, or locked. */
|
||||
function Box({ state, name, disabled, onChange, small }: { state: "all" | "some" | "none"; name: string; disabled?: boolean; onChange: () => void; small?: boolean }) {
|
||||
const on = state !== "none";
|
||||
const size = small ? "h-5 w-5" : "h-[22px] w-[22px]";
|
||||
return (
|
||||
<button
|
||||
type="button" role="checkbox" aria-checked={state === "some" ? "mixed" : on} aria-label={name} disabled={disabled} onClick={onChange}
|
||||
className={`mt-0.5 flex ${size} shrink-0 items-center justify-center rounded-md border-[1.5px] disabled:cursor-not-allowed ${on ? "border-orbit-amber bg-orbit-amber" : "border-[#4a525b] bg-space-950"} ${disabled && on ? "opacity-70" : ""}`}
|
||||
>
|
||||
{state === "all" && <svg aria-hidden width="13" height="13" viewBox="0 0 14 14" fill="none" stroke="#14110d" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M2.5 7.5l3 3 6-7" /></svg>}
|
||||
{state === "some" && <svg aria-hidden width="13" height="13" viewBox="0 0 14 14" fill="none" stroke="#14110d" strokeWidth="2.4" strokeLinecap="round"><path d="M3 7h8" /></svg>}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function when(seconds: number | null) {
|
||||
return seconds ? new Date(seconds * 1000).toLocaleString() : "never";
|
||||
function Chip({ active, onClick, children }: { active?: boolean; onClick: () => void; children: React.ReactNode }) {
|
||||
return (
|
||||
<button type="button" aria-pressed={active} onClick={onClick}
|
||||
className={`rounded-full border px-3 py-1 text-[13px] ${active ? "border-[#f1bc90] bg-[#2a2119] text-[#f1bc90]" : "border-[#3a4149] text-star-200 hover:border-[#5a6068]"}`}>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function Badge({ tone, children }: { tone: "green" | "violet" | "amber" | "red" | "plain"; children: React.ReactNode }) {
|
||||
const tones = {
|
||||
green: "bg-[#1c2b27] text-orbit-green", violet: "bg-[#2a2640] text-wormhole-violet", amber: "bg-[#2a2119] text-orbit-amber",
|
||||
red: "bg-[#3a1f1d] text-orbit-red", plain: "bg-[#26262a] text-star-200",
|
||||
};
|
||||
return <span className={`inline-block rounded-md px-2 py-0.5 text-[13px] font-medium ${tones[tone]}`}>{children}</span>;
|
||||
}
|
||||
|
||||
/** Who may see and do what. Everything here is administrator-only and takes effect on the user's next request. */
|
||||
@@ -25,165 +61,502 @@ 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 relations = useQuery({ queryKey: ["relations"], queryFn: fetchRelations, 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"] });
|
||||
void qc.invalidateQueries({ queryKey: ["relation-access"] });
|
||||
};
|
||||
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 userList: AccessUser[] | undefined = Array.isArray(users.data) ? users.data : undefined;
|
||||
const relationGrants: RelationGrantRow[] = Array.isArray(grantList?.relation_grants) ? grantList.relation_grants : [];
|
||||
const activeRelations: RelationView[] = Array.isArray(relations.data?.relations) ? relations.data.relations.filter((r) => r.active) : [];
|
||||
const roles = grantList?.roles ?? [];
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
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");
|
||||
const groupsSeen = useMemo(() => seenGroups(userList ?? []), [userList]);
|
||||
|
||||
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() } : {}),
|
||||
});
|
||||
const formRef = useRef<HTMLElement>(null);
|
||||
const [editing, setEditing] = useState<AccessRow | undefined>();
|
||||
const [formKey, setFormKey] = useState(0);
|
||||
const [prefill, setPrefill] = useState<{ perms: string[]; expires: string } | undefined>();
|
||||
|
||||
function startEdit(row: AccessRow, renew: boolean) {
|
||||
setEditing(row);
|
||||
setPrefill({ perms: row.permissions, expires: renew ? inDays(30) : row.expires_at ? ymd(new Date(row.expires_at * 1000)) : "" });
|
||||
setFormKey((k) => k + 1);
|
||||
formRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||
}
|
||||
function stopEdit() {
|
||||
setEditing(undefined);
|
||||
setPrefill(undefined);
|
||||
setFormKey((k) => k + 1);
|
||||
}
|
||||
|
||||
// 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),
|
||||
);
|
||||
const remove = useMutation({ mutationFn: async (ids: string[]) => { for (const id of ids) await deleteGrant(id); }, onSuccess: refresh });
|
||||
const removeRefresh = useMutation({ mutationFn: ({ relation, id }: { relation: string; id: string }) => revokeRelationAccess(relation, id), onSuccess: refresh });
|
||||
const fix = useMutation({
|
||||
mutationFn: (row: AccessRow) => replaceGrants({
|
||||
principal_type: row.principal_type, principal: row.principal, ...(row.scope_id ? { orbit_id: row.scope_id } : {}),
|
||||
...(row.expires_at ? { expires_at: new Date(row.expires_at * 1000).toISOString() } : {}),
|
||||
permissions: [...setPermission(new Set(row.permissions), "orbit.read", true)], replaces: row.ids,
|
||||
}),
|
||||
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 rows = useMemo(() => groupGrants(grantList?.grants ?? []), [grantList]);
|
||||
const groupsOf = (row: AccessRow) => (row.principal_type === "user" ? userList?.find((u) => u.id === row.principal)?.groups ?? [] : []);
|
||||
type Line = { key: string; sort: number; attention: boolean; soon: boolean; refresh: boolean; orbit?: AccessRow; relation?: RelationGrantRow };
|
||||
const lines: Line[] = [
|
||||
...rows.map((row): Line => {
|
||||
const state = expiryState(row.expires_at, now);
|
||||
const noEffect = hasNoEffect(row, grantList?.grants ?? [], groupsOf(row), now);
|
||||
return { key: row.key, orbit: row, refresh: false, sort: state === "expired" ? 1 : 0, attention: state === "expired" || noEffect, soon: state === "soon" };
|
||||
}),
|
||||
...relationGrants.map((g): Line => {
|
||||
const state = expiryState(g.expires_at, now);
|
||||
return { key: g.id, relation: g, refresh: true, sort: state === "expired" || !g.active ? 1 : 0, attention: state === "expired" || !g.active, soon: state === "soon" };
|
||||
}),
|
||||
].sort((a, b) => a.sort - b.sort);
|
||||
const [filter, setFilter] = useState<"all" | "attention" | "refresh" | "soon">("all");
|
||||
const shown = lines.filter((l) => filter === "all" || (filter === "attention" && l.attention) || (filter === "refresh" && l.refresh) || (filter === "soon" && l.soon));
|
||||
const count = (f: (l: Line) => boolean) => lines.filter(f).length;
|
||||
|
||||
const people = userList ?? [];
|
||||
const failed = toggle.isError ? toggle.error : signOut.isError ? signOut.error : undefined;
|
||||
|
||||
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>
|
||||
<div className="space-y-10 p-6">
|
||||
<GiveAccess
|
||||
key={formKey} sectionRef={formRef} orbits={orbits} users={people} roles={roles} relations={activeRelations} groupsSeen={groupsSeen}
|
||||
editing={editing} prefill={prefill} adminOnly={grantList?.admin_only ?? Object.keys(ADMIN_LABELS)} onDone={() => { refresh(); void qc.invalidateQueries({ queryKey: ["relations"] }); if (editing) stopEdit(); }}
|
||||
onCancelEdit={stopEdit} userName={userName}
|
||||
/>
|
||||
|
||||
<section aria-labelledby="grants-heading">
|
||||
<h3 id="grants-heading" className="text-lg font-semibold text-star-100">Current access</h3>
|
||||
<div className="flex flex-wrap items-baseline justify-between gap-2">
|
||||
<h3 id="grants-heading" className="text-lg font-semibold text-star-100">Current access</h3>
|
||||
<p className="text-sm text-star-400">One row per person or group, orbit and end date. Refresh grants are listed here too.</p>
|
||||
</div>
|
||||
{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>
|
||||
: lines.length === 0 ? (
|
||||
<div className="mt-3 rounded-xl border border-dashed border-[#3a4149] p-6 text-center">
|
||||
<p className="font-medium text-star-100">Nobody has been granted access yet</p>
|
||||
<p className="mt-1 text-sm text-star-400">Administrators from SSO already see everything. Use the form above to let someone else in.</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="mt-3 flex flex-wrap gap-2" role="group" aria-label="Filter current access">
|
||||
<Chip active={filter === "all"} onClick={() => setFilter("all")}>All · {lines.length}</Chip>
|
||||
<Chip active={filter === "attention"} onClick={() => setFilter("attention")}>Needs attention · {count((l) => l.attention)}</Chip>
|
||||
<Chip active={filter === "refresh"} onClick={() => setFilter("refresh")}>Refresh · {count((l) => l.refresh)}</Chip>
|
||||
<Chip active={filter === "soon"} onClick={() => setFilter("soon")}>Ending soon · {count((l) => l.soon)}</Chip>
|
||||
</div>
|
||||
<div className="mt-3 overflow-x-auto rounded-xl border border-space-700">
|
||||
<table className="w-full min-w-[820px] text-left text-sm">
|
||||
<thead className="bg-[#0d1013] text-star-400"><tr className={label}>
|
||||
<th className="px-4 py-3 font-normal">Who</th><th className="font-normal">Can do</th><th className="font-normal">Orbit</th><th className="font-normal">Ends</th><th />
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
{shown.map((line) => line.orbit
|
||||
? <OrbitLine key={line.key} row={line.orbit} grants={grantList.grants} roles={roles} now={now} people={groupsSeen}
|
||||
who={line.orbit.principal_type === "group" ? line.orbit.principal : userName(line.orbit.principal)}
|
||||
orbit={orbitName(line.orbit.scope_id)} noEffect={hasNoEffect(line.orbit, grantList.grants, groupsOf(line.orbit), now)}
|
||||
busy={remove.isPending || fix.isPending} onEdit={(renew) => startEdit(line.orbit as AccessRow, renew)}
|
||||
onFix={() => fix.mutate(line.orbit as AccessRow)} onRemove={() => remove.mutate((line.orbit as AccessRow).ids)} />
|
||||
: line.relation && <RefreshLine key={line.key} grant={line.relation} now={now} who={line.relation.principal_type === "group" ? line.relation.principal : userName(line.relation.principal)}
|
||||
busy={removeRefresh.isPending} onRemove={() => removeRefresh.mutate({ relation: line.relation!.relation_id, id: line.relation!.id })} />)}
|
||||
{shown.length === 0 && <tr><td colSpan={5} className="px-4 py-5 text-star-400">Nothing matches this filter.</td></tr>}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{(remove.isError || removeRefresh.isError || fix.isError) && <p role="alert" className="mt-3 text-sm text-orbit-red">That change was not saved. Reload the list and try again.</p>}
|
||||
</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>
|
||||
)}
|
||||
<div className="flex flex-wrap items-baseline justify-between gap-2">
|
||||
<h3 id="users-heading" className="text-lg font-semibold text-star-100">People who have signed in</h3>
|
||||
<p className="text-sm text-star-400">Access is what each person can do right now, from every grant and group.</p>
|
||||
</div>
|
||||
{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>
|
||||
<div className="mt-3 overflow-x-auto rounded-xl border border-space-700">
|
||||
<table className="w-full min-w-[820px] text-left text-sm">
|
||||
<thead className="bg-[#0d1013] text-star-400"><tr className={label}>
|
||||
<th className="px-4 py-3 font-normal">Name</th><th className="font-normal">Last sign-in</th><th className="font-normal">Access</th><th className="font-normal">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>
|
||||
))}
|
||||
{people.map((u) => {
|
||||
const self = `oidc:${u.id}` === me.data?.id;
|
||||
const access = u.is_emergency ? undefined : personAccess(u, grantList?.grants ?? [], relationGrants, roles, now);
|
||||
return (
|
||||
<tr key={u.id} className="border-t border-space-700 align-middle text-star-100">
|
||||
<td className="px-4 py-3">{u.is_emergency ? "Emergency operator" : u.display_name}{self && <span className="ml-2 rounded-md bg-[#26262a] px-2 py-0.5 text-xs text-star-200">You</span>}</td>
|
||||
<td className="text-star-200">{when(u.last_login_at)}</td>
|
||||
<td className="pr-3">
|
||||
{u.is_emergency ? <><Badge tone="amber">Administrator</Badge> <span className="text-xs text-star-400">emergency password</span></>
|
||||
: access?.kind === "admin" ? <><Badge tone="amber">Administrator</Badge> <span className="text-xs text-star-400">from SSO settings</span></>
|
||||
: access?.kind === "waiting" ? <><span className="rounded-md border border-[#3a4149] px-2 py-0.5 text-[13px] text-star-200">Waiting</span> <span className="text-xs text-star-400">No access yet.</span></>
|
||||
: access && (
|
||||
<span className="text-[13px] text-star-200">
|
||||
{access.label && <Badge tone="green">{access.label}</Badge>}
|
||||
{access.via.length > 0 && <> via group {access.via.join(", ")}</>}
|
||||
{access.refresh.length > 0 && <>{access.label ? " · " : ""}<Badge tone="violet">Refresh</Badge> {access.refresh.join(", ")}</>}
|
||||
{access.noEffect && <span className="block text-xs text-orbit-amber">⚠ Cannot see any orbit yet: “See the orbit” is missing.</span>}
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td className={u.active ? "" : "text-star-400"}>{u.active ? "Active" : "Disabled"}</td>
|
||||
<td className="space-x-2 whitespace-nowrap px-4 text-right">
|
||||
{!u.is_emergency && (
|
||||
<>
|
||||
<Button disabled={signOut.isPending} onClick={() => signOut.mutate(u.id)}>Sign out everywhere</Button>
|
||||
{!self && <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>}
|
||||
{failed && <p role="alert" className="mt-3 text-sm text-orbit-red">{reasonText(refusalReason(failed), "That change was refused.")}</p>}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function OrbitLine({ row, grants, roles, now, who, orbit, people, noEffect, busy, onEdit, onFix, onRemove }: {
|
||||
row: AccessRow; grants: unknown; roles: { name: string; permissions: string[] }[]; now: number; who: string; orbit: string;
|
||||
people: { name: string; people: number }[]; noEffect: boolean; busy: boolean; onEdit: (renew: boolean) => void; onFix: () => void; onRemove: () => void;
|
||||
}) {
|
||||
void grants;
|
||||
const state = expiryState(row.expires_at, now);
|
||||
const expired = state === "expired";
|
||||
const members = row.principal_type === "group" ? people.find((p) => p.name === row.principal)?.people : undefined;
|
||||
const role = roleLabel(row.permissions, roles);
|
||||
return (
|
||||
<tr className={`border-t border-space-700 align-top text-star-100 ${expired ? "bg-[#14110f]" : ""}`}>
|
||||
<td className="px-4 py-3">
|
||||
<span className={`font-medium ${expired ? "text-star-300" : ""}`}>{who}</span>
|
||||
<span className="block font-mono text-xs text-star-400">{row.principal_type === "group" ? `group${members ? ` · ${members} ${members === 1 ? "person" : "people"}` : ""}` : "person"}</span>
|
||||
</td>
|
||||
<td className="pr-3">
|
||||
<Badge tone={role === "Custom" ? "plain" : expired ? "plain" : "green"}>{role}</Badge>
|
||||
<span className="ml-2 text-[13px] text-star-400">{row.permissions.map(shortName).join(" · ")}</span>
|
||||
{noEffect && <span className="mt-1 block text-[13px] text-orbit-amber">⚠ Has no effect: this person cannot see the orbit. Add “See the orbit”.</span>}
|
||||
</td>
|
||||
<td className="pr-3">{orbit}</td>
|
||||
<td className="pr-3">
|
||||
{expired ? <Badge tone="red">Expired {day(row.expires_at!)}</Badge>
|
||||
: row.expires_at ? <span className={state === "soon" ? "text-orbit-amber" : "text-star-200"}>{day(row.expires_at)}{state === "soon" ? " · ending soon" : ""}</span>
|
||||
: <span className="text-star-300">No end</span>}
|
||||
</td>
|
||||
<td className="space-x-2 whitespace-nowrap px-4 text-right">
|
||||
{noEffect && <Button disabled={busy} onClick={onFix}>Fix</Button>}
|
||||
{expired ? <Button onClick={() => onEdit(true)}>Renew</Button> : <Button onClick={() => onEdit(false)} aria-label={`Edit access for ${who}`}>Edit</Button>}
|
||||
<Button disabled={busy} onClick={onRemove} aria-label={`Remove all access of ${who} on ${orbit}`}>Remove</Button>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
}
|
||||
|
||||
function RefreshLine({ grant, now, who, busy, onRemove }: { grant: RelationGrantRow; now: number; who: string; busy: boolean; onRemove: () => void }) {
|
||||
const state = expiryState(grant.expires_at, now);
|
||||
const expired = state === "expired";
|
||||
return (
|
||||
<tr className={`border-t border-space-700 align-top text-star-100 ${expired || !grant.active ? "bg-[#14110f]" : ""}`}>
|
||||
<td className="px-4 py-3">
|
||||
<span className="font-medium">{who}</span>
|
||||
<span className="block font-mono text-xs text-star-400">{grant.principal_type === "group" ? "group" : "person"}</span>
|
||||
</td>
|
||||
<td className="pr-3">
|
||||
<Badge tone={grant.active ? "violet" : "plain"}>Refresh</Badge>
|
||||
<span className="ml-2 text-[13px] text-star-400">{grant.source_name} → {grant.target_name} · v{grant.version}</span>
|
||||
{!grant.active && <span className="mt-1 block text-[13px] text-orbit-amber">⚠ This relation has ended, so the grant does nothing. Allow them again on its new version.</span>}
|
||||
</td>
|
||||
<td className="pr-3 text-star-400">per relation</td>
|
||||
<td className="pr-3">
|
||||
{expired ? <Badge tone="red">Expired {day(grant.expires_at!)}</Badge>
|
||||
: grant.expires_at ? <span className={state === "soon" ? "text-orbit-amber" : "text-star-200"}>{day(grant.expires_at)}{state === "soon" ? " · ending soon" : ""}</span>
|
||||
: <span className="text-star-300">No end</span>}
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-4 text-right"><Button disabled={busy} onClick={onRemove} aria-label={`Remove refresh access of ${who}`}>Remove</Button></td>
|
||||
</tr>
|
||||
);
|
||||
}
|
||||
|
||||
function GiveAccess({ sectionRef, orbits, users, roles, relations, groupsSeen, adminOnly, editing, prefill, onDone, onCancelEdit, userName }: {
|
||||
sectionRef: React.RefObject<HTMLElement | null>; orbits: Orbit[]; users: AccessUser[]; roles: { name: string; permissions: string[] }[];
|
||||
relations: RelationView[]; groupsSeen: { name: string; people: number }[]; adminOnly: string[]; editing?: AccessRow;
|
||||
prefill?: { perms: string[]; expires: string }; onDone: () => void; onCancelEdit: () => void; userName: (id: string) => string;
|
||||
}) {
|
||||
const [kind, setKind] = useState<Who>(editing?.principal_type ?? "user");
|
||||
const [principal, setPrincipal] = useState(editing?.principal ?? "");
|
||||
const [orbit, setOrbit] = useState(editing?.scope_id ?? "");
|
||||
const [expires, setExpires] = useState(prefill?.expires ?? "");
|
||||
const [perms, setPerms] = useState<Set<string>>(new Set(prefill?.perms ?? ["orbit.read", "snapshot.read"]));
|
||||
const [rels, setRels] = useState<Set<string>>(new Set());
|
||||
const [adminOpen, setAdminOpen] = useState(false);
|
||||
const [report, setReport] = useState<Report | undefined>();
|
||||
|
||||
const candidates = users.filter((u) => !u.is_emergency && !u.admin && u.active);
|
||||
const roleOf = (set: Set<string>) => roleLabel(set, roles);
|
||||
const count = perms.size + rels.size;
|
||||
const ready = count > 0 && principal.trim() !== "" && (!editing || perms.size > 0);
|
||||
|
||||
const submit = useMutation({
|
||||
mutationFn: async (): Promise<Report> => {
|
||||
const base = {
|
||||
principal_type: kind, principal: principal.trim(),
|
||||
...(orbit ? { orbit_id: orbit } : {}),
|
||||
...(expires ? { expires_at: new Date(`${expires}T23:59:59`).toISOString() } : {}),
|
||||
};
|
||||
const out: Report = { added: 0, skipped: 0, failures: [] };
|
||||
if (perms.size > 0) {
|
||||
try {
|
||||
const permissions = [...perms];
|
||||
if (editing) {
|
||||
await replaceGrants({ ...base, permissions, replaces: editing.ids });
|
||||
out.added += permissions.length;
|
||||
} else {
|
||||
const created = await createGrant({ ...base, permissions });
|
||||
out.added += created.length;
|
||||
out.skipped += permissions.length - created.length;
|
||||
}
|
||||
} catch (error) {
|
||||
out.failures.push(reasonText(refusalReason(error), "The permissions could not be saved."));
|
||||
}
|
||||
}
|
||||
for (const id of rels) {
|
||||
const relation = relations.find((r) => r.id === id);
|
||||
const name = relation ? `${relation.source_name} → ${relation.target_name}` : "that relation";
|
||||
try {
|
||||
await grantRelationAccess(id, { principal_type: kind, principal: principal.trim(), ...(base.expires_at ? { expires_at: base.expires_at } : {}) });
|
||||
out.added += 1;
|
||||
} catch {
|
||||
out.failures.push(`Refresh through ${name} was not added. It may already be allowed.`);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
},
|
||||
onSuccess: (result) => {
|
||||
setReport(result);
|
||||
if (result.failures.length === 0) {
|
||||
if (editing) onDone();
|
||||
else {
|
||||
setPerms(new Set(["orbit.read", "snapshot.read"]));
|
||||
setRels(new Set());
|
||||
onDone();
|
||||
}
|
||||
} else onDone();
|
||||
},
|
||||
});
|
||||
|
||||
const preset = (name: string) => setPerms(new Set(roles.find((r) => r.name === name)?.permissions ?? []));
|
||||
const presetActive = (name: string) => {
|
||||
const role = roles.find((r) => r.name === name);
|
||||
return !!role && role.permissions.length === perms.size && role.permissions.every((p) => perms.has(p));
|
||||
};
|
||||
const relKey = (id: string) => (rels.has(id) ? "all" : "none") as "all" | "none";
|
||||
const refreshBranch = relations.map((r) => r.id);
|
||||
const refreshState = branchState(rels, refreshBranch);
|
||||
const summary = [
|
||||
perms.size > 0 && `${[...perms].map(shortName).join(", ")} on ${orbit ? orbits.find((o) => o.id === orbit)?.name ?? "that orbit" : "all orbits"}`,
|
||||
rels.size > 0 && `refresh through ${relations.filter((r) => rels.has(r.id)).map((r) => `${r.source_name} → ${r.target_name}`).join(", ")}`,
|
||||
].filter(Boolean).join(" · ");
|
||||
|
||||
return (
|
||||
<section ref={sectionRef} aria-labelledby="grant-heading">
|
||||
<h3 id="grant-heading" className="text-lg font-semibold text-star-100">{editing ? `Edit access: ${editing.principal_type === "group" ? editing.principal : userName(editing.principal)}` : "Give access"}</h3>
|
||||
<p className="mt-1 max-w-3xl text-sm text-star-300">
|
||||
Administrators come from the SSO configuration. Everyone else sees only what you grant here. Choose who, then tick exactly what they may do.
|
||||
Everything on a branch needs the orbit to be visible, so the tree ticks that for you.
|
||||
</p>
|
||||
<form className="mt-4 space-y-5" onSubmit={(e) => { e.preventDefault(); if (ready) submit.mutate(); }}>
|
||||
<div className="grid gap-6 lg:grid-cols-[1.5fr_1fr_1fr]">
|
||||
<div>
|
||||
<p className={label}>1 · Who</p>
|
||||
{editing ? <p className="mt-2 text-star-100">{editing.principal_type === "group" ? `Group ${editing.principal}` : userName(editing.principal)} <button type="button" className="ml-2 text-sm text-[#f1bc90] underline" onClick={onCancelEdit}>Cancel editing</button></p> : (
|
||||
<>
|
||||
<div className="mt-2 flex rounded-lg border border-[#2f343b] bg-space-950 p-1" role="group" aria-label="Grant to">
|
||||
{(["user", "group"] as const).map((k) => (
|
||||
<button key={k} type="button" aria-pressed={kind === k} onClick={() => { setKind(k); setPrincipal(""); }}
|
||||
className={`h-9 flex-1 rounded-md text-sm font-medium ${kind === k ? "bg-[#2a2119] text-[#f1bc90]" : "text-star-200"}`}>
|
||||
{k === "user" ? "A person" : "An identity-provider group"}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{kind === "user" ? (
|
||||
<label className="mt-3 block text-sm text-star-300">
|
||||
Person
|
||||
<Select value={principal} onChange={(e) => setPrincipal(e.target.value)} required aria-label="Person">
|
||||
<option value="" disabled>Choose…</option>
|
||||
{candidates.map((u) => <option key={u.id} value={u.id}>{u.display_name}</option>)}
|
||||
</Select>
|
||||
<span className="mt-1 block text-xs text-star-400">Only active people who have signed in. Administrators already have everything.</span>
|
||||
</label>
|
||||
) : (
|
||||
<div className="mt-3">
|
||||
<label className="block text-sm text-star-300">
|
||||
Group name
|
||||
<input value={principal} onChange={(e) => setPrincipal(e.target.value)} required maxLength={128} className={field} autoComplete="off" />
|
||||
</label>
|
||||
{groupsSeen.length > 0 && (
|
||||
<>
|
||||
<p className="mt-2 text-xs text-star-400">Seen at recent sign-ins. Names must match the token's groups claim exactly.</p>
|
||||
<div className="mt-2 flex flex-wrap gap-2">
|
||||
{groupsSeen.slice(0, 8).map((g) => (
|
||||
<button key={g.name} type="button" onClick={() => setPrincipal(g.name)}
|
||||
className="rounded-full border border-[#3a4149] px-3 py-1 font-mono text-xs text-star-100 hover:border-[#5a6068]">
|
||||
{g.name} <span className="text-star-400">· {g.people}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className={label}>2 · Where</p>
|
||||
<div className="mt-2">
|
||||
<Select value={orbit} onChange={(e) => setOrbit(e.target.value)} aria-label="Orbit" disabled={!!editing}>
|
||||
<option value="">All orbits</option>
|
||||
{orbits.map((o) => <option key={o.id} value={o.id}>{o.name}</option>)}
|
||||
</Select>
|
||||
</div>
|
||||
{rels.size > 0 && <p className="mt-2 text-xs text-orbit-amber">Refresh is granted per relation, not per orbit. This choice applies to the other ticked rows only.</p>}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className={label}>3 · Until</p>
|
||||
<div className="mt-2 flex flex-wrap gap-2">
|
||||
<Chip active={expires === ""} onClick={() => setExpires("")}>No end</Chip>
|
||||
<Chip active={expires === inDays(30)} onClick={() => setExpires(inDays(30))}>30 days</Chip>
|
||||
<Chip active={expires === inDays(90)} onClick={() => setExpires(inDays(90))}>90 days</Chip>
|
||||
</div>
|
||||
<div className="mt-2"><DatePicker aria-label="Ends on" placeholder="Or pick a date…" min={inDays(1)} value={expires} onChange={(v) => setExpires(v)} /></div>
|
||||
<p className="mt-2 text-xs text-star-400">Grants can run for at most two years.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-2xl border border-space-700 bg-[#0d1013]">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 border-b border-[#22272d] px-5 py-3">
|
||||
<p className={label}>4 · What they may do</p>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="text-[13px] text-star-400">Start from</span>
|
||||
{roles.map((r) => <Chip key={r.name} active={presetActive(r.name)} onClick={() => preset(r.name)}>{r.name.charAt(0).toUpperCase() + r.name.slice(1)}</Chip>)}
|
||||
<Chip onClick={() => { setPerms(new Set()); setRels(new Set()); }}>Clear</Chip>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="columns-1 gap-4 px-5 pb-1 pt-4 md:columns-2">
|
||||
{TREE.map((group) => {
|
||||
const ids = group.items.map((i) => i.id);
|
||||
const state = branchState(perms, ids);
|
||||
return (
|
||||
<div key={group.id} className="mb-4 break-inside-avoid overflow-hidden rounded-xl border border-[#22272d] bg-[#0f1216]">
|
||||
<div className="flex items-start gap-3 bg-[#141920] px-4 py-3">
|
||||
<Box state={state} name={group.label} onChange={() => setPerms(setMany(perms, ids, state !== "all"))} />
|
||||
<div><p className="font-semibold text-star-100">{group.label}</p><p className="text-[13px] text-star-400">{group.note}</p></div>
|
||||
</div>
|
||||
{group.items.map((item) => {
|
||||
const lockedBy = neededBy(perms, item.id);
|
||||
const on = perms.has(item.id);
|
||||
return (
|
||||
<div key={item.id} className="flex items-start gap-3 border-t border-[#1b1f24] py-2.5 pl-[50px] pr-4">
|
||||
<Box small state={on ? "all" : "none"} name={item.label} disabled={on && lockedBy.length > 0} onChange={() => setPerms(setPermission(perms, item.id, !on))} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-baseline justify-between gap-x-3">
|
||||
<span className="text-star-100">{item.label}</span>
|
||||
<code className="font-mono text-[11.5px] text-[#8a9097]">{item.id}</code>
|
||||
</div>
|
||||
{on && lockedBy.length > 0 ? <p className="text-[12.5px] text-star-400">Needed by {lockedBy.map(shortName).join(", ")}.</p>
|
||||
: item.hint ? <p className="text-[12.5px] text-star-400">{item.hint}</p> : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
<div className="mb-4 break-inside-avoid overflow-hidden rounded-xl border border-[#22272d] bg-[#0f1216]">
|
||||
<div className="flex items-start gap-3 bg-[#141920] px-4 py-3">
|
||||
<Box state={refreshState} name="Refresh staging" disabled={refreshBranch.length === 0}
|
||||
onChange={() => setRels(new Set(refreshState === "all" ? [] : refreshBranch))} />
|
||||
<div><p className="font-semibold text-star-100">Refresh staging</p><p className="text-[13px] text-star-400">Per relation, not per orbit. Does not need the orbit to be visible.</p></div>
|
||||
</div>
|
||||
{relations.length === 0 && <p className="border-t border-[#1b1f24] px-4 py-3 text-[13px] text-star-400">No active relations yet. Create one in Relations first.</p>}
|
||||
{relations.map((r) => (
|
||||
<div key={r.id} className="flex items-start gap-3 border-t border-[#1b1f24] py-2.5 pl-[50px] pr-4">
|
||||
<Box small state={relKey(r.id)} name={`Refresh ${r.source_name} to ${r.target_name}`}
|
||||
onChange={() => setRels((cur) => { const next = new Set(cur); if (next.has(r.id)) next.delete(r.id); else next.add(r.id); return next; })} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-baseline justify-between gap-x-3">
|
||||
<span className="text-star-100">{r.source_name} → {r.target_name}</span>
|
||||
<code className="font-mono text-[11.5px] text-[#8a9097]">refresh.run</code>
|
||||
</div>
|
||||
<p className="text-[12.5px] text-star-400">Version {r.version}{r.usable ? " · ready" : " · not usable right now"}</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mx-5 mb-4 rounded-xl border border-[#22272d]">
|
||||
<button type="button" aria-expanded={adminOpen} onClick={() => setAdminOpen((o) => !o)} className="flex w-full items-center gap-3 px-4 py-2.5 text-left text-sm text-star-200">
|
||||
<svg aria-hidden width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="#9298a0" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="6.5" width="8" height="5.5" rx="1.3" /><path d="M5 6.5V4.8a2 2 0 014 0v1.7" /></svg>
|
||||
<span className="flex-1">Administrators only · {adminOnly.length} permissions that are never delegated</span>
|
||||
<span className="text-[13px] text-star-400">{adminOpen ? "Hide" : "Show"}</span>
|
||||
</button>
|
||||
{adminOpen && (
|
||||
<div className="flex flex-wrap gap-2 px-4 pb-3">
|
||||
{adminOnly.map((p) => <span key={p} className="rounded-full border border-dashed border-[#3a4149] px-3 py-1 text-[13px] text-star-400">{ADMIN_LABELS[p] ?? p} <code className="font-mono text-[11.5px] text-[#7d838a]">{p}</code></span>)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center justify-between gap-4 rounded-b-2xl border-t border-[#22272d] bg-[#111418] px-5 py-4">
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm text-star-100" aria-live="polite">
|
||||
{count === 0 ? "Nothing ticked yet" : `${editing ? "Will set" : "Will create"} ${count} grant${count > 1 ? "s" : ""}${perms.size ? ` · ${roleOf(perms)}` : ""}`}
|
||||
</p>
|
||||
<p className="mt-0.5 text-[13px] text-star-400">{count === 0 ? "Tick a row, or start from a role." : `${summary} · ${expires ? `until ${day(new Date(`${expires}T23:59:59`).getTime() / 1000)}` : "no end date"}`}</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
{editing && <Button type="button" onClick={onCancelEdit}>Cancel</Button>}
|
||||
<Button type="submit" variant="primary" disabled={!ready || submit.isPending}>{submit.isPending ? "Saving…" : editing ? "Save changes" : "Grant access"}</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{report && report.failures.length === 0 && (report.added > 0 || report.skipped > 0) && (
|
||||
<p role="status" className="mt-3 text-sm text-orbit-green">
|
||||
{report.added > 0 ? `${report.added} added` : "Nothing new added"}{report.skipped > 0 ? `, ${report.skipped} ${report.skipped === 1 ? "was" : "were"} already there` : ""}.
|
||||
</p>
|
||||
)}
|
||||
{report && report.failures.length > 0 && (
|
||||
<div role="alert" className="mt-3 space-y-1 text-sm text-orbit-red">
|
||||
{report.added > 0 && <p>{report.added} added.</p>}
|
||||
{report.failures.map((f) => <p key={f}>{f}</p>)}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -256,7 +256,14 @@ function RelationAccess({ relationId, onChange }: { relationId: string; onChange
|
||||
<ul className="mt-1 space-y-1 text-sm text-star-100">
|
||||
{list.map((g) => (
|
||||
<li key={g.id} className="flex items-center justify-between gap-3">
|
||||
<span>{g.principal_type === "group" ? `Group ${g.principal}` : nameOf(g.principal)}</span>
|
||||
<span>
|
||||
{g.principal_type === "group" ? `Group ${g.principal}` : nameOf(g.principal)}
|
||||
{g.expires_at && (
|
||||
<span className={`ml-2 text-xs ${g.expires_at * 1000 <= Date.now() ? "text-orbit-red" : "text-star-400"}`}>
|
||||
{g.expires_at * 1000 <= Date.now() ? "expired " : "until "}{new Date(g.expires_at * 1000).toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" })}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<Button disabled={remove.isPending} onClick={() => remove.mutate(g.id)} aria-label={`Remove access for ${g.principal_type === "group" ? g.principal : nameOf(g.principal)}`}>Remove</Button>
|
||||
</li>
|
||||
))}
|
||||
|
||||
213
web/src/lib/access.ts
Normal file
213
web/src/lib/access.ts
Normal file
@@ -0,0 +1,213 @@
|
||||
// Pure rules behind the Access console: what the permission tree ticks together, how stored grants are
|
||||
// grouped into rows, what a row or a person is called, and when a grant does nothing. No React, no fetching.
|
||||
import type { AccessUser, Grant, RelationGrantRow } from "../api";
|
||||
|
||||
type Role = { name: string; permissions: string[] };
|
||||
|
||||
/** The permissions that can be granted, in the order the tree lists them. */
|
||||
export const ORBIT_PERMISSIONS = ["orbit.read", "snapshot.read", "snapshot.download", "capture.run"] as const;
|
||||
|
||||
/** What a ticked permission needs ticked with it: without `orbit.read` the orbit answers 404. */
|
||||
export const REQUIRES: Record<string, string[]> = {
|
||||
"snapshot.read": ["orbit.read"],
|
||||
"snapshot.download": ["orbit.read", "snapshot.read"],
|
||||
"capture.run": ["orbit.read"],
|
||||
};
|
||||
|
||||
export type TreeGroup = { id: string; label: string; note: string; items: { id: string; label: string; hint?: string }[] };
|
||||
|
||||
/** The grantable permissions as a tree. Refresh is not here: it is granted per relation, not per orbit. */
|
||||
export const TREE: TreeGroup[] = [
|
||||
{ id: "orbit", label: "Orbit", note: "Which orbits appear for this person", items: [{ id: "orbit.read", label: "See the orbit" }] },
|
||||
{
|
||||
id: "snapshots", label: "Snapshots", note: "Backups taken from the orbit",
|
||||
items: [
|
||||
{ id: "snapshot.read", label: "List and open snapshots" },
|
||||
{ id: "snapshot.download", label: "Download a snapshot", hint: "Also ticks list and the orbit." },
|
||||
],
|
||||
},
|
||||
{ id: "capture", label: "Capture", note: "Starting a backup", items: [{ id: "capture.run", label: "Run a capture now" }] },
|
||||
];
|
||||
|
||||
/** Plain names for the permissions only administrators hold; an unknown one shows its code. */
|
||||
export const ADMIN_LABELS: Record<string, string> = {
|
||||
"orbit.manage": "Create and edit orbits",
|
||||
"outpost.manage": "Manage Outposts",
|
||||
"retention.manage": "Change retention",
|
||||
"snapshot.delete": "Delete snapshots",
|
||||
"recovery.manage": "Restore and recovery",
|
||||
"relation.manage": "Environments and relations",
|
||||
"access.manage": "Access",
|
||||
};
|
||||
|
||||
/** Tick or untick one permission together with everything that depends on it. */
|
||||
export function setPermission(current: ReadonlySet<string>, id: string, on: boolean): Set<string> {
|
||||
const next = new Set(current);
|
||||
if (on) {
|
||||
next.add(id);
|
||||
for (const needed of REQUIRES[id] ?? []) next.add(needed);
|
||||
} else {
|
||||
next.delete(id);
|
||||
for (const [other, needs] of Object.entries(REQUIRES)) if (needs.includes(id)) next.delete(other);
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
/** Ticked permissions that need `id`, so it cannot be unticked underneath them. */
|
||||
export function neededBy(current: ReadonlySet<string>, id: string): string[] {
|
||||
return [...current].filter((other) => (REQUIRES[other] ?? []).includes(id));
|
||||
}
|
||||
|
||||
/** Tick or untick a whole branch. */
|
||||
export function setMany(current: ReadonlySet<string>, ids: string[], on: boolean): Set<string> {
|
||||
return ids.reduce((set, id) => setPermission(set, id, on), new Set(current));
|
||||
}
|
||||
|
||||
/** How many of `ids` are ticked: `all`, `some` or `none`. */
|
||||
export function branchState(current: ReadonlySet<string>, ids: string[]): "all" | "some" | "none" {
|
||||
const on = ids.filter((id) => current.has(id)).length;
|
||||
return on === 0 ? "none" : on === ids.length ? "all" : "some";
|
||||
}
|
||||
|
||||
const sameSet = (a: ReadonlySet<string>, b: ReadonlySet<string>) => a.size === b.size && [...a].every((x) => b.has(x));
|
||||
|
||||
/**
|
||||
* A name for a set of permissions, from the roles the hub knows: the role it equals, a role plus the extras it has on top
|
||||
* ("Capturer + Download"), or "Custom". The hub stores no role, only permissions, so this is only ever a label.
|
||||
*/
|
||||
export function roleLabel(permissions: Iterable<string>, roles: Role[]): string {
|
||||
const have = new Set(permissions);
|
||||
if (have.size === 0) return "Custom";
|
||||
const named = (role: Role) => role.name.charAt(0).toUpperCase() + role.name.slice(1);
|
||||
const exact = roles.find((role) => sameSet(new Set(role.permissions), have));
|
||||
if (exact) return named(exact);
|
||||
const within = roles
|
||||
.filter((role) => role.permissions.every((p) => have.has(p)))
|
||||
.sort((a, b) => b.permissions.length - a.permissions.length)[0];
|
||||
if (within) {
|
||||
const extra = [...have].filter((p) => !within.permissions.includes(p));
|
||||
if (extra.length > 0 && extra.length <= 2) return `${named(within)} + ${extra.map(shortName).join(", ")}`;
|
||||
}
|
||||
return "Custom";
|
||||
}
|
||||
|
||||
/** What a permission is called in running text. */
|
||||
export function shortName(permission: string): string {
|
||||
return {
|
||||
"orbit.read": "see orbit",
|
||||
"snapshot.read": "list snapshots",
|
||||
"snapshot.download": "download",
|
||||
"capture.run": "run capture",
|
||||
}[permission] ?? permission;
|
||||
}
|
||||
|
||||
const order = (permission: string) => {
|
||||
const at = ORBIT_PERMISSIONS.indexOf(permission as (typeof ORBIT_PERMISSIONS)[number]);
|
||||
return at < 0 ? ORBIT_PERMISSIONS.length : at;
|
||||
};
|
||||
|
||||
export type AccessRow = {
|
||||
key: string;
|
||||
principal_type: "user" | "group";
|
||||
principal: string;
|
||||
scope_id: string | null;
|
||||
expires_at: number | null;
|
||||
permissions: string[];
|
||||
ids: string[];
|
||||
};
|
||||
|
||||
/** One row per person or group, orbit and end date; the permissions inside it are the grants it stands for. */
|
||||
export function groupGrants(grants: Grant[]): AccessRow[] {
|
||||
const rows = new Map<string, AccessRow>();
|
||||
for (const grant of grants) {
|
||||
const key = [grant.principal_type, grant.principal, grant.scope_id ?? "", grant.expires_at ?? ""].join("|");
|
||||
const row = rows.get(key) ?? {
|
||||
key, principal_type: grant.principal_type, principal: grant.principal, scope_id: grant.scope_id,
|
||||
expires_at: grant.expires_at, permissions: [], ids: [],
|
||||
};
|
||||
row.permissions.push(grant.permission);
|
||||
row.ids.push(grant.id);
|
||||
rows.set(key, row);
|
||||
}
|
||||
for (const row of rows.values()) row.permissions.sort((a, b) => order(a) - order(b));
|
||||
return [...rows.values()];
|
||||
}
|
||||
|
||||
export type Expiry = "none" | "soon" | "expired";
|
||||
const SOON_DAYS = 14;
|
||||
|
||||
/** `expires_at` is seconds since the epoch; `now` is too. */
|
||||
export function expiryState(expiresAt: number | null, now: number): Expiry {
|
||||
if (expiresAt === null) return "none";
|
||||
if (expiresAt <= now) return "expired";
|
||||
return expiresAt - now <= SOON_DAYS * 86_400 ? "soon" : "none";
|
||||
}
|
||||
|
||||
export const live = (grant: { expires_at: number | null }, now: number) => grant.expires_at === null || grant.expires_at > now;
|
||||
|
||||
/**
|
||||
* A grant that cannot be used because the person never gets to see the orbit. The row's own permissions are not the whole
|
||||
* story: a global grant, another grant on the same orbit, or one of the person's groups may already give `orbit.read`.
|
||||
*/
|
||||
export function hasNoEffect(row: AccessRow, grants: Grant[], groupsOf: string[], now: number): boolean {
|
||||
if (row.permissions.length === 0 || row.permissions.every((p) => p === "orbit.read")) return false;
|
||||
if (!live(row, now)) return false;
|
||||
const principals = new Set(row.principal_type === "user" ? [`user|${row.principal}`, ...groupsOf.map((g) => `group|${g}`)] : [`group|${row.principal}`]);
|
||||
return !grants.some(
|
||||
(g) => g.permission === "orbit.read" && live(g, now) && principals.has(`${g.principal_type}|${g.principal}`) &&
|
||||
(g.scope_type === "global" || g.scope_id === row.scope_id),
|
||||
);
|
||||
}
|
||||
|
||||
export type PersonAccess = {
|
||||
kind: "admin" | "waiting" | "granted";
|
||||
/** Role-style name of everything they hold through grants (people and their groups together). */
|
||||
label: string;
|
||||
via: string[];
|
||||
refresh: string[];
|
||||
noEffect: boolean;
|
||||
};
|
||||
|
||||
/** What a person can do right now, from every live grant of theirs and of the groups they came in with. */
|
||||
export function personAccess(user: AccessUser, grants: Grant[], relationGrants: RelationGrantRow[], roles: Role[], now: number): PersonAccess {
|
||||
const groups = user.groups ?? [];
|
||||
if (user.admin) return { kind: "admin", label: "Administrator", via: [], refresh: [], noEffect: false };
|
||||
const mine = grants.filter(
|
||||
(g) => live(g, now) && ((g.principal_type === "user" && g.principal === user.id) || (g.principal_type === "group" && groups.includes(g.principal))),
|
||||
);
|
||||
const via = [...new Set(mine.filter((g) => g.principal_type === "group").map((g) => g.principal))];
|
||||
const refresh = relationGrants
|
||||
.filter((g) => g.active && live(g, now) && ((g.principal_type === "user" && g.principal === user.id) || (g.principal_type === "group" && groups.includes(g.principal))))
|
||||
.map((g) => `${g.source_name} → ${g.target_name}`);
|
||||
const permissions = new Set(mine.map((g) => g.permission));
|
||||
if (permissions.size === 0 && refresh.length === 0) return { kind: "waiting", label: "Waiting", via: [], refresh: [], noEffect: false };
|
||||
const noEffect = permissions.size > 0 && !permissions.has("orbit.read");
|
||||
return { kind: "granted", label: permissions.size ? roleLabel(permissions, roles) : "", via, refresh: [...new Set(refresh)], noEffect };
|
||||
}
|
||||
|
||||
/** Groups seen at recent sign-ins, most members first, so a name does not have to be typed from memory. */
|
||||
export function seenGroups(users: AccessUser[]): { name: string; people: number }[] {
|
||||
const counts = new Map<string, number>();
|
||||
for (const user of users) for (const group of new Set(user.groups ?? [])) counts.set(group, (counts.get(group) ?? 0) + 1);
|
||||
return [...counts].map(([name, people]) => ({ name, people })).sort((a, b) => b.people - a.people || a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
const REASONS: Record<string, string> = {
|
||||
already_granted: "Already granted: this person or group already has everything you ticked here.",
|
||||
unknown_user: "That person no longer exists. Reload the list and choose again.",
|
||||
unknown_orbit: "That orbit no longer exists. Reload the list and choose again.",
|
||||
emergency_operator: "The emergency operator is an administrator and never needs a grant.",
|
||||
bad_end_date: "The end date must be in the future and within two years.",
|
||||
bad_group: "Enter a group name of up to 128 characters, without control characters.",
|
||||
bad_person: "Choose a person from the list.",
|
||||
nothing_selected: "Tick at least one permission first.",
|
||||
unknown_permission: "That permission cannot be granted.",
|
||||
grant_mismatch: "Those grants belong to someone else or somewhere else. Reload and try again.",
|
||||
cannot_disable_self: "You cannot disable yourself.",
|
||||
cannot_disable_emergency: "The emergency operator cannot be disabled.",
|
||||
};
|
||||
|
||||
/** A sentence for a refusal code the hub sent; `fallback` when it sent none or a code this screen does not know. */
|
||||
export function reasonText(code: string | undefined, fallback: string): string {
|
||||
return (code && REASONS[code]) || fallback;
|
||||
}
|
||||
Reference in New Issue
Block a user