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

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