feat: access console with a permission tree, grouped grants and effective access
Backend: grants accept a list of permissions; PUT /access/grants edits or renews a set atomically; refusals carry a reason; the grant list includes refresh grants per relation and the administrator-only permissions; users keep their last groups and admin flag; the emergency operator cannot hold grants. Frontend: the Access screen shows the grantable permissions as a checkbox tree with dependencies, rows grouped by person or group, orbit and end date, expiry and no-effect states, and what each person can do right now. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,9 @@
|
||||
//! Administration of access: who holds which permission on which orbit.
|
||||
//! Administrators only (`access.manage` is never delegated). Every change is
|
||||
//! audited by id and effective on the very next request of the affected user.
|
||||
// Refusals are whole responses (`{"reason"}`); they are built once per request, not carried around.
|
||||
#![allow(clippy::result_large_err)]
|
||||
|
||||
use super::routes::{admin_read, admin_write};
|
||||
use crate::auth::{role, AuditAction, AuditOutcome, AuditResource, Permission, ROLE_NAMES};
|
||||
use crate::db::access::NewGrant;
|
||||
@@ -8,6 +11,7 @@ use crate::state::HubState;
|
||||
use axum::{
|
||||
extract::{ConnectInfo, Path, State},
|
||||
http::{header, HeaderMap, HeaderValue, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
routing::{get, post, put},
|
||||
Json, Router,
|
||||
};
|
||||
@@ -17,7 +21,7 @@ use uuid::Uuid;
|
||||
|
||||
pub(super) fn routes() -> Router<HubState> {
|
||||
Router::new()
|
||||
.route("/api/v1/access/grants", get(list).post(create))
|
||||
.route("/api/v1/access/grants", get(list).post(create).put(replace))
|
||||
.route("/api/v1/access/grants/:id", axum::routing::delete(remove))
|
||||
.route("/api/v1/access/users", get(users))
|
||||
.route("/api/v1/access/users/:id", put(set_user))
|
||||
@@ -51,9 +55,26 @@ struct RoleInfo {
|
||||
#[derive(Serialize)]
|
||||
struct GrantList {
|
||||
grants: Vec<crate::db::access::Grant>,
|
||||
/// Refresh grants, one per relation: the `refresh.run` permission is never in `grants`.
|
||||
relation_grants: Vec<crate::db::relations::RelationGrantRow>,
|
||||
roles: Vec<RoleInfo>,
|
||||
/// Permissions that can be granted; all others belong to administrators.
|
||||
grantable: Vec<&'static str>,
|
||||
/// Permissions only administrators hold, for the screen to show as locked.
|
||||
admin_only: Vec<&'static str>,
|
||||
}
|
||||
|
||||
fn names(keep: impl Fn(Permission) -> bool) -> Vec<&'static str> {
|
||||
Permission::ALL
|
||||
.into_iter()
|
||||
.filter(|p| keep(*p))
|
||||
.map(Permission::as_str)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A refusal that says which rule applied (`{"reason": "..."}`), so the screen can say it too.
|
||||
fn refuse(status: StatusCode, reason: &'static str) -> Response {
|
||||
(status, Json(serde_json::json!({ "reason": reason }))).into_response()
|
||||
}
|
||||
|
||||
async fn list(
|
||||
@@ -77,16 +98,10 @@ async fn list(
|
||||
no_store(),
|
||||
Json(GrantList {
|
||||
grants: state.db.list_grants().map_err(internal)?,
|
||||
relation_grants: state.db.list_relation_grants().map_err(internal)?,
|
||||
roles,
|
||||
grantable: [
|
||||
Permission::OrbitRead,
|
||||
Permission::SnapshotRead,
|
||||
Permission::CaptureRun,
|
||||
Permission::SnapshotDownload,
|
||||
]
|
||||
.iter()
|
||||
.map(|p| p.as_str())
|
||||
.collect(),
|
||||
grantable: names(Permission::grantable),
|
||||
admin_only: names(Permission::admin_only),
|
||||
}),
|
||||
))
|
||||
}
|
||||
@@ -97,35 +112,64 @@ struct CreateGrant {
|
||||
/// `user` (a `users.id`) or `group` (an IdP group name).
|
||||
principal_type: String,
|
||||
principal: String,
|
||||
/// Exactly one of `role` and `permission`.
|
||||
/// Exactly one of `role`, `permission` and `permissions`.
|
||||
role: Option<String>,
|
||||
permission: Option<String>,
|
||||
permissions: Option<Vec<String>>,
|
||||
/// Absent = every orbit.
|
||||
orbit_id: Option<Uuid>,
|
||||
/// RFC 3339; absent = no expiry.
|
||||
expires_at: Option<String>,
|
||||
/// Only for `PUT`: grants of the same person or group and orbit that this request replaces.
|
||||
#[serde(default)]
|
||||
replaces: Vec<Uuid>,
|
||||
}
|
||||
|
||||
async fn create(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Json(body): Json<CreateGrant>,
|
||||
) -> Result<(StatusCode, HeaderMap, Json<Vec<crate::db::access::Grant>>), StatusCode> {
|
||||
let actor = admin_write(&state, peer, &headers)?;
|
||||
let now = now();
|
||||
let permissions: Vec<Permission> = match (&body.role, &body.permission) {
|
||||
(Some(name), None) => role(name).ok_or(StatusCode::BAD_REQUEST)?.to_vec(),
|
||||
(None, Some(name)) => vec![Permission::parse(name)
|
||||
/// A request that passed every rule: what to write, and for whom.
|
||||
struct Valid {
|
||||
permissions: Vec<Permission>,
|
||||
orbit: Option<String>,
|
||||
expires_at: Option<i64>,
|
||||
}
|
||||
|
||||
fn validate(state: &HubState, body: &CreateGrant, now: i64) -> Result<Valid, Response> {
|
||||
let bad = |reason| refuse(StatusCode::BAD_REQUEST, reason);
|
||||
let unprocessable = |reason| refuse(StatusCode::UNPROCESSABLE_ENTITY, reason);
|
||||
let mut permissions: Vec<Permission> = match (&body.role, &body.permission, &body.permissions) {
|
||||
(Some(name), None, None) => role(name).ok_or(bad("unknown_role"))?.to_vec(),
|
||||
(None, Some(name), None) => vec![Permission::parse(name)
|
||||
.filter(|p| p.grantable())
|
||||
.ok_or(StatusCode::BAD_REQUEST)?],
|
||||
_ => return Err(StatusCode::BAD_REQUEST),
|
||||
.ok_or(bad("unknown_permission"))?],
|
||||
(None, None, Some(names)) => names
|
||||
.iter()
|
||||
.map(|name| {
|
||||
Permission::parse(name)
|
||||
.filter(|p| p.grantable())
|
||||
.ok_or(bad("unknown_permission"))
|
||||
})
|
||||
.collect::<Result<_, _>>()?,
|
||||
_ => return Err(bad("choose_one")),
|
||||
};
|
||||
permissions.dedup();
|
||||
let mut seen = Vec::new();
|
||||
permissions.retain(|p| {
|
||||
let new = !seen.contains(p);
|
||||
seen.push(*p);
|
||||
new
|
||||
});
|
||||
if permissions.is_empty() {
|
||||
return Err(bad("nothing_selected"));
|
||||
}
|
||||
match body.principal_type.as_str() {
|
||||
"user" => {
|
||||
Uuid::parse_str(&body.principal).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
if !state.db.user_exists(&body.principal).map_err(internal)? {
|
||||
return Err(StatusCode::UNPROCESSABLE_ENTITY);
|
||||
Uuid::parse_str(&body.principal).map_err(|_| bad("bad_person"))?;
|
||||
let user = state
|
||||
.db
|
||||
.user_row(&body.principal)
|
||||
.map_err(|e| internal(e).into_response())?
|
||||
.ok_or(unprocessable("unknown_user"))?;
|
||||
if user.is_emergency {
|
||||
return Err(unprocessable("emergency_operator"));
|
||||
}
|
||||
}
|
||||
"group" => {
|
||||
@@ -133,18 +177,18 @@ async fn create(
|
||||
|| body.principal.len() > 128
|
||||
|| body.principal.chars().any(char::is_control)
|
||||
{
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
return Err(bad("bad_group"));
|
||||
}
|
||||
}
|
||||
_ => return Err(StatusCode::BAD_REQUEST),
|
||||
_ => return Err(bad("bad_principal_type")),
|
||||
}
|
||||
if let Some(orbit) = body.orbit_id {
|
||||
if !state
|
||||
.db
|
||||
.orbit_exists(&orbit.to_string())
|
||||
.map_err(internal)?
|
||||
.map_err(|e| internal(e).into_response())?
|
||||
{
|
||||
return Err(StatusCode::UNPROCESSABLE_ENTITY);
|
||||
return Err(unprocessable("unknown_orbit"));
|
||||
}
|
||||
}
|
||||
let expires_at = body
|
||||
@@ -153,26 +197,48 @@ async fn create(
|
||||
.map(|text| {
|
||||
chrono::DateTime::parse_from_rfc3339(text)
|
||||
.map(|t| t.timestamp())
|
||||
.map_err(|_| StatusCode::BAD_REQUEST)
|
||||
.map_err(|_| bad("bad_end_date"))
|
||||
})
|
||||
.transpose()?;
|
||||
if expires_at.is_some_and(|end| end <= now || end > now + 2 * 366 * 86_400) {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
return Err(bad("bad_end_date"));
|
||||
}
|
||||
let orbit = body.orbit_id.map(|id| id.to_string());
|
||||
Ok(Valid {
|
||||
permissions,
|
||||
orbit: body.orbit_id.map(|id| id.to_string()),
|
||||
expires_at,
|
||||
})
|
||||
}
|
||||
|
||||
async fn create(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Json(body): Json<CreateGrant>,
|
||||
) -> Result<(StatusCode, HeaderMap, Json<Vec<crate::db::access::Grant>>), Response> {
|
||||
let actor = admin_write(&state, peer, &headers).map_err(IntoResponse::into_response)?;
|
||||
let now = now();
|
||||
if !body.replaces.is_empty() {
|
||||
return Err(refuse(StatusCode::BAD_REQUEST, "replaces_needs_put"));
|
||||
}
|
||||
let valid = validate(&state, &body, now)?;
|
||||
let created_by = actor.id();
|
||||
let mut created = Vec::new();
|
||||
for permission in permissions {
|
||||
for permission in valid.permissions {
|
||||
let grant = NewGrant {
|
||||
principal_type: &body.principal_type,
|
||||
principal: &body.principal,
|
||||
permission: permission.as_str(),
|
||||
orbit: orbit.as_deref(),
|
||||
expires_at,
|
||||
orbit: valid.orbit.as_deref(),
|
||||
expires_at: valid.expires_at,
|
||||
created_by: &created_by,
|
||||
};
|
||||
if let Some(grant) = state.db.add_grant(&grant, now).map_err(internal)? {
|
||||
let id = Uuid::parse_str(&grant.id).map_err(internal)?;
|
||||
if let Some(grant) = state
|
||||
.db
|
||||
.add_grant(&grant, now)
|
||||
.map_err(|e| internal(e).into_response())?
|
||||
{
|
||||
let id = Uuid::parse_str(&grant.id).map_err(|e| internal(e).into_response())?;
|
||||
state
|
||||
.db
|
||||
.audit_event(
|
||||
@@ -182,16 +248,68 @@ async fn create(
|
||||
AuditOutcome::Succeeded,
|
||||
actor.request_id,
|
||||
)
|
||||
.map_err(internal)?;
|
||||
.map_err(|e| internal(e).into_response())?;
|
||||
created.push(grant);
|
||||
}
|
||||
}
|
||||
if created.is_empty() {
|
||||
return Err(StatusCode::CONFLICT);
|
||||
return Err(refuse(StatusCode::CONFLICT, "already_granted"));
|
||||
}
|
||||
Ok((StatusCode::CREATED, no_store(), Json(created)))
|
||||
}
|
||||
|
||||
/// Edit or renew: replace some grants of one person or group and orbit with a new set and end date,
|
||||
/// all or nothing. Anything that was already granted keeps working through the change.
|
||||
async fn replace(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Json(body): Json<CreateGrant>,
|
||||
) -> Result<(HeaderMap, Json<Vec<crate::db::access::Grant>>), Response> {
|
||||
let actor = admin_write(&state, peer, &headers).map_err(IntoResponse::into_response)?;
|
||||
let now = now();
|
||||
let valid = validate(&state, &body, now)?;
|
||||
let created_by = actor.id();
|
||||
let new: Vec<NewGrant> = valid
|
||||
.permissions
|
||||
.iter()
|
||||
.map(|permission| NewGrant {
|
||||
principal_type: &body.principal_type,
|
||||
principal: &body.principal,
|
||||
permission: permission.as_str(),
|
||||
orbit: valid.orbit.as_deref(),
|
||||
expires_at: valid.expires_at,
|
||||
created_by: &created_by,
|
||||
})
|
||||
.collect();
|
||||
let replaces: Vec<String> = body.replaces.iter().map(Uuid::to_string).collect();
|
||||
let outcome = state
|
||||
.db
|
||||
.replace_grants(&replaces, &new, now)
|
||||
.map_err(|e| internal(e).into_response())?;
|
||||
let crate::db::access::Replace::Done { removed, written } = outcome else {
|
||||
return Err(refuse(StatusCode::UNPROCESSABLE_ENTITY, "grant_mismatch"));
|
||||
};
|
||||
for (id, action) in removed
|
||||
.iter()
|
||||
.map(|id| (id, AuditAction::GrantDelete))
|
||||
.chain(written.iter().map(|g| (&g.id, AuditAction::GrantCreate)))
|
||||
{
|
||||
let id = Uuid::parse_str(id).map_err(|e| internal(e).into_response())?;
|
||||
state
|
||||
.db
|
||||
.audit_event(
|
||||
&actor.principal,
|
||||
action,
|
||||
AuditResource::Grant(id),
|
||||
AuditOutcome::Succeeded,
|
||||
actor.request_id,
|
||||
)
|
||||
.map_err(|e| internal(e).into_response())?;
|
||||
}
|
||||
Ok((no_store(), Json(written)))
|
||||
}
|
||||
|
||||
async fn remove(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
@@ -241,16 +359,17 @@ fn target_user(
|
||||
state: &HubState,
|
||||
actor: &super::routes::OperatorActor,
|
||||
id: Uuid,
|
||||
) -> Result<crate::db::access::UserRow, StatusCode> {
|
||||
) -> Result<crate::db::access::UserRow, Response> {
|
||||
let user = state
|
||||
.db
|
||||
.list_users()
|
||||
.map_err(internal)?
|
||||
.into_iter()
|
||||
.find(|u| u.id == id.to_string())
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
if actor.subject.user_id.as_deref() == Some(user.id.as_str()) || user.is_emergency {
|
||||
return Err(StatusCode::CONFLICT);
|
||||
.user_row(&id.to_string())
|
||||
.map_err(|e| internal(e).into_response())?
|
||||
.ok_or(StatusCode::NOT_FOUND.into_response())?;
|
||||
if actor.subject.user_id.as_deref() == Some(user.id.as_str()) {
|
||||
return Err(refuse(StatusCode::CONFLICT, "cannot_disable_self"));
|
||||
}
|
||||
if user.is_emergency {
|
||||
return Err(refuse(StatusCode::CONFLICT, "cannot_disable_emergency"));
|
||||
}
|
||||
Ok(user)
|
||||
}
|
||||
@@ -261,13 +380,13 @@ async fn set_user(
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(body): Json<UserState>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
let actor = admin_write(&state, peer, &headers)?;
|
||||
) -> Result<StatusCode, Response> {
|
||||
let actor = admin_write(&state, peer, &headers).map_err(IntoResponse::into_response)?;
|
||||
let user = target_user(&state, &actor, id)?;
|
||||
state
|
||||
.db
|
||||
.set_user_active(&user.id, body.active)
|
||||
.map_err(internal)?;
|
||||
.map_err(|e| internal(e).into_response())?;
|
||||
state
|
||||
.db
|
||||
.audit_event(
|
||||
@@ -277,7 +396,7 @@ async fn set_user(
|
||||
AuditOutcome::Succeeded,
|
||||
actor.request_id,
|
||||
)
|
||||
.map_err(internal)?;
|
||||
.map_err(|e| internal(e).into_response())?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
|
||||
@@ -403,6 +403,9 @@ fn recipe(w: &World, row: &Row) -> (String, Option<Value>) {
|
||||
("POST", "/api/v1/access/grants") => {
|
||||
Some(json!({"principal_type": "group", "principal": "matrix-group", "role": "viewer"}))
|
||||
}
|
||||
("PUT", "/api/v1/access/grants") => Some(
|
||||
json!({"principal_type": "group", "principal": "matrix-group", "permissions": ["orbit.read"]}),
|
||||
),
|
||||
("PUT", "/api/v1/access/users/:id") => Some(json!({"active": true})),
|
||||
("PUT", "/api/v1/orbits/:id/environment")
|
||||
| ("PUT", "/api/v1/restore-targets/:id/environment") => {
|
||||
@@ -1722,3 +1725,193 @@ async fn revoking_an_outpost_or_deleting_a_relation_takes_refreshers_off_immedia
|
||||
.unwrap();
|
||||
assert_eq!(b["active"], true);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_set_of_permissions_can_be_granted_edited_and_renewed_all_or_nothing() {
|
||||
let w = world().await;
|
||||
let admin = w.caller("admin", true, &[]);
|
||||
let target = w.caller("target", false, &["qa"]);
|
||||
let uid = target.user_id.clone().unwrap();
|
||||
let grants = "/api/v1/access/grants";
|
||||
let orbit = w.a.orbit;
|
||||
let end = |days: i64| (chrono::Utc::now() + chrono::Duration::days(days)).to_rfc3339();
|
||||
|
||||
// a list of single permissions, in one request; refusals say which rule applied
|
||||
let (status, created) = w
|
||||
.send(&admin, "POST", grants, Some(json!({"principal_type": "user", "principal": uid, "permissions": ["orbit.read", "snapshot.read", "capture.run"], "orbit_id": orbit})))
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::CREATED);
|
||||
assert_eq!(created.as_array().unwrap().len(), 3);
|
||||
let (status, body) = w
|
||||
.send(&admin, "POST", grants, Some(json!({"principal_type": "user", "principal": uid, "permissions": ["orbit.read"], "orbit_id": orbit})))
|
||||
.await;
|
||||
assert_eq!(
|
||||
(status, body["reason"].as_str()),
|
||||
(StatusCode::CONFLICT, Some("already_granted"))
|
||||
);
|
||||
for (what, body, reason) in [
|
||||
(
|
||||
"empty list",
|
||||
json!({"principal_type": "group", "principal": "g", "permissions": []}),
|
||||
"nothing_selected",
|
||||
),
|
||||
(
|
||||
"admin-only permission",
|
||||
json!({"principal_type": "group", "principal": "g", "permissions": ["orbit.manage"]}),
|
||||
"unknown_permission",
|
||||
),
|
||||
(
|
||||
"refresh is per relation",
|
||||
json!({"principal_type": "group", "principal": "g", "permissions": ["refresh.run"]}),
|
||||
"unknown_permission",
|
||||
),
|
||||
(
|
||||
"two ways at once",
|
||||
json!({"principal_type": "group", "principal": "g", "role": "viewer", "permissions": ["orbit.read"]}),
|
||||
"choose_one",
|
||||
),
|
||||
(
|
||||
"replaces belongs to PUT",
|
||||
json!({"principal_type": "group", "principal": "g", "role": "viewer", "replaces": [Uuid::new_v4()]}),
|
||||
"replaces_needs_put",
|
||||
),
|
||||
(
|
||||
"bad end date",
|
||||
json!({"principal_type": "group", "principal": "g", "role": "viewer", "expires_at": "2020-01-01T00:00:00Z"}),
|
||||
"bad_end_date",
|
||||
),
|
||||
(
|
||||
"unknown orbit",
|
||||
json!({"principal_type": "group", "principal": "g", "role": "viewer", "orbit_id": Uuid::new_v4()}),
|
||||
"unknown_orbit",
|
||||
),
|
||||
] {
|
||||
let (status, body) = w.send(&admin, "POST", grants, Some(body)).await;
|
||||
assert!(status.is_client_error(), "{what}");
|
||||
assert_eq!(body["reason"], reason, "{what}");
|
||||
}
|
||||
|
||||
// the emergency operator is an administrator and never holds grants
|
||||
let emergency = w
|
||||
.state
|
||||
.db
|
||||
.list_users()
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.find(|u| u.is_emergency);
|
||||
if let Some(emergency) = emergency {
|
||||
let (status, body) = w
|
||||
.send(
|
||||
&admin,
|
||||
"POST",
|
||||
grants,
|
||||
Some(
|
||||
json!({"principal_type": "user", "principal": emergency.id, "role": "viewer"}),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
(status, body["reason"].as_str()),
|
||||
(StatusCode::UNPROCESSABLE_ENTITY, Some("emergency_operator"))
|
||||
);
|
||||
}
|
||||
|
||||
// renew: the same set with a new end date replaces the old rows; nothing is ever missing in between
|
||||
let ids: Vec<Value> = created
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|g| g["id"].clone())
|
||||
.collect();
|
||||
let (status, renewed) = w
|
||||
.send(&admin, "PUT", grants, Some(json!({"principal_type": "user", "principal": uid, "permissions": ["orbit.read", "snapshot.read", "capture.run"], "orbit_id": orbit, "expires_at": end(30), "replaces": ids})))
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(renewed.as_array().unwrap().len(), 3);
|
||||
let stored = w.state.db.list_grants().unwrap();
|
||||
let mine: Vec<_> = stored.iter().filter(|g| g.principal == uid).collect();
|
||||
assert_eq!(mine.len(), 3, "renewing does not duplicate");
|
||||
assert!(mine.iter().all(|g| g.expires_at.is_some()));
|
||||
|
||||
// edit: dropping a permission removes just that one
|
||||
let ids: Vec<Value> = mine.iter().map(|g| json!(g.id)).collect();
|
||||
let (status, _) = w
|
||||
.send(&admin, "PUT", grants, Some(json!({"principal_type": "user", "principal": uid, "permissions": ["orbit.read", "snapshot.read"], "orbit_id": orbit, "replaces": ids})))
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
let after: Vec<String> = w
|
||||
.state
|
||||
.db
|
||||
.list_grants()
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.filter(|g| g.principal == uid)
|
||||
.map(|g| g.permission)
|
||||
.collect();
|
||||
assert_eq!(after.len(), 2);
|
||||
assert!(!after.contains(&"capture.run".to_string()));
|
||||
|
||||
// a grant of someone else cannot be swept into the replacement, and nothing changes when it is refused
|
||||
let other = w
|
||||
.state
|
||||
.db
|
||||
.add_grant(
|
||||
&NewGrant {
|
||||
principal_type: "group",
|
||||
principal: "elsewhere",
|
||||
permission: "orbit.read",
|
||||
orbit: None,
|
||||
expires_at: None,
|
||||
created_by: "test",
|
||||
},
|
||||
now(),
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let before = w.state.db.list_grants().unwrap().len();
|
||||
let (status, body) = w
|
||||
.send(&admin, "PUT", grants, Some(json!({"principal_type": "user", "principal": uid, "permissions": ["orbit.read"], "orbit_id": orbit, "replaces": [other.id]})))
|
||||
.await;
|
||||
assert_eq!(
|
||||
(status, body["reason"].as_str()),
|
||||
(StatusCode::UNPROCESSABLE_ENTITY, Some("grant_mismatch"))
|
||||
);
|
||||
assert_eq!(w.state.db.list_grants().unwrap().len(), before);
|
||||
|
||||
// the listing carries refresh grants and the administrator-only permissions
|
||||
let (status, listing) = w.send(&admin, "GET", grants, None).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert!(listing["relation_grants"].is_array());
|
||||
let admin_only: Vec<&str> = listing["admin_only"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.collect();
|
||||
assert!(
|
||||
admin_only.contains(&"access.manage")
|
||||
&& !admin_only.contains(&"refresh.run")
|
||||
&& !admin_only.contains(&"orbit.read")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_user_list_keeps_what_the_identity_provider_said_at_the_last_sign_in() {
|
||||
let w = world().await;
|
||||
let admin = w.caller("admin", true, &[]);
|
||||
let _qa = w.caller("qa-person", false, &["qa", "developer"]);
|
||||
let (status, users) = w.send(&admin, "GET", "/api/v1/access/users", None).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
let find = |name: &str| {
|
||||
users
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|u| u["display_name"] == name)
|
||||
.cloned()
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(find("admin")["admin"], true);
|
||||
assert_eq!(find("qa-person")["admin"], false);
|
||||
assert_eq!(find("qa-person")["groups"], json!(["qa", "developer"]));
|
||||
}
|
||||
|
||||
@@ -100,7 +100,6 @@ pub(super) fn scoped(
|
||||
/// Use one relation. Administrators always; anyone else only through a live grant on that very relation
|
||||
/// (not on its orbit, not on an older version of it). Everything else answers 404, so a relation's
|
||||
/// existence is not confirmed to someone who cannot use it.
|
||||
#[allow(dead_code)] // used by the refresh run (M6c); the matrix already exercises the list built on the same grants
|
||||
pub(super) fn relation(
|
||||
state: &HubState,
|
||||
actor: &OperatorActor,
|
||||
|
||||
@@ -496,8 +496,10 @@ async fn grant_access(
|
||||
match body.principal_type.as_str() {
|
||||
"user" => {
|
||||
Uuid::parse_str(&body.principal).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
if !state.db.user_exists(&body.principal).map_err(internal)? {
|
||||
return Err(StatusCode::UNPROCESSABLE_ENTITY);
|
||||
// The emergency operator is an administrator and never holds grants.
|
||||
match state.db.user_row(&body.principal).map_err(internal)? {
|
||||
Some(user) if !user.is_emergency => {}
|
||||
_ => return Err(StatusCode::UNPROCESSABLE_ENTITY),
|
||||
}
|
||||
}
|
||||
"group" => {
|
||||
|
||||
@@ -95,8 +95,7 @@ struct Me {
|
||||
refresh_relations: Vec<String>,
|
||||
}
|
||||
|
||||
/// The caller's own identity. Every authenticated principal is an administrator
|
||||
/// until scoped grants exist (M5), which is what `capabilities` reports.
|
||||
/// The caller's own identity and what it may use: `admin`, its live grants, and the relations it may refresh through.
|
||||
async fn me(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
|
||||
@@ -172,23 +172,31 @@ impl Permission {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every permission, in the order the administration screens list them.
|
||||
pub const ALL: [Permission; 12] = [
|
||||
Self::OrbitRead,
|
||||
Self::SnapshotRead,
|
||||
Self::CaptureRun,
|
||||
Self::SnapshotDownload,
|
||||
Self::OrbitManage,
|
||||
Self::OutpostManage,
|
||||
Self::RetentionManage,
|
||||
Self::SnapshotDelete,
|
||||
Self::RecoveryManage,
|
||||
Self::AccessManage,
|
||||
Self::RelationManage,
|
||||
Self::RefreshRun,
|
||||
];
|
||||
|
||||
pub fn parse(text: &str) -> Option<Self> {
|
||||
[
|
||||
Self::OrbitRead,
|
||||
Self::SnapshotRead,
|
||||
Self::CaptureRun,
|
||||
Self::SnapshotDownload,
|
||||
Self::OrbitManage,
|
||||
Self::OutpostManage,
|
||||
Self::RetentionManage,
|
||||
Self::SnapshotDelete,
|
||||
Self::RecoveryManage,
|
||||
Self::AccessManage,
|
||||
Self::RelationManage,
|
||||
Self::RefreshRun,
|
||||
]
|
||||
.into_iter()
|
||||
.find(|permission| permission.as_str() == text)
|
||||
Self::ALL
|
||||
.into_iter()
|
||||
.find(|permission| permission.as_str() == text)
|
||||
}
|
||||
|
||||
/// Held only by administrators (neither grantable nor the per-relation refresh).
|
||||
pub fn admin_only(self) -> bool {
|
||||
!self.grantable() && self != Self::RefreshRun
|
||||
}
|
||||
|
||||
/// May be given to a non-administrator through a grant.
|
||||
|
||||
@@ -28,6 +28,16 @@ pub struct NewGrant<'a> {
|
||||
pub created_by: &'a str,
|
||||
}
|
||||
|
||||
/// Outcome of [`Db::replace_grants`].
|
||||
pub enum Replace {
|
||||
Done {
|
||||
removed: Vec<String>,
|
||||
written: Vec<Grant>,
|
||||
},
|
||||
/// A grant to replace belongs to someone or somewhere else than the new set.
|
||||
Mismatch,
|
||||
}
|
||||
|
||||
/// Orbits a subject may use for one permission.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct Permitted {
|
||||
@@ -44,6 +54,10 @@ pub struct UserRow {
|
||||
pub created_at: i64,
|
||||
pub last_login_at: Option<i64>,
|
||||
pub is_emergency: bool,
|
||||
/// Administrator at the last sign-in (the SSO admin mapping; the emergency operator always is).
|
||||
pub admin: bool,
|
||||
/// Groups the identity provider reported at the last sign-in.
|
||||
pub groups: Vec<String>,
|
||||
}
|
||||
|
||||
pub(super) fn migrate(conn: &Connection) -> Result<()> {
|
||||
@@ -106,6 +120,76 @@ impl Db {
|
||||
}))
|
||||
}
|
||||
|
||||
/// Edit or renew a set of grants in one transaction: remove `replaces` (each must belong to the same
|
||||
/// principal and scope), then write `grants`, updating the end date of any that already exist.
|
||||
/// Returns the removed ids and the written grants. `Err(None)`-style conflicts are reported as `Replace::Mismatch`.
|
||||
pub fn replace_grants(
|
||||
&self,
|
||||
replaces: &[String],
|
||||
grants: &[NewGrant<'_>],
|
||||
now: i64,
|
||||
) -> Result<Replace> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction()?;
|
||||
let mut removed = Vec::new();
|
||||
for id in replaces {
|
||||
let row: Option<(String, String, String, String)> = tx
|
||||
.query_row(
|
||||
"SELECT principal_type,principal,scope_type,scope_id FROM access_grants WHERE id=?1",
|
||||
params![id],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
|
||||
)
|
||||
.optional()?;
|
||||
let Some((kind, who, scope_type, scope_id)) = row else {
|
||||
continue;
|
||||
};
|
||||
let same = grants.iter().all(|g| {
|
||||
g.principal_type == kind
|
||||
&& g.principal == who
|
||||
&& match g.orbit {
|
||||
Some(orbit) => scope_type == "orbit" && scope_id == orbit,
|
||||
None => scope_type == "global",
|
||||
}
|
||||
});
|
||||
if !same {
|
||||
return Ok(Replace::Mismatch);
|
||||
}
|
||||
tx.execute("DELETE FROM access_grants WHERE id=?1", params![id])?;
|
||||
removed.push(id.clone());
|
||||
}
|
||||
let mut written = Vec::new();
|
||||
for grant in grants {
|
||||
let (scope_type, scope_id) = match grant.orbit {
|
||||
Some(orbit) => ("orbit", orbit),
|
||||
None => ("global", ""),
|
||||
};
|
||||
tx.execute(
|
||||
"INSERT INTO access_grants(id,principal_type,principal,permission,scope_type,scope_id,expires_at,created_by,created_at)
|
||||
VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9)
|
||||
ON CONFLICT(principal_type,principal,permission,scope_type,scope_id) DO UPDATE SET expires_at=excluded.expires_at",
|
||||
params![Uuid::new_v4().to_string(), grant.principal_type, grant.principal, grant.permission, scope_type, scope_id, grant.expires_at, grant.created_by, now],
|
||||
)?;
|
||||
let id: String = tx.query_row(
|
||||
"SELECT id FROM access_grants WHERE principal_type=?1 AND principal=?2 AND permission=?3 AND scope_type=?4 AND scope_id=?5",
|
||||
params![grant.principal_type, grant.principal, grant.permission, scope_type, scope_id],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
written.push(Grant {
|
||||
id,
|
||||
principal_type: grant.principal_type.into(),
|
||||
principal: grant.principal.into(),
|
||||
permission: grant.permission.into(),
|
||||
scope_type: scope_type.into(),
|
||||
scope_id: grant.orbit.map(str::to_string),
|
||||
expires_at: grant.expires_at,
|
||||
created_by: grant.created_by.into(),
|
||||
created_at: now,
|
||||
});
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(Replace::Done { removed, written })
|
||||
}
|
||||
|
||||
pub fn delete_grant(&self, id: &str) -> Result<bool> {
|
||||
Ok(self
|
||||
.conn
|
||||
@@ -209,28 +293,28 @@ impl Db {
|
||||
|
||||
pub fn list_users(&self) -> Result<Vec<UserRow>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare("SELECT id,issuer,display_name,active,created_at,last_login_at FROM users ORDER BY display_name, id")?;
|
||||
let mut stmt = conn.prepare("SELECT id,issuer,display_name,active,created_at,last_login_at,last_groups,last_admin FROM users ORDER BY display_name, id")?;
|
||||
let rows = stmt.query_map([], |r| {
|
||||
let issuer: String = r.get(1)?;
|
||||
let is_emergency = issuer == crate::admin::EMERGENCY_ISSUER;
|
||||
Ok(UserRow {
|
||||
id: r.get(0)?,
|
||||
is_emergency: issuer == crate::admin::EMERGENCY_ISSUER,
|
||||
is_emergency,
|
||||
issuer,
|
||||
display_name: r.get(2)?,
|
||||
active: r.get::<_, i64>(3)? == 1,
|
||||
created_at: r.get(4)?,
|
||||
last_login_at: r.get(5)?,
|
||||
groups: serde_json::from_str(&r.get::<_, String>(6)?).unwrap_or_default(),
|
||||
admin: is_emergency || r.get::<_, i64>(7)? == 1,
|
||||
})
|
||||
})?;
|
||||
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||
}
|
||||
|
||||
pub fn user_exists(&self, id: &str) -> Result<bool> {
|
||||
Ok(self.conn.lock().unwrap().query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM users WHERE id=?1)",
|
||||
params![id],
|
||||
|r| r.get(0),
|
||||
)?)
|
||||
/// One user, or `None`.
|
||||
pub fn user_row(&self, id: &str) -> Result<Option<UserRow>> {
|
||||
Ok(self.list_users()?.into_iter().find(|u| u.id == id))
|
||||
}
|
||||
|
||||
/// Enable or disable a user. Disabling also ends every session at once.
|
||||
|
||||
@@ -91,6 +91,22 @@ pub struct RelationGrant {
|
||||
pub created_at: i64,
|
||||
}
|
||||
|
||||
/// A refresh grant with what it applies to, for the access screen.
|
||||
#[derive(Clone, Debug, serde::Serialize)]
|
||||
pub struct RelationGrantRow {
|
||||
pub id: String,
|
||||
pub principal_type: String,
|
||||
pub principal: String,
|
||||
pub relation_id: String,
|
||||
pub version: i64,
|
||||
/// An ended relation (or an older version of one) grants nothing.
|
||||
pub active: bool,
|
||||
pub source_name: String,
|
||||
pub target_name: String,
|
||||
pub expires_at: Option<i64>,
|
||||
pub created_at: i64,
|
||||
}
|
||||
|
||||
pub(super) fn migrate(conn: &Connection) -> Result<()> {
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE IF NOT EXISTS orbit_environments (
|
||||
@@ -616,6 +632,34 @@ impl Db {
|
||||
)? == 1)
|
||||
}
|
||||
|
||||
/// Every refresh grant with its relation's names, newest relations first.
|
||||
pub fn list_relation_grants(&self) -> Result<Vec<RelationGrantRow>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT g.id,g.principal_type,g.principal,g.relation_id,r.version,r.active,
|
||||
COALESCE((SELECT name FROM orbits WHERE id=r.source_orbit_id),''),
|
||||
COALESCE((SELECT json_extract(profile,'$.name') FROM restore_targets WHERE id=r.target_id),''),
|
||||
g.expires_at,g.created_at
|
||||
FROM relation_grants g JOIN orbit_relations r ON r.id=g.relation_id
|
||||
ORDER BY r.active DESC, g.principal_type, g.principal, g.created_at",
|
||||
)?;
|
||||
let rows = stmt.query_map([], |r| {
|
||||
Ok(RelationGrantRow {
|
||||
id: r.get(0)?,
|
||||
principal_type: r.get(1)?,
|
||||
principal: r.get(2)?,
|
||||
relation_id: r.get(3)?,
|
||||
version: r.get(4)?,
|
||||
active: r.get::<_, i64>(5)? == 1,
|
||||
source_name: r.get(6)?,
|
||||
target_name: r.get(7)?,
|
||||
expires_at: r.get(8)?,
|
||||
created_at: r.get(9)?,
|
||||
})
|
||||
})?;
|
||||
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||
}
|
||||
|
||||
pub fn relation_grants(&self, relation: &str) -> Result<Vec<RelationGrant>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare("SELECT id,principal_type,principal,relation_id,expires_at,created_by,created_at FROM relation_grants WHERE relation_id=?1 ORDER BY principal_type, principal")?;
|
||||
|
||||
@@ -63,6 +63,10 @@ pub(super) fn migrate(conn: &Connection) -> Result<()> {
|
||||
// Added after the first M2 build; default 0 keeps old rows without admin rights.
|
||||
super::ensure_column(conn, "sessions", "admin", "INTEGER NOT NULL DEFAULT 0")?;
|
||||
super::ensure_column(conn, "sessions", "groups", "TEXT NOT NULL DEFAULT '[]'")?;
|
||||
// What the identity provider said at the user's last sign-in, kept after the session ends so the
|
||||
// access screens can still say who is an administrator and which groups a person comes through.
|
||||
super::ensure_column(conn, "users", "last_groups", "TEXT NOT NULL DEFAULT '[]'")?;
|
||||
super::ensure_column(conn, "users", "last_admin", "INTEGER NOT NULL DEFAULT 0")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -112,6 +116,12 @@ impl Db {
|
||||
SELECT ?1, id, generation, ?3, ?4, ?5, ?5, ?5, ?6, ?7, ?8 FROM users WHERE id=?2 AND active=1",
|
||||
params![session_digest(id), user_id, auth_method, credential_fp, now, now + ABSOLUTE_SECS, admin, serde_json::to_string(groups)?],
|
||||
)?;
|
||||
if inserted == 1 {
|
||||
conn.execute(
|
||||
"UPDATE users SET last_groups=?2, last_admin=?3 WHERE id=?1",
|
||||
params![user_id, serde_json::to_string(groups)?, admin],
|
||||
)?;
|
||||
}
|
||||
Ok(inserted == 1)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user