feat: access console with a permission tree, grouped grants and effective access
Some checks failed
ci / rust (push) Has been cancelled
ci / supply-chain (push) Has been cancelled
ci / web (push) Has been cancelled

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:
2026-11-15 20:20:25 +07:00
parent 3bd0a1c9a3
commit c938afe1b5
15 changed files with 1412 additions and 223 deletions

View File

@@ -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)
}

View File

@@ -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"]));
}

View File

@@ -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,

View File

@@ -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" => {

View File

@@ -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>,