//! 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, csrf: Option, user_id: Option, } 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 { world_with(None).await } async fn world_with(exports: Option) -> World { let dir = tempfile::tempdir().unwrap(); let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault").await.unwrap(); if let Some(gate) = exports { state.exports = std::sync::Arc::new(gate); } 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 = 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) { self.grant("user", user, role_name, orbit); } fn grant(&self, kind: &str, principal: &str, role_name: &str, orbit: Option) { 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) -> (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::().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 { 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) { 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 { let pick = |path: &[&str]| -> Vec { 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::().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); } #[tokio::test] async fn a_caller_who_may_not_download_cannot_use_up_the_export_slots() { // One slot in total. If admission ran before the permission check, a capture-only user could starve everyone. let w = world_with(Some(crate::exports::ExportGate::new(1, 0))).await; let capturer = w.caller("capturer", false, &[]); let downloader = w.caller("downloader", false, &[]); let nobody = w.caller("nobody", 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 uri = format!("/api/v1/snapshots/{}/download", w.a.snapshot); for _ in 0..5 { assert_eq!(w.send(&capturer, "GET", &uri, None).await.0, StatusCode::FORBIDDEN); assert_eq!(w.send(&nobody, "GET", &uri, None).await.0, StatusCode::NOT_FOUND); assert_eq!(w.send(&anonymous(), "GET", &uri, None).await.0, StatusCode::UNAUTHORIZED); } assert_eq!(w.send(&downloader, "GET", &uri, None).await.0, StatusCode::OK, "the slot was never taken by the refused callers"); let audited: i64 = rusqlite::Connection::open(w._dir.path().join("tessera.db")).unwrap() .query_row("SELECT COUNT(*) FROM audit_events WHERE action='export.requested'", [], |r| r.get(0)).unwrap(); assert_eq!(audited, 1, "only the permitted request counts as an export request"); }