feat: per-orbit access grants and an Access console (auth M5)

Authorization
- one gate for every human endpoint: authenticate, resolve the resource, then
  admin_only / scoped / visible; require_admin* removed so each handler must choose
- grants (user or IdP group; global or one orbit; optional end date) read live on
  every request; only orbit.read, snapshot.read, capture.run and snapshot.download
  can be granted, everything else stays with configured administrators
- an orbit without orbit.read is 404, a visible one without the permission is 403,
  a caller with nothing to see gets 403 on lists; job history is filtered before LIMIT
- jobs and audit record the stable principal id, not the IdP display name
- restore targets and restore history are admin-only until self-service (M6)
- sessions keep the groups verified at sign-in

Administration
- /api/v1/access grants and users (enable, disable, sign out everywhere), validated
  and audited by id; admins cannot disable themselves or the emergency operator
- Access console with the shared Select and a themed DatePicker; non-administrators
  only see Vault and Activity and never call administrator endpoints
- the Window/Radar view is stored per account (/api/v1/me/preferences)
- UI tolerates older hubs and mocks (missing admin/grants) and a console that fails
  to render no longer blanks the app

Tests: a matrix generated from the endpoint contract exercises every human route
against real resources in two orbits for each kind of caller.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-14 14:45:41 +07:00
parent 54abd02250
commit d12472ba02
29 changed files with 2284 additions and 169 deletions

View File

@@ -236,10 +236,15 @@ pub struct BrowserSession {
pub auth_method: String,
/// May use the management API. A signed-in user without a grant is `false`.
pub admin: bool,
pub groups: Vec<String>,
pub expires_at: i64,
}
impl BrowserSession {
pub fn subject(&self) -> crate::auth::Subject {
crate::auth::Subject { user_id: Some(self.user_id.clone()), groups: self.groups.clone(), admin: self.admin }
}
/// Audit identity. Never derived from IdP-supplied names: OIDC users are
/// identified by their stable user id, so a username of "operator" cannot
/// be mistaken for the emergency account.
@@ -335,6 +340,7 @@ impl SessionGate {
user_id: stored.user_id,
auth_method: stored.auth_method,
admin: stored.admin,
groups: stored.groups,
expires_at: stored.expires_at,
})
}
@@ -363,7 +369,7 @@ impl SessionGate {
let id = uuid::Uuid::new_v4();
let created = self
.db
.create_session(&id.to_string(), &user_id, "password", Some(&config.fingerprint), true, now)
.create_session(&id.to_string(), &user_id, "password", Some(&config.fingerprint), true, &[], now)
.map_err(internal)?;
if !created {
// Inactive user row: the break-glass account has been disabled.
@@ -376,6 +382,7 @@ impl SessionGate {
user_id,
auth_method: "password".into(),
admin: true,
groups: vec![],
expires_at: now + crate::db::sessions::ABSOLUTE_SECS,
})
}
@@ -387,12 +394,13 @@ impl SessionGate {
user_id: &str,
display_name: &str,
admin: bool,
groups: &[String],
now: i64,
) -> anyhow::Result<BrowserSession> {
let fp = self.oidc_fp.as_deref().ok_or_else(|| anyhow::anyhow!("OIDC is not configured"))?;
let id = uuid::Uuid::new_v4();
anyhow::ensure!(
self.db.create_session(&id.to_string(), user_id, "oidc", Some(fp), admin, now)?,
self.db.create_session(&id.to_string(), user_id, "oidc", Some(fp), admin, groups, now)?,
"user is disabled"
);
Ok(BrowserSession {
@@ -402,6 +410,7 @@ impl SessionGate {
user_id: user_id.to_string(),
auth_method: "oidc".into(),
admin,
groups: groups.to_vec(),
expires_at: now + crate::db::sessions::ABSOLUTE_SECS,
})
}
@@ -570,7 +579,7 @@ mod session_gate_tests {
let (_dir, db) = db().await;
let user = db.upsert_user("https://idp.example", "alice", "Alice", unix_now()).unwrap();
let gate = SessionGate::without_operator(db.clone()).with_oidc("fp-a");
let session = gate.create_oidc(&user, "Alice", true, unix_now()).unwrap();
let session = gate.create_oidc(&user, "Alice", true, &[], unix_now()).unwrap();
assert_eq!(session.principal().fields().0, format!("oidc:{user}"));
assert!(gate.active(&cookie(&session)).is_some());
// admin mapping changed (different fingerprint) or OIDC switched off: dead
@@ -584,7 +593,7 @@ mod session_gate_tests {
async fn an_oidc_display_name_never_becomes_the_emergency_principal() {
let (_dir, db) = db().await;
let user = db.upsert_user("https://idp.example", "mallory", "operator", unix_now()).unwrap();
let session = SessionGate::without_operator(db).with_oidc("fp").create_oidc(&user, "operator", false, unix_now()).unwrap();
let session = SessionGate::without_operator(db).with_oidc("fp").create_oidc(&user, "operator", false, &[], unix_now()).unwrap();
let (id, kind, method) = session.principal().fields();
assert_eq!((kind, method), ("user", "oidc"));
assert!(id.starts_with("oidc:") && !id.contains("emergency"));

View File

@@ -0,0 +1,232 @@
//! Administration of access: who holds which permission on which orbit.
//! Administrators only (`access.manage` is never delegated). Every change is
//! audited by id and effective on the very next request of the affected user.
use super::routes::{admin_read, admin_write};
use crate::auth::{role, AuditAction, AuditOutcome, AuditResource, Permission, ROLE_NAMES};
use crate::db::access::NewGrant;
use crate::state::HubState;
use axum::{
extract::{ConnectInfo, Path, State},
http::{header, HeaderMap, HeaderValue, StatusCode},
routing::{get, post, put},
Json, Router,
};
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
use uuid::Uuid;
pub(super) fn routes() -> Router<HubState> {
Router::new()
.route("/api/v1/access/grants", get(list).post(create))
.route("/api/v1/access/grants/:id", axum::routing::delete(remove))
.route("/api/v1/access/users", get(users))
.route("/api/v1/access/users/:id", put(set_user))
.route("/api/v1/access/users/:id/revoke-sessions", post(revoke_sessions))
}
fn no_store() -> HeaderMap {
let mut headers = HeaderMap::new();
headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
headers
}
fn now() -> i64 {
chrono::Utc::now().timestamp()
}
fn internal(error: impl std::fmt::Display) -> StatusCode {
tracing::error!("access administration failed: {error:#}");
StatusCode::INTERNAL_SERVER_ERROR
}
#[derive(Serialize)]
struct RoleInfo {
name: &'static str,
permissions: Vec<&'static str>,
}
#[derive(Serialize)]
struct GrantList {
grants: Vec<crate::db::access::Grant>,
roles: Vec<RoleInfo>,
/// Permissions that can be granted; all others belong to administrators.
grantable: Vec<&'static str>,
}
async fn list(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<(HeaderMap, Json<GrantList>), StatusCode> {
admin_read(&state, peer, &headers)?;
let roles = ROLE_NAMES
.iter()
.map(|name| RoleInfo { name, permissions: role(name).unwrap_or(&[]).iter().map(|p| p.as_str()).collect() })
.collect();
Ok((
no_store(),
Json(GrantList {
grants: state.db.list_grants().map_err(internal)?,
roles,
grantable: [Permission::OrbitRead, Permission::SnapshotRead, Permission::CaptureRun, Permission::SnapshotDownload]
.iter()
.map(|p| p.as_str())
.collect(),
}),
))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct CreateGrant {
/// `user` (a `users.id`) or `group` (an IdP group name).
principal_type: String,
principal: String,
/// Exactly one of `role` and `permission`.
role: Option<String>,
permission: Option<String>,
/// Absent = every orbit.
orbit_id: Option<Uuid>,
/// RFC 3339; absent = no expiry.
expires_at: Option<String>,
}
async fn create(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Json(body): Json<CreateGrant>,
) -> Result<(StatusCode, HeaderMap, Json<Vec<crate::db::access::Grant>>), StatusCode> {
let actor = admin_write(&state, peer, &headers)?;
let now = now();
let permissions: Vec<Permission> = match (&body.role, &body.permission) {
(Some(name), None) => role(name).ok_or(StatusCode::BAD_REQUEST)?.to_vec(),
(None, Some(name)) => vec![Permission::parse(name).filter(|p| p.grantable()).ok_or(StatusCode::BAD_REQUEST)?],
_ => return Err(StatusCode::BAD_REQUEST),
};
match body.principal_type.as_str() {
"user" => {
Uuid::parse_str(&body.principal).map_err(|_| StatusCode::BAD_REQUEST)?;
if !state.db.user_exists(&body.principal).map_err(internal)? {
return Err(StatusCode::UNPROCESSABLE_ENTITY);
}
}
"group" => {
if body.principal.is_empty() || body.principal.len() > 128 || body.principal.chars().any(char::is_control) {
return Err(StatusCode::BAD_REQUEST);
}
}
_ => return Err(StatusCode::BAD_REQUEST),
}
if let Some(orbit) = body.orbit_id {
if !state.db.orbit_exists(&orbit.to_string()).map_err(internal)? {
return Err(StatusCode::UNPROCESSABLE_ENTITY);
}
}
let expires_at = body
.expires_at
.as_deref()
.map(|text| chrono::DateTime::parse_from_rfc3339(text).map(|t| t.timestamp()).map_err(|_| StatusCode::BAD_REQUEST))
.transpose()?;
if expires_at.is_some_and(|end| end <= now || end > now + 2 * 366 * 86_400) {
return Err(StatusCode::BAD_REQUEST);
}
let orbit = body.orbit_id.map(|id| id.to_string());
let created_by = actor.id();
let mut created = Vec::new();
for permission in permissions {
let grant = NewGrant {
principal_type: &body.principal_type,
principal: &body.principal,
permission: permission.as_str(),
orbit: orbit.as_deref(),
expires_at,
created_by: &created_by,
};
if let Some(grant) = state.db.add_grant(&grant, now).map_err(internal)? {
let id = Uuid::parse_str(&grant.id).map_err(internal)?;
state
.db
.audit_event(&actor.principal, AuditAction::GrantCreate, AuditResource::Grant(id), AuditOutcome::Succeeded, actor.request_id)
.map_err(internal)?;
created.push(grant);
}
}
if created.is_empty() {
return Err(StatusCode::CONFLICT);
}
Ok((StatusCode::CREATED, no_store(), Json(created)))
}
async fn remove(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<StatusCode, StatusCode> {
let actor = admin_write(&state, peer, &headers)?;
let removed = state.db.delete_grant(&id.to_string()).map_err(internal)?;
state
.db
.audit_event(&actor.principal, AuditAction::GrantDelete, AuditResource::Grant(id),
if removed { AuditOutcome::Succeeded } else { AuditOutcome::Failed }, actor.request_id)
.map_err(internal)?;
if removed { Ok(StatusCode::NO_CONTENT) } else { Err(StatusCode::NOT_FOUND) }
}
async fn users(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<(HeaderMap, Json<Vec<crate::db::access::UserRow>>), StatusCode> {
admin_read(&state, peer, &headers)?;
Ok((no_store(), Json(state.db.list_users().map_err(internal)?)))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct UserState {
active: bool,
}
/// Look up the target user and refuse the two changes that would lock everyone out.
fn target_user(state: &HubState, actor: &super::routes::OperatorActor, id: Uuid) -> Result<crate::db::access::UserRow, StatusCode> {
let user = state.db.list_users().map_err(internal)?.into_iter().find(|u| u.id == id.to_string()).ok_or(StatusCode::NOT_FOUND)?;
if actor.subject.user_id.as_deref() == Some(user.id.as_str()) || user.is_emergency {
return Err(StatusCode::CONFLICT);
}
Ok(user)
}
async fn set_user(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
Json(body): Json<UserState>,
) -> Result<StatusCode, StatusCode> {
let actor = admin_write(&state, peer, &headers)?;
let user = target_user(&state, &actor, id)?;
state.db.set_user_active(&user.id, body.active).map_err(internal)?;
state
.db
.audit_event(&actor.principal, AuditAction::UserState, AuditResource::User(id), AuditOutcome::Succeeded, actor.request_id)
.map_err(internal)?;
Ok(StatusCode::NO_CONTENT)
}
async fn revoke_sessions(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<StatusCode, StatusCode> {
let actor = admin_write(&state, peer, &headers)?;
let user = state.db.list_users().map_err(internal)?.into_iter().find(|u| u.id == id.to_string()).ok_or(StatusCode::NOT_FOUND)?;
state.db.revoke_user_sessions(&user.id).map_err(internal)?;
state
.db
.audit_event(&actor.principal, AuditAction::SessionsRevoke, AuditResource::User(id), AuditOutcome::Succeeded, actor.request_id)
.map_err(internal)?;
Ok(StatusCode::NO_CONTENT)
}

View File

@@ -0,0 +1,573 @@
//! Authorization matrix, generated from `tasks/auth-endpoint-contract.md`.
//!
//! Every `human` route in the contract is exercised against real resources in two
//! orbits with six kinds of caller. A route added to the contract without a
//! request recipe here fails the test, so nothing ships ungated by accident.
use crate::admin::SessionGate;
use crate::auth::{role, Permission};
use crate::db::access::NewGrant;
use crate::state::HubState;
use axum::body::{to_bytes, Body};
use axum::extract::ConnectInfo;
use axum::http::{header, Method, Request, StatusCode};
use serde_json::{json, Value};
use std::net::SocketAddr;
use tessera_core::job::{CaptureFormat, CaptureProfile};
use tessera_core::manifest::SnapshotManifest;
use tessera_core::restore::{DatabaseIdentity, Engine, RestoreTarget};
use tower::ServiceExt;
use uuid::Uuid;
const CONTRACT: &str = include_str!("../../../../tasks/auth-endpoint-contract.md");
const ISSUER: &str = "https://idp.example";
struct Fixture {
orbit: Uuid,
application: Uuid,
outpost: Uuid,
snapshot: Uuid,
job: Uuid,
}
struct Caller {
name: &'static str,
cookie: Option<String>,
csrf: Option<String>,
user_id: Option<String>,
}
struct World {
app: axum::Router,
state: HubState,
a: Fixture,
b: Fixture,
_dir: tempfile::TempDir,
}
fn now() -> i64 {
chrono::Utc::now().timestamp()
}
async fn fixture(state: &HubState, name: &str) -> Fixture {
let orbit = Uuid::new_v4();
state
.db
.upsert_orbit(&crate::db::OrbitRow {
id: orbit,
name: name.into(),
provider: "wormhole".into(),
provider_config: "{}".into(),
schedule: None,
decay_preset: "week-of-dailies".into(),
retention: None,
dry_run: false,
last_status: "idle".into(),
})
.await
.unwrap();
let outpost = Uuid::new_v4();
state.db.insert_test_credential(&format!("token-{name}"), &outpost.to_string(), name);
let application = Uuid::new_v4();
let profile = CaptureProfile { application_id: application, orbit_id: orbit, outpost_id: outpost, format: CaptureFormat::PostgresCustom, schedule: None, retention: None };
assert!(state.db.register_capture_profile(&profile, now()).unwrap());
let job = state.db.enqueue_capture(application, "seed", now()).unwrap().unwrap().id;
let snapshot = Uuid::new_v4();
let manifest = SnapshotManifest {
snapshot_id: snapshot,
orbit_id: orbit,
orbit_name: name.into(),
labels: vec![],
provider: "filesystem".into(),
paths: vec![],
restore_hints: Value::Null,
};
state.vault.write().await.snapshot(manifest, b"synthetic payload", false).unwrap();
let target = RestoreTarget {
id: Uuid::new_v4(),
application_id: application,
outpost_id: outpost,
name: format!("{name}-staging"),
engine: Engine::Postgres,
identity: DatabaseIdentity { instance: if name == "orbit-a" { "123" } else { "124" }.into(), database: "app".into() },
};
assert!(state.db.register_restore_target(&target).unwrap());
Fixture { orbit, application, outpost, snapshot, job }
}
async fn world() -> World {
let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault").await.unwrap();
state.sessions = SessionGate::without_operator(state.db.clone()).with_oidc("matrix-fp");
let a = fixture(&state, "orbit-a").await;
let b = fixture(&state, "orbit-b").await;
let app = crate::api::router(state.clone());
World { app, state, a, b, _dir: dir }
}
impl World {
fn caller(&self, name: &'static str, admin: bool, groups: &[&str]) -> Caller {
let groups: Vec<String> = groups.iter().map(|g| g.to_string()).collect();
let user = self.state.db.upsert_user(ISSUER, name, name, now()).unwrap();
let session = self.state.sessions.create_oidc(&user, name, admin, &groups, now()).unwrap();
Caller { name, cookie: Some(format!("__Host-tessera-session={}", session.id)), csrf: Some(session.csrf), user_id: Some(user) }
}
fn grant_role(&self, user: &str, role_name: &str, orbit: Option<Uuid>) {
self.grant("user", user, role_name, orbit);
}
fn grant(&self, kind: &str, principal: &str, role_name: &str, orbit: Option<Uuid>) {
let orbit = orbit.map(|o| o.to_string());
for permission in role(role_name).unwrap() {
self.state
.db
.add_grant(
&NewGrant { principal_type: kind, principal, permission: permission.as_str(), orbit: orbit.as_deref(), expires_at: None, created_by: "test" },
now(),
)
.unwrap();
}
}
async fn send(&self, caller: &Caller, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
let mut request = Request::builder()
.method(Method::from_bytes(method.as_bytes()).unwrap())
.uri(uri)
.extension(ConnectInfo("127.0.0.1:4000".parse::<SocketAddr>().unwrap()));
if let Some(cookie) = &caller.cookie {
request = request.header(header::COOKIE, cookie);
}
if method != "GET" {
if let Some(csrf) = &caller.csrf {
request = request.header("x-tessera-csrf", csrf);
}
}
let request = match body {
Some(json) => request.header(header::CONTENT_TYPE, "application/json").body(Body::from(json.to_string())).unwrap(),
None => request.body(Body::empty()).unwrap(),
};
let response = self.app.clone().oneshot(request).await.unwrap();
let status = response.status();
let bytes = to_bytes(response.into_body(), 1 << 22).await.unwrap();
(status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
}
}
fn anonymous() -> Caller {
Caller { name: "anonymous", cookie: None, csrf: None, user_id: None }
}
#[derive(Clone, Copy, PartialEq, Debug)]
enum Kind {
SelfOnly,
AdminOnly,
List(Permission),
Resource(Permission),
}
struct Row {
method: String,
template: String,
kind: Kind,
}
/// Every method of every `human` row of the contract.
fn rows() -> Vec<Row> {
let mut out = Vec::new();
for line in CONTRACT.lines().filter(|l| l.starts_with("| /")) {
let f: Vec<_> = line.split('|').map(str::trim).collect();
if f[3] != "human" {
continue;
}
let kind = if f[4] == "session.self" {
Kind::SelfOnly
} else {
let permission = Permission::parse(f[4]).unwrap_or_else(|| panic!("unknown permission {} in the contract", f[4]));
if !permission.grantable() {
Kind::AdminOnly
} else if f[1].contains(":id") {
Kind::Resource(permission)
} else {
Kind::List(permission)
}
};
for method in f[2].split(',') {
out.push(Row { method: method.trim().to_string(), template: f[1].to_string(), kind });
}
}
out
}
/// A concrete request for a contract row, aimed at orbit A's resources.
fn recipe(w: &World, row: &Row) -> (String, Option<Value>) {
let a = &w.a;
let unknown = Uuid::new_v4();
let id = match row.template.as_str() {
"/api/v1/snapshots/:id" | "/api/v1/snapshots/:id/download" | "/api/v1/snapshots/:id/restore-targets" | "/api/v1/snapshots/:id/restore-jobs" => a.snapshot,
"/api/v1/orbits/:id/retention" | "/api/v1/orbits/:id/run" | "/api/v1/orbits/:id/outpost" => a.orbit,
"/api/v1/capture-profiles/:id/jobs" | "/api/v1/capture-profiles/:id/restore-targets" => a.application,
"/api/v1/capture-jobs/:id" | "/api/v1/capture-jobs/:id/events" => a.job,
"/api/v1/wormhole/outposts/:id/rotate" | "/api/v1/wormhole/outposts/:id/revoke" => a.outpost,
_ => unknown,
};
let uri = row.template.replace(":id", &id.to_string());
let target = RestoreTarget {
id: Uuid::new_v4(), application_id: a.application, outpost_id: a.outpost, name: "new-target".into(), engine: Engine::Postgres,
identity: DatabaseIdentity { instance: "456".into(), database: "other".into() },
};
let body = match (row.method.as_str(), row.template.as_str()) {
("POST", "/api/v1/orbits") => Some(json!({"name": "created", "provider": "filesystem", "source": "filesystem", "provider_config": {"path": "/nonexistent"}})),
("PUT", "/api/v1/orbits/:id/retention") => Some(json!({"decay_preset": "week-of-dailies"})),
("PUT", "/api/v1/orbits/:id/outpost") => Some(json!({"outpost_id": a.outpost})),
("POST", "/api/v1/reconstitute") => Some(json!({"snapshot_id": a.snapshot, "target_path": "out"})),
("POST", "/api/v1/capture-profiles") => Some(serde_json::to_value(CaptureProfile { application_id: Uuid::new_v4(), orbit_id: a.orbit, outpost_id: a.outpost, format: CaptureFormat::PostgresCustom, schedule: None, retention: None }).unwrap()),
("POST", "/api/v1/restore-targets") => Some(serde_json::to_value(target).unwrap()),
("POST", "/api/v1/restore-jobs") => Some(json!({"snapshot_id": a.snapshot, "target_id": unknown, "confirmation": "x"})),
("POST", "/api/v1/restore-jobs/:id/reconcile") => Some(json!({"confirmation": "x"})),
("POST", "/api/v1/access/grants") => Some(json!({"principal_type": "group", "principal": "matrix-group", "role": "viewer"})),
("PUT", "/api/v1/access/users/:id") => Some(json!({"active": true})),
("POST" | "PUT" | "DELETE" | "GET", _) => None,
other => panic!("no request recipe for {other:?}"),
};
(uri, body)
}
/// The orbit ids a list response contains, per list route.
fn orbits_in(template: &str, body: &Value) -> Vec<String> {
let pick = |path: &[&str]| -> Vec<String> {
body.as_array().unwrap_or(&vec![]).iter().filter_map(|item| {
let mut v = item;
for key in path {
v = v.get(key)?;
}
v.as_str().map(str::to_string)
}).collect()
};
match template {
"/api/v1/orbits" => pick(&["id"]),
"/api/v1/snapshots" | "/api/v1/capture-profiles" => pick(&["orbit_id"]),
"/api/v1/capture-jobs" => pick(&["profile", "orbit_id"]),
other => panic!("no list reader for {other}"),
}
}
fn denied(status: StatusCode) -> bool {
matches!(status, StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN | StatusCode::NOT_FOUND)
}
#[tokio::test]
async fn every_human_route_enforces_the_matrix_for_every_kind_of_caller() {
let w = world().await;
let nogrant = w.caller("nogrant", false, &[]);
let viewer_b = w.caller("viewer-b", false, &[]);
let viewer_a = w.caller("viewer-a", false, &[]);
let capturer_a = w.caller("capturer-a", false, &[]);
let downloader_a = w.caller("downloader-a", false, &[]);
let group_a = w.caller("group-a", false, &["qa"]);
let admin = w.caller("admin", true, &[]);
w.grant_role(viewer_b.user_id.as_ref().unwrap(), "viewer", Some(w.b.orbit));
w.grant_role(viewer_a.user_id.as_ref().unwrap(), "viewer", Some(w.a.orbit));
w.grant_role(capturer_a.user_id.as_ref().unwrap(), "capturer", Some(w.a.orbit));
w.grant_role(downloader_a.user_id.as_ref().unwrap(), "downloader", Some(w.a.orbit));
w.grant("group", "qa", "viewer", Some(w.a.orbit));
let (a, b) = (w.a.orbit.to_string(), w.b.orbit.to_string());
// scoped routes first, so the destructive admin-only ones cannot disturb their fixtures
let mut rows = rows();
rows.sort_by_key(|row| matches!(row.kind, Kind::AdminOnly));
let mut covered = 0;
for row in &rows {
if row.kind == Kind::SelfOnly {
continue;
}
covered += 1;
let (uri, body) = recipe(&w, row);
let label = format!("{} {}", row.method, row.template);
// no credential: always 401
let (status, _) = w.send(&anonymous(), &row.method, &uri, body.clone()).await;
assert_eq!(status, StatusCode::UNAUTHORIZED, "{label} anonymous");
// every non-admin caller, with the exact status the contract implies
for caller in [&nogrant, &viewer_b, &viewer_a, &capturer_a, &downloader_a, &group_a] {
let (status, body_out) = w.send(caller, &row.method, &uri, body.clone()).await;
let on_a = !std::ptr::eq(caller, &viewer_b) && !std::ptr::eq(caller, &nogrant);
let held: &[Permission] = match caller.name {
"viewer-a" | "viewer-b" | "group-a" => role("viewer").unwrap(),
"capturer-a" => role("capturer").unwrap(),
"downloader-a" => role("downloader").unwrap(),
_ => &[],
};
let who = format!("{label} as {}", caller.name);
match row.kind {
Kind::AdminOnly => assert_eq!(status, StatusCode::FORBIDDEN, "{who}"),
Kind::Resource(permission) => {
let expected = if !on_a {
StatusCode::NOT_FOUND
} else if held.contains(&permission) {
// allowed: whatever the handler says, but never a gate answer
assert!(!denied(status), "{who}: {status}");
continue;
} else {
StatusCode::FORBIDDEN
};
assert_eq!(status, expected, "{who}");
}
Kind::List(_) => {
if caller.name == "nogrant" {
assert_eq!(status, StatusCode::FORBIDDEN, "{who}");
} else if row.method == "GET" {
assert_eq!(status, StatusCode::OK, "{who}");
let seen = orbits_in(&row.template, &body_out);
let own = if caller.name == "viewer-b" { &b } else { &a };
assert!(!seen.is_empty() && seen.iter().all(|id| id == own), "{who} sees only its own orbit: {seen:?}");
} else {
assert!(!denied(status), "{who}: {status}");
}
}
Kind::SelfOnly => unreachable!(),
}
// the invariant that catches a forgotten gate: no grant, no success
if caller.name == "nogrant" {
assert!(!status.is_success(), "{who}: a caller without any grant got {status}");
}
}
// the administrator is never turned away by the gate
let (status, body_out) = w.send(&admin, &row.method, &uri, body.clone()).await;
assert!(status != StatusCode::UNAUTHORIZED && status != StatusCode::FORBIDDEN, "{label} as admin: {status}");
if let (Kind::List(_), "GET") = (row.kind, row.method.as_str()) {
let seen = orbits_in(&row.template, &body_out);
assert!(seen.contains(&a) && seen.contains(&b), "{label}: the administrator sees every orbit");
}
}
assert!(covered >= 25, "the matrix covered {covered} routes");
}
#[tokio::test]
async fn permissions_are_separate_capture_does_not_imply_download_and_the_reverse() {
let w = world().await;
let capturer = w.caller("capturer", false, &[]);
let downloader = w.caller("downloader", false, &[]);
w.grant_role(capturer.user_id.as_ref().unwrap(), "capturer", Some(w.a.orbit));
w.grant_role(downloader.user_id.as_ref().unwrap(), "downloader", Some(w.a.orbit));
let download = format!("/api/v1/snapshots/{}/download", w.a.snapshot);
let enqueue = format!("/api/v1/capture-profiles/{}/jobs", w.a.application);
assert_eq!(w.send(&capturer, "POST", &enqueue, None).await.0, StatusCode::ACCEPTED);
assert_eq!(w.send(&capturer, "GET", &download, None).await.0, StatusCode::FORBIDDEN);
assert_eq!(w.send(&downloader, "GET", &download, None).await.0, StatusCode::OK);
assert_eq!(w.send(&downloader, "POST", &enqueue, None).await.0, StatusCode::FORBIDDEN);
// download on the other orbit stays invisible for both
let other = format!("/api/v1/snapshots/{}/download", w.b.snapshot);
assert_eq!(w.send(&downloader, "GET", &other, None).await.0, StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn a_revoked_or_expired_grant_is_refused_on_the_next_request_and_groups_follow_the_login() {
let w = world().await;
let user = w.caller("temp", false, &[]);
let id = user.user_id.clone().unwrap();
let uri = "/api/v1/orbits";
assert_eq!(w.send(&user, "GET", uri, None).await.0, StatusCode::FORBIDDEN, "no grant yet");
w.grant_role(&id, "viewer", Some(w.a.orbit));
assert_eq!(w.send(&user, "GET", uri, None).await.0, StatusCode::OK, "effective at once");
let grants = w.state.db.list_grants().unwrap();
for grant in grants.iter().filter(|g| g.principal == id) {
assert!(w.state.db.delete_grant(&grant.id).unwrap());
}
assert_eq!(w.send(&user, "GET", uri, None).await.0, StatusCode::FORBIDDEN, "revoked at once");
// an expiry in the past is ignored even though the row is still there
w.state
.db
.add_grant(&NewGrant { principal_type: "user", principal: &id, permission: "orbit.read", orbit: None, expires_at: Some(now() - 5), created_by: "test" }, now() - 100)
.unwrap();
assert_eq!(w.send(&user, "GET", uri, None).await.0, StatusCode::FORBIDDEN, "expired");
// a group grant applies to the groups of the session, not to a later claim
w.grant("group", "qa", "viewer", None);
let in_group = w.caller("member", false, &["qa"]);
let no_claim = w.caller("no-claim", false, &[]);
assert_eq!(w.send(&in_group, "GET", uri, None).await.0, StatusCode::OK);
assert_eq!(w.send(&no_claim, "GET", uri, None).await.0, StatusCode::FORBIDDEN, "a missing groups claim grants nothing");
}
#[tokio::test]
async fn a_restricted_caller_still_gets_a_full_page_of_their_own_jobs() {
let w = world().await;
// orbit B has one job; orbit A gets many newer ones that would fill a page
for _ in 0..5 {
w.state.db.enqueue_capture(w.a.application, "seed", now() + 10).unwrap();
}
let viewer = w.caller("viewer-b", false, &[]);
w.grant_role(viewer.user_id.as_ref().unwrap(), "viewer", Some(w.b.orbit));
let (status, body) = w.send(&viewer, "GET", "/api/v1/capture-jobs?limit=1", None).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body.as_array().unwrap().len(), 1, "filtered before the limit");
assert_eq!(body[0]["profile"]["orbit_id"], w.b.orbit.to_string());
// asking for the other orbit's application by id is a 404, not an empty list
let uri = format!("/api/v1/capture-jobs?application_id={}", w.a.application);
assert_eq!(w.send(&viewer, "GET", &uri, None).await.0, StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn jobs_are_attributed_to_the_stable_principal_never_to_an_idp_display_name() {
let w = world().await;
// an IdP user who calls themselves "scheduler" must not look like the scheduler
let user = w.caller("scheduler", false, &[]);
let id = user.user_id.clone().unwrap();
w.grant_role(&id, "capturer", Some(w.a.orbit));
let enqueue = format!("/api/v1/capture-profiles/{}/jobs", w.a.application);
let (status, job) = w.send(&user, "POST", &enqueue, None).await;
assert_eq!(status, StatusCode::ACCEPTED);
assert_eq!(job["actor"], format!("oidc:{id}"));
assert_ne!(job["actor"], "scheduler");
}
#[tokio::test]
async fn the_grant_api_validates_audits_and_is_for_administrators_only() {
let w = world().await;
let admin = w.caller("admin", true, &[]);
let plain = w.caller("plain", false, &[]);
let target = w.caller("target", false, &[]);
let uid = target.user_id.clone().unwrap();
let grants = "/api/v1/access/grants";
let user_grant = |extra: Value| {
let mut base = json!({"principal_type": "user", "principal": uid, "role": "viewer", "orbit_id": w.a.orbit});
base.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
base
};
// not for non-admins, not even for someone who holds grants
w.grant_role(plain.user_id.as_ref().unwrap(), "viewer", None);
assert_eq!(w.send(&plain, "POST", grants, Some(user_grant(json!({})))).await.0, StatusCode::FORBIDDEN);
assert_eq!(w.send(&plain, "GET", grants, None).await.0, StatusCode::FORBIDDEN);
// validation: each of these must be refused
for (what, body, expected) in [
("unknown permission", user_grant(json!({"role": null, "permission": "orbit.reader"})), StatusCode::BAD_REQUEST),
("prefix of a permission", user_grant(json!({"role": null, "permission": "orbit"})), StatusCode::BAD_REQUEST),
("ungrantable permission", user_grant(json!({"role": null, "permission": "orbit.manage"})), StatusCode::BAD_REQUEST),
("access.manage is never delegated", user_grant(json!({"role": null, "permission": "access.manage"})), StatusCode::BAD_REQUEST),
("unknown role", user_grant(json!({"role": "root"})), StatusCode::BAD_REQUEST),
("role and permission together", user_grant(json!({"permission": "orbit.read"})), StatusCode::BAD_REQUEST),
("neither role nor permission", user_grant(json!({"role": null})), StatusCode::BAD_REQUEST),
("unknown principal type", user_grant(json!({"principal_type": "service"})), StatusCode::BAD_REQUEST),
("unknown user", user_grant(json!({"principal": Uuid::new_v4()})), StatusCode::UNPROCESSABLE_ENTITY),
("unknown orbit", user_grant(json!({"orbit_id": Uuid::new_v4()})), StatusCode::UNPROCESSABLE_ENTITY),
("expiry in the past", user_grant(json!({"expires_at": "2020-01-01T00:00:00Z"})), StatusCode::BAD_REQUEST),
("expiry far in the future", user_grant(json!({"expires_at": "2099-01-01T00:00:00Z"})), StatusCode::BAD_REQUEST),
("malformed expiry", user_grant(json!({"expires_at": "tomorrow"})), StatusCode::BAD_REQUEST),
("oversized group", json!({"principal_type": "group", "principal": "g".repeat(200), "role": "viewer"}), StatusCode::BAD_REQUEST),
] {
assert_eq!(w.send(&admin, "POST", grants, Some(body)).await.0, expected, "{what}");
}
assert_eq!(w.state.db.list_grants().unwrap().iter().filter(|g| g.principal == uid).count(), 0, "nothing was stored by the rejected requests");
// a valid grant takes effect on the very next request, and removing it ends that
let (status, created) = w.send(&admin, "POST", grants, Some(user_grant(json!({"expires_at": (chrono::Utc::now() + chrono::Duration::days(30)).to_rfc3339()})))).await;
assert_eq!(status, StatusCode::CREATED);
assert_eq!(created.as_array().unwrap().len(), 2, "the viewer role expands to orbit.read and snapshot.read");
assert_eq!(w.send(&target, "GET", "/api/v1/orbits", None).await.0, StatusCode::OK);
assert_eq!(w.send(&admin, "POST", grants, Some(user_grant(json!({})))).await.0, StatusCode::CONFLICT, "duplicates are refused");
for grant in created.as_array().unwrap() {
let uri = format!("/api/v1/access/grants/{}", grant["id"].as_str().unwrap());
assert_eq!(w.send(&admin, "DELETE", &uri, None).await.0, StatusCode::NO_CONTENT);
}
assert_eq!(w.send(&target, "GET", "/api/v1/orbits", None).await.0, StatusCode::FORBIDDEN);
// listing: roles and the grantable permissions come from the server
let (status, listing) = w.send(&admin, "GET", grants, None).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(listing["grantable"].as_array().unwrap().len(), 4);
assert!(listing["roles"].as_array().unwrap().iter().any(|r| r["name"] == "downloader"));
// every change is audited by id, attributed to the administrator
let conn = rusqlite::Connection::open(w._dir.path().join("tessera.db")).unwrap();
let created_rows: i64 = conn
.query_row("SELECT COUNT(*) FROM audit_events WHERE action='access.grant_create' AND outcome='succeeded' AND resource_type='grant' AND actor_id LIKE 'oidc:%'", [], |r| r.get(0))
.unwrap();
let deleted_rows: i64 = conn.query_row("SELECT COUNT(*) FROM audit_events WHERE action='access.grant_delete' AND outcome='succeeded'", [], |r| r.get(0)).unwrap();
assert_eq!((created_rows, deleted_rows), (2, 2));
let denied_actor: String = conn
.query_row("SELECT actor_id FROM audit_events WHERE action='authorization.check' AND outcome='denied' ORDER BY id LIMIT 1", [], |r| r.get(0))
.unwrap();
assert!(denied_actor.starts_with("oidc:"), "{denied_actor}");
}
#[tokio::test]
async fn disabling_a_user_ends_their_access_at_once_and_cannot_lock_out_the_caller() {
let w = world().await;
let admin = w.caller("admin", true, &[]);
let user = w.caller("leaver", false, &[]);
let id = user.user_id.clone().unwrap();
w.grant_role(&id, "viewer", None);
assert_eq!(w.send(&user, "GET", "/api/v1/orbits", None).await.0, StatusCode::OK);
let uri = format!("/api/v1/access/users/{id}");
assert_eq!(w.send(&admin, "PUT", &uri, Some(json!({"active": false}))).await.0, StatusCode::NO_CONTENT);
assert_eq!(w.send(&user, "GET", "/api/v1/orbits", None).await.0, StatusCode::UNAUTHORIZED, "the session is gone");
// an administrator cannot disable themselves
let own = format!("/api/v1/access/users/{}", admin.user_id.as_ref().unwrap());
assert_eq!(w.send(&admin, "PUT", &own, Some(json!({"active": false}))).await.0, StatusCode::CONFLICT);
// revoking sessions leaves the user able to sign in again
let again = w.caller("returner", false, &[]);
let rid = again.user_id.clone().unwrap();
w.grant_role(&rid, "viewer", None);
let revoke = format!("/api/v1/access/users/{rid}/revoke-sessions");
assert_eq!(w.send(&admin, "POST", &revoke, None).await.0, StatusCode::NO_CONTENT);
assert_eq!(w.send(&again, "GET", "/api/v1/orbits", None).await.0, StatusCode::UNAUTHORIZED);
let users = w.send(&admin, "GET", "/api/v1/access/users", None).await.1;
assert!(users.as_array().unwrap().iter().any(|u| u["id"] == id && u["active"] == false));
}
#[tokio::test]
async fn me_and_the_session_status_describe_what_the_caller_can_use() {
let w = world().await;
let user = w.caller("viewer", false, &[]);
let id = user.user_id.clone().unwrap();
let none = w.send(&user, "GET", "/api/v1/operator/session", None).await.1;
assert_eq!((none["authorized"].clone(), none["admin"].clone()), (json!(false), json!(false)), "no grant: the app stays closed");
w.grant_role(&id, "downloader", Some(w.a.orbit));
let status = w.send(&user, "GET", "/api/v1/operator/session", None).await.1;
assert_eq!((status["authorized"].clone(), status["admin"].clone()), (json!(true), json!(false)));
let me = w.send(&user, "GET", "/api/v1/me", None).await.1;
assert_eq!(me["admin"], false);
assert!(me["capabilities"].as_array().unwrap().iter().any(|c| c == "snapshot.download"));
assert!(me["grants"].as_array().unwrap().iter().all(|g| g["orbit_id"] == w.a.orbit.to_string()));
assert!(!me.to_string().contains("csrf"));
let admin = w.caller("admin", true, &[]);
let me = w.send(&admin, "GET", "/api/v1/me", None).await.1;
assert_eq!((me["admin"].clone(), me["capabilities"][0].clone()), (json!(true), json!("admin")));
assert!(me["id"].as_str().unwrap().starts_with("oidc:"));
}
#[tokio::test]
async fn display_preferences_stick_to_the_account_and_are_validated() {
let w = world().await;
let ann = w.caller("ann", false, &[]);
let ben = w.caller("ben", false, &[]);
let prefs = "/api/v1/me/preferences";
assert_eq!(w.send(&anonymous(), "GET", prefs, None).await.0, StatusCode::UNAUTHORIZED);
assert_eq!(w.send(&anonymous(), "PUT", prefs, Some(json!({"look": "radar"}))).await.0, StatusCode::UNAUTHORIZED);
// nothing stored yet; works for a user who holds no grant at all
let (status, body) = w.send(&ann, "GET", prefs, None).await;
assert_eq!((status, body["look"].clone()), (StatusCode::OK, Value::Null));
assert_eq!(w.send(&ann, "PUT", prefs, Some(json!({"look": "radar"}))).await.0, StatusCode::NO_CONTENT);
assert_eq!(w.send(&ann, "GET", prefs, None).await.1["look"], "radar");
// another account is unaffected; invalid values and unknown keys are refused
assert_eq!(w.send(&ben, "GET", prefs, None).await.1["look"], Value::Null);
assert_eq!(w.send(&ann, "PUT", prefs, Some(json!({"look": "neon"}))).await.0, StatusCode::BAD_REQUEST);
assert_eq!(w.send(&ann, "PUT", prefs, Some(json!({"theme": "x"}))).await.0, StatusCode::UNPROCESSABLE_ENTITY);
assert_eq!(w.send(&ann, "GET", prefs, None).await.1["look"], "radar", "a refused change leaves the choice alone");
// it follows the account, not the session: a fresh sign-in sees it
let again = w.caller("ann", false, &[]);
assert_eq!(w.send(&again, "GET", prefs, None).await.1["look"], "radar");
// the legacy admin token has no account: empty, and nothing to write to
let mut request = Request::builder().method("PUT").uri(prefs)
.extension(ConnectInfo("127.0.0.1:4000".parse::<SocketAddr>().unwrap()))
.header(header::CONTENT_TYPE, "application/json").header("x-tessera-admin-token", "legacy-token")
.body(Body::from(json!({"look": "window"}).to_string())).unwrap();
let mut state = w.state.clone();
state.admin.token = Some("legacy-token".into());
let app = crate::api::router(state);
*request.uri_mut() = prefs.parse().unwrap();
assert_eq!(app.oneshot(request).await.unwrap().status(), StatusCode::NOT_FOUND);
}

View File

@@ -1,4 +1,5 @@
use super::routes::{require_admin, require_admin_mutation};
use super::routes::{admin_write, authenticate};
use crate::auth::Permission;
use crate::state::HubState;
use axum::{
body::Body,
@@ -24,7 +25,7 @@ async fn download(
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<Response, StatusCode> {
require_admin(&state, peer, &headers)?;
let actor = authenticate(&state, peer, &headers, false)?;
let snapshot = state
.vault
.read()
@@ -33,6 +34,7 @@ async fn download(
.map_err(internal)?
.filter(|snapshot| snapshot.manifest.provider != "legacy-history")
.ok_or(StatusCode::NOT_FOUND)?;
super::gate::scoped(&state, &actor, Permission::SnapshotDownload, snapshot.manifest.orbit_id)?;
let staging = tempfile::tempdir_in(&state.data_dir).map_err(internal)?;
let path = staging.path().join("download");
let size = state
@@ -73,7 +75,7 @@ async fn delete(
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<StatusCode, StatusCode> {
let actor = require_admin_mutation(&state, peer, &headers)?;
let actor = admin_write(&state, peer, &headers)?;
let mut vault = state.vault.clone().write_owned().await;
if state.db.snapshot_in_restore(id).map_err(internal)?
|| state.db.offsite_pending(id).map_err(internal)? || state.active_exports().await.contains(&id)

View File

@@ -0,0 +1,124 @@
//! The one place that decides what an authenticated caller may do.
//!
//! Order everywhere: authenticate (401 / CSRF 403), resolve the resource, then
//! the gate. A resource the caller cannot see answers 404 (it is not confirmed to
//! exist); one they can see but may not use answers 403. Grants are read from the
//! database on every call, so a revoke is effective on the next request.
use super::routes::OperatorActor;
use crate::auth::{AuditAction, AuditOutcome, AuditResource, Permission};
use crate::state::HubState;
use axum::http::StatusCode;
use std::collections::HashSet;
use uuid::Uuid;
fn now() -> i64 {
chrono::Utc::now().timestamp()
}
fn audit(state: &HubState, actor: &OperatorActor, resource: AuditResource, allowed: bool) -> Result<(), StatusCode> {
state
.db
.audit_event(
&actor.principal,
AuditAction::Authorization,
resource,
if allowed { AuditOutcome::Allowed } else { AuditOutcome::Denied },
actor.request_id,
)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
}
fn internal(error: impl std::fmt::Display) -> StatusCode {
tracing::error!("authorization lookup failed: {error}");
StatusCode::INTERNAL_SERVER_ERROR
}
/// Management actions are never delegated: anyone who is not a configured
/// administrator gets 403 without any lookup, so this also reveals nothing about resources.
pub(super) fn admin_only(state: &HubState, actor: &OperatorActor) -> Result<(), StatusCode> {
let allowed = actor.subject.admin;
audit(state, actor, AuditResource::Api, allowed)?;
if allowed { Ok(()) } else { Err(StatusCode::FORBIDDEN) }
}
/// Use `permission` on one orbit. Not visible (no `orbit.read`) is 404, visible
/// but not permitted is 403. A permission that cannot be granted is admin-only.
pub(super) fn scoped(state: &HubState, actor: &OperatorActor, permission: Permission, orbit: Uuid) -> Result<(), StatusCode> {
let resource = AuditResource::Orbit(orbit);
if actor.subject.admin {
return audit(state, actor, resource, true);
}
let held = |permission: Permission| -> Result<bool, StatusCode> {
permission.grantable().then(|| {
state
.db
.has_permission(actor.subject.user_id.as_deref(), &actor.subject.groups, permission.as_str(), &orbit.to_string(), now())
.map_err(internal)
})
.unwrap_or(Ok(false))
};
if !held(Permission::OrbitRead)? {
audit(state, actor, resource, false)?;
return Err(StatusCode::NOT_FOUND);
}
let allowed = held(permission)?;
audit(state, actor, resource, allowed)?;
if allowed { Ok(()) } else { Err(StatusCode::FORBIDDEN) }
}
/// Which orbits a list may show.
pub(super) enum Visible {
All,
Only(HashSet<Uuid>),
}
impl Visible {
pub(super) fn contains(&self, orbit: Uuid) -> bool {
match self {
Self::All => true,
Self::Only(set) => set.contains(&orbit),
}
}
/// SQL-friendly form: `None` = no restriction.
pub(super) fn restriction(&self) -> Option<Vec<String>> {
match self {
Self::All => None,
Self::Only(set) => Some(set.iter().map(Uuid::to_string).collect()),
}
}
}
/// Orbits where the caller holds both `orbit.read` and `permission`. A caller
/// with nothing to see gets 403 rather than an empty list.
pub(super) fn visible(state: &HubState, actor: &OperatorActor, permission: Permission) -> Result<Visible, StatusCode> {
if actor.subject.admin {
audit(state, actor, AuditResource::Api, true)?;
return Ok(Visible::All);
}
let fetch = |permission: Permission| {
if !permission.grantable() {
return Ok(Default::default());
}
state
.db
.permitted_orbits(actor.subject.user_id.as_deref(), &actor.subject.groups, permission.as_str(), now())
.map_err(internal)
};
let read = fetch(Permission::OrbitRead)?;
let wanted = if permission == Permission::OrbitRead { None } else { Some(fetch(permission)?) };
let parse = |set: &HashSet<String>| -> HashSet<Uuid> { set.iter().filter_map(|id| Uuid::parse_str(id).ok()).collect() };
let result = match wanted {
None if read.everywhere => Visible::All,
None => Visible::Only(parse(&read.orbits)),
Some(w) => match (read.everywhere, w.everywhere) {
(true, true) => Visible::All,
(true, false) => Visible::Only(parse(&w.orbits)),
(false, true) => Visible::Only(parse(&read.orbits)),
(false, false) => Visible::Only(parse(&read.orbits).intersection(&parse(&w.orbits)).copied().collect()),
},
};
let nothing = matches!(&result, Visible::Only(set) if set.is_empty());
audit(state, actor, AuditResource::Api, !nothing)?;
if nothing { Err(StatusCode::FORBIDDEN) } else { Ok(result) }
}

View File

@@ -1,4 +1,5 @@
use super::routes::{require_admin, require_admin_mutation, upload_token};
use super::routes::{admin_write, authenticate, upload_token};
use crate::auth::Permission;
use crate::state::HubState;
use axum::{
body::{Body, HttpBody},
@@ -38,8 +39,10 @@ async fn profiles(
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<Json<Vec<CaptureProfile>>, StatusCode> {
require_admin(&state, peer, &headers)?;
state.db.capture_profiles().map(Json).map_err(internal)
let actor = authenticate(&state, peer, &headers, false)?;
let visible = super::gate::visible(&state, &actor, Permission::OrbitRead)?;
let profiles = state.db.capture_profiles().map_err(internal)?;
Ok(Json(profiles.into_iter().filter(|profile| visible.contains(profile.orbit_id)).collect()))
}
async fn register_profile(
@@ -48,7 +51,7 @@ async fn register_profile(
headers: HeaderMap,
Json(profile): Json<CaptureProfile>,
) -> Result<(StatusCode, Json<CaptureProfile>), StatusCode> {
let actor = require_admin_mutation(&state, peer, &headers)?;
let actor = admin_write(&state, peer, &headers)?;
if profile
.retention
.is_some_and(|retention| !retention.is_valid())
@@ -83,10 +86,19 @@ async fn enqueue(
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<(StatusCode, Json<CaptureJob>), StatusCode> {
let actor = require_admin_mutation(&state, peer, &headers)?;
let actor = authenticate(&state, peer, &headers, true)?;
let orbit = state.db.orbit_of_application(id).map_err(internal)?;
match orbit {
Some(orbit) => super::gate::scoped(&state, &actor, Permission::CaptureRun, orbit)?,
// no such application: administrators learn that, everyone else cannot tell it from "not visible"
None => {
super::gate::admin_only(&state, &actor).map_err(|_| StatusCode::NOT_FOUND)?;
return Err(StatusCode::NOT_FOUND);
}
}
let job = state
.db
.enqueue_capture(id, &actor.name, now())
.enqueue_capture(id, &actor.id(), now())
.map_err(internal)?
.ok_or(StatusCode::NOT_FOUND)?;
Ok((StatusCode::ACCEPTED, Json(job)))
@@ -105,7 +117,14 @@ async fn history(
headers: HeaderMap,
Query(filter): Query<JobFilter>,
) -> Result<Json<Vec<CaptureJob>>, StatusCode> {
require_admin(&state, peer, &headers)?;
let actor = authenticate(&state, peer, &headers, false)?;
let visible = super::gate::visible(&state, &actor, Permission::OrbitRead)?;
if let Some(application) = filter.application_id {
let orbit = state.db.orbit_of_application(application).map_err(internal)?;
if !orbit.is_some_and(|orbit| visible.contains(orbit)) {
return Err(StatusCode::NOT_FOUND);
}
}
if filter
.status
.as_deref()
@@ -119,24 +138,36 @@ async fn history(
filter.application_id,
filter.status.as_deref(),
filter.limit.unwrap_or(50).clamp(1, 200),
visible.restriction().as_deref(),
)
.map(Json)
.map_err(internal)
}
/// A capture job, if the caller may read its orbit; otherwise 404.
fn job_in_scope(state: &HubState, actor: &super::routes::OperatorActor, id: Uuid) -> Result<CaptureJob, StatusCode> {
let job = state.db.capture_job(id).map_err(internal)?;
match job {
Some(job) => {
super::gate::scoped(state, actor, Permission::OrbitRead, job.profile.orbit_id)?;
Ok(job)
}
None => {
super::gate::admin_only(state, actor).map_err(|_| StatusCode::NOT_FOUND)?;
Err(StatusCode::NOT_FOUND)
}
}
}
async fn events(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<Json<Vec<CaptureEvent>>, StatusCode> {
require_admin(&state, peer, &headers)?;
state
.db
.capture_job(id)
.map_err(internal)?
.ok_or(StatusCode::NOT_FOUND)?;
state.db.capture_events(id).map(Json).map_err(internal)
let actor = authenticate(&state, peer, &headers, false)?;
let job = job_in_scope(&state, &actor, id)?;
state.db.capture_events(job.id).map(Json).map_err(internal)
}
async fn job(
@@ -145,13 +176,8 @@ async fn job(
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<Json<CaptureJob>, StatusCode> {
require_admin(&state, peer, &headers)?;
state
.db
.capture_job(id)
.map_err(internal)?
.map(Json)
.ok_or(StatusCode::NOT_FOUND)
let actor = authenticate(&state, peer, &headers, false)?;
job_in_scope(&state, &actor, id).map(Json)
}
async fn claim(

View File

@@ -1,4 +1,6 @@
mod access;
mod catalog;
mod gate;
mod jobs;
mod oidc;
mod orbit;
@@ -11,6 +13,8 @@ mod auth_contract;
mod oidc_tests;
#[cfg(test)]
mod credentials_tests;
#[cfg(test)]
mod access_tests;
pub use orbit::run_orbit_internal;
pub use routes::router;

View File

@@ -147,12 +147,14 @@ async fn complete(
}
};
let admin = oidc.config.is_admin(&identity);
// Bounded, so a hostile or huge claim cannot bloat the session row.
let groups: Vec<String> = identity.groups.iter().filter(|g| !g.is_empty() && g.len() <= 128).take(64).cloned().collect();
let now = now();
let session = state
.db
.upsert_user(&identity.issuer, &identity.subject, &identity.display_name, now)
.map_err(anyhow::Error::from)
.and_then(|user_id| state.sessions.create_oidc(&user_id, &identity.display_name, admin, now));
.and_then(|user_id| state.sessions.create_oidc(&user_id, &identity.display_name, admin, &groups, now));
match session {
Ok(session) => {
audit(&session.principal(), AuditOutcome::Succeeded);

View File

@@ -1,6 +1,6 @@
use super::{
jobs::{header_value, internal, now, outpost, receive_payload},
routes::{require_admin, require_admin_mutation},
routes::{admin_read, admin_write},
};
use crate::state::HubState;
use axum::{
@@ -46,7 +46,7 @@ async fn register(
headers: HeaderMap,
Json(target): Json<RestoreTarget>,
) -> Result<(StatusCode, Json<RestoreTarget>), StatusCode> {
let actor = require_admin_mutation(&state, peer, &headers)?;
let actor = admin_write(&state, peer, &headers)?;
if target.name.trim().is_empty()
|| target.name.len() > 128
|| target.name.chars().any(char::is_control)
@@ -84,7 +84,7 @@ async fn targets(
headers: HeaderMap,
Path(application): Path<Uuid>,
) -> Result<Json<Vec<RestoreTarget>>, StatusCode> {
require_admin(&state, peer, &headers)?;
admin_read(&state, peer, &headers)?;
state
.db
.restore_targets(application)
@@ -105,7 +105,7 @@ async fn snapshot_targets(
headers: HeaderMap,
Path(snapshot): Path<Uuid>,
) -> Result<Json<Vec<SnapshotTarget>>, StatusCode> {
require_admin(&state, peer, &headers)?;
admin_read(&state, peer, &headers)?;
let vault = state.vault.read().await;
let snap = vault
.get_snapshot(snapshot)
@@ -137,7 +137,7 @@ async fn enqueue(
headers: HeaderMap,
Json(request): Json<RestoreRequest>,
) -> Result<(StatusCode, Json<RestoreJob>), StatusCode> {
let actor = require_admin_mutation(&state, peer, &headers)?;
let actor = admin_write(&state, peer, &headers)?;
if request.confirmation != RestoreRequest::confirmation(request.snapshot_id, request.target_id)
{
return Err(StatusCode::BAD_REQUEST);
@@ -156,7 +156,7 @@ async fn enqueue(
request.snapshot_id,
application,
request.target_id,
&actor.name,
&actor.id(),
&artifact,
now(),
)
@@ -199,7 +199,7 @@ async fn job(
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<Json<RestoreJob>, StatusCode> {
require_admin(&state, peer, &headers)?;
admin_read(&state, peer, &headers)?;
state
.db
.restore_job(id, now())
@@ -214,7 +214,7 @@ async fn history(
headers: HeaderMap,
Path(snapshot): Path<Uuid>,
) -> Result<Json<Vec<RestoreJob>>, StatusCode> {
require_admin(&state, peer, &headers)?;
admin_read(&state, peer, &headers)?;
state
.db
.restore_history(snapshot, now())
@@ -234,7 +234,7 @@ async fn recent(
headers: HeaderMap,
Query(query): Query<Recent>,
) -> Result<Json<Vec<RestoreJob>>, StatusCode> {
require_admin(&state, peer, &headers)?;
admin_read(&state, peer, &headers)?;
state
.db
.restore_recent(query.limit.unwrap_or(50).clamp(1, 200), now())
@@ -248,10 +248,10 @@ async fn cancel(
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<StatusCode, StatusCode> {
let actor = require_admin_mutation(&state, peer, &headers)?;
let actor = admin_write(&state, peer, &headers)?;
if !state
.db
.cancel_restore(id, &actor.name, now())
.cancel_restore(id, &actor.id(), now())
.map_err(internal)?
{
return Err(StatusCode::CONFLICT);
@@ -271,13 +271,13 @@ async fn reconcile(
Path(id): Path<Uuid>,
Json(body): Json<Reconcile>,
) -> Result<StatusCode, StatusCode> {
let actor = require_admin_mutation(&state, peer, &headers)?;
let actor = admin_write(&state, peer, &headers)?;
if body.confirmation != format!("RECONCILE {id}") {
return Err(StatusCode::BAD_REQUEST);
}
if !state
.db
.reconcile_restore(id, &actor.name, now())
.reconcile_restore(id, &actor.id(), now())
.map_err(internal)?
{
return Err(StatusCode::CONFLICT);

View File

@@ -1,5 +1,5 @@
use crate::db::OrbitRow;
use crate::auth::{AuditAction, AuditOutcome, AuditResource, Principal};
use crate::auth::{AuditAction, AuditOutcome, AuditResource, Permission, Principal, Subject};
use crate::state::{HubState, ManagedRetention};
use crate::upload::write_at;
use axum::{
@@ -238,35 +238,32 @@ struct ReconstituteStartResponse {
}
pub(super) struct OperatorActor {
/// Display only. Never record this as "who did it": an IdP can call a user anything.
pub(super) name: String,
browser: bool,
pub(super) browser: bool,
pub(super) principal: Principal,
request_id: Uuid,
pub(super) subject: Subject,
pub(super) request_id: Uuid,
}
impl OperatorActor {
/// Stable identity for job attribution and audit details (`oidc:<users.id>`, ...).
pub(super) fn id(&self) -> String {
self.principal.fields().0
}
}
impl std::fmt::Display for OperatorActor {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.name.fmt(formatter)
self.id().fmt(formatter)
}
}
pub(super) fn require_admin(
state: &HubState,
peer: SocketAddr,
headers: &HeaderMap,
) -> Result<(), StatusCode> {
authorize_operator(state, peer, headers, false).map(|_| ())
}
pub(super) fn require_admin_mutation(
state: &HubState,
peer: SocketAddr,
headers: &HeaderMap,
) -> Result<OperatorActor, StatusCode> {
authorize_operator(state, peer, headers, true)
}
pub(super) fn authorize_operator(
/// Who is calling, and nothing more: no permission is checked here. A request
/// with no or a wrong credential is 401, a mutation without CSRF is 403. Every
/// handler must then choose a gate from `gate.rs` (`admin_only`, `scoped`,
/// `visible`); there is deliberately no "signed in is enough" path.
pub(super) fn authenticate(
state: &HubState,
peer: SocketAddr,
headers: &HeaderMap,
@@ -275,43 +272,53 @@ pub(super) fn authorize_operator(
let request_id = Uuid::new_v4();
// Resolve the session once: each lookup is a DB query and may slide the idle window.
let session = state.sessions.active(headers);
let attempted_actor = session.as_ref()
.map(|session| session.principal()).unwrap_or(Principal::Anonymous);
let result = authorize_operator_inner(state, peer, headers, mutation, request_id, session);
let actor = result.as_ref().map(|actor| &actor.principal).unwrap_or(&attempted_actor);
state.db.audit_event(actor, AuditAction::Authorization, AuditResource::Api,
if result.is_ok() { AuditOutcome::Allowed } else { AuditOutcome::Denied }, request_id)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let attempted = session.as_ref().map(|s| s.principal()).unwrap_or(Principal::Anonymous);
let result = authenticate_inner(state, peer, headers, mutation, request_id, session);
if result.is_err() {
state.db.audit_event(&attempted, AuditAction::Authentication, AuditResource::Api, AuditOutcome::Denied, request_id)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
}
result
}
fn authorize_operator_inner(
fn authenticate_inner(
state: &HubState, peer: SocketAddr, headers: &HeaderMap, mutation: bool, request_id: Uuid,
session: Option<crate::admin::BrowserSession>,
) -> Result<OperatorActor, StatusCode> {
let configured_admin = |name: &str, principal: Principal| OperatorActor {
name: name.into(), browser: false, principal,
subject: Subject { user_id: None, groups: vec![], admin: true }, request_id,
};
if state.admin.token.is_some() && state.admin.authorize(peer, headers).is_ok() {
return Ok(OperatorActor { name: "api-token".into(), browser: false,
principal: Principal::Service("legacy-admin-token"), request_id });
return Ok(configured_admin("api-token", Principal::Service("legacy-admin-token")));
}
if let Some(session) = session {
// Signed in is not the same as allowed: a user without a grant gets 403.
if !session.admin {
return Err(StatusCode::FORBIDDEN);
}
if mutation {
super::session::require_csrf(headers, &session.csrf.to_string())?;
}
return Ok(OperatorActor { principal: session.principal(),
return Ok(OperatorActor { principal: session.principal(), subject: session.subject(),
name: session.actor, browser: true, request_id });
}
if !state.sessions.enabled() {
state.admin.authorize(peer, headers)?;
return Ok(OperatorActor { name: "local-development".into(), browser: false,
principal: Principal::LocalDevelopment, request_id });
return Ok(configured_admin("local-development", Principal::LocalDevelopment));
}
Err(StatusCode::UNAUTHORIZED)
}
/// Management endpoints that only a configured administrator may use.
pub(super) fn admin_read(state: &HubState, peer: SocketAddr, headers: &HeaderMap) -> Result<OperatorActor, StatusCode> {
let actor = authenticate(state, peer, headers, false)?;
super::gate::admin_only(state, &actor)?;
Ok(actor)
}
pub(super) fn admin_write(state: &HubState, peer: SocketAddr, headers: &HeaderMap) -> Result<OperatorActor, StatusCode> {
let actor = authenticate(state, peer, headers, true)?;
super::gate::admin_only(state, &actor)?;
Ok(actor)
}
pub fn router(state: HubState) -> Router {
let api = Router::new()
.route("/health", get(health))
@@ -340,6 +347,7 @@ pub fn router(state: HubState) -> Router {
.merge(super::catalog::routes())
.merge(super::session::routes())
.merge(super::oidc::routes())
.merge(super::access::routes())
.merge(super::restore::routes())
.with_state(state);
@@ -363,12 +371,14 @@ async fn list_snapshots(
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<Json<Vec<SnapshotSummary>>, StatusCode> {
require_admin(&state, peer, &headers)?;
let actor = authenticate(&state, peer, &headers, false)?;
let visible = super::gate::visible(&state, &actor, Permission::SnapshotRead)?;
let vault = state.vault.read().await;
let snaps = vault.list_snapshots().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let out = snaps
.into_iter()
.filter(|s| s.manifest.provider != "legacy-history")
.filter(|s| visible.contains(s.manifest.orbit_id))
.map(|s| SnapshotSummary {
id: s.id,
orbit_id: s.manifest.orbit_id,
@@ -389,7 +399,8 @@ async fn list_orbits(
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<Json<Vec<OrbitResponse>>, StatusCode> {
require_admin(&state, peer, &headers)?;
let actor = authenticate(&state, peer, &headers, false)?;
let visible = super::gate::visible(&state, &actor, Permission::OrbitRead)?;
let profiles: std::collections::HashMap<_, _> = state
.db
.capture_profiles()
@@ -400,6 +411,7 @@ async fn list_orbits(
let rows = state.db.list_orbits().await.map_err(super::jobs::internal)?;
let responses = rows
.into_iter()
.filter(|row| visible.contains(row.id))
.map(|row| {
let mut response = OrbitResponse::from(row);
if let Some(profile) = profiles.get(&response.id) {
@@ -430,7 +442,7 @@ async fn create_orbit(
headers: HeaderMap,
Json(req): Json<CreateOrbitRequest>,
) -> Result<Json<OrbitResponse>, (StatusCode, &'static str)> {
require_admin_mutation(&state, peer, &headers).map_err(|status| (status, "unauthorized"))?;
admin_write(&state, peer, &headers).map_err(|status| (status, "unauthorized"))?;
if req.name.trim().is_empty() {
return Err((StatusCode::BAD_REQUEST, "orbit name is required"));
}
@@ -523,7 +535,7 @@ async fn update_orbit_retention(
Path(id): Path<Uuid>,
Json(req): Json<RetentionUpdate>,
) -> Result<StatusCode, (StatusCode, &'static str)> {
require_admin_mutation(&state, peer, &headers).map_err(|status| (status, "unauthorized"))?;
admin_write(&state, peer, &headers).map_err(|status| (status, "unauthorized"))?;
if req.decay_preset.is_none() && req.retention.is_none() {
return Err((
StatusCode::BAD_REQUEST,
@@ -553,12 +565,14 @@ async fn trigger_orbit(
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<(StatusCode, HeaderMap), (StatusCode, String)> {
require_admin_mutation(&state, peer, &headers).map_err(|status| (status, "unauthorized".into()))?;
let actor = authenticate(&state, peer, &headers, true).map_err(|status| (status, "unauthorized".into()))?;
let orbit = state.db.list_orbits().await
.map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "could not read orbits".into()))?
.into_iter()
.find(|orbit| orbit.id == id)
.ok_or((StatusCode::NOT_FOUND, "orbit not found".into()))?;
.find(|orbit| orbit.id == id);
// Gate on the id first: unknown and not-visible look the same to a caller without access.
super::gate::scoped(&state, &actor, Permission::CaptureRun, id).map_err(|status| (status, "not permitted".into()))?;
let orbit = orbit.ok_or((StatusCode::NOT_FOUND, "orbit not found".into()))?;
if orbit.provider == "wormhole" {
return Err((StatusCode::CONFLICT, "queue the capture through its Outpost profile or run the legacy agent".into()));
}
@@ -588,7 +602,7 @@ async fn start_reconstitute(
headers: HeaderMap,
Json(req): Json<ReconstituteRequest>,
) -> Result<Json<ReconstituteStartResponse>, StatusCode> {
let actor = require_admin_mutation(&state, peer, &headers)?;
let actor = admin_write(&state, peer, &headers)?;
let destination = if actor.browser {
browser_export_path(&state, &req.target_path)?
} else {
@@ -695,7 +709,7 @@ async fn reconstitute_status(
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<Json<ReconstituteSession>, StatusCode> {
require_admin(&state, peer, &headers)?;
admin_read(&state, peer, &headers)?;
let map = state.reconstitute_sessions.read().await;
map.get(&id).cloned().map(Json).ok_or(StatusCode::NOT_FOUND)
}
@@ -706,7 +720,7 @@ async fn abort_reconstitute(
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<StatusCode, StatusCode> {
require_admin_mutation(&state, peer, &headers)?;
admin_write(&state, peer, &headers)?;
let mut map = state.reconstitute_sessions.write().await;
if let Some(s) = map.get_mut(&id) {
if matches!(
@@ -725,7 +739,7 @@ async fn outposts(
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<Json<Vec<OutpostSummary>>, StatusCode> {
require_admin(&state, peer, &headers)?;
admin_read(&state, peer, &headers)?;
state.db.list_outposts().map(Json).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
}
@@ -735,7 +749,7 @@ async fn pairing_start(
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<Json<PairingResponse>, StatusCode> {
require_admin_mutation(&state, peer, &headers)?;
admin_write(&state, peer, &headers)?;
const ALPHABET: &[u8] = b"23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
let code: String = {
let mut random = rand::thread_rng();
@@ -832,7 +846,7 @@ async fn rotate_outpost_token(
Path(id): Path<Uuid>,
axum::extract::Query(query): axum::extract::Query<RotateQuery>,
) -> Result<(HeaderMap, Json<RotateResponse>), StatusCode> {
let actor = require_admin_mutation(&state, peer, &headers)?;
let actor = admin_write(&state, peer, &headers)?;
let grace = query.grace_minutes.unwrap_or(60);
if !(0..=1440).contains(&grace) {
return Err(StatusCode::BAD_REQUEST);
@@ -872,7 +886,7 @@ async fn revoke_outpost(
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<StatusCode, StatusCode> {
let actor = require_admin_mutation(&state, peer, &headers)?;
let actor = admin_write(&state, peer, &headers)?;
let known = state
.db
.revoke_outpost(&id.to_string(), chrono::Utc::now().timestamp())
@@ -901,7 +915,7 @@ async fn bind_outpost(
Path(orbit): Path<Uuid>,
Json(binding): Json<OutpostBinding>,
) -> Result<StatusCode, StatusCode> {
let actor = require_admin_mutation(&state, peer, &headers)?;
let actor = admin_write(&state, peer, &headers)?;
let _vault = state.vault.write().await;
if !state.db.bind_legacy_outpost(orbit, binding.outpost_id)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? {

View File

@@ -15,6 +15,7 @@ struct Status {
login_enabled: bool,
oidc_enabled: bool,
authorized: bool,
admin: bool,
actor: Option<String>,
csrf: Option<String>,
expires_at: Option<i64>,
@@ -31,6 +32,7 @@ pub(super) fn routes() -> Router<HubState> {
.route("/api/v1/operator/session", get(status).delete(logout))
.route("/api/v1/operator/login", post(login))
.route("/api/v1/me", get(me))
.route("/api/v1/me/preferences", get(preferences).put(set_preferences))
}
async fn status(
@@ -39,7 +41,15 @@ async fn status(
headers: HeaderMap,
) -> (HeaderMap, Json<Status>) {
let browser = state.sessions.active(&headers);
let authorized = browser.as_ref().is_some_and(|session| session.admin)
// The app opens for an administrator or for anyone holding a live grant that lets them read an orbit.
let reads_something = browser.as_ref().is_some_and(|session| {
!session.admin
&& state
.db
.permitted_orbits(Some(&session.user_id), &session.groups, "orbit.read", chrono::Utc::now().timestamp())
.is_ok_and(|p| p.everywhere || !p.orbits.is_empty())
});
let authorized = browser.as_ref().is_some_and(|session| session.admin) || reads_something
|| (browser.is_none() && !state.sessions.enabled() && state.admin.token.is_none()
&& state.admin.authorize(peer, &headers).is_ok());
(
@@ -48,6 +58,7 @@ async fn status(
login_enabled: state.sessions.password_enabled(),
oidc_enabled: state.oidc.is_some(),
authorized,
admin: browser.as_ref().map_or(authorized, |session| session.admin),
actor: browser.as_ref().map(|session| session.actor.clone()),
expires_at: browser.as_ref().map(|session| session.expires_at),
csrf: browser.map(|session| session.csrf.to_string()),
@@ -55,13 +66,22 @@ async fn status(
)
}
#[derive(Serialize)]
struct MyGrant {
permission: String,
/// `None` = every orbit.
orbit_id: Option<String>,
}
#[derive(Serialize)]
struct Me {
id: String,
kind: &'static str,
auth_method: &'static str,
display_name: String,
capabilities: Vec<&'static str>,
admin: bool,
capabilities: Vec<String>,
grants: Vec<MyGrant>,
}
/// The caller's own identity. Every authenticated principal is an administrator
@@ -71,20 +91,81 @@ async fn me(
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<(HeaderMap, Json<Me>), StatusCode> {
// A signed-in user without a grant still gets their identity (capabilities empty).
if let Some(session) = state.sessions.active(&headers) {
let (id, kind, auth_method) = session.principal().fields();
let capabilities = if session.admin { vec!["admin"] } else { vec![] };
return Ok((no_store(), Json(Me { id, kind, auth_method, display_name: session.actor, capabilities })));
}
let actor = super::routes::authorize_operator(&state, peer, &headers, false)?;
// Identity only, no gate: a signed-in user without any grant still gets this (empty grants).
let actor = super::routes::authenticate(&state, peer, &headers, false)?;
let (id, kind, auth_method) = actor.principal.fields();
let grants: Vec<MyGrant> = if actor.subject.admin {
vec![]
} else {
state
.db
.grants_of(actor.subject.user_id.as_deref(), &actor.subject.groups, chrono::Utc::now().timestamp())
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.into_iter()
.map(|(permission, orbit_id)| MyGrant { permission, orbit_id })
.collect()
};
let mut capabilities: Vec<String> = if actor.subject.admin {
vec!["admin".into()]
} else {
let mut names: Vec<String> = grants.iter().map(|g| g.permission.clone()).collect();
names.dedup();
names
};
capabilities.sort();
Ok((
no_store(),
Json(Me { id, kind, auth_method, display_name: actor.name.clone(), capabilities: vec!["admin"] }),
Json(Me { id, kind, auth_method, display_name: actor.name.clone(), admin: actor.subject.admin, capabilities, grants }),
))
}
/// Display choices an account keeps across browsers. Every key has a closed set of values.
const LOOKS: [&str; 2] = ["window", "radar"];
#[derive(Serialize)]
struct Preferences {
look: Option<String>,
}
/// The caller's own preferences. A caller without an account (the legacy token, local
/// development) simply has none.
async fn preferences(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<(HeaderMap, Json<Preferences>), StatusCode> {
let actor = super::routes::authenticate(&state, peer, &headers, false)?;
let stored = match actor.subject.user_id.as_deref() {
Some(user) => state.db.preferences(user).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
None => Default::default(),
};
let look = stored.get("look").filter(|value| LOOKS.contains(&value.as_str())).cloned();
Ok((no_store(), Json(Preferences { look })))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SetPreferences {
look: Option<String>,
}
async fn set_preferences(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Json(body): Json<SetPreferences>,
) -> Result<StatusCode, StatusCode> {
let actor = super::routes::authenticate(&state, peer, &headers, true)?;
let user = actor.subject.user_id.as_deref().ok_or(StatusCode::NOT_FOUND)?;
if let Some(look) = body.look {
if !LOOKS.contains(&look.as_str()) {
return Err(StatusCode::BAD_REQUEST);
}
state.db.set_preference(user, "look", &look, chrono::Utc::now().timestamp()).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
}
Ok(StatusCode::NO_CONTENT)
}
async fn login(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
@@ -133,6 +214,7 @@ async fn login(
login_enabled: true,
oidc_enabled: state.oidc.is_some(),
authorized: true,
admin: true,
actor: Some(session.actor),
expires_at: Some(session.expires_at),
csrf: Some(session.csrf.to_string()),

View File

@@ -34,6 +34,10 @@ pub enum AuditAction {
OutpostPair,
CredentialRotate,
CredentialRevoke,
GrantCreate,
GrantDelete,
UserState,
SessionsRevoke,
}
impl AuditAction {
@@ -47,6 +51,10 @@ impl AuditAction {
Self::OutpostPair => "outpost.pair",
Self::CredentialRotate => "outpost.credential_rotate",
Self::CredentialRevoke => "outpost.credential_revoke",
Self::GrantCreate => "access.grant_create",
Self::GrantDelete => "access.grant_delete",
Self::UserState => "access.user_state",
Self::SessionsRevoke => "access.sessions_revoke",
}
}
}
@@ -75,6 +83,8 @@ pub enum AuditResource {
Orbit(Uuid),
Outpost(Uuid),
UploadSession(Uuid),
Grant(Uuid),
User(Uuid),
}
impl AuditResource {
@@ -85,6 +95,82 @@ impl AuditResource {
Self::Orbit(id) => ("orbit", Some(id.to_string())),
Self::Outpost(id) => ("outpost", Some(id.to_string())),
Self::UploadSession(id) => ("upload_session", Some(id.to_string())),
Self::Grant(id) => ("grant", Some(id.to_string())),
Self::User(id) => ("user", Some(id.to_string())),
}
}
}
/// What a signed-in user may do. Only the first four can be granted to a
/// non-administrator; everything else belongs to the configured administrators
/// (SSO admin mapping, the emergency operator, the legacy admin token). Names are
/// matched exactly, never by prefix.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum Permission {
OrbitRead,
SnapshotRead,
CaptureRun,
SnapshotDownload,
OrbitManage,
OutpostManage,
RetentionManage,
SnapshotDelete,
RecoveryManage,
AccessManage,
}
impl Permission {
pub fn as_str(self) -> &'static str {
match self {
Self::OrbitRead => "orbit.read",
Self::SnapshotRead => "snapshot.read",
Self::CaptureRun => "capture.run",
Self::SnapshotDownload => "snapshot.download",
Self::OrbitManage => "orbit.manage",
Self::OutpostManage => "outpost.manage",
Self::RetentionManage => "retention.manage",
Self::SnapshotDelete => "snapshot.delete",
Self::RecoveryManage => "recovery.manage",
Self::AccessManage => "access.manage",
}
}
pub fn parse(text: &str) -> Option<Self> {
[
Self::OrbitRead, Self::SnapshotRead, Self::CaptureRun, Self::SnapshotDownload, Self::OrbitManage,
Self::OutpostManage, Self::RetentionManage, Self::SnapshotDelete, Self::RecoveryManage, Self::AccessManage,
]
.into_iter()
.find(|permission| permission.as_str() == text)
}
/// May be given to a non-administrator through a grant.
pub fn grantable(self) -> bool {
matches!(self, Self::OrbitRead | Self::SnapshotRead | Self::CaptureRun | Self::SnapshotDownload)
}
}
/// Named bundles that expand into individual grants. Every bundle includes
/// `orbit.read`: without it a resource is invisible and answers 404.
pub fn role(name: &str) -> Option<&'static [Permission]> {
use Permission::*;
match name {
"viewer" => Some(&[OrbitRead, SnapshotRead]),
"capturer" => Some(&[OrbitRead, SnapshotRead, CaptureRun]),
"downloader" => Some(&[OrbitRead, SnapshotRead, SnapshotDownload]),
_ => None,
}
}
pub const ROLE_NAMES: [&str; 3] = ["viewer", "capturer", "downloader"];
/// Who is asking, as far as authorization is concerned.
#[derive(Clone, Debug)]
pub struct Subject {
/// `users.id` for signed-in users; `None` for the legacy token and local development.
pub user_id: Option<String>,
/// Groups verified at sign-in. Changes at the IdP apply at the next sign-in.
pub groups: Vec<String>,
/// Configured administrator: holds every permission everywhere.
pub admin: bool,
}

View File

@@ -4,6 +4,7 @@ mod audit;
pub mod sessions;
pub(crate) mod oidc_login;
pub(crate) mod credentials;
pub(crate) mod access;
pub(crate) use restore::restore_target_mismatch;
use anyhow::Result;
@@ -97,6 +98,7 @@ impl Db {
audit::migrate(&conn)?;
sessions::migrate(&conn)?;
oidc_login::migrate(&conn)?;
access::migrate(&conn)?;
Ok(())
}

View File

@@ -0,0 +1,329 @@
//! Grants: which permission a user (or an IdP group) holds, globally or on one orbit.
//!
//! Grants are read live on every request, never cached, so a revoke or an expiry
//! is effective on the very next request. Anything stored that does not parse as a
//! known permission or scope is ignored by the gate.
use super::*;
use std::collections::HashSet;
#[derive(Clone, Debug, serde::Serialize)]
pub struct Grant {
pub id: String,
pub principal_type: String,
pub principal: String,
pub permission: String,
pub scope_type: String,
pub scope_id: Option<String>,
pub expires_at: Option<i64>,
pub created_by: String,
pub created_at: i64,
}
pub struct NewGrant<'a> {
pub principal_type: &'a str,
pub principal: &'a str,
pub permission: &'a str,
pub orbit: Option<&'a str>,
pub expires_at: Option<i64>,
pub created_by: &'a str,
}
/// Orbits a subject may use for one permission.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Permitted {
pub everywhere: bool,
pub orbits: HashSet<String>,
}
#[derive(Clone, Debug, serde::Serialize)]
pub struct UserRow {
pub id: String,
pub issuer: String,
pub display_name: String,
pub active: bool,
pub created_at: i64,
pub last_login_at: Option<i64>,
pub is_emergency: bool,
}
pub(super) fn migrate(conn: &Connection) -> Result<()> {
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS access_grants (
id TEXT PRIMARY KEY,
principal_type TEXT NOT NULL CHECK(principal_type IN ('user','group')),
principal TEXT NOT NULL,
permission TEXT NOT NULL,
scope_type TEXT NOT NULL CHECK(scope_type IN ('global','orbit')),
scope_id TEXT NOT NULL DEFAULT '',
expires_at INTEGER,
created_by TEXT NOT NULL,
created_at INTEGER NOT NULL,
UNIQUE(principal_type, principal, permission, scope_type, scope_id)
);
CREATE INDEX IF NOT EXISTS access_grants_principal ON access_grants(principal_type, principal);
CREATE TABLE IF NOT EXISTS user_preferences (
user_id TEXT NOT NULL,
key TEXT NOT NULL,
value TEXT NOT NULL,
updated_at INTEGER NOT NULL,
PRIMARY KEY(user_id, key)
);",
)?;
Ok(())
}
const LIVE: &str = "(expires_at IS NULL OR expires_at > ?2)
AND ((principal_type='user' AND principal=?3) OR (principal_type='group' AND principal IN (SELECT value FROM json_each(?4))))";
fn groups_json(groups: &[String]) -> String {
serde_json::to_string(groups).unwrap_or_else(|_| "[]".into())
}
impl Db {
/// Insert one grant; `None` when an identical grant already exists.
pub fn add_grant(&self, grant: &NewGrant<'_>, now: i64) -> Result<Option<Grant>> {
let conn = self.conn.lock().unwrap();
let id = Uuid::new_v4().to_string();
let (scope_type, scope_id) = match grant.orbit {
Some(orbit) => ("orbit", orbit),
None => ("global", ""),
};
let inserted = conn.execute(
"INSERT OR IGNORE INTO access_grants(id,principal_type,principal,permission,scope_type,scope_id,expires_at,created_by,created_at)
VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9)",
params![id, grant.principal_type, grant.principal, grant.permission, scope_type, scope_id, grant.expires_at, grant.created_by, now],
)?;
Ok((inserted == 1).then(|| Grant {
id,
principal_type: grant.principal_type.into(),
principal: grant.principal.into(),
permission: grant.permission.into(),
scope_type: scope_type.into(),
scope_id: grant.orbit.map(str::to_string),
expires_at: grant.expires_at,
created_by: grant.created_by.into(),
created_at: now,
}))
}
pub fn delete_grant(&self, id: &str) -> Result<bool> {
Ok(self.conn.lock().unwrap().execute("DELETE FROM access_grants WHERE id=?1", params![id])? == 1)
}
pub fn list_grants(&self) -> Result<Vec<Grant>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT id,principal_type,principal,permission,scope_type,scope_id,expires_at,created_by,created_at
FROM access_grants ORDER BY principal_type, principal, scope_type, scope_id, permission",
)?;
let rows = stmt.query_map([], |r| {
let scope_type: String = r.get(4)?;
let scope_id: String = r.get(5)?;
Ok(Grant {
id: r.get(0)?,
principal_type: r.get(1)?,
principal: r.get(2)?,
permission: r.get(3)?,
scope_id: (scope_type == "orbit").then_some(scope_id),
scope_type,
expires_at: r.get(6)?,
created_by: r.get(7)?,
created_at: r.get(8)?,
})
})?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
/// Does the subject hold `permission` on `orbit` (a global grant counts)?
pub fn has_permission(&self, user: Option<&str>, groups: &[String], permission: &str, orbit: &str, now: i64) -> Result<bool> {
let conn = self.conn.lock().unwrap();
Ok(conn.query_row(
&format!(
"SELECT EXISTS(SELECT 1 FROM access_grants WHERE permission=?1 AND {LIVE}
AND (scope_type='global' OR (scope_type='orbit' AND scope_id=?5)))"
),
params![permission, now, user, groups_json(groups), orbit],
|r| r.get(0),
)?)
}
pub fn permitted_orbits(&self, user: Option<&str>, groups: &[String], permission: &str, now: i64) -> Result<Permitted> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(&format!(
"SELECT scope_type, scope_id FROM access_grants WHERE permission=?1 AND {LIVE}"
))?;
let rows = stmt.query_map(params![permission, now, user, groups_json(groups)], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
let mut out = Permitted::default();
for row in rows {
let (scope, id) = row?;
if scope == "global" {
out.everywhere = true;
} else {
out.orbits.insert(id);
}
}
Ok(out)
}
/// Live grants of one subject, for `/me`.
pub fn grants_of(&self, user: Option<&str>, groups: &[String], now: i64) -> Result<Vec<(String, Option<String>)>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(&format!(
"SELECT permission, scope_type, scope_id FROM access_grants WHERE (expires_at IS NULL OR expires_at > ?1)
AND ((principal_type='user' AND principal=?2) OR (principal_type='group' AND principal IN (SELECT value FROM json_each(?3))))
ORDER BY permission, scope_id"
).replace("?1", "?1"))?;
let rows = stmt.query_map(params![now, user, groups_json(groups)], |r| {
let scope_type: String = r.get(1)?;
let scope_id: String = r.get(2)?;
Ok((r.get::<_, String>(0)?, (scope_type == "orbit").then_some(scope_id)))
})?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
pub fn list_users(&self) -> Result<Vec<UserRow>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare("SELECT id,issuer,display_name,active,created_at,last_login_at FROM users ORDER BY display_name, id")?;
let rows = stmt.query_map([], |r| {
let issuer: String = r.get(1)?;
Ok(UserRow {
id: r.get(0)?,
is_emergency: issuer == crate::admin::EMERGENCY_ISSUER,
issuer,
display_name: r.get(2)?,
active: r.get::<_, i64>(3)? == 1,
created_at: r.get(4)?,
last_login_at: r.get(5)?,
})
})?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
pub fn user_exists(&self, id: &str) -> Result<bool> {
Ok(self.conn.lock().unwrap().query_row("SELECT EXISTS(SELECT 1 FROM users WHERE id=?1)", params![id], |r| r.get(0))?)
}
/// Enable or disable a user. Disabling also ends every session at once.
pub fn set_user_active(&self, id: &str, active: bool) -> Result<bool> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction()?;
let changed = tx.execute("UPDATE users SET active=?2, generation=generation+1 WHERE id=?1", params![id, active])? == 1;
if changed && !active {
tx.execute("DELETE FROM sessions WHERE user_id=?1", params![id])?;
}
tx.commit()?;
Ok(changed)
}
/// Per-account display preferences (for example the Window/Radar view).
pub fn preferences(&self, user: &str) -> Result<std::collections::BTreeMap<String, String>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare("SELECT key, value FROM user_preferences WHERE user_id=?1")?;
let rows = stmt.query_map(params![user], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
pub fn set_preference(&self, user: &str, key: &str, value: &str, now: i64) -> Result<()> {
self.conn.lock().unwrap().execute(
"INSERT INTO user_preferences(user_id,key,value,updated_at) VALUES (?1,?2,?3,?4)
ON CONFLICT(user_id,key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at",
params![user, key, value, now],
)?;
Ok(())
}
pub fn orbit_exists(&self, id: &str) -> Result<bool> {
Ok(self.conn.lock().unwrap().query_row("SELECT EXISTS(SELECT 1 FROM orbits WHERE id=?1)", params![id], |r| r.get(0))?)
}
/// The orbit an application (capture profile) belongs to.
pub fn orbit_of_application(&self, application: Uuid) -> Result<Option<Uuid>> {
let conn = self.conn.lock().unwrap();
let orbit: Option<String> = conn
.query_row("SELECT orbit_id FROM capture_profiles WHERE application_id=?1", params![application.to_string()], |r| r.get(0))
.optional()?;
Ok(orbit.and_then(|id| Uuid::parse_str(&id).ok()))
}
}
#[cfg(test)]
mod tests {
use super::*;
async fn db() -> (tempfile::TempDir, Db) {
let dir = tempfile::tempdir().unwrap();
let db = Db::connect(&dir.path().join("t.db")).await.unwrap();
db.migrate().await.unwrap();
(dir, db)
}
fn grant<'a>(kind: &'a str, who: &'a str, permission: &'a str, orbit: Option<&'a str>, expires: Option<i64>) -> NewGrant<'a> {
NewGrant { principal_type: kind, principal: who, permission, orbit, expires_at: expires, created_by: "test" }
}
#[tokio::test]
async fn a_grant_applies_to_its_user_scope_and_permission_only() {
let (_d, db) = db().await;
db.add_grant(&grant("user", "u1", "orbit.read", Some("orbit-a"), None), 10).unwrap().unwrap();
let has = |user: &str, perm: &str, orbit: &str| db.has_permission(Some(user), &[], perm, orbit, 20).unwrap();
assert!(has("u1", "orbit.read", "orbit-a"));
assert!(!has("u1", "orbit.read", "orbit-b"), "other orbit");
assert!(!has("u1", "snapshot.read", "orbit-a"), "other permission");
assert!(!has("u2", "orbit.read", "orbit-a"), "other user");
assert!(!has("u1", "orbit.", "orbit-a") && !has("u1", "orbit", "orbit-a"), "never by prefix");
assert!(!db.has_permission(None, &[], "orbit.read", "orbit-a", 20).unwrap(), "no user, no groups");
}
#[tokio::test]
async fn a_global_grant_covers_every_orbit_and_a_group_grant_covers_its_members() {
let (_d, db) = db().await;
db.add_grant(&grant("group", "qa", "capture.run", None, None), 10).unwrap().unwrap();
let qa = vec!["qa".to_string()];
assert!(db.has_permission(Some("anyone"), &qa, "capture.run", "any-orbit", 11).unwrap());
assert!(!db.has_permission(Some("anyone"), &["devs".to_string()], "capture.run", "any-orbit", 11).unwrap());
assert!(!db.has_permission(Some("anyone"), &[], "capture.run", "any-orbit", 11).unwrap(), "claim missing = no groups");
let p = db.permitted_orbits(Some("anyone"), &qa, "capture.run", 11).unwrap();
assert!(p.everywhere && p.orbits.is_empty());
}
#[tokio::test]
async fn expired_and_deleted_grants_stop_applying_on_the_next_check() {
let (_d, db) = db().await;
let timed = db.add_grant(&grant("user", "u1", "orbit.read", Some("o"), Some(100)), 10).unwrap().unwrap();
assert!(db.has_permission(Some("u1"), &[], "orbit.read", "o", 99).unwrap());
assert!(!db.has_permission(Some("u1"), &[], "orbit.read", "o", 100).unwrap(), "expiry is exclusive");
let forever = db.add_grant(&grant("user", "u1", "snapshot.read", Some("o"), None), 10).unwrap().unwrap();
assert!(db.has_permission(Some("u1"), &[], "snapshot.read", "o", 1_000_000).unwrap());
assert!(db.delete_grant(&forever.id).unwrap());
assert!(!db.has_permission(Some("u1"), &[], "snapshot.read", "o", 11).unwrap(), "revoked at once");
assert!(!db.delete_grant(&forever.id).unwrap());
let _ = timed;
}
#[tokio::test]
async fn duplicates_are_ignored_and_the_list_filters_by_permission() {
let (_d, db) = db().await;
assert!(db.add_grant(&grant("user", "u1", "orbit.read", Some("a"), None), 1).unwrap().is_some());
assert!(db.add_grant(&grant("user", "u1", "orbit.read", Some("a"), None), 2).unwrap().is_none());
db.add_grant(&grant("user", "u1", "orbit.read", Some("b"), None), 1).unwrap();
db.add_grant(&grant("user", "u1", "capture.run", Some("c"), None), 1).unwrap();
let p = db.permitted_orbits(Some("u1"), &[], "orbit.read", 5).unwrap();
assert!(!p.everywhere);
assert_eq!(p.orbits, ["a".to_string(), "b".to_string()].into_iter().collect());
assert_eq!(db.list_grants().unwrap().len(), 3);
assert_eq!(db.grants_of(Some("u1"), &[], 5).unwrap().len(), 3);
}
#[tokio::test]
async fn disabling_a_user_ends_their_sessions_and_blocks_new_ones() {
let (_d, db) = db().await;
let user = db.upsert_user("https://idp.example", "sub", "Sam", 1).unwrap();
db.create_session("s1", &user, "oidc", None, false, &[], 1).unwrap();
assert!(db.set_user_active(&user, false).unwrap());
assert!(db.lookup_session("s1", 2).unwrap().is_none());
assert!(!db.create_session("s2", &user, "oidc", None, false, &[], 2).unwrap());
assert!(db.set_user_active(&user, true).unwrap());
assert!(db.create_session("s3", &user, "oidc", None, false, &[], 3).unwrap());
assert!(!db.set_user_active("missing", false).unwrap());
}
}

View File

@@ -176,14 +176,20 @@ impl Db {
application: Option<Uuid>,
status: Option<&str>,
limit: u16,
orbits: Option<&[String]>,
) -> Result<Vec<CaptureJob>> {
let conn = self.conn.lock().unwrap();
// The orbit restriction is part of the query, before LIMIT, so a restricted
// caller still gets a full page of their own jobs.
let mut stmt = conn.prepare(&format!(
"{JOB_VIEW} WHERE (?1 IS NULL OR j.application_id = ?1) AND (?2 IS NULL OR j.status = ?2)
AND (?4 IS NULL OR j.application_id IN (
SELECT application_id FROM capture_profiles WHERE orbit_id IN (SELECT value FROM json_each(?4))))
ORDER BY j.created_at DESC, j.rowid DESC LIMIT ?3"
))?;
let restriction = orbits.map(|ids| serde_json::to_string(ids)).transpose()?;
let rows = stmt.query_map(
params![application.map(|id| id.to_string()), status, limit],
params![application.map(|id| id.to_string()), status, limit, restriction],
read_job,
)?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
@@ -633,17 +639,17 @@ mod tests {
}
let tick = crate::scheduler::tick_capture_schedules;
tick(&db, registered).unwrap();
assert!(db.capture_jobs(None, None, 100).unwrap().is_empty());
assert!(db.capture_jobs(None, None, 100, None).unwrap().is_empty());
let now = Utc.with_ymd_and_hms(2026, 11, 8, 19, 5, 0).unwrap();
tick(&db, now).unwrap();
drop(db);
let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap();
tick(&db, now).unwrap();
let all = db.capture_jobs(None, Some("queued"), 100).unwrap();
let all = db.capture_jobs(None, Some("queued"), 100, None).unwrap();
assert_eq!(all.len(), 4);
let history = db
.capture_jobs(Some(a.application_id), Some("queued"), 100)
.capture_jobs(Some(a.application_id), Some("queued"), 100, None)
.unwrap();
assert_eq!(history.len(), 2);
assert!(history.iter().all(|job| job.actor == "scheduler"));
@@ -669,7 +675,7 @@ mod tests {
.unwrap());
}
let failed = db
.capture_jobs(Some(a.application_id), Some("failed"), 100)
.capture_jobs(Some(a.application_id), Some("failed"), 100, None)
.unwrap();
assert_eq!(failed.len(), 1);
let events = db.capture_events(first.job_id).unwrap();

View File

@@ -28,6 +28,8 @@ pub struct StoredSession {
pub auth_method: String,
pub credential_fp: Option<String>,
pub admin: bool,
/// Groups verified at sign-in (JSON in the table).
pub groups: Vec<String>,
pub expires_at: i64,
}
@@ -60,6 +62,7 @@ pub(super) fn migrate(conn: &Connection) -> Result<()> {
)?;
// Added after the first M2 build; default 0 keeps old rows without admin rights.
super::ensure_column(conn, "sessions", "admin", "INTEGER NOT NULL DEFAULT 0")?;
super::ensure_column(conn, "sessions", "groups", "TEXT NOT NULL DEFAULT '[]'")?;
Ok(())
}
@@ -89,14 +92,15 @@ impl Db {
auth_method: &str,
credential_fp: Option<&str>,
admin: bool,
groups: &[String],
now: i64,
) -> Result<bool> {
let conn = self.conn.lock().unwrap();
conn.execute("DELETE FROM sessions WHERE expires_at <= ?1 OR last_seen + ?2 <= ?1", params![now, IDLE_SECS])?;
let inserted = conn.execute(
"INSERT INTO sessions(token_digest,user_id,generation,auth_method,credential_fp,auth_time,created_at,last_seen,expires_at,admin)
SELECT ?1, id, generation, ?3, ?4, ?5, ?5, ?5, ?6, ?7 FROM users WHERE id=?2 AND active=1",
params![session_digest(id), user_id, auth_method, credential_fp, now, now + ABSOLUTE_SECS, admin],
"INSERT INTO sessions(token_digest,user_id,generation,auth_method,credential_fp,auth_time,created_at,last_seen,expires_at,admin,groups)
SELECT ?1, id, generation, ?3, ?4, ?5, ?5, ?5, ?6, ?7, ?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)?],
)?;
Ok(inserted == 1)
}
@@ -109,7 +113,7 @@ impl Db {
let conn = self.conn.lock().unwrap();
let found: Option<(StoredSession, i64)> = conn
.query_row(
"SELECT s.user_id,u.display_name,s.auth_method,s.credential_fp,s.expires_at,s.last_seen,s.admin
"SELECT s.user_id,u.display_name,s.auth_method,s.credential_fp,s.expires_at,s.last_seen,s.admin,s.groups
FROM sessions s JOIN users u ON u.id=s.user_id
WHERE s.token_digest=?1 AND u.active=1 AND s.generation=u.generation
AND s.expires_at>?2 AND s.last_seen+?3>?2",
@@ -123,6 +127,7 @@ impl Db {
credential_fp: row.get(3)?,
expires_at: row.get(4)?,
admin: row.get(6)?,
groups: serde_json::from_str(&row.get::<_, String>(7)?).unwrap_or_default(),
},
row.get(5)?,
))
@@ -141,8 +146,6 @@ impl Db {
Ok(())
}
/// Used by the per-user revoke endpoint planned for M5 (admin).
#[allow(dead_code)]
/// Invalidate every session of a user, including any created concurrently
/// from the previous generation. Returns the number of rows removed.
pub fn revoke_user_sessions(&self, user_id: &str) -> Result<usize> {
@@ -180,13 +183,13 @@ mod tests {
async fn idle_and_absolute_deadlines_use_the_supplied_clock() {
let (_dir, db) = db().await;
let user = db.upsert_user("local:emergency", "ops", "ops", 1000).unwrap();
assert!(db.create_session("a", &user, "password", Some("fp"), true, 1000).unwrap());
assert!(db.create_session("a", &user, "password", Some("fp"), true, &[], 1000).unwrap());
assert!(db.lookup_session("a", 1000 + IDLE_SECS - 1).unwrap().is_some());
// sliding: the touch above moved last_seen, so a request just inside the
// new idle window is still fine, one beyond it is not
assert!(db.lookup_session("a", 1000 + 2 * IDLE_SECS - 2).unwrap().is_some());
assert!(db.lookup_session("a", 1000 + 3 * IDLE_SECS).unwrap().is_none());
assert!(db.create_session("b", &user, "password", None, true, 5000).unwrap());
assert!(db.create_session("b", &user, "password", None, true, &[], 5000).unwrap());
let mut now = 5000;
while now + IDLE_SECS - 10 < 5000 + ABSOLUTE_SECS {
now += IDLE_SECS - 10;
@@ -200,7 +203,7 @@ mod tests {
async fn only_a_digest_is_stored_and_csrf_is_not_the_key() {
let (_dir, db) = db().await;
let user = db.upsert_user("local:emergency", "ops", "ops", 1).unwrap();
db.create_session("raw-session-id", &user, "password", None, true, 1).unwrap();
db.create_session("raw-session-id", &user, "password", None, true, &[], 1).unwrap();
let conn = db.conn.lock().unwrap();
let key: String = conn.query_row("SELECT token_digest FROM sessions", [], |r| r.get(0)).unwrap();
assert_ne!(key, "raw-session-id");
@@ -216,7 +219,7 @@ mod tests {
async fn revoked_sessions_cannot_be_resurrected_by_a_late_touch() {
let (_dir, db) = db().await;
let user = db.upsert_user("local:emergency", "ops", "ops", 1000).unwrap();
db.create_session("a", &user, "password", None, true, 1000).unwrap();
db.create_session("a", &user, "password", None, true, &[], 1000).unwrap();
db.revoke_session("a").unwrap();
assert!(db.lookup_session("a", 1000 + 2 * TOUCH_AFTER_SECS).unwrap().is_none());
assert_eq!(db.session_rows(), 0);
@@ -228,14 +231,14 @@ mod tests {
let one = db.upsert_user("https://idp.example", "alice", "Alice", 10).unwrap();
let two = db.upsert_user("https://idp.example", "bob", "Bob", 10).unwrap();
for id in ["a1", "a2"] {
db.create_session(id, &one, "oidc", None, true, 10).unwrap();
db.create_session(id, &one, "oidc", None, true, &[], 10).unwrap();
}
db.create_session("b1", &two, "oidc", None, true, 10).unwrap();
db.create_session("b1", &two, "oidc", None, true, &[], 10).unwrap();
assert_eq!(db.revoke_user_sessions(&one).unwrap(), 2);
assert!(db.lookup_session("a1", 11).unwrap().is_none());
assert!(db.lookup_session("a2", 11).unwrap().is_none());
assert!(db.lookup_session("b1", 11).unwrap().is_some());
assert!(db.create_session("a3", &one, "oidc", None, true, 12).unwrap());
assert!(db.create_session("a3", &one, "oidc", None, true, &[], 12).unwrap());
assert!(db.lookup_session("a3", 13).unwrap().is_some());
}
@@ -243,11 +246,11 @@ mod tests {
async fn inactive_users_have_no_valid_or_new_sessions() {
let (_dir, db) = db().await;
let user = db.upsert_user("https://idp.example", "carol", "Carol", 10).unwrap();
db.create_session("c1", &user, "oidc", None, true, 10).unwrap();
db.create_session("c1", &user, "oidc", None, true, &[], 10).unwrap();
db.conn.lock().unwrap().execute("UPDATE users SET active=0 WHERE id=?1", params![user]).unwrap();
assert!(db.lookup_session("c1", 11).unwrap().is_none());
assert!(!db.create_session("c2", &user, "oidc", None, true, 11).unwrap());
assert!(!db.create_session("c3", "no-such-user", "oidc", None, true, 11).unwrap());
assert!(!db.create_session("c2", &user, "oidc", None, true, &[], 11).unwrap());
assert!(!db.create_session("c3", "no-such-user", "oidc", None, true, &[], 11).unwrap());
}
#[tokio::test]
@@ -270,8 +273,8 @@ mod tests {
let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap();
let user = db.upsert_user("local:emergency", "ops", "ops", 1000).unwrap();
db.create_session("live", &user, "password", Some("fp"), true, 1000).unwrap();
db.create_session("old", &user, "password", Some("fp"), true, 1000).unwrap();
db.create_session("live", &user, "password", Some("fp"), true, &[], 1000).unwrap();
db.create_session("old", &user, "password", Some("fp"), true, &[], 1000).unwrap();
}
let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap();