1720 lines
57 KiB
Rust
1720 lines
57 KiB
Rust
//! Authorization matrix, generated from `docs/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!("../../../../docs/auth-endpoint-contract.md");
|
|
const ISSUER: &str = "https://idp.example";
|
|
|
|
struct Fixture {
|
|
orbit: Uuid,
|
|
application: Uuid,
|
|
outpost: Uuid,
|
|
snapshot: Uuid,
|
|
job: Uuid,
|
|
target: Uuid,
|
|
relation: 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,
|
|
/// A refresh run on orbit A's relation, started by an administrator.
|
|
run: String,
|
|
_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());
|
|
// orbit -> its staging database, with both environments set explicitly
|
|
state
|
|
.db
|
|
.set_orbit_environment(orbit, "production", now())
|
|
.unwrap();
|
|
state
|
|
.db
|
|
.set_target_environment(target.id, "staging", now())
|
|
.unwrap();
|
|
let relation = state
|
|
.db
|
|
.create_relation(orbit, target.id, None, false, true, "seed", now())
|
|
.unwrap()
|
|
.unwrap();
|
|
Fixture {
|
|
orbit,
|
|
application,
|
|
outpost,
|
|
snapshot,
|
|
job,
|
|
target: target.id,
|
|
relation: Uuid::parse_str(&relation.id).unwrap(),
|
|
}
|
|
}
|
|
|
|
async fn world() -> World {
|
|
world_with(None).await
|
|
}
|
|
|
|
async fn world_with(exports: Option<crate::exports::ExportGate>) -> 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 confirmation = crate::db::refresh::confirmation_text("orbit-a", "orbit-a-staging", 1);
|
|
let (run, _) = state
|
|
.db
|
|
.create_refresh_run(
|
|
&a.relation.to_string(),
|
|
&confirmation,
|
|
"seed",
|
|
None,
|
|
"admin",
|
|
"seed-run",
|
|
3600,
|
|
50,
|
|
now(),
|
|
)
|
|
.unwrap()
|
|
.unwrap();
|
|
let app = crate::api::router(state.clone());
|
|
World {
|
|
app,
|
|
state,
|
|
a,
|
|
b,
|
|
run: run.id,
|
|
_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,
|
|
/// `/refresh-runs`: starting, listing, watching and cancelling a refresh; per-method expectations.
|
|
RunRow,
|
|
/// Visible only to people holding a grant on a relation (`refresh.run`).
|
|
RelationList,
|
|
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 if f[4] == "refresh.run" && f[1].starts_with("/api/v1/refresh-runs") {
|
|
Kind::RunRow
|
|
} else if f[4] == "refresh.run" {
|
|
Kind::RelationList
|
|
} 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
|
|
}
|
|
"/api/v1/refresh-runs/:id" => Uuid::parse_str(&w.run).unwrap(),
|
|
"/api/v1/orbits/:id/environment" => a.orbit,
|
|
"/api/v1/restore-targets/:id/environment" => a.target,
|
|
"/api/v1/relations/:id"
|
|
| "/api/v1/relations/:id/access"
|
|
| "/api/v1/relations/:id/access/:grant" => a.relation,
|
|
_ => unknown,
|
|
};
|
|
let uri = row
|
|
.template
|
|
.replace(":id", &id.to_string())
|
|
.replace(":grant", &unknown.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})),
|
|
("PUT", "/api/v1/orbits/:id/environment")
|
|
| ("PUT", "/api/v1/restore-targets/:id/environment") => {
|
|
Some(json!({"environment": "staging"}))
|
|
}
|
|
("POST", "/api/v1/refresh-runs") => Some(json!({
|
|
"relation_id": a.relation,
|
|
"confirmation": crate::db::refresh::confirmation_text("orbit-a", "orbit-a-staging", 1),
|
|
"idempotency_key": format!("matrix-{}", Uuid::new_v4()),
|
|
})),
|
|
("POST", "/api/v1/relations") => {
|
|
Some(json!({"source_orbit_id": a.orbit, "target_id": a.target}))
|
|
}
|
|
("PUT", "/api/v1/relations/:id") => Some(json!({"target_id": a.target})),
|
|
("POST", "/api/v1/relations/:id/access") => {
|
|
Some(json!({"principal_type": "group", "principal": "matrix-refreshers"}))
|
|
}
|
|
("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));
|
|
// holds nothing on any orbit, only the right to refresh through orbit A's relation
|
|
let refresher_a = w.caller("refresher-a", false, &[]);
|
|
w.state
|
|
.db
|
|
.add_relation_grant(
|
|
"user",
|
|
refresher_a.user_id.as_ref().unwrap(),
|
|
&w.a.relation.to_string(),
|
|
None,
|
|
"test",
|
|
now(),
|
|
)
|
|
.unwrap()
|
|
.unwrap();
|
|
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,
|
|
&refresher_a,
|
|
&viewer_b,
|
|
&viewer_a,
|
|
&capturer_a,
|
|
&downloader_a,
|
|
&group_a,
|
|
] {
|
|
let (status, body_out) = w.send(caller, &row.method, &uri, body.clone()).await;
|
|
let no_orbit_access = matches!(caller.name, "nogrant" | "refresher-a");
|
|
let on_a = !std::ptr::eq(caller, &viewer_b) && !no_orbit_access;
|
|
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::RunRow => match (row.method.as_str(), caller.name) {
|
|
// someone who holds a grant on the relation, and did not start this run
|
|
("GET", "refresher-a") => {
|
|
assert_eq!(status, StatusCode::OK, "{who}");
|
|
if row.template.ends_with(":id") {
|
|
assert_eq!(body_out["id"], w.run.as_str());
|
|
} else {
|
|
assert_eq!(
|
|
body_out.as_array().unwrap().len(),
|
|
1,
|
|
"{who} sees only runs on its relation"
|
|
);
|
|
}
|
|
for secret in [
|
|
"requested_by",
|
|
"snapshot_id",
|
|
"identity",
|
|
"instance",
|
|
"outpost",
|
|
] {
|
|
assert!(
|
|
!body_out.to_string().contains(secret),
|
|
"{who}: a refresher's view leaks {secret}"
|
|
);
|
|
}
|
|
}
|
|
("POST", "refresher-a") => assert!(!denied(status), "{who}: {status}"),
|
|
("DELETE", "refresher-a") => assert_eq!(
|
|
status,
|
|
StatusCode::FORBIDDEN,
|
|
"{who}: may see the run but not cancel someone else's"
|
|
),
|
|
// everyone else: not a holder of any relation grant
|
|
("GET", _) if !row.template.ends_with(":id") => {
|
|
assert_eq!(status, StatusCode::FORBIDDEN, "{who}")
|
|
}
|
|
_ => assert_eq!(
|
|
status,
|
|
StatusCode::NOT_FOUND,
|
|
"{who}: a relation or run they hold no grant on does not exist for them"
|
|
),
|
|
},
|
|
Kind::RelationList => {
|
|
if caller.name == "refresher-a" {
|
|
assert_eq!(status, StatusCode::OK, "{who}");
|
|
let relations = body_out.as_array().unwrap();
|
|
assert_eq!(
|
|
relations.len(),
|
|
1,
|
|
"{who} sees only the relation it was granted"
|
|
);
|
|
assert_eq!(relations[0]["id"], w.a.relation.to_string());
|
|
// never where the database is
|
|
let shown = body_out.to_string();
|
|
for secret in [
|
|
"identity",
|
|
"instance",
|
|
"outpost",
|
|
"application",
|
|
"\"database\"",
|
|
"host",
|
|
] {
|
|
assert!(
|
|
!shown.contains(secret),
|
|
"{who}: the refresher's view leaks {secret}: {shown}"
|
|
);
|
|
}
|
|
assert_eq!(
|
|
(
|
|
relations[0]["source_name"].as_str(),
|
|
relations[0]["target_name"].as_str()
|
|
),
|
|
(Some("orbit-a"), Some("orbit-a-staging"))
|
|
);
|
|
} else {
|
|
// orbit access of any kind is not the right to refresh
|
|
assert_eq!(status, StatusCode::FORBIDDEN, "{who}");
|
|
}
|
|
}
|
|
Kind::List(_) => {
|
|
if no_orbit_access {
|
|
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 no_orbit_access
|
|
&& !(caller.name == "refresher-a"
|
|
&& matches!(row.kind, Kind::RelationList | Kind::RunRow))
|
|
{
|
|
assert!(
|
|
!status.is_success(),
|
|
"{who}: a caller without any matching 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"
|
|
);
|
|
}
|
|
if row.kind == Kind::RelationList {
|
|
let ids: Vec<_> = body_out
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.map(|r| r["id"].as_str().unwrap().to_string())
|
|
.collect();
|
|
assert!(
|
|
ids.contains(&w.a.relation.to_string()) && ids.contains(&w.b.relation.to_string()),
|
|
"{label}: the administrator sees every relation"
|
|
);
|
|
}
|
|
}
|
|
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
|
|
);
|
|
}
|
|
|
|
#[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"
|
|
);
|
|
}
|
|
|
|
async fn snapshot_with_identity(w: &World, orbit: Uuid, instance: &str, database: &str) {
|
|
let id = Uuid::new_v4();
|
|
let manifest = SnapshotManifest {
|
|
snapshot_id: id,
|
|
orbit_id: orbit,
|
|
orbit_name: "fixture".into(),
|
|
labels: vec![],
|
|
provider: "postgres".into(),
|
|
paths: vec![],
|
|
restore_hints: json!({"format": "custom", "source_identity": {"instance": instance, "database": database}}),
|
|
};
|
|
w.state
|
|
.vault
|
|
.write()
|
|
.await
|
|
.snapshot(manifest, b"PGDMP", false)
|
|
.unwrap();
|
|
}
|
|
|
|
fn db_conn(w: &World) -> rusqlite::Connection {
|
|
rusqlite::Connection::open(w._dir.path().join("tessera.db")).unwrap()
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn relations_follow_their_rules_over_http_and_name_the_rule_that_refused() {
|
|
let w = world().await;
|
|
let admin = w.caller("admin", true, &[]);
|
|
let rel = "/api/v1/relations";
|
|
// the fixture already has A -> its staging target; asking again is a conflict, not a second relation
|
|
let body = json!({"source_orbit_id": w.a.orbit, "target_id": w.a.target});
|
|
let (status, refusal) = w.send(&admin, "POST", rel, Some(body.clone())).await;
|
|
assert_eq!(
|
|
(status, refusal["reason"].clone()),
|
|
(StatusCode::CONFLICT, json!("relation_exists"))
|
|
);
|
|
// a target is for its own application; and an unlabelled or production target fails closed
|
|
let (status, refusal) = w
|
|
.send(
|
|
&admin,
|
|
"POST",
|
|
rel,
|
|
Some(json!({"source_orbit_id": w.a.orbit, "target_id": w.b.target})),
|
|
)
|
|
.await;
|
|
assert_eq!(
|
|
(status, refusal["reason"].clone()),
|
|
(
|
|
StatusCode::UNPROCESSABLE_ENTITY,
|
|
json!("application_mismatch")
|
|
)
|
|
);
|
|
let (status, refusal) = w
|
|
.send(
|
|
&admin,
|
|
"POST",
|
|
rel,
|
|
Some(json!({"source_orbit_id": Uuid::new_v4(), "target_id": w.a.target})),
|
|
)
|
|
.await;
|
|
assert_eq!(
|
|
(status, refusal["reason"].clone()),
|
|
(StatusCode::NOT_FOUND, json!("unknown_source"))
|
|
);
|
|
assert_eq!(
|
|
w.send(
|
|
&admin,
|
|
"POST",
|
|
rel,
|
|
Some(json!({"source_orbit_id": w.a.orbit, "target_id": Uuid::new_v4()}))
|
|
)
|
|
.await
|
|
.1["reason"],
|
|
"unknown_target"
|
|
);
|
|
assert_eq!(
|
|
w.send(
|
|
&admin,
|
|
"POST",
|
|
rel,
|
|
Some(json!({"source_orbit_id": w.a.orbit}))
|
|
)
|
|
.await
|
|
.0,
|
|
StatusCode::UNPROCESSABLE_ENTITY,
|
|
"malformed body"
|
|
);
|
|
|
|
// environments: only the three names, and nothing is assumed
|
|
let orbit_env = format!("/api/v1/orbits/{}/environment", w.a.orbit);
|
|
assert_eq!(
|
|
w.send(
|
|
&admin,
|
|
"PUT",
|
|
&orbit_env,
|
|
Some(json!({"environment": "prod"}))
|
|
)
|
|
.await
|
|
.0,
|
|
StatusCode::BAD_REQUEST
|
|
);
|
|
assert_eq!(
|
|
w.send(
|
|
&admin,
|
|
"PUT",
|
|
&format!("/api/v1/orbits/{}/environment", Uuid::new_v4()),
|
|
Some(json!({"environment": "staging"}))
|
|
)
|
|
.await
|
|
.0,
|
|
StatusCode::NOT_FOUND
|
|
);
|
|
let overview = w.send(&admin, "GET", rel, None).await.1;
|
|
let orbit = overview["orbits"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.find(|o| o["id"] == w.a.orbit.to_string())
|
|
.unwrap();
|
|
assert_eq!(
|
|
(
|
|
orbit["ready"].clone(),
|
|
orbit["environment"].clone(),
|
|
orbit["engine"].clone()
|
|
),
|
|
(json!(true), json!("production"), json!("postgres"))
|
|
);
|
|
let target = overview["targets"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.find(|t| t["id"] == w.a.target.to_string())
|
|
.unwrap();
|
|
assert_eq!(
|
|
(
|
|
target["environment"].clone(),
|
|
target["outpost_active"].clone(),
|
|
target["identity"]["instance"].clone()
|
|
),
|
|
(json!("staging"), json!(true), json!("123"))
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn a_production_database_labelled_staging_is_caught_by_the_snapshots() {
|
|
let w = world().await;
|
|
let admin = w.caller("admin", true, &[]);
|
|
let rel = "/api/v1/relations";
|
|
let existing = w.a.relation.to_string();
|
|
assert_eq!(
|
|
w.send(&admin, "DELETE", &format!("{rel}/{existing}"), None)
|
|
.await
|
|
.0,
|
|
StatusCode::NO_CONTENT
|
|
);
|
|
// orbit B (production) captures a database whose identity is exactly orbit A's "staging" target
|
|
snapshot_with_identity(&w, w.b.orbit, "123", "app").await;
|
|
let body = json!({"source_orbit_id": w.a.orbit, "target_id": w.a.target});
|
|
let (status, refusal) = w.send(&admin, "POST", rel, Some(body.clone())).await;
|
|
assert_eq!(
|
|
(status, refusal["reason"].clone()),
|
|
(
|
|
StatusCode::UNPROCESSABLE_ENTITY,
|
|
json!("target_matches_a_production_source")
|
|
)
|
|
);
|
|
// if that capturing orbit is itself a staging orbit, it is the target's own backup and does not count
|
|
let b_env = format!("/api/v1/orbits/{}/environment", w.b.orbit);
|
|
assert_eq!(
|
|
w.send(
|
|
&admin,
|
|
"PUT",
|
|
&b_env,
|
|
Some(json!({"environment": "staging"}))
|
|
)
|
|
.await
|
|
.0,
|
|
StatusCode::NO_CONTENT
|
|
);
|
|
let (status, created) = w.send(&admin, "POST", rel, Some(body)).await;
|
|
assert_eq!(status, StatusCode::CREATED);
|
|
assert_eq!(
|
|
created["verified"], false,
|
|
"the source has no snapshot yet, so the refresh must check again before applying"
|
|
);
|
|
// once the source itself has been seen, a relation is verified
|
|
let retarget = format!("{rel}/{}", created["id"].as_str().unwrap());
|
|
snapshot_with_identity(&w, w.a.orbit, "999", "prod").await;
|
|
let (status, second) = w
|
|
.send(
|
|
&admin,
|
|
"PUT",
|
|
&retarget,
|
|
Some(json!({"target_id": w.a.target})),
|
|
)
|
|
.await;
|
|
assert_eq!(status, StatusCode::CREATED);
|
|
assert_eq!(
|
|
(second["verified"].clone(), second["version"].clone()),
|
|
(json!(true), json!(2))
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn refresh_access_binds_to_one_relation_and_ends_when_that_relation_does() {
|
|
let w = world().await;
|
|
let admin = w.caller("admin", true, &[]);
|
|
let qa = w.caller("qa", false, &["testers"]);
|
|
let qa_id = qa.user_id.clone().unwrap();
|
|
let rel = w.a.relation.to_string();
|
|
let access = format!("/api/v1/relations/{rel}/access");
|
|
let mine = "/api/v1/refresh-relations";
|
|
assert_eq!(
|
|
w.send(&qa, "GET", mine, None).await.0,
|
|
StatusCode::FORBIDDEN,
|
|
"nothing granted yet"
|
|
);
|
|
assert_eq!(
|
|
w.send(
|
|
&qa,
|
|
"POST",
|
|
&access,
|
|
Some(json!({"principal_type": "user", "principal": qa_id}))
|
|
)
|
|
.await
|
|
.0,
|
|
StatusCode::FORBIDDEN,
|
|
"not for non-administrators"
|
|
);
|
|
|
|
// validation
|
|
for (what, body, expected) in [
|
|
(
|
|
"unknown user",
|
|
json!({"principal_type": "user", "principal": Uuid::new_v4()}),
|
|
StatusCode::UNPROCESSABLE_ENTITY,
|
|
),
|
|
(
|
|
"not a uuid",
|
|
json!({"principal_type": "user", "principal": "bob"}),
|
|
StatusCode::BAD_REQUEST,
|
|
),
|
|
(
|
|
"unknown type",
|
|
json!({"principal_type": "service", "principal": "x"}),
|
|
StatusCode::BAD_REQUEST,
|
|
),
|
|
(
|
|
"oversized group",
|
|
json!({"principal_type": "group", "principal": "g".repeat(200)}),
|
|
StatusCode::BAD_REQUEST,
|
|
),
|
|
(
|
|
"past expiry",
|
|
json!({"principal_type": "user", "principal": qa_id, "expires_at": "2020-01-01T00:00:00Z"}),
|
|
StatusCode::BAD_REQUEST,
|
|
),
|
|
] {
|
|
assert_eq!(
|
|
w.send(&admin, "POST", &access, Some(body)).await.0,
|
|
expected,
|
|
"{what}"
|
|
);
|
|
}
|
|
assert_eq!(
|
|
w.send(
|
|
&admin,
|
|
"POST",
|
|
&format!("/api/v1/relations/{}/access", Uuid::new_v4()),
|
|
Some(json!({"principal_type": "group", "principal": "testers"}))
|
|
)
|
|
.await
|
|
.0,
|
|
StatusCode::NOT_FOUND
|
|
);
|
|
|
|
// by group: effective on the very next request; removing it ends it
|
|
let (status, grant) = w
|
|
.send(
|
|
&admin,
|
|
"POST",
|
|
&access,
|
|
Some(json!({"principal_type": "group", "principal": "testers"})),
|
|
)
|
|
.await;
|
|
assert_eq!(status, StatusCode::CREATED);
|
|
assert_eq!(w.send(&qa, "GET", mine, None).await.0, StatusCode::OK);
|
|
assert_eq!(
|
|
w.send(
|
|
&admin,
|
|
"POST",
|
|
&access,
|
|
Some(json!({"principal_type": "group", "principal": "testers"}))
|
|
)
|
|
.await
|
|
.0,
|
|
StatusCode::CONFLICT
|
|
);
|
|
assert_eq!(
|
|
w.send(&admin, "GET", &access, None)
|
|
.await
|
|
.1
|
|
.as_array()
|
|
.unwrap()
|
|
.len(),
|
|
1
|
|
);
|
|
let revoke = format!("{access}/{}", grant["id"].as_str().unwrap());
|
|
assert_eq!(
|
|
w.send(&admin, "DELETE", &revoke, None).await.0,
|
|
StatusCode::NO_CONTENT
|
|
);
|
|
assert_eq!(
|
|
w.send(&qa, "GET", mine, None).await.0,
|
|
StatusCode::FORBIDDEN,
|
|
"revoked at once"
|
|
);
|
|
|
|
// by person; a retarget gives a new relation id and the old access does not follow
|
|
w.send(
|
|
&admin,
|
|
"POST",
|
|
&access,
|
|
Some(json!({"principal_type": "user", "principal": qa_id})),
|
|
)
|
|
.await;
|
|
assert_eq!(w.send(&qa, "GET", mine, None).await.1[0]["id"], rel);
|
|
let other_target = RestoreTarget {
|
|
id: Uuid::new_v4(),
|
|
application_id: w.a.application,
|
|
outpost_id: w.a.outpost,
|
|
name: "second-staging".into(),
|
|
engine: Engine::Postgres,
|
|
identity: DatabaseIdentity {
|
|
instance: "777".into(),
|
|
database: "app".into(),
|
|
},
|
|
};
|
|
assert!(w.state.db.register_restore_target(&other_target).unwrap());
|
|
let target_env = format!("/api/v1/restore-targets/{}/environment", other_target.id);
|
|
assert_eq!(
|
|
w.send(
|
|
&admin,
|
|
"PUT",
|
|
&target_env,
|
|
Some(json!({"environment": "development"}))
|
|
)
|
|
.await
|
|
.0,
|
|
StatusCode::OK
|
|
);
|
|
let (status, next) = w
|
|
.send(
|
|
&admin,
|
|
"PUT",
|
|
&format!("/api/v1/relations/{rel}"),
|
|
Some(json!({"target_id": other_target.id})),
|
|
)
|
|
.await;
|
|
assert_eq!(status, StatusCode::CREATED);
|
|
assert_ne!(next["id"], rel.as_str());
|
|
assert_eq!(
|
|
w.send(&qa, "GET", mine, None).await.0,
|
|
StatusCode::FORBIDDEN,
|
|
"the new database starts with no access"
|
|
);
|
|
|
|
// grant it, then relabel the target as production: the relation ends in that very request
|
|
let new_access = format!("/api/v1/relations/{}/access", next["id"].as_str().unwrap());
|
|
w.send(
|
|
&admin,
|
|
"POST",
|
|
&new_access,
|
|
Some(json!({"principal_type": "user", "principal": qa_id})),
|
|
)
|
|
.await;
|
|
assert_eq!(w.send(&qa, "GET", mine, None).await.1[0]["usable"], true);
|
|
let (status, ended) = w
|
|
.send(
|
|
&admin,
|
|
"PUT",
|
|
&target_env,
|
|
Some(json!({"environment": "production"})),
|
|
)
|
|
.await;
|
|
assert_eq!(
|
|
(status, ended["ended_relations"].as_array().unwrap().len()),
|
|
(StatusCode::OK, 1)
|
|
);
|
|
assert_eq!(
|
|
w.send(&qa, "GET", mine, None).await.0,
|
|
StatusCode::FORBIDDEN
|
|
);
|
|
let (status, refusal) = w
|
|
.send(
|
|
&admin,
|
|
"PUT",
|
|
&format!("/api/v1/relations/{rel}"),
|
|
Some(json!({"target_id": other_target.id})),
|
|
)
|
|
.await;
|
|
assert_eq!(
|
|
status,
|
|
StatusCode::NOT_FOUND,
|
|
"a replaced relation cannot be replaced again: {refusal}"
|
|
);
|
|
|
|
// every administrative step left a trail
|
|
let conn = db_conn(&w);
|
|
let count = |action: &str| -> i64 {
|
|
conn.query_row(
|
|
"SELECT COUNT(*) FROM audit_events WHERE action=?1 AND outcome='succeeded'",
|
|
[action],
|
|
|r| r.get(0),
|
|
)
|
|
.unwrap()
|
|
};
|
|
assert_eq!(
|
|
(
|
|
count("relation.grant_create"),
|
|
count("relation.grant_delete"),
|
|
count("relation.retarget"),
|
|
count("environment.set")
|
|
),
|
|
(3, 1, 1, 2)
|
|
);
|
|
assert!(count("relation.deactivate") >= 1);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn revoking_an_outpost_or_deleting_a_relation_takes_refreshers_off_immediately() {
|
|
let w = world().await;
|
|
let admin = w.caller("admin", true, &[]);
|
|
let qa = w.caller("qa", false, &[]);
|
|
let rel = w.a.relation.to_string();
|
|
w.send(
|
|
&admin,
|
|
"POST",
|
|
&format!("/api/v1/relations/{rel}/access"),
|
|
Some(json!({"principal_type": "user", "principal": qa.user_id.clone().unwrap()})),
|
|
)
|
|
.await;
|
|
assert_eq!(
|
|
w.send(&qa, "GET", "/api/v1/refresh-relations", None)
|
|
.await
|
|
.0,
|
|
StatusCode::OK
|
|
);
|
|
assert_eq!(
|
|
w.send(
|
|
&admin,
|
|
"POST",
|
|
&format!("/api/v1/wormhole/outposts/{}/revoke", w.a.outpost),
|
|
None
|
|
)
|
|
.await
|
|
.0,
|
|
StatusCode::NO_CONTENT
|
|
);
|
|
assert_eq!(
|
|
w.send(&qa, "GET", "/api/v1/refresh-relations", None)
|
|
.await
|
|
.0,
|
|
StatusCode::FORBIDDEN
|
|
);
|
|
let overview = w.send(&admin, "GET", "/api/v1/relations", None).await.1;
|
|
let stored = overview["relations"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.find(|r| r["id"] == rel.as_str())
|
|
.unwrap();
|
|
assert_eq!(
|
|
(
|
|
stored["active"].clone(),
|
|
stored["deactivated_reason"].clone()
|
|
),
|
|
(json!(false), json!("outpost_revoked"))
|
|
);
|
|
// deleting an already ended relation is a 404, not a second success
|
|
assert_eq!(
|
|
w.send(&admin, "DELETE", &format!("/api/v1/relations/{rel}"), None)
|
|
.await
|
|
.0,
|
|
StatusCode::NOT_FOUND
|
|
);
|
|
// orbit B's relation is untouched by A's Outpost
|
|
let b = overview["relations"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.find(|r| r["id"] == w.b.relation.to_string())
|
|
.unwrap();
|
|
assert_eq!(b["active"], true);
|
|
}
|