diff --git a/crates/tessera-hub/src/api/access.rs b/crates/tessera-hub/src/api/access.rs index 8b57c00..3bce115 100644 --- a/crates/tessera-hub/src/api/access.rs +++ b/crates/tessera-hub/src/api/access.rs @@ -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 { 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, + /// Refresh grants, one per relation: the `refresh.run` permission is never in `grants`. + relation_grants: Vec, roles: Vec, /// 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, permission: Option, + permissions: Option>, /// Absent = every orbit. orbit_id: Option, /// RFC 3339; absent = no expiry. expires_at: Option, + /// Only for `PUT`: grants of the same person or group and orbit that this request replaces. + #[serde(default)] + replaces: Vec, } -async fn create( - ConnectInfo(peer): ConnectInfo, - State(state): State, - headers: HeaderMap, - Json(body): Json, -) -> Result<(StatusCode, HeaderMap, Json>), StatusCode> { - let actor = admin_write(&state, peer, &headers)?; - let now = now(); - let permissions: Vec = 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, + orbit: Option, + expires_at: Option, +} + +fn validate(state: &HubState, body: &CreateGrant, now: i64) -> Result { + let bad = |reason| refuse(StatusCode::BAD_REQUEST, reason); + let unprocessable = |reason| refuse(StatusCode::UNPROCESSABLE_ENTITY, reason); + let mut permissions: Vec = 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::>()?, + _ => 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, + State(state): State, + headers: HeaderMap, + Json(body): Json, +) -> Result<(StatusCode, HeaderMap, Json>), 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, + State(state): State, + headers: HeaderMap, + Json(body): Json, +) -> Result<(HeaderMap, Json>), 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 = 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 = 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, State(state): State, @@ -241,16 +359,17 @@ fn target_user( state: &HubState, actor: &super::routes::OperatorActor, id: Uuid, -) -> Result { +) -> Result { 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, Json(body): Json, -) -> Result { - let actor = admin_write(&state, peer, &headers)?; +) -> Result { + 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) } diff --git a/crates/tessera-hub/src/api/access_tests.rs b/crates/tessera-hub/src/api/access_tests.rs index 0b36128..52fd34c 100644 --- a/crates/tessera-hub/src/api/access_tests.rs +++ b/crates/tessera-hub/src/api/access_tests.rs @@ -403,6 +403,9 @@ fn recipe(w: &World, row: &Row) -> (String, Option) { ("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 = 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 = 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 = 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"])); +} diff --git a/crates/tessera-hub/src/api/gate.rs b/crates/tessera-hub/src/api/gate.rs index 4091680..8940dd8 100644 --- a/crates/tessera-hub/src/api/gate.rs +++ b/crates/tessera-hub/src/api/gate.rs @@ -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, diff --git a/crates/tessera-hub/src/api/relations.rs b/crates/tessera-hub/src/api/relations.rs index 5d2ac59..c852483 100644 --- a/crates/tessera-hub/src/api/relations.rs +++ b/crates/tessera-hub/src/api/relations.rs @@ -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" => { diff --git a/crates/tessera-hub/src/api/session.rs b/crates/tessera-hub/src/api/session.rs index 99de2fd..b8f2978 100644 --- a/crates/tessera-hub/src/api/session.rs +++ b/crates/tessera-hub/src/api/session.rs @@ -95,8 +95,7 @@ struct Me { refresh_relations: Vec, } -/// 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, State(state): State, diff --git a/crates/tessera-hub/src/auth.rs b/crates/tessera-hub/src/auth.rs index 11f8d85..1d16aa4 100644 --- a/crates/tessera-hub/src/auth.rs +++ b/crates/tessera-hub/src/auth.rs @@ -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::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. diff --git a/crates/tessera-hub/src/db/access.rs b/crates/tessera-hub/src/db/access.rs index 1645e58..9e886b2 100644 --- a/crates/tessera-hub/src/db/access.rs +++ b/crates/tessera-hub/src/db/access.rs @@ -28,6 +28,16 @@ pub struct NewGrant<'a> { pub created_by: &'a str, } +/// Outcome of [`Db::replace_grants`]. +pub enum Replace { + Done { + removed: Vec, + written: Vec, + }, + /// 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, 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, } 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 { + 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 { Ok(self .conn @@ -209,28 +293,28 @@ impl Db { pub fn list_users(&self) -> Result> { 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::>()?) } - pub fn user_exists(&self, id: &str) -> Result { - 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> { + Ok(self.list_users()?.into_iter().find(|u| u.id == id)) } /// Enable or disable a user. Disabling also ends every session at once. diff --git a/crates/tessera-hub/src/db/relations.rs b/crates/tessera-hub/src/db/relations.rs index 684cf8e..ea905a2 100644 --- a/crates/tessera-hub/src/db/relations.rs +++ b/crates/tessera-hub/src/db/relations.rs @@ -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, + 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> { + 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::>()?) + } + pub fn relation_grants(&self, relation: &str) -> Result> { 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")?; diff --git a/crates/tessera-hub/src/db/sessions.rs b/crates/tessera-hub/src/db/sessions.rs index 09c3c81..ebccbe7 100644 --- a/crates/tessera-hub/src/db/sessions.rs +++ b/crates/tessera-hub/src/db/sessions.rs @@ -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) } diff --git a/docs/auth-endpoint-contract.md b/docs/auth-endpoint-contract.md index 311a44b..77b1f51 100644 --- a/docs/auth-endpoint-contract.md +++ b/docs/auth-endpoint-contract.md @@ -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 | diff --git a/web/scripts/access.test.mjs b/web/scripts/access.test.mjs new file mode 100644 index 0000000..717db74 --- /dev/null +++ b/web/scripts/access.test.mjs @@ -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"); +}); diff --git a/web/src/api.ts b/web/src/api.ts index 4374a05..d09179a 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -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("/api/v1/access/grants"); export const fetchAccessUsers = () => api("/api/v1/access/users"); export const createGrant = (grant: NewGrant) => api("/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("/api/v1/access/grants", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(grant) }); export const deleteGrant = (id: string) => api(`/api/v1/access/grants/${id}`, { method: "DELETE" }); export const setUserActive = (id: string, active: boolean) => api(`/api/v1/access/users/${id}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ active }) }); diff --git a/web/src/components/access/AccessView.tsx b/web/src/components/access/AccessView.tsx index 82871eb..d3959d1 100644 --- a/web/src/components/access/AccessView.tsx +++ b/web/src/components/access/AccessView.tsx @@ -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 ( + + ); } -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 ( + + ); +} + +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 {children}; } /** 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) { - 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(null); + const [editing, setEditing] = useState(); + 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 ( -
-
-

Give access

-

- 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. -

-
- - {kind === "user" ? ( - - ) : ( - - )} - - - -
- -
-
- {add.isError &&

Could not grant access. Check the person, the orbit and the end date; an identical grant may already exist.

} -
+
+ { refresh(); void qc.invalidateQueries({ queryKey: ["relations"] }); if (editing) stopEdit(); }} + onCancelEdit={stopEdit} userName={userName} + />
-

Current access

+
+

Current access

+

One row per person or group, orbit and end date. Refresh grants are listed here too.

+
{grants.isPending ?

Loading…

: grants.isError || !grantList ?

Could not load grants. This hub may not support access management.

- : grantList.grants.length === 0 ?

Nobody has been granted access yet.

- : ( -
- - - - - - {grantList.grants.map((g: Grant) => ( - - - - - - - - ))} - -
WhoPermissionOrbitEnds
{g.principal_type === "group" ? `Group ${g.principal}` : userName(g.principal)}{g.permission}{orbitName(g.scope_id)}{when(g.expires_at)} - -
+ : lines.length === 0 ? ( +
+

Nobody has been granted access yet

+

Administrators from SSO already see everything. Use the form above to let someone else in.

+ ) : ( + <> +
+ setFilter("all")}>All · {lines.length} + setFilter("attention")}>Needs attention · {count((l) => l.attention)} + setFilter("refresh")}>Refresh · {count((l) => l.refresh)} + setFilter("soon")}>Ending soon · {count((l) => l.soon)} +
+
+ + + + + {shown.map((line) => line.orbit + ? startEdit(line.orbit as AccessRow, renew)} + onFix={() => fix.mutate(line.orbit as AccessRow)} onRemove={() => remove.mutate((line.orbit as AccessRow).ids)} /> + : line.relation && removeRefresh.mutate({ relation: line.relation!.relation_id, id: line.relation!.id })} />)} + {shown.length === 0 && } + +
WhoCan doOrbitEnds +
Nothing matches this filter.
+
+ )} + {(remove.isError || removeRefresh.isError || fix.isError) &&

That change was not saved. Reload the list and try again.

}
-

People who have signed in

- {pendingUsers.length > 0 && ( -

- Signed in but not granted anything yet: {pendingUsers.map((u) => u.display_name).join(", ")}. Administrators from the SSO settings are not shown as waiting. -

- )} +
+

People who have signed in

+

Access is what each person can do right now, from every grant and group.

+
{userList && ( -
- - +
+
NameLast sign-inStatus
+ + - {userList.map((u) => ( - - - - - - - ))} + {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 ( + + + + + + + + ); + })}
NameLast sign-inAccessStatus +
{u.display_name}{u.is_emergency ? " (emergency operator)" : ""}{when(u.last_login_at)}{u.active ? "Active" : "Disabled"} - {!u.is_emergency && ( - <> - - - - )} -
{u.is_emergency ? "Emergency operator" : u.display_name}{self && You}{when(u.last_login_at)} + {u.is_emergency ? <>Administrator emergency password + : access?.kind === "admin" ? <>Administrator from SSO settings + : access?.kind === "waiting" ? <>Waiting No access yet. + : access && ( + + {access.label && {access.label}} + {access.via.length > 0 && <> via group {access.via.join(", ")}} + {access.refresh.length > 0 && <>{access.label ? " · " : ""}Refresh {access.refresh.join(", ")}} + {access.noEffect && ⚠ Cannot see any orbit yet: “See the orbit” is missing.} + + )} + {u.active ? "Active" : "Disabled"} + {!u.is_emergency && ( + <> + + {!self && } + + )} +
)} - {(toggle.isError || signOut.isError) &&

That change was refused. You cannot disable yourself or the emergency operator.

} + {failed &&

{reasonText(refusalReason(failed), "That change was refused.")}

}
); } + +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 ( + + + {who} + {row.principal_type === "group" ? `group${members ? ` · ${members} ${members === 1 ? "person" : "people"}` : ""}` : "person"} + + + {role} + {row.permissions.map(shortName).join(" · ")} + {noEffect && ⚠ Has no effect: this person cannot see the orbit. Add “See the orbit”.} + + {orbit} + + {expired ? Expired {day(row.expires_at!)} + : row.expires_at ? {day(row.expires_at)}{state === "soon" ? " · ending soon" : ""} + : No end} + + + {noEffect && } + {expired ? : } + + + + ); +} + +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 ( + + + {who} + {grant.principal_type === "group" ? "group" : "person"} + + + Refresh + {grant.source_name} → {grant.target_name} · v{grant.version} + {!grant.active && ⚠ This relation has ended, so the grant does nothing. Allow them again on its new version.} + + per relation + + {expired ? Expired {day(grant.expires_at!)} + : grant.expires_at ? {day(grant.expires_at)}{state === "soon" ? " · ending soon" : ""} + : No end} + + + + ); +} + +function GiveAccess({ sectionRef, orbits, users, roles, relations, groupsSeen, adminOnly, editing, prefill, onDone, onCancelEdit, userName }: { + sectionRef: React.RefObject; 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(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>(new Set(prefill?.perms ?? ["orbit.read", "snapshot.read"])); + const [rels, setRels] = useState>(new Set()); + const [adminOpen, setAdminOpen] = useState(false); + const [report, setReport] = useState(); + + const candidates = users.filter((u) => !u.is_emergency && !u.admin && u.active); + const roleOf = (set: Set) => 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 => { + 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 ( +
+

{editing ? `Edit access: ${editing.principal_type === "group" ? editing.principal : userName(editing.principal)}` : "Give access"}

+

+ 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. +

+
{ e.preventDefault(); if (ready) submit.mutate(); }}> +
+
+

1 · Who

+ {editing ?

{editing.principal_type === "group" ? `Group ${editing.principal}` : userName(editing.principal)}

: ( + <> +
+ {(["user", "group"] as const).map((k) => ( + + ))} +
+ {kind === "user" ? ( + + ) : ( +
+ + {groupsSeen.length > 0 && ( + <> +

Seen at recent sign-ins. Names must match the token's groups claim exactly.

+
+ {groupsSeen.slice(0, 8).map((g) => ( + + ))} +
+ + )} +
+ )} + + )} +
+ +
+

2 · Where

+
+ +
+ {rels.size > 0 &&

Refresh is granted per relation, not per orbit. This choice applies to the other ticked rows only.

} +
+ +
+

3 · Until

+
+ setExpires("")}>No end + setExpires(inDays(30))}>30 days + setExpires(inDays(90))}>90 days +
+
setExpires(v)} />
+

Grants can run for at most two years.

+
+
+ +
+
+

4 · What they may do

+
+ Start from + {roles.map((r) => preset(r.name)}>{r.name.charAt(0).toUpperCase() + r.name.slice(1)})} + { setPerms(new Set()); setRels(new Set()); }}>Clear +
+
+ +
+ {TREE.map((group) => { + const ids = group.items.map((i) => i.id); + const state = branchState(perms, ids); + return ( +
+
+ setPerms(setMany(perms, ids, state !== "all"))} /> +

{group.label}

{group.note}

+
+ {group.items.map((item) => { + const lockedBy = neededBy(perms, item.id); + const on = perms.has(item.id); + return ( +
+ 0} onChange={() => setPerms(setPermission(perms, item.id, !on))} /> +
+
+ {item.label} + {item.id} +
+ {on && lockedBy.length > 0 ?

Needed by {lockedBy.map(shortName).join(", ")}.

+ : item.hint ?

{item.hint}

: null} +
+
+ ); + })} +
+ ); + })} + +
+
+ setRels(new Set(refreshState === "all" ? [] : refreshBranch))} /> +

Refresh staging

Per relation, not per orbit. Does not need the orbit to be visible.

+
+ {relations.length === 0 &&

No active relations yet. Create one in Relations first.

} + {relations.map((r) => ( +
+ setRels((cur) => { const next = new Set(cur); if (next.has(r.id)) next.delete(r.id); else next.add(r.id); return next; })} /> +
+
+ {r.source_name} → {r.target_name} + refresh.run +
+

Version {r.version}{r.usable ? " · ready" : " · not usable right now"}

+
+
+ ))} +
+
+ +
+ + {adminOpen && ( +
+ {adminOnly.map((p) => {ADMIN_LABELS[p] ?? p} {p})} +
+ )} +
+ +
+
+

+ {count === 0 ? "Nothing ticked yet" : `${editing ? "Will set" : "Will create"} ${count} grant${count > 1 ? "s" : ""}${perms.size ? ` · ${roleOf(perms)}` : ""}`} +

+

{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"}`}

+
+
+ {editing && } + +
+
+
+
+ + {report && report.failures.length === 0 && (report.added > 0 || report.skipped > 0) && ( +

+ {report.added > 0 ? `${report.added} added` : "Nothing new added"}{report.skipped > 0 ? `, ${report.skipped} ${report.skipped === 1 ? "was" : "were"} already there` : ""}. +

+ )} + {report && report.failures.length > 0 && ( +
+ {report.added > 0 &&

{report.added} added.

} + {report.failures.map((f) =>

{f}

)} +
+ )} +
+ ); +} diff --git a/web/src/components/relations/RelationsView.tsx b/web/src/components/relations/RelationsView.tsx index 60cbd58..be972c5 100644 --- a/web/src/components/relations/RelationsView.tsx +++ b/web/src/components/relations/RelationsView.tsx @@ -256,7 +256,14 @@ function RelationAccess({ relationId, onChange }: { relationId: string; onChange
    {list.map((g) => (
  • - {g.principal_type === "group" ? `Group ${g.principal}` : nameOf(g.principal)} + + {g.principal_type === "group" ? `Group ${g.principal}` : nameOf(g.principal)} + {g.expires_at && ( + + {g.expires_at * 1000 <= Date.now() ? "expired " : "until "}{new Date(g.expires_at * 1000).toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" })} + + )} +
  • ))} diff --git a/web/src/lib/access.ts b/web/src/lib/access.ts new file mode 100644 index 0000000..62207ce --- /dev/null +++ b/web/src/lib/access.ts @@ -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 = { + "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 = { + "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, id: string, on: boolean): Set { + 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, id: string): string[] { + return [...current].filter((other) => (REQUIRES[other] ?? []).includes(id)); +} + +/** Tick or untick a whole branch. */ +export function setMany(current: ReadonlySet, ids: string[], on: boolean): Set { + 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, 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, b: ReadonlySet) => 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, 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(); + 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(); + 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 = { + 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; +}