diff --git a/crates/tessera-agent/src/jobs.rs b/crates/tessera-agent/src/jobs.rs index 4d33468..0e06515 100644 --- a/crates/tessera-agent/src/jobs.rs +++ b/crates/tessera-agent/src/jobs.rs @@ -13,7 +13,8 @@ use std::{ time::Duration, }; use tessera_core::job::{ - CaptureFormat, CaptureLease, CaptureProgress, CaptureReport, ResticCaptureCommit, CAPTURE_HEARTBEAT_SECONDS, + CaptureFormat, CaptureLease, CaptureProgress, CaptureReport, ResticCaptureCommit, + CAPTURE_HEARTBEAT_SECONDS, }; use tessera_core::restore::DatabaseIdentity; use tessera_providers::{MysqlSource, PostgresSource}; @@ -83,9 +84,9 @@ pub async fn run(cli: &Cli, path: &Path) -> Result<()> { "capture timeout must be positive" ); anyhow::ensure!( - profiles - .values() - .all(|profile| profile.source.is_some() || !profile.paths.is_empty() || !profile.targets.is_empty()), + profiles.values().all(|profile| profile.source.is_some() + || !profile.paths.is_empty() + || !profile.targets.is_empty()), "application requires a source or at least one restore target" ); let url = cli @@ -195,7 +196,11 @@ async fn capture(hub: &Arc, lease: &CaptureLease, profile: &Profile) -> Res } let identity = match before { Some(identity) - if lease.profile.format.engine().is_some_and(|engine| identity.valid(engine)) + if lease + .profile + .format + .engine() + .is_some_and(|engine| identity.valid(engine)) && probe_identity(source).await.as_ref() == Some(&identity) => { Some(identity) @@ -248,39 +253,73 @@ async fn commit_backup( identity: Option, ) -> Result<()> { let result = tokio::time::timeout(Duration::from_secs(profile.timeout_seconds), async { - let repository = profile.restic_repository.as_deref().context("configure the profile Restic repository")?; + let repository = profile + .restic_repository + .as_deref() + .context("configure the profile Restic repository")?; let mut command = crate::restic_command(repository)?; if let Some(path) = &profile.restic_password_file { - command.env_remove("RESTIC_PASSWORD").env_remove("RESTIC_PASSWORD_COMMAND") + command + .env_remove("RESTIC_PASSWORD") + .env_remove("RESTIC_PASSWORD_COMMAND") .env("RESTIC_PASSWORD_FILE", path); } if let Some(path) = &profile.rest_server_password_file { - let password = tokio::fs::read_to_string(path).await.context("read Rest Server password")?; - command.env("RESTIC_REST_USERNAME", lease.profile.orbit_id.to_string()) - .env("RESTIC_REST_PASSWORD", password.trim_end_matches(['\r', '\n'])); + let password = tokio::fs::read_to_string(path) + .await + .context("read Rest Server password")?; + command + .env("RESTIC_REST_USERNAME", lease.profile.orbit_id.to_string()) + .env( + "RESTIC_REST_PASSWORD", + password.trim_end_matches(['\r', '\n']), + ); } - command.args(["backup", "--json", "--quiet", "--tag", &format!("tessera-{}", lease.job_id)]); + command.args([ + "backup", + "--json", + "--quiet", + "--tag", + &format!("tessera-{}", lease.job_id), + ]); let sha256 = if let Some(mut file) = stage { let (file, hash) = tokio::task::spawn_blocking(move || { let (_, hash) = digest_file(&mut file)?; file.seek(SeekFrom::Start(0))?; Ok::<_, anyhow::Error>((file, hash)) - }).await??; - command.args(["--stdin", "--stdin-filename", "payload"]).stdin(Stdio::from(file)); + }) + .await??; + command + .args(["--stdin", "--stdin-filename", "payload"]) + .stdin(Stdio::from(file)); Some(hash) } else { command.arg("--").args(&profile.paths); None }; let snapshot_id = crate::restic_snapshot(command).await?; - let body = serde_json::to_value(ResticCaptureCommit { lease_id: lease.lease_id, snapshot_id, identity, sha256 })?; + let body = serde_json::to_value(ResticCaptureCommit { + lease_id: lease.lease_id, + snapshot_id, + identity, + sha256, + })?; for _ in 0..3 { - if hub.post(format!("capture/{}/restic", lease.job_id), body.clone(), None).await.is_ok() { + if hub + .post( + format!("capture/{}/restic", lease.job_id), + body.clone(), + None, + ) + .await + .is_ok() + { return Ok(()); } } anyhow::bail!("could not register the Restic snapshot") - }).await; + }) + .await; match result { Ok(Ok(())) => Ok(()), failure => { diff --git a/crates/tessera-agent/src/main.rs b/crates/tessera-agent/src/main.rs index 5f072be..d749c8f 100644 --- a/crates/tessera-agent/src/main.rs +++ b/crates/tessera-agent/src/main.rs @@ -211,15 +211,10 @@ async fn beam_restic(repository: &str, hub: &str, token: &str, orbit_id: uuid::U let registered = reply["snapshot_id"] .as_str() .context("hub did not register the Restic snapshot")?; - info!( - snapshot, - registered, - "committed Restic backup" - ); + info!(snapshot, registered, "committed Restic backup"); Ok(()) } - fn restic_command(repository: &str) -> Result { let authority = repository .strip_prefix("rest:https://") @@ -229,7 +224,8 @@ fn restic_command(repository: &str) -> Result { "TESSERA_RESTIC_REPOSITORY must be a rest:https:// URL without embedded credentials" ); let mut command = tokio::process::Command::new("restic"); - command.env("RESTIC_REPOSITORY", repository) + command + .env("RESTIC_REPOSITORY", repository) .env_remove("RESTIC_REPOSITORY_FILE") .stdin(std::process::Stdio::null()) .kill_on_drop(true); @@ -237,13 +233,23 @@ fn restic_command(repository: &str) -> Result { } async fn restic_snapshot(mut command: tokio::process::Command) -> Result { - let output = command.output().await.context("starting restic (install restic on PATH)")?; - anyhow::ensure!(output.status.success(), "restic backup failed ({})", output.status); + let output = command + .output() + .await + .context("starting restic (install restic on PATH)")?; + anyhow::ensure!( + output.status.success(), + "restic backup failed ({})", + output.status + ); let summary: serde_json::Value = serde_json::from_str( std::str::from_utf8(&output.stdout)? .lines() .last() .context("missing restic summary")?, )?; - Ok(summary["snapshot_id"].as_str().context("missing restic snapshot ID")?.to_owned()) + Ok(summary["snapshot_id"] + .as_str() + .context("missing restic snapshot ID")? + .to_owned()) } diff --git a/crates/tessera-cli/src/main.rs b/crates/tessera-cli/src/main.rs index eee378b..716d258 100644 --- a/crates/tessera-cli/src/main.rs +++ b/crates/tessera-cli/src/main.rs @@ -196,7 +196,7 @@ fn main() -> Result<()> { } => cmd_reconstitute(&cli, snapshot_id, target)?, Commands::Decay { preset } => cmd_decay(&cli, &preset)?, Commands::Gc => { - Vault::open(&vault_path(&cli.data_dir), require_passphrase(&cli)?)?.collect_garbage()? + Vault::open(vault_path(&cli.data_dir), require_passphrase(&cli)?)?.collect_garbage()? } Commands::Wormhole { ref cmd } => match cmd { WormholeCmd::Pair { code, name } => wormhole_pair(&cli, code, name)?, @@ -326,7 +326,7 @@ fn cmd_snap(cli: &Cli, orbit_name: Option) -> Result<()> { } fn cmd_list(cli: &Cli) -> Result<()> { - let vault = Vault::open(&vault_path(&cli.data_dir), require_passphrase(cli)?)?; + let vault = Vault::open(vault_path(&cli.data_dir), require_passphrase(cli)?)?; for s in vault.list_snapshots()? { let stored = s .stored_bytes @@ -345,14 +345,14 @@ fn cmd_list(cli: &Cli) -> Result<()> { } fn cmd_reconstitute(cli: &Cli, snapshot_id: Uuid, target: String) -> Result<()> { - let vault = Vault::open(&vault_path(&cli.data_dir), require_passphrase(cli)?)?; + let vault = Vault::open(vault_path(&cli.data_dir), require_passphrase(cli)?)?; let n = vault.restore_snapshot(snapshot_id, std::path::Path::new(&target))?; println!("Reconstituted {n} bytes to {target}"); Ok(()) } fn cmd_decay(cli: &Cli, preset: &str) -> Result<()> { - let mut vault = Vault::open(&vault_path(&cli.data_dir), require_passphrase(cli)?)?; + let mut vault = Vault::open(vault_path(&cli.data_dir), require_passphrase(cli)?)?; let pruned = vault.prune_with_decay(preset)?; println!("{} snapshots decayed.", pruned.len()); Ok(()) diff --git a/crates/tessera-core/src/decay.rs b/crates/tessera-core/src/decay.rs index 6ec5816..bfea5cc 100644 --- a/crates/tessera-core/src/decay.rs +++ b/crates/tessera-core/src/decay.rs @@ -61,8 +61,13 @@ impl RetentionPolicy { #[derive(Debug, Clone, Copy, Serialize, Deserialize)] #[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)] pub enum CaptureRetention { - Age { days: u16 }, - Count { #[serde(default = "fallback_count")] keep: u16 }, + Age { + days: u16, + }, + Count { + #[serde(default = "fallback_count")] + keep: u16, + }, } fn fallback_count() -> u16 { @@ -90,13 +95,20 @@ pub fn evaluate_capture_retention( now: DateTime, ) -> Vec { snapshots.sort_unstable_by_key(|snapshot| std::cmp::Reverse((snapshot.taken_at, snapshot.id))); - snapshots.into_iter().enumerate().skip(1).filter_map(|(index, snapshot)| { - let expired = match policy { - CaptureRetention::Age { days } => now.signed_duration_since(snapshot.taken_at).num_days() >= i64::from(days), - CaptureRetention::Count { keep } => index >= usize::from(keep), - }; - expired.then_some(snapshot.id) - }).collect() + snapshots + .into_iter() + .enumerate() + .skip(1) + .filter_map(|(index, snapshot)| { + let expired = match policy { + CaptureRetention::Age { days } => { + now.signed_duration_since(snapshot.taken_at).num_days() >= i64::from(days) + } + CaptureRetention::Count { keep } => index >= usize::from(keep), + }; + expired.then_some(snapshot.id) + }) + .collect() } /// Keep the newest snapshot in each of the most recent occupied UTC periods. @@ -175,7 +187,10 @@ pub fn evaluate_decay(policy: &DecayPolicy, mut snapshots: Vec) -> let mut months: Vec<(i32, u32, SnapshotRef)> = Vec::new(); for s in &snapshots { let key = (s.taken_at.year(), s.taken_at.month()); - if let Some(pos) = months.iter().position(|(y, m, _)| *y == key.0 && *m == key.1) { + if let Some(pos) = months + .iter() + .position(|(y, m, _)| *y == key.0 && *m == key.1) + { if s.taken_at > months[pos].2.taken_at { months[pos] = (key.0, key.1, s.clone()); } @@ -204,14 +219,23 @@ mod tests { #[test] fn capture_retention_keeps_one_old_archive_or_the_latest_five() { let now = Utc::now(); - let snapshots: Vec<_> = (0..6).map(|i| SnapshotRef { - id: Uuid::new_v4(), - taken_at: now - Duration::days(15 + i), - }).collect(); - assert_eq!(evaluate_capture_retention(CaptureRetention::default(), snapshots.clone(), now), - snapshots[1..].iter().map(|snap| snap.id).collect::>()); - assert_eq!(evaluate_capture_retention(CaptureRetention::Count { keep: 5 }, snapshots.clone(), now), - [snapshots[5].id]); + let snapshots: Vec<_> = (0..6) + .map(|i| SnapshotRef { + id: Uuid::new_v4(), + taken_at: now - Duration::days(15 + i), + }) + .collect(); + assert_eq!( + evaluate_capture_retention(CaptureRetention::default(), snapshots.clone(), now), + snapshots[1..] + .iter() + .map(|snap| snap.id) + .collect::>() + ); + assert_eq!( + evaluate_capture_retention(CaptureRetention::Count { keep: 5 }, snapshots.clone(), now), + [snapshots[5].id] + ); } #[test] diff --git a/crates/tessera-core/src/errors.rs b/crates/tessera-core/src/errors.rs index 05911a3..4d57d95 100644 --- a/crates/tessera-core/src/errors.rs +++ b/crates/tessera-core/src/errors.rs @@ -21,9 +21,7 @@ impl TesseraError { "Another orbit is still circling the vault. Try again when it finishes." } TesseraError::WrongPassphrase => "That key doesn't unlock this vault.", - TesseraError::ProviderUnreachable(_) => { - "We couldn't reach the source at this outpost." - } + TesseraError::ProviderUnreachable(_) => "We couldn't reach the source at this outpost.", TesseraError::DiskFull { .. } => { "The vault is out of space—free room or widen the hold." } diff --git a/crates/tessera-demo/src/lib.rs b/crates/tessera-demo/src/lib.rs index ae981bd..aa3d3eb 100644 --- a/crates/tessera-demo/src/lib.rs +++ b/crates/tessera-demo/src/lib.rs @@ -54,7 +54,10 @@ impl DemoOrbit { } fn demo_id(kind: &str, name: &str) -> Uuid { - Uuid::new_v5(&Uuid::NAMESPACE_OID, format!("{DEMO_NS}:{kind}:{name}").as_bytes()) + Uuid::new_v5( + &Uuid::NAMESPACE_OID, + format!("{DEMO_NS}:{kind}:{name}").as_bytes(), + ) } pub fn apply(data_dir: &Path, vault_pass: &str, force: bool) -> Result { @@ -161,10 +164,7 @@ pub fn clear_demo(data_dir: &Path, vault_pass: &str) -> Result<()> { let id = demo_id("orbit", o.slug).to_string(); conn.execute("DELETE FROM orbits WHERE id = ?1", params![id])?; } - conn.execute( - "DELETE FROM outposts WHERE id LIKE 'demo-%'", - [], - )?; + conn.execute("DELETE FROM outposts WHERE id LIKE 'demo-%'", [])?; } let vault_path = data_dir.join("vault"); if vault_path.join("config").exists() { @@ -416,7 +416,12 @@ mod tests { assert!(orbit.snapshot_age(0) > Duration::zero()); for index in 1..orbit.snap_count { let gap = orbit.snapshot_age(index) - orbit.snapshot_age(index - 1); - assert!((gap - Duration::hours(orbit.interval_hours)).num_minutes().abs() < 45); + assert!( + (gap - Duration::hours(orbit.interval_hours)) + .num_minutes() + .abs() + < 45 + ); } } } diff --git a/crates/tessera-hub/src/admin.rs b/crates/tessera-hub/src/admin.rs index 3c4ad28..68f7aaa 100644 --- a/crates/tessera-hub/src/admin.rs +++ b/crates/tessera-hub/src/admin.rs @@ -21,11 +21,19 @@ impl AdminGate { Ok("0" | "false" | "") | Err(std::env::VarError::NotPresent) => false, _ => anyhow::bail!("TESSERA_LOCAL_DEVELOPMENT must be true, false, 1 or 0"), }; - let token_expires_at = match std::env::var("TESSERA_ADMIN_TOKEN_EXPIRES").ok().map(|v| v.trim().to_string()).filter(|v| !v.is_empty()) { + let token_expires_at = match std::env::var("TESSERA_ADMIN_TOKEN_EXPIRES") + .ok() + .map(|v| v.trim().to_string()) + .filter(|v| !v.is_empty()) + { None => None, Some(value) => Some(parse_end_date(&value)?), }; - Ok(Self { token, token_expires_at, local_development }) + Ok(Self { + token, + token_expires_at, + local_development, + }) } pub fn validate_listener(&self, addr: SocketAddr) -> anyhow::Result<()> { @@ -67,7 +75,9 @@ impl AdminGate { pub fn authorize(&self, peer: SocketAddr, headers: &HeaderMap) -> Result<(), StatusCode> { let presented = presented_token(headers); match &self.token { - Some(_) if self.token_expired(chrono::Utc::now().timestamp()) => Err(StatusCode::UNAUTHORIZED), + Some(_) if self.token_expired(chrono::Utc::now().timestamp()) => { + Err(StatusCode::UNAUTHORIZED) + } Some(expected) => { if presented.is_some_and(|value| tokens_match(expected, value)) { Ok(()) @@ -75,9 +85,15 @@ impl AdminGate { Err(StatusCode::UNAUTHORIZED) } } - None if self.local_development && peer.ip().is_loopback() + None if self.local_development + && peer.ip().is_loopback() && !headers.contains_key("forwarded") - && !headers.keys().any(|key| key.as_str().starts_with("x-forwarded-")) => Ok(()), + && !headers + .keys() + .any(|key| key.as_str().starts_with("x-forwarded-")) => + { + Ok(()) + } None => Err(StatusCode::UNAUTHORIZED), } } @@ -110,8 +126,9 @@ fn parse_end_date(value: &str) -> anyhow::Result { if let Ok(time) = chrono::DateTime::parse_from_rfc3339(value) { return Ok(time.timestamp()); } - let date = chrono::NaiveDate::parse_from_str(value, "%Y-%m-%d") - .map_err(|_| anyhow::anyhow!("TESSERA_ADMIN_TOKEN_EXPIRES must be YYYY-MM-DD or an RFC 3339 timestamp"))?; + let date = chrono::NaiveDate::parse_from_str(value, "%Y-%m-%d").map_err(|_| { + anyhow::anyhow!("TESSERA_ADMIN_TOKEN_EXPIRES must be YYYY-MM-DD or an RFC 3339 timestamp") + })?; Ok(date.and_hms_opt(23, 59, 59).unwrap().and_utc().timestamp()) } @@ -137,7 +154,11 @@ mod tests { #[test] fn loopback_without_credentials_is_denied_even_behind_a_local_proxy() { - let gate = AdminGate { token: None, local_development: false, ..Default::default() }; + let gate = AdminGate { + token: None, + local_development: false, + ..Default::default() + }; let headers = HeaderMap::new(); assert!(gate .authorize(peer(IpAddr::V4(Ipv4Addr::LOCALHOST)), &headers) @@ -187,19 +208,34 @@ mod tests { #[test] fn development_is_explicit_loopback_only_and_rejects_forwarded_requests() { - let gate = AdminGate { token: None, local_development: true, ..Default::default() }; + let gate = AdminGate { + token: None, + local_development: true, + ..Default::default() + }; for addr in ["127.0.0.1:8787", "[::1]:8787"] { assert!(gate.validate_listener(addr.parse().unwrap()).is_ok()); - assert!(gate.authorize(addr.parse().unwrap(), &HeaderMap::new()).is_ok()); + assert!(gate + .authorize(addr.parse().unwrap(), &HeaderMap::new()) + .is_ok()); } for addr in ["0.0.0.0:8787", "[::]:8787", "192.0.2.1:8787"] { assert!(gate.validate_listener(addr.parse().unwrap()).is_err()); - assert!(gate.authorize(addr.parse().unwrap(), &HeaderMap::new()).is_err()); + assert!(gate + .authorize(addr.parse().unwrap(), &HeaderMap::new()) + .is_err()); } - for name in ["forwarded", "x-forwarded-for", "x-forwarded-host", "x-forwarded-proto"] { + for name in [ + "forwarded", + "x-forwarded-for", + "x-forwarded-host", + "x-forwarded-proto", + ] { let mut headers = HeaderMap::new(); headers.insert(name, HeaderValue::from_static("synthetic-proxy")); - assert!(gate.authorize("127.0.0.1:8787".parse().unwrap(), &headers).is_err()); + assert!(gate + .authorize("127.0.0.1:8787".parse().unwrap(), &headers) + .is_err()); } } } @@ -242,7 +278,11 @@ pub struct BrowserSession { impl BrowserSession { pub fn subject(&self) -> crate::auth::Subject { - crate::auth::Subject { user_id: Some(self.user_id.clone()), groups: self.groups.clone(), admin: self.admin } + crate::auth::Subject { + user_id: Some(self.user_id.clone()), + groups: self.groups.clone(), + admin: self.admin, + } } /// Audit identity. Never derived from IdP-supplied names: OIDC users are @@ -258,7 +298,9 @@ impl BrowserSession { fn fingerprint(password_hash: &str) -> String { use sha2::{Digest, Sha256}; - hex::encode(Sha256::digest(format!("tessera-operator-credential-v1:{password_hash}"))) + hex::encode(Sha256::digest(format!( + "tessera-operator-credential-v1:{password_hash}" + ))) } fn unix_now() -> i64 { @@ -297,7 +339,11 @@ impl SessionGate { Err(std::env::VarError::NotPresent) => None, Err(_) => anyhow::bail!("operator password hash must be UTF-8"), }; - Ok(Self { config, db, oidc_fp }) + Ok(Self { + config, + db, + oidc_fp, + }) } /// Any browser login method is configured (emergency password and/or OIDC). @@ -326,7 +372,10 @@ impl SessionGate { // Sessions only count while the credential/configuration that created // them is still the active one, so unsetting or rotating either revokes them. let expected = match stored.auth_method.as_str() { - "password" => self.config.as_ref().map(|config| config.fingerprint.as_str()), + "password" => self + .config + .as_ref() + .map(|config| config.fingerprint.as_str()), "oidc" => self.oidc_fp.as_deref(), _ => None, }?; @@ -369,7 +418,15 @@ impl SessionGate { let id = uuid::Uuid::new_v4(); let created = self .db - .create_session(&id.to_string(), &user_id, "password", Some(&config.fingerprint), true, &[], now) + .create_session( + &id.to_string(), + &user_id, + "password", + Some(&config.fingerprint), + true, + &[], + now, + ) .map_err(internal)?; if !created { // Inactive user row: the break-glass account has been disabled. @@ -397,10 +454,21 @@ impl SessionGate { groups: &[String], now: i64, ) -> anyhow::Result { - let fp = self.oidc_fp.as_deref().ok_or_else(|| anyhow::anyhow!("OIDC is not configured"))?; + let fp = self + .oidc_fp + .as_deref() + .ok_or_else(|| anyhow::anyhow!("OIDC is not configured"))?; let id = uuid::Uuid::new_v4(); anyhow::ensure!( - self.db.create_session(&id.to_string(), user_id, "oidc", Some(fp), admin, groups, now)?, + self.db.create_session( + &id.to_string(), + user_id, + "oidc", + Some(fp), + admin, + groups, + now + )?, "user is disabled" ); Ok(BrowserSession { @@ -480,7 +548,11 @@ impl SessionGate { /// Same database, no operator configured (hash unset after a restart). pub fn without_operator(db: crate::db::Db) -> Self { - Self { config: None, db, oidc_fp: None } + Self { + config: None, + db, + oidc_fp: None, + } } pub fn with_oidc(mut self, fingerprint: &str) -> Self { @@ -517,7 +589,9 @@ mod session_gate_tests { async fn db() -> (tempfile::TempDir, crate::db::Db) { let dir = tempfile::tempdir().unwrap(); - let db = crate::db::Db::connect(&dir.path().join("t.db")).await.unwrap(); + let db = crate::db::Db::connect(&dir.path().join("t.db")) + .await + .unwrap(); db.migrate().await.unwrap(); (dir, db) } @@ -525,16 +599,32 @@ mod session_gate_tests { #[tokio::test] async fn a_session_outlives_a_restart_only_with_the_same_operator_credential() { let (_dir, db) = db().await; - let first = SessionGate::with_hash(db.clone(), "ops", hash("correct-horse-battery", b"salt-number-one")); - let session = first.login(&HeaderMap::new(), "correct-horse-battery").unwrap(); + let first = SessionGate::with_hash( + db.clone(), + "ops", + hash("correct-horse-battery", b"salt-number-one"), + ); + let session = first + .login(&HeaderMap::new(), "correct-horse-battery") + .unwrap(); // restart with the same credential: still valid - let restarted = SessionGate::with_hash(db.clone(), "ops", hash("correct-horse-battery", b"salt-number-one")); + let restarted = SessionGate::with_hash( + db.clone(), + "ops", + hash("correct-horse-battery", b"salt-number-one"), + ); assert!(restarted.active(&cookie(&session)).is_some()); // hash rotated after a suspected compromise: old cookie is dead - let rotated = SessionGate::with_hash(db.clone(), "ops", hash("another-long-password", b"salt-number-two")); + let rotated = SessionGate::with_hash( + db.clone(), + "ops", + hash("another-long-password", b"salt-number-two"), + ); assert!(rotated.active(&cookie(&session)).is_none()); // emergency login disabled by unsetting the hash: old cookie is dead - assert!(SessionGate::without_operator(db.clone()).active(&cookie(&session)).is_none()); + assert!(SessionGate::without_operator(db.clone()) + .active(&cookie(&session)) + .is_none()); // and it comes back only if the exact credential is configured again assert!(restarted.active(&cookie(&session)).is_some()); } @@ -542,33 +632,52 @@ mod session_gate_tests { #[tokio::test] async fn login_replaces_a_presented_session_id() { let (_dir, db) = db().await; - let gate = SessionGate::with_hash(db, "ops", hash("correct-horse-battery", b"salt-number-one")); - let old = gate.login(&HeaderMap::new(), "correct-horse-battery").unwrap(); + let gate = + SessionGate::with_hash(db, "ops", hash("correct-horse-battery", b"salt-number-one")); + let old = gate + .login(&HeaderMap::new(), "correct-horse-battery") + .unwrap(); let new = gate.login(&cookie(&old), "correct-horse-battery").unwrap(); assert_ne!(old.id, new.id); assert!(gate.active(&cookie(&old)).is_none()); assert!(gate.active(&cookie(&new)).is_some()); - assert_eq!(old.user_id, new.user_id, "same break-glass user row across logins"); + assert_eq!( + old.user_id, new.user_id, + "same break-glass user row across logins" + ); } #[tokio::test] async fn absolute_expiry_and_user_revoke_apply_to_the_gate() { let (_dir, db) = db().await; - let gate = SessionGate::with_hash(db.clone(), "ops", hash("correct-horse-battery", b"salt-number-one")); - let session = gate.login(&HeaderMap::new(), "correct-horse-battery").unwrap(); + let gate = SessionGate::with_hash( + db.clone(), + "ops", + hash("correct-horse-battery", b"salt-number-one"), + ); + let session = gate + .login(&HeaderMap::new(), "correct-horse-battery") + .unwrap(); let now = unix_now(); assert!(gate.active_at(&cookie(&session), now + 60).is_some()); - assert!(gate.active_at(&cookie(&session), now + crate::db::sessions::ABSOLUTE_SECS).is_none()); + assert!(gate + .active_at(&cookie(&session), now + crate::db::sessions::ABSOLUTE_SECS) + .is_none()); assert_eq!(db.revoke_user_sessions(&session.user_id).unwrap(), 1); assert!(gate.active(&cookie(&session)).is_none()); - assert!(gate.login(&HeaderMap::new(), "correct-horse-battery").is_ok()); + assert!(gate + .login(&HeaderMap::new(), "correct-horse-battery") + .is_ok()); } #[tokio::test] async fn the_csrf_token_is_stable_for_a_session_and_not_the_cookie() { let (_dir, db) = db().await; - let gate = SessionGate::with_hash(db, "ops", hash("correct-horse-battery", b"salt-number-one")); - let session = gate.login(&HeaderMap::new(), "correct-horse-battery").unwrap(); + let gate = + SessionGate::with_hash(db, "ops", hash("correct-horse-battery", b"salt-number-one")); + let session = gate + .login(&HeaderMap::new(), "correct-horse-battery") + .unwrap(); let again = gate.active(&cookie(&session)).unwrap(); assert_eq!(session.csrf, again.csrf); assert!(!session.csrf.contains(&session.id.to_string())); @@ -577,23 +686,40 @@ mod session_gate_tests { #[tokio::test] async fn oidc_sessions_end_when_the_oidc_configuration_changes_or_is_removed() { let (_dir, db) = db().await; - let user = db.upsert_user("https://idp.example", "alice", "Alice", unix_now()).unwrap(); + let user = db + .upsert_user("https://idp.example", "alice", "Alice", unix_now()) + .unwrap(); let gate = SessionGate::without_operator(db.clone()).with_oidc("fp-a"); - let session = gate.create_oidc(&user, "Alice", true, &[], unix_now()).unwrap(); + let session = gate + .create_oidc(&user, "Alice", true, &[], unix_now()) + .unwrap(); assert_eq!(session.principal().fields().0, format!("oidc:{user}")); assert!(gate.active(&cookie(&session)).is_some()); // admin mapping changed (different fingerprint) or OIDC switched off: dead - assert!(SessionGate::without_operator(db.clone()).with_oidc("fp-b").active(&cookie(&session)).is_none()); - assert!(SessionGate::without_operator(db.clone()).active(&cookie(&session)).is_none()); + assert!(SessionGate::without_operator(db.clone()) + .with_oidc("fp-b") + .active(&cookie(&session)) + .is_none()); + assert!(SessionGate::without_operator(db.clone()) + .active(&cookie(&session)) + .is_none()); // configuration restored: the same session is valid again - assert!(SessionGate::without_operator(db).with_oidc("fp-a").active(&cookie(&session)).is_some()); + assert!(SessionGate::without_operator(db) + .with_oidc("fp-a") + .active(&cookie(&session)) + .is_some()); } #[tokio::test] async fn an_oidc_display_name_never_becomes_the_emergency_principal() { let (_dir, db) = db().await; - let user = db.upsert_user("https://idp.example", "mallory", "operator", unix_now()).unwrap(); - let session = SessionGate::without_operator(db).with_oidc("fp").create_oidc(&user, "operator", false, &[], unix_now()).unwrap(); + let user = db + .upsert_user("https://idp.example", "mallory", "operator", unix_now()) + .unwrap(); + let session = SessionGate::without_operator(db) + .with_oidc("fp") + .create_oidc(&user, "operator", false, &[], unix_now()) + .unwrap(); let (id, kind, method) = session.principal().fields(); assert_eq!((kind, method), ("user", "oidc")); assert!(id.starts_with("oidc:") && !id.contains("emergency")); diff --git a/crates/tessera-hub/src/api/access.rs b/crates/tessera-hub/src/api/access.rs index 269a329..8b57c00 100644 --- a/crates/tessera-hub/src/api/access.rs +++ b/crates/tessera-hub/src/api/access.rs @@ -21,7 +21,10 @@ pub(super) fn routes() -> Router { .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)) + .route( + "/api/v1/access/users/:id/revoke-sessions", + post(revoke_sessions), + ) } fn no_store() -> HeaderMap { @@ -61,17 +64,29 @@ async fn list( 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() }) + .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(), + grantable: [ + Permission::OrbitRead, + Permission::SnapshotRead, + Permission::CaptureRun, + Permission::SnapshotDownload, + ] + .iter() + .map(|p| p.as_str()) + .collect(), }), )) } @@ -101,7 +116,9 @@ async fn create( let now = now(); let permissions: Vec = 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)?], + (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() { @@ -112,21 +129,32 @@ async fn create( } } "group" => { - if body.principal.is_empty() || body.principal.len() > 128 || body.principal.chars().any(char::is_control) { + 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)? { + 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)) + .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); @@ -147,7 +175,13 @@ async fn create( 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) + .audit_event( + &actor.principal, + AuditAction::GrantCreate, + AuditResource::Grant(id), + AuditOutcome::Succeeded, + actor.request_id, + ) .map_err(internal)?; created.push(grant); } @@ -168,10 +202,23 @@ async fn remove( 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) + .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) } + if removed { + Ok(StatusCode::NO_CONTENT) + } else { + Err(StatusCode::NOT_FOUND) + } } async fn users( @@ -190,8 +237,18 @@ struct UserState { } /// 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 { - let user = state.db.list_users().map_err(internal)?.into_iter().find(|u| u.id == id.to_string()).ok_or(StatusCode::NOT_FOUND)?; +fn target_user( + state: &HubState, + actor: &super::routes::OperatorActor, + id: Uuid, +) -> Result { + 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); } @@ -207,10 +264,19 @@ async fn set_user( ) -> Result { 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) + .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) } @@ -222,11 +288,23 @@ async fn revoke_sessions( Path(id): Path, ) -> Result { 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)?; + 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) + .audit_event( + &actor.principal, + AuditAction::SessionsRevoke, + AuditResource::User(id), + AuditOutcome::Succeeded, + actor.request_id, + ) .map_err(internal)?; Ok(StatusCode::NO_CONTENT) } diff --git a/crates/tessera-hub/src/api/access_tests.rs b/crates/tessera-hub/src/api/access_tests.rs index eb7a8b0..2260cf1 100644 --- a/crates/tessera-hub/src/api/access_tests.rs +++ b/crates/tessera-hub/src/api/access_tests.rs @@ -70,11 +70,25 @@ async fn fixture(state: &HubState, name: &str) -> Fixture { .await .unwrap(); let outpost = Uuid::new_v4(); - state.db.insert_test_credential(&format!("token-{name}"), &outpost.to_string(), name); + 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 }; + 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 job = state + .db + .enqueue_capture(application, "seed", now()) + .unwrap() + .unwrap() + .id; let snapshot = Uuid::new_v4(); let manifest = SnapshotManifest { snapshot_id: snapshot, @@ -85,21 +99,47 @@ async fn fixture(state: &HubState, name: &str) -> Fixture { paths: vec![], restore_hints: Value::Null, }; - state.vault.write().await.snapshot(manifest, b"synthetic payload", false).unwrap(); + 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() }, + 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() } + 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 { @@ -108,7 +148,9 @@ async fn world() -> World { 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(); + 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); } @@ -118,19 +160,49 @@ async fn world_with(exports: Option) -> World { 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()) + .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 } + 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 = 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) } + 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) { @@ -143,14 +215,27 @@ impl World { self.state .db .add_grant( - &NewGrant { principal_type: kind, principal, permission: permission.as_str(), orbit: orbit.as_deref(), expires_at: None, created_by: "test" }, + &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) { + 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) @@ -164,18 +249,29 @@ impl World { } } let request = match body { - Some(json) => request.header(header::CONTENT_TYPE, "application/json").body(Body::from(json.to_string())).unwrap(), + 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)) + ( + status, + serde_json::from_slice(&bytes).unwrap_or(Value::Null), + ) } } fn anonymous() -> Caller { - Caller { name: "anonymous", cookie: None, csrf: None, user_id: None } + Caller { + name: "anonymous", + cookie: None, + csrf: None, + user_id: None, + } } #[derive(Clone, Copy, PartialEq, Debug)] @@ -211,7 +307,8 @@ fn rows() -> Vec { } 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])); + 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") { @@ -221,7 +318,11 @@ fn rows() -> Vec { } }; for method in f[2].split(',') { - out.push(Row { method: method.trim().to_string(), template: f[1].to_string(), kind }); + out.push(Row { + method: method.trim().to_string(), + template: f[1].to_string(), + kind, + }); } } out @@ -232,42 +333,88 @@ 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/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/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, + "/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 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() }, + 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"}})), + ("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/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") => { + 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"})), + ("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"})), + ("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})), + ("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", "/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:?}"), }; @@ -277,13 +424,17 @@ fn recipe(w: &World, row: &Row) -> (String, Option) { /// 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() + 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"]), @@ -294,7 +445,10 @@ fn orbits_in(template: &str, body: &Value) -> Vec { } fn denied(status: StatusCode) -> bool { - matches!(status, StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN | StatusCode::NOT_FOUND) + matches!( + status, + StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN | StatusCode::NOT_FOUND + ) } #[tokio::test] @@ -307,14 +461,41 @@ async fn every_human_route_enforces_the_matrix_for_every_kind_of_caller() { 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_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(); + 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 @@ -334,7 +515,15 @@ async fn every_human_route_enforces_the_matrix_for_every_kind_of_caller() { 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] { + 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; @@ -366,30 +555,73 @@ async fn every_human_route_enforces_the_matrix_for_every_kind_of_caller() { 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"); + 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}"); + 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"), + ("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"), + ("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.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}"); + 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"))); + 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}"); @@ -402,7 +634,10 @@ async fn every_human_route_enforces_the_matrix_for_every_kind_of_caller() { 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:?}"); + assert!( + !seen.is_empty() && seen.iter().all(|id| id == own), + "{who} sees only its own orbit: {seen:?}" + ); } else { assert!(!denied(status), "{who}: {status}"); } @@ -410,21 +645,41 @@ async fn every_human_route_enforces_the_matrix_for_every_kind_of_caller() { 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}"); + 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}"); + 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!( + 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"); + 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"); @@ -435,17 +690,40 @@ async fn permissions_are_separate_capture_does_not_imply_download_and_the_revers 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)); + 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); + 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); + assert_eq!( + w.send(&downloader, "GET", &other, None).await.0, + StatusCode::NOT_FOUND + ); } #[tokio::test] @@ -454,26 +732,56 @@ async fn a_revoked_or_expired_grant_is_refused_on_the_next_request_and_groups_fo 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"); + 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"); + 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"); + 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) + .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"); + 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"); + assert_eq!( + w.send(&no_claim, "GET", uri, None).await.0, + StatusCode::FORBIDDEN, + "a missing groups claim grants nothing" + ); } #[tokio::test] @@ -481,17 +789,29 @@ 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(); + 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; + 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.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); + assert_eq!( + w.send(&viewer, "GET", &uri, None).await.0, + StatusCode::NOT_FOUND + ); } #[tokio::test] @@ -518,53 +838,156 @@ async fn the_grant_api_validates_audits_and_is_for_administrators_only() { 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.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); + 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), + ( + "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.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"); + 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"); + 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(&admin, "DELETE", &uri, None).await.0, + StatusCode::NO_CONTENT + ); } - assert_eq!(w.send(&target, "GET", "/api/v1/orbits", None).await.0, StatusCode::FORBIDDEN); + 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")); + 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(); @@ -586,22 +1009,49 @@ async fn disabling_a_user_ends_their_access_at_once_and_cannot_lock_out_the_call 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); + 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"); + 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); + 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); + 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)); + assert!(users + .as_array() + .unwrap() + .iter() + .any(|u| u["id"] == id && u["active"] == false)); } #[tokio::test] @@ -609,19 +1059,43 @@ 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"); + 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 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["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_eq!( + (me["admin"].clone(), me["capabilities"][0].clone()), + (json!(true), json!("admin")) + ); assert!(me["id"].as_str().unwrap().starts_with("oidc:")); } @@ -631,31 +1105,71 @@ async fn display_preferences_stick_to_the_account_and_are_validated() { 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); + 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!( + (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"); + 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) + 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(); + .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); + assert_eq!( + app.oneshot(request).await.unwrap().status(), + StatusCode::NOT_FOUND + ); } #[tokio::test] @@ -665,21 +1179,50 @@ async fn a_caller_who_may_not_download_cannot_use_up_the_export_slots() { 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)); + 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(&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"); + 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 { @@ -691,7 +1234,12 @@ async fn snapshot_with_identity(w: &World, orbit: Uuid, instance: &str, database paths: vec![], restore_hints: json!({"format": "custom", "source_identity": {"instance": instance, "database": database}}), }; - w.state.vault.write().await.snapshot(manifest, b"PGDMP", false).unwrap(); + w.state + .vault + .write() + .await + .snapshot(manifest, b"PGDMP", false) + .unwrap(); } fn db_conn(w: &World) -> rusqlite::Connection { @@ -706,24 +1254,115 @@ async fn relations_follow_their_rules_over_http_and_name_the_rule_that_refused() // 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"))); + 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"); + 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); + 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"))); + 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] @@ -732,24 +1371,58 @@ async fn a_production_database_labelled_staging_is_caught_by_the_snapshots() { 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); + 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"))); + 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); + 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"); + 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; + 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))); + assert_eq!( + (second["verified"].clone(), second["version"].clone()), + (json!(true), json!(2)) + ); } #[tokio::test] @@ -761,60 +1434,220 @@ async fn refresh_access_binds_to_one_relation_and_ends_when_that_relation_does() 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"); + 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), + ( + "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", &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); + 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; + 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); + 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"); + 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; + 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() }, + 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!( + 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"); + 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; + 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}"); + 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)); + 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); } @@ -824,16 +1657,63 @@ async fn revoking_an_outpost_or_deleting_a_relation_takes_refreshers_off_immedia 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); + 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"))); + 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); + 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(); + let b = overview["relations"] + .as_array() + .unwrap() + .iter() + .find(|r| r["id"] == w.b.relation.to_string()) + .unwrap(); assert_eq!(b["active"], true); } diff --git a/crates/tessera-hub/src/api/auth_contract.rs b/crates/tessera-hub/src/api/auth_contract.rs index b0af6bc..cf12d24 100644 --- a/crates/tessera-hub/src/api/auth_contract.rs +++ b/crates/tessera-hub/src/api/auth_contract.rs @@ -40,7 +40,9 @@ async fn human_read_endpoints_reject_anonymous_and_outpost_tokens() { state.sessions = crate::admin::SessionGate::fixture(state.db.clone()); state.admin.token = Some("synthetic-admin".into()); let outpost = uuid::Uuid::new_v4(); - state.db.insert_test_credential("synthetic-outpost", &outpost.to_string(), "fixture"); + state + .db + .insert_test_credential("synthetic-outpost", &outpost.to_string(), "fixture"); let app = router(state); for row in CONTRACT.lines().filter(|line| line.starts_with("| /")) { let fields: Vec<_> = row.split('|').map(str::trim).collect(); diff --git a/crates/tessera-hub/src/api/catalog.rs b/crates/tessera-hub/src/api/catalog.rs index 57e8faf..cd7560c 100644 --- a/crates/tessera-hub/src/api/catalog.rs +++ b/crates/tessera-hub/src/api/catalog.rs @@ -1,12 +1,9 @@ use super::routes::{admin_write, authenticate}; use crate::auth::{AuditAction, AuditOutcome, AuditResource, Permission}; use crate::exports::{self, Guarded, Refused, EXPORT_PREFIX}; +use crate::state::HubState; use async_compression::tokio::bufread::GzipEncoder; use axum::body::Bytes; -use futures_core::Stream; -use std::pin::Pin; -use tokio::io::{AsyncReadExt, AsyncSeekExt}; -use crate::state::HubState; use axum::{ body::Body, extract::{ConnectInfo, Path, State}, @@ -15,7 +12,10 @@ use axum::{ routing::get, Router, }; +use futures_core::Stream; use std::net::SocketAddr; +use std::pin::Pin; +use tokio::io::{AsyncReadExt, AsyncSeekExt}; use tokio_util::io::ReaderStream; use uuid::Uuid; @@ -51,10 +51,24 @@ 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)?; + super::gate::scoped( + &state, + &actor, + Permission::SnapshotDownload, + snapshot.manifest.orbit_id, + )?; let audit = |action: AuditAction, outcome: AuditOutcome| { - state.db.audit_event(&actor.principal, action, AuditResource::Snapshot(id), outcome, actor.request_id).map_err(internal) + state + .db + .audit_event( + &actor.principal, + action, + AuditResource::Snapshot(id), + outcome, + actor.request_id, + ) + .map_err(internal) }; audit(AuditAction::ExportRequested, AuditOutcome::Allowed)?; let permit = match state.exports.admit(&state.data_dir, snapshot.size_bytes) { @@ -67,15 +81,23 @@ async fn download( }); } }; - let staging = tempfile::Builder::new().prefix(EXPORT_PREFIX).tempdir_in(&state.data_dir).map_err(internal)?; + let staging = tempfile::Builder::new() + .prefix(EXPORT_PREFIX) + .tempdir_in(&state.data_dir) + .map_err(internal)?; let path = staging.path().join("download"); - state.export_snapshot(id, path.clone()).await.map_err(internal)?; + state + .export_snapshot(id, path.clone()) + .await + .map_err(internal)?; let mut file = tokio::fs::File::open(&path).await.map_err(internal)?; let size = file.metadata().await.map_err(internal)?.len(); let mut head = vec![0u8; 512]; let read = file.read(&mut head).await.map_err(internal)?; head.truncate(read); - file.seek(std::io::SeekFrom::Start(0)).await.map_err(internal)?; + file.seek(std::io::SeekFrom::Start(0)) + .await + .map_err(internal)?; let plan = exports::plan(&snapshot.manifest.restore_hints, &head); audit(AuditAction::ExportReady, AuditOutcome::Succeeded)?; @@ -85,16 +107,31 @@ async fn download( } else { Box::pin(ReaderStream::with_capacity(reader, CHUNK)) }; - let body = Guarded::new(stream, permit, staging, state.db.clone(), actor.principal.clone(), id, actor.request_id); + let body = Guarded::new( + stream, + permit, + staging, + state.db.clone(), + actor.principal.clone(), + id, + actor.request_id, + ); let mut response = Response::new(Body::from_stream(body)); let headers = response.headers_mut(); - headers.insert(header::CONTENT_TYPE, HeaderValue::from_static(plan.content_type)); + headers.insert( + header::CONTENT_TYPE, + HeaderValue::from_static(plan.content_type), + ); headers.insert( header::CONTENT_DISPOSITION, - HeaderValue::from_str(&format!("attachment; filename=\"{id}.{}\"", plan.extension)).map_err(internal)?, + HeaderValue::from_str(&format!("attachment; filename=\"{id}.{}\"", plan.extension)) + .map_err(internal)?, ); headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); - headers.insert(header::X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")); + headers.insert( + header::X_CONTENT_TYPE_OPTIONS, + HeaderValue::from_static("nosniff"), + ); // The exact size is only known when the bytes are sent as they are. Never `Content-Encoding`: this // is the file itself, and a browser must not unpack it. if !plan.compress { @@ -112,11 +149,16 @@ async fn delete( 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) + || state.db.offsite_pending(id).map_err(internal)? + || state.active_exports().await.contains(&id) { return Err(StatusCode::CONFLICT); } - if vault.get_snapshot(id).map_err(internal)?.is_none_or(|snapshot| snapshot.manifest.provider == "legacy-history") { + if vault + .get_snapshot(id) + .map_err(internal)? + .is_none_or(|snapshot| snapshot.manifest.provider == "legacy-history") + { return Err(StatusCode::NOT_FOUND); } state diff --git a/crates/tessera-hub/src/api/credentials_tests.rs b/crates/tessera-hub/src/api/credentials_tests.rs index 20e1103..8a9b4b9 100644 --- a/crates/tessera-hub/src/api/credentials_tests.rs +++ b/crates/tessera-hub/src/api/credentials_tests.rs @@ -22,7 +22,9 @@ struct Harness { async fn harness_with(configure: impl FnOnce(&mut HubState)) -> Harness { let dir = tempfile::tempdir().unwrap(); - let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault").await.unwrap(); + let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") + .await + .unwrap(); state.admin.token = Some(ADMIN.into()); configure(&mut state); let app = crate::api::router(state.clone()); @@ -33,27 +35,41 @@ async fn harness() -> Harness { harness_with(|_| {}).await } -fn request(method: &str, uri: &str, peer: &str, auth: Option<&str>, body: Option) -> Request { +fn request( + method: &str, + uri: &str, + peer: &str, + auth: Option<&str>, + body: Option, +) -> Request { let mut builder = Request::builder() .method(method) .uri(uri) - .extension(ConnectInfo(format!("{peer}:4000").parse::().unwrap())); + .extension(ConnectInfo( + format!("{peer}:4000").parse::().unwrap(), + )); if let Some(token) = auth { builder = builder.header("x-tessera-admin-token", token); } match body { - Some(json) => builder.header(header::CONTENT_TYPE, "application/json").body(Body::from(json.to_string())).unwrap(), + Some(json) => builder + .header(header::CONTENT_TYPE, "application/json") + .body(Body::from(json.to_string())) + .unwrap(), None => builder.body(Body::empty()).unwrap(), } } fn as_outpost(mut request: Request, token: &str) -> Request { - request.headers_mut().insert("x-tessera-upload-token", token.parse().unwrap()); + request + .headers_mut() + .insert("x-tessera-upload-token", token.parse().unwrap()); request } async fn json_of(response: Response) -> Value { - serde_json::from_slice(&to_bytes(response.into_body(), 1 << 20).await.unwrap()).unwrap_or(Value::Null) + serde_json::from_slice(&to_bytes(response.into_body(), 1 << 20).await.unwrap()) + .unwrap_or(Value::Null) } impl Harness { @@ -67,20 +83,47 @@ impl Harness { /// The real HTTP pairing path: start (admin) then claim (agent). async fn pair(&self, name: &str) -> (String, String) { - let start = self.call(request("POST", "/api/v1/wormhole/pairing", "127.0.0.1", Some(ADMIN), None)).await; + let start = self + .call(request( + "POST", + "/api/v1/wormhole/pairing", + "127.0.0.1", + Some(ADMIN), + None, + )) + .await; assert_eq!(start.status(), StatusCode::OK); let code = json_of(start).await["code"].as_str().unwrap().to_string(); let claim = self - .call(request("POST", "/api/v1/wormhole/claim", "198.51.100.20", None, Some(json!({"code": code, "outpost_name": name})))) + .call(request( + "POST", + "/api/v1/wormhole/claim", + "198.51.100.20", + None, + Some(json!({"code": code, "outpost_name": name})), + )) .await; assert_eq!(claim.status(), StatusCode::OK); let body = json_of(claim).await; - (body["outpost_id"].as_str().unwrap().to_string(), body["upload_token"].as_str().unwrap().to_string()) + ( + body["outpost_id"].as_str().unwrap().to_string(), + body["upload_token"].as_str().unwrap().to_string(), + ) } /// An Outpost-authenticated request: 401 only if the token is refused. async fn outpost_status(&self, token: &str, path: &str) -> StatusCode { - self.status(as_outpost(request("POST", path, "198.51.100.20", None, Some(json!({"orbit_id": "00000000-0000-0000-0000-000000000001", "total_bytes": 1}))), token)).await + self.status(as_outpost( + request( + "POST", + path, + "198.51.100.20", + None, + Some(json!({"orbit_id": "00000000-0000-0000-0000-000000000001", "total_bytes": 1})), + ), + token, + )) + .await } fn db_file(&self) -> std::path::PathBuf { @@ -88,7 +131,10 @@ impl Harness { } fn scalar(&self, sql: &str) -> T { - rusqlite::Connection::open(self.db_file()).unwrap().query_row(sql, [], |r| r.get(0)).unwrap() + rusqlite::Connection::open(self.db_file()) + .unwrap() + .query_row(sql, [], |r| r.get(0)) + .unwrap() } } @@ -100,17 +146,38 @@ async fn pairing_over_http_mints_the_token_at_claim_and_stores_only_digests() { let h = harness().await; let (outpost, token) = h.pair("agent-one").await; assert_eq!(token.len(), 64); - assert_ne!(h.outpost_status(&token, UPLOAD).await, StatusCode::UNAUTHORIZED, "the minted token authenticates"); - assert_eq!(h.outpost_status("not-the-token", UPLOAD).await, StatusCode::UNAUTHORIZED); + assert_ne!( + h.outpost_status(&token, UPLOAD).await, + StatusCode::UNAUTHORIZED, + "the minted token authenticates" + ); + assert_eq!( + h.outpost_status("not-the-token", UPLOAD).await, + StatusCode::UNAUTHORIZED + ); // the code works exactly once let again = h - .call(request("POST", "/api/v1/wormhole/claim", "198.51.100.20", None, Some(json!({"code": "WHATEVER", "outpost_name": "x"})))) + .call(request( + "POST", + "/api/v1/wormhole/claim", + "198.51.100.20", + None, + Some(json!({"code": "WHATEVER", "outpost_name": "x"})), + )) .await; assert_eq!(again.status(), StatusCode::GONE); // neither the token nor the code is anywhere on disk let code: String = { // recover nothing from the DB: ask for a second pairing and look for it afterwards - let start = h.call(request("POST", "/api/v1/wormhole/pairing", "127.0.0.1", Some(ADMIN), None)).await; + let start = h + .call(request( + "POST", + "/api/v1/wormhole/pairing", + "127.0.0.1", + Some(ADMIN), + None, + )) + .await; json_of(start).await["code"].as_str().unwrap().to_string() }; let mut bytes = Vec::new(); @@ -119,9 +186,15 @@ async fn pairing_over_http_mints_the_token_at_claim_and_stores_only_digests() { name.push(suffix); bytes.extend(std::fs::read(name).unwrap_or_default()); } - assert!(bytes.windows(9).any(|w| w == b"agent-one"), "sanity: the scan really reads the database file"); + assert!( + bytes.windows(9).any(|w| w == b"agent-one"), + "sanity: the scan really reads the database file" + ); for secret in [token.as_str(), code.as_str()] { - assert!(!bytes.windows(secret.len()).any(|w| w == secret.as_bytes()), "clear-text secret on disk"); + assert!( + !bytes.windows(secret.len()).any(|w| w == secret.as_bytes()), + "clear-text secret on disk" + ); } let audited: i64 = h.scalar(&format!("SELECT COUNT(*) FROM audit_events WHERE action='outpost.pair' AND outcome='succeeded' AND actor_id='{outpost}'")); assert_eq!(audited, 1); @@ -133,32 +206,86 @@ async fn pairing_over_http_mints_the_token_at_claim_and_stores_only_digests() { async fn revoking_an_outpost_refuses_it_on_its_very_next_request() { let h = harness().await; let (outpost, token) = h.pair("agent-one").await; - assert_ne!(h.outpost_status(&token, UPLOAD).await, StatusCode::UNAUTHORIZED); - assert_ne!(h.outpost_status(&token, LEASED).await, StatusCode::UNAUTHORIZED, "lease-bearing endpoint accepts it before"); + assert_ne!( + h.outpost_status(&token, UPLOAD).await, + StatusCode::UNAUTHORIZED + ); + assert_ne!( + h.outpost_status(&token, LEASED).await, + StatusCode::UNAUTHORIZED, + "lease-bearing endpoint accepts it before" + ); - let revoke = |auth| request("POST", &format!("/api/v1/wormhole/outposts/{outpost}/revoke"), "127.0.0.1", auth, None); - assert_eq!(h.status(revoke(None)).await, StatusCode::UNAUTHORIZED, "anonymous cannot revoke"); - assert_eq!(h.status(as_outpost(revoke(None), &token)).await, StatusCode::UNAUTHORIZED, "an Outpost cannot revoke itself or others"); + let revoke = |auth| { + request( + "POST", + &format!("/api/v1/wormhole/outposts/{outpost}/revoke"), + "127.0.0.1", + auth, + None, + ) + }; + assert_eq!( + h.status(revoke(None)).await, + StatusCode::UNAUTHORIZED, + "anonymous cannot revoke" + ); + assert_eq!( + h.status(as_outpost(revoke(None), &token)).await, + StatusCode::UNAUTHORIZED, + "an Outpost cannot revoke itself or others" + ); assert_eq!(h.status(revoke(Some(ADMIN))).await, StatusCode::NO_CONTENT); - assert_eq!(h.outpost_status(&token, UPLOAD).await, StatusCode::UNAUTHORIZED); - assert_eq!(h.outpost_status(&token, LEASED).await, StatusCode::UNAUTHORIZED, "the lease-bearing path is refused too"); + assert_eq!( + h.outpost_status(&token, UPLOAD).await, + StatusCode::UNAUTHORIZED + ); + assert_eq!( + h.outpost_status(&token, LEASED).await, + StatusCode::UNAUTHORIZED, + "the lease-bearing path is refused too" + ); // a revoked Outpost cannot be rotated back to life, an unknown one is 404 - let rotate = request("POST", &format!("/api/v1/wormhole/outposts/{outpost}/rotate"), "127.0.0.1", Some(ADMIN), None); + let rotate = request( + "POST", + &format!("/api/v1/wormhole/outposts/{outpost}/rotate"), + "127.0.0.1", + Some(ADMIN), + None, + ); assert_eq!(h.status(rotate).await, StatusCode::NOT_FOUND); - let unknown = request("POST", "/api/v1/wormhole/outposts/00000000-0000-0000-0000-00000000dead/revoke", "127.0.0.1", Some(ADMIN), None); + let unknown = request( + "POST", + "/api/v1/wormhole/outposts/00000000-0000-0000-0000-00000000dead/revoke", + "127.0.0.1", + Some(ADMIN), + None, + ); assert_eq!(h.status(unknown).await, StatusCode::NOT_FOUND); let events: Vec<(String, String)> = { let conn = rusqlite::Connection::open(h.db_file()).unwrap(); let mut stmt = conn.prepare("SELECT action, outcome FROM audit_events WHERE action LIKE 'outpost.credential_%' ORDER BY id").unwrap(); - stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?))).unwrap().collect::>().unwrap() + stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?))) + .unwrap() + .collect::>() + .unwrap() }; assert_eq!( events, [ - ("outpost.credential_revoke".to_string(), "succeeded".to_string()), - ("outpost.credential_rotate".to_string(), "failed".to_string()), - ("outpost.credential_revoke".to_string(), "failed".to_string()), + ( + "outpost.credential_revoke".to_string(), + "succeeded".to_string() + ), + ( + "outpost.credential_rotate".to_string(), + "failed".to_string() + ), + ( + "outpost.credential_revoke".to_string(), + "failed".to_string() + ), ] ); } @@ -167,7 +294,15 @@ async fn revoking_an_outpost_refuses_it_on_its_very_next_request() { async fn rotation_returns_the_new_token_once_and_bounds_the_old_one() { let h = harness().await; let (outpost, old) = h.pair("agent-one").await; - let rotate = |query: &str| request("POST", &format!("/api/v1/wormhole/outposts/{outpost}/rotate{query}"), "127.0.0.1", Some(ADMIN), None); + let rotate = |query: &str| { + request( + "POST", + &format!("/api/v1/wormhole/outposts/{outpost}/rotate{query}"), + "127.0.0.1", + Some(ADMIN), + None, + ) + }; // default grace: both work let first = h.call(rotate("")).await; assert_eq!(first.status(), StatusCode::OK); @@ -175,34 +310,86 @@ async fn rotation_returns_the_new_token_once_and_bounds_the_old_one() { let first = json_of(first).await; let fresh = first["upload_token"].as_str().unwrap().to_string(); assert!(first["previous_valid_until"].is_string()); - assert_ne!(h.outpost_status(&old, UPLOAD).await, StatusCode::UNAUTHORIZED); - assert_ne!(h.outpost_status(&fresh, UPLOAD).await, StatusCode::UNAUTHORIZED); + assert_ne!( + h.outpost_status(&old, UPLOAD).await, + StatusCode::UNAUTHORIZED + ); + assert_ne!( + h.outpost_status(&fresh, UPLOAD).await, + StatusCode::UNAUTHORIZED + ); // grace 0 ends every older token immediately let second = json_of(h.call(rotate("?grace_minutes=0")).await).await; assert!(second["previous_valid_until"].is_null()); - assert_eq!(h.outpost_status(&old, UPLOAD).await, StatusCode::UNAUTHORIZED); - assert_eq!(h.outpost_status(&fresh, UPLOAD).await, StatusCode::UNAUTHORIZED); - assert_ne!(h.outpost_status(second["upload_token"].as_str().unwrap(), UPLOAD).await, StatusCode::UNAUTHORIZED); - assert_eq!(h.status(rotate("?grace_minutes=5000")).await, StatusCode::BAD_REQUEST); - assert_eq!(h.status(request("POST", &format!("/api/v1/wormhole/outposts/{outpost}/rotate"), "127.0.0.1", None, None)).await, StatusCode::UNAUTHORIZED); + assert_eq!( + h.outpost_status(&old, UPLOAD).await, + StatusCode::UNAUTHORIZED + ); + assert_eq!( + h.outpost_status(&fresh, UPLOAD).await, + StatusCode::UNAUTHORIZED + ); + assert_ne!( + h.outpost_status(second["upload_token"].as_str().unwrap(), UPLOAD) + .await, + StatusCode::UNAUTHORIZED + ); + assert_eq!( + h.status(rotate("?grace_minutes=5000")).await, + StatusCode::BAD_REQUEST + ); + assert_eq!( + h.status(request( + "POST", + &format!("/api/v1/wormhole/outposts/{outpost}/rotate"), + "127.0.0.1", + None, + None + )) + .await, + StatusCode::UNAUTHORIZED + ); } #[tokio::test] async fn pairing_claims_are_limited_per_source_and_a_spoofed_header_does_not_help() { let h = harness().await; let claim = |peer: &str| { - let mut r = request("POST", "/api/v1/wormhole/claim", peer, None, Some(json!({"code": "GUESS", "outpost_name": "x"}))); - r.headers_mut().insert("x-forwarded-for", "198.51.100.77".parse().unwrap()); + let mut r = request( + "POST", + "/api/v1/wormhole/claim", + peer, + None, + Some(json!({"code": "GUESS", "outpost_name": "x"})), + ); + r.headers_mut() + .insert("x-forwarded-for", "198.51.100.77".parse().unwrap()); r }; let mut codes = Vec::new(); for _ in 0..8 { codes.push(h.status(claim("203.0.113.5")).await); } - assert_eq!(codes.iter().filter(|c| **c == StatusCode::GONE).count(), 5, "burst of five guesses"); - assert_eq!(codes.iter().filter(|c| **c == StatusCode::TOO_MANY_REQUESTS).count(), 3); - assert_eq!(h.status(claim("203.0.113.6")).await, StatusCode::GONE, "another source still has its own budget"); - let denied: i64 = h.scalar("SELECT COUNT(*) FROM audit_events WHERE action='outpost.pair' AND outcome='denied'"); + assert_eq!( + codes.iter().filter(|c| **c == StatusCode::GONE).count(), + 5, + "burst of five guesses" + ); + assert_eq!( + codes + .iter() + .filter(|c| **c == StatusCode::TOO_MANY_REQUESTS) + .count(), + 3 + ); + assert_eq!( + h.status(claim("203.0.113.6")).await, + StatusCode::GONE, + "another source still has its own budget" + ); + let denied: i64 = h.scalar( + "SELECT COUNT(*) FROM audit_events WHERE action='outpost.pair' AND outcome='denied'", + ); assert_eq!(denied, 1, "a flood is audited once, not once per request"); } @@ -213,22 +400,53 @@ fn operator_state(state: &mut HubState) { #[tokio::test] async fn an_emergency_login_flood_from_one_source_does_not_lock_out_a_legitimate_user() { let h = harness_with(operator_state).await; - let login = |peer: &str, password: &str| request("POST", "/api/v1/operator/login", peer, None, Some(json!({"password": password}))); + let login = |peer: &str, password: &str| { + request( + "POST", + "/api/v1/operator/login", + peer, + None, + Some(json!({"password": password})), + ) + }; let mut attacker = Vec::new(); for _ in 0..20 { let mut r = login("203.0.113.9", "wrong-guess"); - r.headers_mut().insert("x-forwarded-for", "192.0.2.1".parse().unwrap()); + r.headers_mut() + .insert("x-forwarded-for", "192.0.2.1".parse().unwrap()); attacker.push(h.status(r).await); } - assert_eq!(attacker.iter().filter(|s| **s == StatusCode::UNAUTHORIZED).count(), 5); - assert_eq!(attacker.iter().filter(|s| **s == StatusCode::TOO_MANY_REQUESTS).count(), 15); + assert_eq!( + attacker + .iter() + .filter(|s| **s == StatusCode::UNAUTHORIZED) + .count(), + 5 + ); + assert_eq!( + attacker + .iter() + .filter(|s| **s == StatusCode::TOO_MANY_REQUESTS) + .count(), + 15 + ); // the attacker with the right password is still refused while over budget ... - assert_eq!(h.status(login("203.0.113.9", "fixture-operator-password")).await, StatusCode::TOO_MANY_REQUESTS); + assert_eq!( + h.status(login("203.0.113.9", "fixture-operator-password")) + .await, + StatusCode::TOO_MANY_REQUESTS + ); // ... and a different source signs in fine - assert_eq!(h.status(login("198.51.100.1", "fixture-operator-password")).await, StatusCode::OK); - let denied: i64 = h.scalar("SELECT COUNT(*) FROM audit_events WHERE action='auth.login' AND outcome='denied'"); + assert_eq!( + h.status(login("198.51.100.1", "fixture-operator-password")) + .await, + StatusCode::OK + ); + let denied: i64 = h + .scalar("SELECT COUNT(*) FROM audit_events WHERE action='auth.login' AND outcome='denied'"); assert_eq!(denied, 1, "one audit row per source per minute"); - let passwords: i64 = h.scalar("SELECT COUNT(*) FROM audit_events WHERE actor_id||action LIKE '%wrong-guess%'"); + let passwords: i64 = + h.scalar("SELECT COUNT(*) FROM audit_events WHERE actor_id||action LIKE '%wrong-guess%'"); assert_eq!(passwords, 0); } @@ -237,19 +455,44 @@ async fn argon2_work_is_bounded_and_the_permit_is_released_after_each_login() { // no permits: refused at once rather than queued behind hashing let none = harness_with(|state| { operator_state(state); - state.limits = Arc::new(Limits::new(LimitConfig { argon2_concurrency: 0, ..LimitConfig::default() }, vec![])); + state.limits = Arc::new(Limits::new( + LimitConfig { + argon2_concurrency: 0, + ..LimitConfig::default() + }, + vec![], + )); }) .await; - let login = |peer: &str| request("POST", "/api/v1/operator/login", peer, None, Some(json!({"password": "fixture-operator-password"}))); + let login = |peer: &str| { + request( + "POST", + "/api/v1/operator/login", + peer, + None, + Some(json!({"password": "fixture-operator-password"})), + ) + }; let started = std::time::Instant::now(); - assert_eq!(none.status(login("203.0.113.1")).await, StatusCode::TOO_MANY_REQUESTS); - assert!(started.elapsed() < std::time::Duration::from_millis(500), "no hashing was started"); + assert_eq!( + none.status(login("203.0.113.1")).await, + StatusCode::TOO_MANY_REQUESTS + ); + assert!( + started.elapsed() < std::time::Duration::from_millis(500), + "no hashing was started" + ); // one permit, generous budgets: sequential logins all succeed, so the permit is returned let one = harness_with(|state| { operator_state(state); let loose = Quota::per_second(NonZeroU32::new(1000).unwrap()); state.limits = Arc::new(Limits::new( - LimitConfig { argon2_concurrency: 1, login_source: loose, login_account: loose, ..LimitConfig::default() }, + LimitConfig { + argon2_concurrency: 1, + login_source: loose, + login_account: loose, + ..LimitConfig::default() + }, vec![], )); }) @@ -261,25 +504,81 @@ async fn argon2_work_is_bounded_and_the_permit_is_released_after_each_login() { #[tokio::test] async fn the_shared_admin_token_stops_working_after_its_end_date() { - let ok = harness_with(|state| state.admin = AdminGate { token: Some(ADMIN.into()), token_expires_at: Some(chrono::Utc::now().timestamp() + 3600), ..Default::default() }).await; - assert_eq!(ok.status(request("GET", "/api/v1/orbits", "127.0.0.1", Some(ADMIN), None)).await, StatusCode::OK); + let ok = harness_with(|state| { + state.admin = AdminGate { + token: Some(ADMIN.into()), + token_expires_at: Some(chrono::Utc::now().timestamp() + 3600), + ..Default::default() + } + }) + .await; + assert_eq!( + ok.status(request( + "GET", + "/api/v1/orbits", + "127.0.0.1", + Some(ADMIN), + None + )) + .await, + StatusCode::OK + ); let actor: String = ok.scalar("SELECT actor_id FROM audit_events WHERE action='authorization.check' AND outcome='allowed' LIMIT 1"); - assert_eq!(actor, "legacy-admin-token", "every use is attributed to the legacy token in the audit log"); + assert_eq!( + actor, "legacy-admin-token", + "every use is attributed to the legacy token in the audit log" + ); - let past = harness_with(|state| state.admin = AdminGate { token: Some(ADMIN.into()), token_expires_at: Some(chrono::Utc::now().timestamp() - 1), ..Default::default() }).await; - assert_eq!(past.status(request("GET", "/api/v1/orbits", "127.0.0.1", Some(ADMIN), None)).await, StatusCode::UNAUTHORIZED); + let past = harness_with(|state| { + state.admin = AdminGate { + token: Some(ADMIN.into()), + token_expires_at: Some(chrono::Utc::now().timestamp() - 1), + ..Default::default() + } + }) + .await; + assert_eq!( + past.status(request( + "GET", + "/api/v1/orbits", + "127.0.0.1", + Some(ADMIN), + None + )) + .await, + StatusCode::UNAUTHORIZED + ); // an expired token must not silently fall back to anonymous development access either - let dev = harness_with(|state| state.admin = AdminGate { token: Some(ADMIN.into()), token_expires_at: Some(1), local_development: true }).await; - assert_eq!(dev.status(request("GET", "/api/v1/orbits", "127.0.0.1", None, None)).await, StatusCode::UNAUTHORIZED); + let dev = harness_with(|state| { + state.admin = AdminGate { + token: Some(ADMIN.into()), + token_expires_at: Some(1), + local_development: true, + } + }) + .await; + assert_eq!( + dev.status(request("GET", "/api/v1/orbits", "127.0.0.1", None, None)) + .await, + StatusCode::UNAUTHORIZED + ); assert!(!dev.state.admin.token_active()); } #[tokio::test] async fn sso_endpoints_are_rate_limited_per_source() { let h = harness().await; // OIDC disabled answers 404 before limiting; exercise the limiter directly - let source = h.state.limits.source(Some("203.0.113.1:1".parse().unwrap()), &axum::http::HeaderMap::new()); - let allowed = (0..60).filter(|_| h.state.limits.oidc_login_allowed(source)).count(); + let source = h.state.limits.source( + Some("203.0.113.1:1".parse().unwrap()), + &axum::http::HeaderMap::new(), + ); + let allowed = (0..60) + .filter(|_| h.state.limits.oidc_login_allowed(source)) + .count(); assert_eq!(allowed, 15, "burst, then refused"); - let other = h.state.limits.source(Some("203.0.113.2:1".parse().unwrap()), &axum::http::HeaderMap::new()); + let other = h.state.limits.source( + Some("203.0.113.2:1".parse().unwrap()), + &axum::http::HeaderMap::new(), + ); assert!(h.state.limits.oidc_login_allowed(other)); } diff --git a/crates/tessera-hub/src/api/export_tests.rs b/crates/tessera-hub/src/api/export_tests.rs index 15128ef..aab4c26 100644 --- a/crates/tessera-hub/src/api/export_tests.rs +++ b/crates/tessera-hub/src/api/export_tests.rs @@ -23,7 +23,9 @@ struct Harness { async fn harness_with(gate: Option) -> Harness { let dir = tempfile::tempdir().unwrap(); - let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault").await.unwrap(); + let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") + .await + .unwrap(); state.admin.token = Some(ADMIN.into()); if let Some(gate) = gate { state.exports = std::sync::Arc::new(gate); @@ -48,7 +50,12 @@ impl Harness { paths: vec![], restore_hints: hints, }; - self.state.vault.write().await.snapshot(manifest, payload, false).unwrap(); + self.state + .vault + .write() + .await + .snapshot(manifest, payload, false) + .unwrap(); id } @@ -77,19 +84,28 @@ impl Harness { let mut stmt = conn .prepare("SELECT action, outcome FROM audit_events WHERE resource_type='snapshot' AND resource_id=?1 ORDER BY id") .unwrap(); - stmt.query_map([snapshot.to_string()], |r| Ok((r.get(0)?, r.get(1)?))).unwrap().collect::>().unwrap() + stmt.query_map([snapshot.to_string()], |r| Ok((r.get(0)?, r.get(1)?))) + .unwrap() + .collect::>() + .unwrap() } } async fn gunzip(bytes: &[u8]) -> Vec { let mut out = Vec::new(); - GzipDecoder::new(tokio::io::BufReader::new(bytes)).read_to_end(&mut out).await.unwrap(); + GzipDecoder::new(tokio::io::BufReader::new(bytes)) + .read_to_end(&mut out) + .await + .unwrap(); out } async fn gzip(bytes: &[u8]) -> Vec { let mut out = Vec::new(); - GzipEncoder::new(tokio::io::BufReader::new(bytes)).read_to_end(&mut out).await.unwrap(); + GzipEncoder::new(tokio::io::BufReader::new(bytes)) + .read_to_end(&mut out) + .await + .unwrap(); out } @@ -106,47 +122,142 @@ async fn each_kind_of_snapshot_downloads_with_the_right_format_and_honest_header let already_gzip = gzip(b"SELECT 1;\n").await; let pg_custom = [b"PGDMP\x01\x0e\x00".as_slice(), &[7u8; 300]].concat(); let cases: Vec<(&str, serde_json::Value, Vec, &str, bool)> = vec![ - ("postgres plain", serde_json::json!({"engine": "postgres", "format": "plain"}), b"CREATE TABLE t (x int);\n".repeat(200), "sql.gz", true), - ("mysql plain", serde_json::json!({"engine": "mysql", "format": "plain"}), b"INSERT INTO t VALUES (1);\n".repeat(200), "sql.gz", true), - ("postgres custom", serde_json::json!({"format": "custom"}), pg_custom, "dump", false), - ("tar by hint", serde_json::json!({"format": "tar"}), ustar(b"file contents"), "tar.gz", true), - ("tar with no hint (legacy restic)", serde_json::Value::Null, ustar(b"file contents"), "tar.gz", true), - ("hub filesystem archive", serde_json::json!({"format": "tessera-fs-v1", "paths": []}), b"k\0\x02\0\0\0\0\0\0\0ab".to_vec(), "tessera-fs.gz", true), - ("sqlite", serde_json::json!({"format": "sqlite"}), [b"SQLite format 3\0".as_slice(), &[0u8; 200]].concat(), "sqlite.gz", true), - ("sql already gzip", serde_json::json!({"format": "sql_gzip"}), already_gzip.clone(), "sql.gz", false), - ("labelled plain but gzip", serde_json::json!({"format": "plain"}), already_gzip, "sql.gz", false), - ("no hints at all", serde_json::Value::Null, b"opaque".repeat(100), "dump.gz", true), + ( + "postgres plain", + serde_json::json!({"engine": "postgres", "format": "plain"}), + b"CREATE TABLE t (x int);\n".repeat(200), + "sql.gz", + true, + ), + ( + "mysql plain", + serde_json::json!({"engine": "mysql", "format": "plain"}), + b"INSERT INTO t VALUES (1);\n".repeat(200), + "sql.gz", + true, + ), + ( + "postgres custom", + serde_json::json!({"format": "custom"}), + pg_custom, + "dump", + false, + ), + ( + "tar by hint", + serde_json::json!({"format": "tar"}), + ustar(b"file contents"), + "tar.gz", + true, + ), + ( + "tar with no hint (legacy restic)", + serde_json::Value::Null, + ustar(b"file contents"), + "tar.gz", + true, + ), + ( + "hub filesystem archive", + serde_json::json!({"format": "tessera-fs-v1", "paths": []}), + b"k\0\x02\0\0\0\0\0\0\0ab".to_vec(), + "tessera-fs.gz", + true, + ), + ( + "sqlite", + serde_json::json!({"format": "sqlite"}), + [b"SQLite format 3\0".as_slice(), &[0u8; 200]].concat(), + "sqlite.gz", + true, + ), + ( + "sql already gzip", + serde_json::json!({"format": "sql_gzip"}), + already_gzip.clone(), + "sql.gz", + false, + ), + ( + "labelled plain but gzip", + serde_json::json!({"format": "plain"}), + already_gzip, + "sql.gz", + false, + ), + ( + "no hints at all", + serde_json::Value::Null, + b"opaque".repeat(100), + "dump.gz", + true, + ), ]; for (name, hints, payload, extension, compressed) in cases { let id = h.snapshot(hints, &payload).await; let response = h.download(id, Method::GET).await; assert_eq!(response.status(), StatusCode::OK, "{name}"); let headers = response.headers().clone(); - assert!(headers.get(header::CONTENT_ENCODING).is_none(), "{name}: the file must not be content-encoded"); + assert!( + headers.get(header::CONTENT_ENCODING).is_none(), + "{name}: the file must not be content-encoded" + ); assert_eq!(headers[header::CACHE_CONTROL], "no-store", "{name}"); assert_eq!(headers[header::X_CONTENT_TYPE_OPTIONS], "nosniff", "{name}"); - assert_eq!(headers[header::CONTENT_DISPOSITION], format!("attachment; filename=\"{id}.{extension}\""), "{name}"); - let content_type = if extension.ends_with("gz") { "application/gzip" } else { "application/octet-stream" }; + assert_eq!( + headers[header::CONTENT_DISPOSITION], + format!("attachment; filename=\"{id}.{extension}\""), + "{name}" + ); + let content_type = if extension.ends_with("gz") { + "application/gzip" + } else { + "application/octet-stream" + }; assert_eq!(headers[header::CONTENT_TYPE], content_type, "{name}"); - let body = to_bytes(response.into_body(), 1 << 26).await.unwrap().to_vec(); + let body = to_bytes(response.into_body(), 1 << 26) + .await + .unwrap() + .to_vec(); if compressed { - assert!(headers.get(header::CONTENT_LENGTH).is_none(), "{name}: the compressed size is not known up front"); + assert!( + headers.get(header::CONTENT_LENGTH).is_none(), + "{name}: the compressed size is not known up front" + ); assert_eq!(&body[..2], &[0x1f, 0x8b], "{name}: a real gzip stream"); - assert_eq!(gunzip(&body).await, payload, "{name}: decompresses to exactly the original bytes"); + assert_eq!( + gunzip(&body).await, + payload, + "{name}: decompresses to exactly the original bytes" + ); } else { assert_eq!(body, payload, "{name}: sent untouched"); - assert_eq!(headers[header::CONTENT_LENGTH], payload.len().to_string(), "{name}: exact length"); + assert_eq!( + headers[header::CONTENT_LENGTH], + payload.len().to_string(), + "{name}: exact length" + ); } } - assert!(h.export_dirs().is_empty(), "nothing is left behind after the downloads"); + assert!( + h.export_dirs().is_empty(), + "nothing is left behind after the downloads" + ); } #[tokio::test] async fn a_large_snapshot_is_streamed_in_small_frames_and_arrives_intact() { let h = harness().await; let line = b"INSERT INTO events VALUES (1, 'a fairly ordinary row of text');\n"; - let payload: Vec = line.iter().copied().cycle().take(24 * 1024 * 1024).collect(); - let id = h.snapshot(serde_json::json!({"format": "plain"}), &payload).await; + let payload: Vec = line + .iter() + .copied() + .cycle() + .take(24 * 1024 * 1024) + .collect(); + let id = h + .snapshot(serde_json::json!({"format": "plain"}), &payload) + .await; let response = h.download(id, Method::GET).await; let mut stream = response.into_body().into_data_stream(); let (mut compressed, mut frames, mut largest) = (Vec::new(), 0, 0); @@ -156,65 +267,129 @@ async fn a_large_snapshot_is_streamed_in_small_frames_and_arrives_intact() { largest = largest.max(frame.len()); compressed.extend_from_slice(&frame); } - assert!(frames > 5 && largest <= 256 * 1024, "{frames} frames, largest {largest} bytes"); + assert!( + frames > 5 && largest <= 256 * 1024, + "{frames} frames, largest {largest} bytes" + ); let restored = gunzip(&compressed).await; - assert_eq!((restored.len(), Sha256::digest(&restored)), (payload.len(), Sha256::digest(&payload))); - assert!(compressed.len() < payload.len() / 10, "the stream really is compressed"); + assert_eq!( + (restored.len(), Sha256::digest(&restored)), + (payload.len(), Sha256::digest(&payload)) + ); + assert!( + compressed.len() < payload.len() / 10, + "the stream really is compressed" + ); } #[tokio::test] async fn the_audit_trail_and_cleanup_cover_a_finished_and_an_abandoned_download() { let h = harness().await; - let finished = h.snapshot(serde_json::json!({"format": "plain"}), &b"SELECT 1;\n".repeat(50_000)).await; - let body = to_bytes(h.download(finished, Method::GET).await.into_body(), 1 << 26).await.unwrap(); + let finished = h + .snapshot( + serde_json::json!({"format": "plain"}), + &b"SELECT 1;\n".repeat(50_000), + ) + .await; + let body = to_bytes(h.download(finished, Method::GET).await.into_body(), 1 << 26) + .await + .unwrap(); assert!(!body.is_empty()); let expected = |last: (&str, &str)| { - vec![("export.requested".to_string(), "allowed".to_string()), ("export.ready".into(), "succeeded".into()), (last.0.to_string(), last.1.to_string())] + vec![ + ("export.requested".to_string(), "allowed".to_string()), + ("export.ready".into(), "succeeded".into()), + (last.0.to_string(), last.1.to_string()), + ] }; - assert_eq!(h.audit(finished), expected(("export.finished", "succeeded"))); + assert_eq!( + h.audit(finished), + expected(("export.finished", "succeeded")) + ); assert!(h.export_dirs().is_empty()); // The client reads one frame and goes away. - let abandoned = h.snapshot(serde_json::json!({"format": "plain"}), &b"SELECT 2;\n".repeat(2_000_000)).await; + let abandoned = h + .snapshot( + serde_json::json!({"format": "plain"}), + &b"SELECT 2;\n".repeat(2_000_000), + ) + .await; let response = h.download(abandoned, Method::GET).await; - assert_eq!(h.export_dirs().len(), 1, "the export exists while the body is alive"); + assert_eq!( + h.export_dirs().len(), + 1, + "the export exists while the body is alive" + ); let mut stream = response.into_body().into_data_stream(); stream.next().await.unwrap().unwrap(); drop(stream); - assert_eq!(h.audit(abandoned), expected(("export.disconnected", "failed"))); - assert!(h.export_dirs().is_empty(), "the export is deleted when the client disconnects"); + assert_eq!( + h.audit(abandoned), + expected(("export.disconnected", "failed")) + ); + assert!( + h.export_dirs().is_empty(), + "the export is deleted when the client disconnects" + ); } #[tokio::test] async fn only_one_export_runs_when_the_limit_is_one_and_a_refused_request_leaks_nothing() { let h = harness_with(Some(ExportGate::new(1, 0))).await; - let id = h.snapshot(serde_json::json!({"format": "plain"}), &b"SELECT 1;\n".repeat(10_000)).await; + let id = h + .snapshot( + serde_json::json!({"format": "plain"}), + &b"SELECT 1;\n".repeat(10_000), + ) + .await; let first = h.download(id, Method::GET).await; assert_eq!(first.status(), StatusCode::OK); let started = std::time::Instant::now(); let second = h.download(id, Method::GET).await; assert_eq!(second.status(), StatusCode::TOO_MANY_REQUESTS); - assert!(started.elapsed() < std::time::Duration::from_secs(1), "refused at once, not queued"); - assert_eq!(h.export_dirs().len(), 1, "the refused request wrote nothing"); + assert!( + started.elapsed() < std::time::Duration::from_secs(1), + "refused at once, not queued" + ); + assert_eq!( + h.export_dirs().len(), + 1, + "the refused request wrote nothing" + ); drop(first); let third = h.download(id, Method::GET).await; - assert_eq!(third.status(), StatusCode::OK, "the slot returns when the first download ends"); + assert_eq!( + third.status(), + StatusCode::OK, + "the slot returns when the first download ends" + ); let audited = h.audit(id); - assert!(audited.contains(&("export.requested".to_string(), "failed".to_string())), "{audited:?}"); + assert!( + audited.contains(&("export.requested".to_string(), "failed".to_string())), + "{audited:?}" + ); } #[tokio::test] async fn an_export_that_would_not_fit_on_the_disk_is_refused_before_anything_is_written() { let h = harness_with(Some(ExportGate::new(2, u64::MAX / 2))).await; - let id = h.snapshot(serde_json::json!({"format": "plain"}), b"SELECT 1;\n").await; - assert_eq!(h.download(id, Method::GET).await.status(), StatusCode::INSUFFICIENT_STORAGE); + let id = h + .snapshot(serde_json::json!({"format": "plain"}), b"SELECT 1;\n") + .await; + assert_eq!( + h.download(id, Method::GET).await.status(), + StatusCode::INSUFFICIENT_STORAGE + ); assert!(h.export_dirs().is_empty()); } #[tokio::test] async fn head_requests_do_not_run_an_export() { let h = harness().await; - let id = h.snapshot(serde_json::json!({"format": "plain"}), b"SELECT 1;\n").await; + let id = h + .snapshot(serde_json::json!({"format": "plain"}), b"SELECT 1;\n") + .await; let response = h.download(id, Method::HEAD).await; assert_eq!(response.status(), StatusCode::METHOD_NOT_ALLOWED); assert!(h.export_dirs().is_empty()); diff --git a/crates/tessera-hub/src/api/gate.rs b/crates/tessera-hub/src/api/gate.rs index 8fea817..4091680 100644 --- a/crates/tessera-hub/src/api/gate.rs +++ b/crates/tessera-hub/src/api/gate.rs @@ -15,14 +15,23 @@ fn now() -> i64 { chrono::Utc::now().timestamp() } -fn audit(state: &HubState, actor: &OperatorActor, resource: AuditResource, allowed: bool) -> Result<(), StatusCode> { +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 }, + if allowed { + AuditOutcome::Allowed + } else { + AuditOutcome::Denied + }, actor.request_id, ) .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR) @@ -38,24 +47,42 @@ fn internal(error: impl std::fmt::Display) -> StatusCode { 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) } + 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> { +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 { - 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 permission.grantable() { + { + state + .db + .has_permission( + actor.subject.user_id.as_deref(), + &actor.subject.groups, + permission.as_str(), + &orbit.to_string(), + now(), + ) + .map_err(internal) + } + } else { + Ok(false) + } }; if !held(Permission::OrbitRead)? { audit(state, actor, resource, false)?; @@ -63,40 +90,67 @@ pub(super) fn scoped(state: &HubState, actor: &OperatorActor, permission: Permis } let allowed = held(permission)?; audit(state, actor, resource, allowed)?; - if allowed { Ok(()) } else { Err(StatusCode::FORBIDDEN) } + if allowed { + Ok(()) + } else { + Err(StatusCode::FORBIDDEN) + } } /// Use one relation. Administrators always; anyone else only through a live grant on that very relation /// (not on its orbit, not on an older version of it). Everything else answers 404, so a relation's /// existence is not confirmed to someone who cannot use it. #[allow(dead_code)] // used by the refresh run (M6c); the matrix already exercises the list built on the same grants -pub(super) fn relation(state: &HubState, actor: &OperatorActor, relation: Uuid) -> Result<(), StatusCode> { +pub(super) fn relation( + state: &HubState, + actor: &OperatorActor, + relation: Uuid, +) -> Result<(), StatusCode> { let resource = AuditResource::Relation(relation); if actor.subject.admin { return audit(state, actor, resource, true); } let granted = state .db - .granted_relations(actor.subject.user_id.as_deref(), &actor.subject.groups, now()) + .granted_relations( + actor.subject.user_id.as_deref(), + &actor.subject.groups, + now(), + ) .map_err(internal)?; let allowed = granted.iter().any(|id| id == &relation.to_string()); audit(state, actor, resource, allowed)?; - if allowed { Ok(()) } else { Err(StatusCode::NOT_FOUND) } + if allowed { + Ok(()) + } else { + Err(StatusCode::NOT_FOUND) + } } /// The relations a caller may use: `None` for an administrator (all), otherwise their granted ids. /// A caller with none gets 403 rather than an empty list. -pub(super) fn visible_relations(state: &HubState, actor: &OperatorActor) -> Result>, StatusCode> { +pub(super) fn visible_relations( + state: &HubState, + actor: &OperatorActor, +) -> Result>, StatusCode> { if actor.subject.admin { audit(state, actor, AuditResource::Api, true)?; return Ok(None); } let granted = state .db - .granted_relations(actor.subject.user_id.as_deref(), &actor.subject.groups, now()) + .granted_relations( + actor.subject.user_id.as_deref(), + &actor.subject.groups, + now(), + ) .map_err(internal)?; audit(state, actor, AuditResource::Api, !granted.is_empty())?; - if granted.is_empty() { Err(StatusCode::FORBIDDEN) } else { Ok(Some(granted)) } + if granted.is_empty() { + Err(StatusCode::FORBIDDEN) + } else { + Ok(Some(granted)) + } } /// Which orbits a list may show. @@ -124,7 +178,11 @@ impl Visible { /// 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 { +pub(super) fn visible( + state: &HubState, + actor: &OperatorActor, + permission: Permission, +) -> Result { if actor.subject.admin { audit(state, actor, AuditResource::Api, true)?; return Ok(Visible::All); @@ -135,12 +193,25 @@ pub(super) fn visible(state: &HubState, actor: &OperatorActor, permission: Permi } state .db - .permitted_orbits(actor.subject.user_id.as_deref(), &actor.subject.groups, permission.as_str(), now()) + .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| -> HashSet { set.iter().filter_map(|id| Uuid::parse_str(id).ok()).collect() }; + let wanted = if permission == Permission::OrbitRead { + None + } else { + Some(fetch(permission)?) + }; + let parse = |set: &HashSet| -> HashSet { + 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)), @@ -148,10 +219,19 @@ pub(super) fn visible(state: &HubState, actor: &OperatorActor, permission: Permi (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()), + (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) } + if nothing { + Err(StatusCode::FORBIDDEN) + } else { + Ok(result) + } } diff --git a/crates/tessera-hub/src/api/jobs.rs b/crates/tessera-hub/src/api/jobs.rs index 0a8b543..e83eebf 100644 --- a/crates/tessera-hub/src/api/jobs.rs +++ b/crates/tessera-hub/src/api/jobs.rs @@ -12,7 +12,8 @@ use base64::Engine; use sha2::{Digest, Sha256}; use std::{net::SocketAddr, pin::Pin, time::Duration}; use tessera_core::job::{ - CaptureEvent, CaptureFormat, CaptureJob, CaptureLease, CaptureProfile, CaptureReport, ResticCaptureCommit, + CaptureEvent, CaptureFormat, CaptureJob, CaptureLease, CaptureProfile, CaptureReport, + ResticCaptureCommit, }; use tessera_core::{restore::DatabaseIdentity, SnapshotManifest}; use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt}; @@ -42,7 +43,12 @@ async fn profiles( 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())) + Ok(Json( + profiles + .into_iter() + .filter(|profile| visible.contains(profile.orbit_id)) + .collect(), + )) } async fn register_profile( @@ -120,7 +126,10 @@ async fn history( 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)?; + 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); } @@ -145,7 +154,11 @@ async fn history( } /// 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 { +fn job_in_scope( + state: &HubState, + actor: &super::routes::OperatorActor, + id: Uuid, +) -> Result { let job = state.db.capture_job(id).map_err(internal)?; match job { Some(job) => { @@ -186,10 +199,18 @@ async fn claim( Path(application): Path, ) -> Result>, StatusCode> { let outpost = outpost(&state, &headers)?; - let mut lease = state.db.claim_capture(outpost, application, now()).map_err(internal)?; + let mut lease = state + .db + .claim_capture(outpost, application, now()) + .map_err(internal)?; if let Some(lease) = &mut lease { lease.restic |= lease.profile.format == CaptureFormat::Filesystem - || state.vault.read().await.outpost_repository_configured(lease.profile.orbit_id).map_err(internal)?; + || state + .vault + .read() + .await + .outpost_repository_configured(lease.profile.orbit_id) + .map_err(internal)?; } Ok(Json(lease)) } @@ -227,8 +248,16 @@ async fn upload( .map_err(internal)? .ok_or(StatusCode::CONFLICT)?; if job.profile.format == CaptureFormat::Filesystem - || state.db.restic_required(job.profile.orbit_id).map_err(internal)? - || state.vault.read().await.outpost_repository_configured(job.profile.orbit_id).map_err(internal)? + || state + .db + .restic_required(job.profile.orbit_id) + .map_err(internal)? + || state + .vault + .read() + .await + .outpost_repository_configured(job.profile.orbit_id) + .map_err(internal)? { return Err(StatusCode::CONFLICT); } @@ -240,7 +269,12 @@ async fn upload( .map_err(|_| StatusCode::BAD_REQUEST)?; let identity: DatabaseIdentity = serde_json::from_slice(&decoded).map_err(|_| StatusCode::BAD_REQUEST)?; - if !job.profile.format.engine().is_some_and(|engine| identity.valid(engine)) { + if !job + .profile + .format + .engine() + .is_some_and(|engine| identity.valid(engine)) + { return Err(StatusCode::BAD_REQUEST); } Ok(identity) @@ -301,16 +335,23 @@ async fn commit_restic( Json(commit): Json, ) -> Result, StatusCode> { let outpost = outpost(&state, &headers)?; - let job = state.db.capture_upload(outpost, id, commit.lease_id, now()) - .map_err(internal)?.ok_or(StatusCode::CONFLICT)?; + let job = state + .db + .capture_upload(outpost, id, commit.lease_id, now()) + .map_err(internal)? + .ok_or(StatusCode::CONFLICT)?; if let Some(snapshot) = job.snapshot_id { return Ok(Json(serde_json::json!({ "snapshot_id": snapshot }))); } let engine = job.profile.format.engine(); - if commit.identity.as_ref().is_some_and(|identity| !engine.is_some_and(|engine| identity.valid(engine))) - || (engine.is_some() && !commit.sha256.as_ref().is_some_and(|hash| { - hash.len() == 64 && hash.bytes().all(|byte| byte.is_ascii_hexdigit()) - })) + if commit + .identity + .as_ref() + .is_some_and(|identity| !engine.is_some_and(|engine| identity.valid(engine))) + || (engine.is_some() + && !commit.sha256.as_ref().is_some_and(|hash| { + hash.len() == 64 && hash.bytes().all(|byte| byte.is_ascii_hexdigit()) + })) || (engine.is_none() && commit.sha256.is_some()) { return Err(StatusCode::BAD_REQUEST); @@ -328,7 +369,11 @@ async fn commit_restic( } Ok(()) }) - }).await.map_err(internal)?.map_err(internal)?.ok_or(StatusCode::CONFLICT)?; + }) + .await + .map_err(internal)? + .map_err(internal)? + .ok_or(StatusCode::CONFLICT)?; if created && state.prune_orbit(orbit_id).await.is_err() { tracing::warn!(%id, %orbit_id, "could not apply capture retention"); } @@ -437,10 +482,27 @@ pub(super) fn outpost(state: &HubState, headers: &HeaderMap) -> Result (Principal::Outpost(id), AuditResource::Outpost(id), AuditOutcome::Allowed), - Err(_) => (Principal::Anonymous, AuditResource::Api, AuditOutcome::Denied), + Ok(id) => ( + Principal::Outpost(id), + AuditResource::Outpost(id), + AuditOutcome::Allowed, + ), + Err(_) => ( + Principal::Anonymous, + AuditResource::Api, + AuditOutcome::Denied, + ), }; - state.db.audit_event(&actor, AuditAction::Authentication, resource, outcome, Uuid::new_v4()).map_err(internal)?; + state + .db + .audit_event( + &actor, + AuditAction::Authentication, + resource, + outcome, + Uuid::new_v4(), + ) + .map_err(internal)?; result } diff --git a/crates/tessera-hub/src/api/mod.rs b/crates/tessera-hub/src/api/mod.rs index 65a0981..128e580 100644 --- a/crates/tessera-hub/src/api/mod.rs +++ b/crates/tessera-hub/src/api/mod.rs @@ -1,28 +1,28 @@ mod access; -mod catalog; -mod gate; -mod jobs; -mod oidc; -mod refresh; -mod relations; -mod orbit; -mod restore; -mod routes; -mod session; -#[cfg(test)] -mod auth_contract; -#[cfg(test)] -mod oidc_tests; -#[cfg(test)] -mod credentials_tests; #[cfg(test)] mod access_tests; #[cfg(test)] +mod auth_contract; +mod catalog; +#[cfg(test)] +mod credentials_tests; +#[cfg(test)] mod export_tests; +mod gate; +mod jobs; +mod oidc; +#[cfg(test)] +mod oidc_tests; +mod orbit; +mod refresh; #[cfg(test)] mod refresh_tests; +mod relations; +mod restore; +mod routes; +mod session; pub use orbit::run_orbit_internal; -pub use routes::router; -pub(crate) use restore::artifact; pub(crate) use relations::identity_facts; +pub(crate) use restore::artifact; +pub use routes::router; diff --git a/crates/tessera-hub/src/api/oidc.rs b/crates/tessera-hub/src/api/oidc.rs index b2eb5cc..387a880 100644 --- a/crates/tessera-hub/src/api/oidc.rs +++ b/crates/tessera-hub/src/api/oidc.rs @@ -39,7 +39,11 @@ fn correlation_cookie(value: Option<&str>) -> HeaderValue { let text = format!( "{CORRELATION}={}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age={}", value.unwrap_or_default(), - if value.is_some() { crate::db::oidc_login::TTL_SECS } else { 0 }, + if value.is_some() { + crate::db::oidc_login::TTL_SECS + } else { + 0 + }, ); HeaderValue::from_str(&text).expect("cookie is ASCII") } @@ -56,12 +60,19 @@ fn correlation_from(headers: &HeaderMap) -> Option { .flat_map(|line| line.split(';')) .find_map(|pair| { let (name, value) = pair.trim().split_once('=')?; - (name == CORRELATION && !value.is_empty() && value.len() <= 128).then(|| value.to_string()) + (name == CORRELATION && !value.is_empty() && value.len() <= 128) + .then(|| value.to_string()) }) } -async fn login(peer: Option>, State(state): State, headers: HeaderMap) -> Response { - let Some(oidc) = state.oidc.clone() else { return StatusCode::NOT_FOUND.into_response() }; +async fn login( + peer: Option>, + State(state): State, + headers: HeaderMap, +) -> Response { + let Some(oidc) = state.oidc.clone() else { + return StatusCode::NOT_FOUND.into_response(); + }; let source = state.limits.source(peer.map(|ConnectInfo(a)| a), &headers); if !state.limits.oidc_login_allowed(source) { return StatusCode::TOO_MANY_REQUESTS.into_response(); @@ -71,13 +82,18 @@ async fn login(peer: Option>, State(state): State return failure(&state, "unavailable", StatusCode::SERVICE_UNAVAILABLE).await, }; let browser = uuid::Uuid::new_v4().to_string(); - let stored = state.db.begin_oidc_login(&begun.state, &browser, &begun.nonce, &begun.verifier, now()); + let stored = + state + .db + .begin_oidc_login(&begun.state, &browser, &begun.nonce, &begun.verifier, now()); if !matches!(stored, Ok(true)) { return failure(&state, "unavailable", StatusCode::SERVICE_UNAVAILABLE).await; } let mut response = Redirect::to(&begun.url).into_response(); no_store(response.headers_mut()); - response.headers_mut().append(header::SET_COOKIE, correlation_cookie(Some(&browser))); + response + .headers_mut() + .append(header::SET_COOKIE, correlation_cookie(Some(&browser))); response } @@ -87,7 +103,9 @@ async fn callback( headers: HeaderMap, Query(query): Query, ) -> Response { - let Some(oidc) = state.oidc.clone() else { return StatusCode::NOT_FOUND.into_response() }; + let Some(oidc) = state.oidc.clone() else { + return StatusCode::NOT_FOUND.into_response(); + }; let source = state.limits.source(peer.map(|ConnectInfo(a)| a), &headers); if !state.limits.oidc_callback_allowed(source) { return StatusCode::TOO_MANY_REQUESTS.into_response(); @@ -105,7 +123,9 @@ async fn callback( }; no_store(response.headers_mut()); // The correlation cookie is single-use whatever happened. - response.headers_mut().append(header::SET_COOKIE, correlation_cookie(None)); + response + .headers_mut() + .append(header::SET_COOKIE, correlation_cookie(None)); response } @@ -118,14 +138,22 @@ async fn complete( ) -> Result { let request = uuid::Uuid::new_v4(); let audit = |principal: &Principal, outcome| { - let _ = state.db.audit_event(principal, AuditAction::Login, AuditResource::Session, outcome, request); + let _ = state.db.audit_event( + principal, + AuditAction::Login, + AuditResource::Session, + outcome, + request, + ); }; let Some(state_param) = query.state.as_deref() else { audit(&Principal::Anonymous, AuditOutcome::Failed); return Err("invalid_state"); }; let browser = correlation_from(headers); - let transaction = state.db.consume_oidc_login(state_param, browser.as_deref(), now()); + let transaction = state + .db + .consume_oidc_login(state_param, browser.as_deref(), now()); let Ok(Some((nonce, verifier))) = transaction else { audit(&Principal::Anonymous, AuditOutcome::Failed); return Err("invalid_state"); @@ -135,7 +163,11 @@ async fn complete( audit(&Principal::Anonymous, AuditOutcome::Failed); return Err("denied"); } - let Some(code) = query.code.as_deref().filter(|c| !c.is_empty() && c.len() <= 2048) else { + let Some(code) = query + .code + .as_deref() + .filter(|c| !c.is_empty() && c.len() <= 2048) + else { audit(&Principal::Anonymous, AuditOutcome::Failed); return Err("failed"); }; @@ -143,18 +175,36 @@ async fn complete( Ok(identity) => identity, Err(error) => { audit(&Principal::Anonymous, AuditOutcome::Failed); - return Err(if matches!(error, OidcError::Unavailable) { "unavailable" } else { "failed" }); + return Err(if matches!(error, OidcError::Unavailable) { + "unavailable" + } else { + "failed" + }); } }; let admin = oidc.config.is_admin(&identity); // Bounded, so a hostile or huge claim cannot bloat the session row. - let groups: Vec = identity.groups.iter().filter(|g| !g.is_empty() && g.len() <= 128).take(64).cloned().collect(); + let groups: Vec = 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, &groups, now)); + .upsert_user( + &identity.issuer, + &identity.subject, + &identity.display_name, + 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); @@ -169,7 +219,13 @@ async fn complete( } async fn failure(state: &HubState, code: &'static str, status: StatusCode) -> Response { - let _ = state.db.audit_event(&Principal::Anonymous, AuditAction::Login, AuditResource::Session, AuditOutcome::Failed, uuid::Uuid::new_v4()); + let _ = state.db.audit_event( + &Principal::Anonymous, + AuditAction::Login, + AuditResource::Session, + AuditOutcome::Failed, + uuid::Uuid::new_v4(), + ); let mut response = (status, code).into_response(); no_store(response.headers_mut()); response diff --git a/crates/tessera-hub/src/api/oidc_tests.rs b/crates/tessera-hub/src/api/oidc_tests.rs index 2014f14..7848972 100644 --- a/crates/tessera-hub/src/api/oidc_tests.rs +++ b/crates/tessera-hub/src/api/oidc_tests.rs @@ -94,7 +94,9 @@ fn sign(alg: &str, kid: &str, signer: usize, claims: &Value) -> String { let header = json!({"alg": alg, "typ": "JWT", "kid": kid}); let signing_input = format!("{}.{}", b64(header.to_string()), b64(claims.to_string())); let signature = match alg { - "RS256" => b64(SigningKey::::new(keys()[signer].clone()).sign(signing_input.as_bytes()).to_bytes()), + "RS256" => b64(SigningKey::::new(keys()[signer].clone()) + .sign(signing_input.as_bytes()) + .to_bytes()), "HS256" => { let mut mac = Hmac::::new_from_slice(CLIENT_SECRET.as_bytes()).unwrap(); mac.update(signing_input.as_bytes()); @@ -112,10 +114,14 @@ impl Respond for TokenEndpoint { return ResponseTemplate::new(scenario.token_status); } let form: std::collections::HashMap = - openidconnect::url::form_urlencoded::parse(&request.body).into_owned().collect(); + openidconnect::url::form_urlencoded::parse(&request.body) + .into_owned() + .collect(); // Real PKCE check: S256(code_verifier) must equal the challenge sent at /authorize. let verifier = form.get("code_verifier").cloned().unwrap_or_default(); - if b64(Sha256::digest(verifier.as_bytes())) != scenario.challenge || form.get("code").map(String::as_str) != Some("good-code") { + if b64(Sha256::digest(verifier.as_bytes())) != scenario.challenge + || form.get("code").map(String::as_str) != Some("good-code") + { return ResponseTemplate::new(400).set_body_json(json!({"error": "invalid_grant"})); } let now = chrono::Utc::now().timestamp(); @@ -155,12 +161,17 @@ impl Idp { async fn start() -> Self { // Generate the RSA keys up front: inside a mock handler, a slow debug-build // keygen would eat the hub's HTTP timeout. - tokio::task::spawn_blocking(|| { keys(); }).await.unwrap(); + tokio::task::spawn_blocking(|| { + keys(); + }) + .await + .unwrap(); let server = MockServer::start().await; let scenario = Arc::new(Mutex::new(Scenario::default())); let jwks = Arc::new(Mutex::new(vec![("k1", 0usize)])); let issuer = server.uri(); - Mock::given(method("GET")).and(path("/.well-known/openid-configuration")) + Mock::given(method("GET")) + .and(path("/.well-known/openid-configuration")) .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "issuer": issuer, "authorization_endpoint": format!("{issuer}/authorize"), @@ -170,22 +181,39 @@ impl Idp { "subject_types_supported": ["public"], "id_token_signing_alg_values_supported": ["RS256"], }))) - .mount(&server).await; + .mount(&server) + .await; let served = jwks.clone(); - Mock::given(method("GET")).and(path("/jwks")) + Mock::given(method("GET")) + .and(path("/jwks")) .respond_with(move |_: &MockRequest| { - let keys_json: Vec = served.lock().unwrap().iter().map(|(kid, index)| { - let public = keys()[*index].to_public_key(); - json!({"kty":"RSA","use":"sig","alg":"RS256","kid":kid, + let keys_json: Vec = served + .lock() + .unwrap() + .iter() + .map(|(kid, index)| { + let public = keys()[*index].to_public_key(); + json!({"kty":"RSA","use":"sig","alg":"RS256","kid":kid, "n": b64(public.n().to_bytes_be()), "e": b64(public.e().to_bytes_be())}) - }).collect(); + }) + .collect(); ResponseTemplate::new(200).set_body_json(json!({"keys": keys_json})) }) - .mount(&server).await; - Mock::given(method("POST")).and(path("/token")) - .respond_with(TokenEndpoint { scenario: scenario.clone(), issuer }) - .mount(&server).await; - Self { server, scenario, jwks } + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/token")) + .respond_with(TokenEndpoint { + scenario: scenario.clone(), + issuer, + }) + .mount(&server) + .await; + Self { + server, + scenario, + jwks, + } } fn issuer(&self) -> String { @@ -193,7 +221,13 @@ impl Idp { } async fn hits(&self, route: &str) -> usize { - self.server.received_requests().await.unwrap().iter().filter(|r| r.url.path() == route).count() + self.server + .received_requests() + .await + .unwrap() + .iter() + .filter(|r| r.url.path() == route) + .count() } } @@ -214,12 +248,24 @@ fn config(idp: &Idp) -> OidcConfig { async fn harness_with(min_refresh: Duration) -> Harness { let idp = Idp::start().await; let dir = tempfile::tempdir().unwrap(); - let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault").await.unwrap(); + let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") + .await + .unwrap(); let config = config(&idp); - state.sessions = SessionGate::without_operator(state.db.clone()).with_oidc(&config.fingerprint()); - state.oidc = Some(Arc::new(OidcProvider::new(config).unwrap().with_min_refresh(min_refresh))); + state.sessions = + SessionGate::without_operator(state.db.clone()).with_oidc(&config.fingerprint()); + state.oidc = Some(Arc::new( + OidcProvider::new(config) + .unwrap() + .with_min_refresh(min_refresh), + )); let app = crate::api::router(state.clone()); - Harness { app, state, idp, _dir: dir } + Harness { + app, + state, + idp, + _dir: dir, + } } async fn harness() -> Harness { @@ -227,7 +273,9 @@ async fn harness() -> Harness { } fn get(uri: &str, cookies: &[String]) -> Request { - let mut request = Request::builder().uri(uri).extension(ConnectInfo("127.0.0.1:9000".parse::().unwrap())); + let mut request = Request::builder() + .uri(uri) + .extension(ConnectInfo("127.0.0.1:9000".parse::().unwrap())); if !cookies.is_empty() { request = request.header(header::COOKIE, cookies.join("; ")); } @@ -235,7 +283,12 @@ fn get(uri: &str, cookies: &[String]) -> Request { } fn set_cookies(response: &Response) -> Vec { - response.headers().get_all(header::SET_COOKIE).iter().map(|v| v.to_str().unwrap().to_string()).collect() + response + .headers() + .get_all(header::SET_COOKIE) + .iter() + .map(|v| v.to_str().unwrap().to_string()) + .collect() } fn cookie_pair(set_cookie: &str) -> String { @@ -243,7 +296,10 @@ fn cookie_pair(set_cookie: &str) -> String { } fn location(response: &Response) -> String { - response.headers()[header::LOCATION].to_str().unwrap().to_string() + response.headers()[header::LOCATION] + .to_str() + .unwrap() + .to_string() } struct Started { @@ -260,10 +316,17 @@ impl Harness { /// nonce and PKCE challenge the hub generated. async fn start(&self) -> Started { let response = self.call(get("/api/v1/auth/oidc/login", &[])).await; - assert!(response.status().is_redirection(), "login redirects, got {}", response.status()); + assert!( + response.status().is_redirection(), + "login redirects, got {}", + response.status() + ); let target = openidconnect::url::Url::parse(&location(&response)).unwrap(); - assert!(target.as_str().starts_with(&format!("{}/authorize", self.idp.issuer()))); - let q: std::collections::HashMap = target.query_pairs().into_owned().collect(); + assert!(target + .as_str() + .starts_with(&format!("{}/authorize", self.idp.issuer()))); + let q: std::collections::HashMap = + target.query_pairs().into_owned().collect(); assert_eq!(q["response_type"], "code"); assert_eq!(q["client_id"], CLIENT_ID); assert_eq!(q["redirect_uri"], REDIRECT); @@ -281,17 +344,26 @@ impl Harness { scenario.nonce = q["nonce"].clone(); scenario.challenge = q["code_challenge"].clone(); } - Started { state: q["state"].clone(), correlation: cookie_pair(&cookies[0]) } + Started { + state: q["state"].clone(), + correlation: cookie_pair(&cookies[0]), + } } async fn callback(&self, started: &Started, query: &str) -> Response { - self.call(get(&format!("/api/v1/auth/oidc/callback?{query}"), &[started.correlation.clone()])).await + self.call(get( + &format!("/api/v1/auth/oidc/callback?{query}"), + std::slice::from_ref(&started.correlation), + )) + .await } /// Full successful-or-not login with the current scenario. async fn login(&self) -> (Response, Started) { let started = self.start().await; - let response = self.callback(&started, &format!("code=good-code&state={}", started.state)).await; + let response = self + .callback(&started, &format!("code=good-code&state={}", started.state)) + .await; (response, started) } @@ -307,13 +379,19 @@ impl Harness { } fn query(&self, sql: &str) -> T { - rusqlite::Connection::open(self.state.data_dir.join("tessera.db")).unwrap().query_row(sql, [], |r| r.get(0)).unwrap() + rusqlite::Connection::open(self.state.data_dir.join("tessera.db")) + .unwrap() + .query_row(sql, [], |r| r.get(0)) + .unwrap() } } fn session_cookie(response: &Response) -> String { let cookies = set_cookies(response); - let session = cookies.iter().find(|c| c.starts_with("__Host-tessera-session=") && !c.contains("Max-Age=0")).expect("session cookie"); + let session = cookies + .iter() + .find(|c| c.starts_with("__Host-tessera-session=") && !c.contains("Max-Age=0")) + .expect("session cookie"); for flag in ["HttpOnly", "Secure", "SameSite=Strict"] { assert!(session.contains(flag)); } @@ -331,14 +409,25 @@ async fn an_admin_subject_signs_in_and_gets_a_session_but_never_a_token() { assert_eq!(response.status(), StatusCode::SEE_OTHER); assert_eq!(location(&response), "/", "fixed redirect target"); let cookies = set_cookies(&response); - assert_eq!(cookies.len(), 2, "session cookie plus cleared correlation cookie: {cookies:?}"); - assert!(cookies.iter().any(|c| c.starts_with("__Host-tessera-oidc=;") && c.contains("Max-Age=0"))); + assert_eq!( + cookies.len(), + 2, + "session cookie plus cleared correlation cookie: {cookies:?}" + ); + assert!(cookies + .iter() + .any(|c| c.starts_with("__Host-tessera-oidc=;") && c.contains("Max-Age=0"))); let session = session_cookie(&response); let headers_text = format!("{:?}", response.headers()); assert!(!headers_text.contains("synthetic-access-token") && !headers_text.contains("eyJ")); - assert!(to_bytes(response.into_body(), 4096).await.unwrap().is_empty()); + assert!(to_bytes(response.into_body(), 4096) + .await + .unwrap() + .is_empty()); - let me = h.call(get("/api/v1/me", &[session.clone()])).await; + let me = h + .call(get("/api/v1/me", std::slice::from_ref(&session))) + .await; assert_eq!(me.status(), StatusCode::OK); let me = json_body(me).await; assert_eq!(me["kind"], "user"); @@ -346,18 +435,29 @@ async fn an_admin_subject_signs_in_and_gets_a_session_but_never_a_token() { assert!(me["id"].as_str().unwrap().starts_with("oidc:")); assert_eq!(me["display_name"], "Ada Admin"); assert_eq!(me["capabilities"][0], "admin"); - assert_eq!(h.call(get("/api/v1/orbits", &[session.clone()])).await.status(), StatusCode::OK); + assert_eq!( + h.call(get("/api/v1/orbits", std::slice::from_ref(&session))) + .await + .status(), + StatusCode::OK + ); // Identity is (issuer, subject); the transaction was consumed; the audit actor is the stable user id. let issuer: String = h.query("SELECT issuer FROM users"); assert_eq!(issuer, h.idp.issuer()); assert_eq!(h.count("oidc_login"), 0); - let actor: String = h.query("SELECT actor_id FROM audit_events WHERE action='auth.login' AND outcome='succeeded'"); + let actor: String = h.query( + "SELECT actor_id FROM audit_events WHERE action='auth.login' AND outcome='succeeded'", + ); assert_eq!(actor, me["id"]); // PKCE verified by the IdP and the code is not reusable by replaying the callback. - let replay = h.callback(&started, &format!("code=good-code&state={}", started.state)).await; + let replay = h + .callback(&started, &format!("code=good-code&state={}", started.state)) + .await; assert_eq!(location(&replay), "/?auth_error=invalid_state"); - assert!(set_cookies(&replay).iter().all(|c| !c.starts_with("__Host-tessera-session=") || c.contains("Max-Age=0"))); + assert!(set_cookies(&replay) + .iter() + .all(|c| !c.starts_with("__Host-tessera-session=") || c.contains("Max-Age=0"))); assert_eq!(h.count("sessions"), 1); } @@ -365,29 +465,57 @@ async fn an_admin_subject_signs_in_and_gets_a_session_but_never_a_token() { async fn a_signed_in_user_without_a_grant_gets_identity_but_no_api_access() { let h = harness().await; // Display name "operator" must not be mistaken for the emergency account. - h.mutate(|s| { s.sub = Some("plain-user".into()); s.name = Some("operator".into()); }); + h.mutate(|s| { + s.sub = Some("plain-user".into()); + s.name = Some("operator".into()); + }); let (response, _) = h.login().await; assert_eq!(location(&response), "/"); let session = session_cookie(&response); - let me = json_body(h.call(get("/api/v1/me", &[session.clone()])).await).await; + let me = json_body( + h.call(get("/api/v1/me", std::slice::from_ref(&session))) + .await, + ) + .await; assert_eq!(me["capabilities"].as_array().unwrap().len(), 0); assert!(me["id"].as_str().unwrap().starts_with("oidc:"), "{me}"); - let status = json_body(h.call(get("/api/v1/operator/session", &[session.clone()])).await).await; + let status = json_body( + h.call(get( + "/api/v1/operator/session", + std::slice::from_ref(&session), + )) + .await, + ) + .await; assert_eq!(status["authorized"], false); assert_eq!(status["actor"], "operator"); assert!(status["csrf"].is_string(), "can still sign out"); - assert_eq!(h.call(get("/api/v1/orbits", &[session.clone()])).await.status(), StatusCode::FORBIDDEN); + assert_eq!( + h.call(get("/api/v1/orbits", std::slice::from_ref(&session))) + .await + .status(), + StatusCode::FORBIDDEN + ); let denied_actor: String = h.query("SELECT actor_id FROM audit_events WHERE action='authorization.check' AND outcome='denied' ORDER BY id DESC LIMIT 1"); - assert!(denied_actor.starts_with("oidc:"), "audited as the OIDC user, not emergency:operator: {denied_actor}"); + assert!( + denied_actor.starts_with("oidc:"), + "audited as the OIDC user, not emergency:operator: {denied_actor}" + ); - let logout = Request::builder().method("DELETE").uri("/api/v1/operator/session") + let logout = Request::builder() + .method("DELETE") + .uri("/api/v1/operator/session") .extension(ConnectInfo("127.0.0.1:9000".parse::().unwrap())) .header(header::COOKIE, session.clone()) .header("x-tessera-csrf", status["csrf"].as_str().unwrap()) - .body(Body::empty()).unwrap(); + .body(Body::empty()) + .unwrap(); assert_eq!(h.call(logout).await.status(), StatusCode::NO_CONTENT); - assert_eq!(h.call(get("/api/v1/me", &[session])).await.status(), StatusCode::UNAUTHORIZED); + assert_eq!( + h.call(get("/api/v1/me", &[session])).await.status(), + StatusCode::UNAUTHORIZED + ); } #[tokio::test] @@ -401,11 +529,22 @@ async fn admin_comes_from_a_verified_group_claim_and_a_bad_claim_grants_nothing( (Some(json!([["tessera-admins"]])), false), (None, false), ] { - h.mutate(|s| { s.sub = Some("group-user".into()); s.groups = groups.clone(); }); + h.mutate(|s| { + s.sub = Some("group-user".into()); + s.groups = groups.clone(); + }); let (response, _) = h.login().await; let session = session_cookie(&response); - let expected = if expect_admin { StatusCode::OK } else { StatusCode::FORBIDDEN }; - assert_eq!(h.call(get("/api/v1/orbits", &[session])).await.status(), expected, "{groups:?}"); + let expected = if expect_admin { + StatusCode::OK + } else { + StatusCode::FORBIDDEN + }; + assert_eq!( + h.call(get("/api/v1/orbits", &[session])).await.status(), + expected, + "{groups:?}" + ); } } @@ -413,27 +552,56 @@ async fn admin_comes_from_a_verified_group_claim_and_a_bad_claim_grants_nothing( async fn the_same_email_under_a_different_subject_is_a_different_user() { let h = harness().await; for sub in ["sub-a", "sub-b", "sub-a"] { - h.mutate(|s| { s.sub = Some(sub.into()); s.email = Some("same@example.com".into()); }); + h.mutate(|s| { + s.sub = Some(sub.into()); + s.email = Some("same@example.com".into()); + }); let (response, _) = h.login().await; assert_eq!(location(&response), "/"); } - assert_eq!(h.count("users"), 2, "two subjects, no linking by email; the repeat logs in as the first"); + assert_eq!( + h.count("users"), + 2, + "two subjects, no linking by email; the repeat logs in as the first" + ); } #[tokio::test] async fn invalid_tokens_never_create_a_session_or_a_user() { let _ = tracing_subscriber::fmt().with_test_writer().try_init(); let h = harness().await; - let cases: Vec<(&str, Box)> = vec![ - ("wrong nonce", Box::new(|s| s.nonce = "not-the-nonce".into())), - ("wrong issuer", Box::new(|s| s.iss = Some("https://evil.example".into()))), - ("wrong audience", Box::new(|s| s.aud = json!("someone-else"))), - ("extra audience without azp", Box::new(|s| s.aud = json!([CLIENT_ID, "other"]))), - ("azp is another client", Box::new(|s| { s.aud = json!([CLIENT_ID, "other"]); s.azp = Some("other".into()); })), + type Case = (&'static str, Box); + let cases: Vec = vec![ + ( + "wrong nonce", + Box::new(|s| s.nonce = "not-the-nonce".into()), + ), + ( + "wrong issuer", + Box::new(|s| s.iss = Some("https://evil.example".into())), + ), + ( + "wrong audience", + Box::new(|s| s.aud = json!("someone-else")), + ), + ( + "extra audience without azp", + Box::new(|s| s.aud = json!([CLIENT_ID, "other"])), + ), + ( + "azp is another client", + Box::new(|s| { + s.aud = json!([CLIENT_ID, "other"]); + s.azp = Some("other".into()); + }), + ), ("expired", Box::new(|s| s.exp_in = -3600)), ("signed by an attacker key", Box::new(|s| s.signer = 2)), ("alg none", Box::new(|s| s.alg = "none")), - ("HS256 with the client secret", Box::new(|s| s.alg = "HS256")), + ( + "HS256 with the client secret", + Box::new(|s| s.alg = "HS256"), + ), ("no subject", Box::new(|s| s.sub = None)), ("empty subject", Box::new(|s| s.sub = Some(String::new()))), ]; @@ -441,10 +609,17 @@ async fn invalid_tokens_never_create_a_session_or_a_user() { h.mutate(|s| *s = Scenario::default()); let started = h.start().await; h.mutate(|s| change(s)); - let response = h.callback(&started, &format!("code=good-code&state={}", started.state)).await; + let response = h + .callback(&started, &format!("code=good-code&state={}", started.state)) + .await; let target = location(&response); assert!(target == "/?auth_error=failed", "{name}: {target}"); - assert!(set_cookies(&response).iter().all(|c| !c.starts_with("__Host-tessera-session=") || c.contains("Max-Age=0")), "{name}"); + assert!( + set_cookies(&response) + .iter() + .all(|c| !c.starts_with("__Host-tessera-session=") || c.contains("Max-Age=0")), + "{name}" + ); assert_eq!(h.count("sessions"), 0, "{name}"); assert_eq!(h.count("users"), 0, "{name}"); } @@ -455,28 +630,74 @@ async fn login_transactions_cannot_be_replayed_borrowed_or_forged() { let h = harness().await; // Another browser (no / wrong correlation cookie) holding the right state. let started = h.start().await; - let no_cookie = h.call(get(&format!("/api/v1/auth/oidc/callback?code=good-code&state={}", started.state), &[])).await; + let no_cookie = h + .call(get( + &format!( + "/api/v1/auth/oidc/callback?code=good-code&state={}", + started.state + ), + &[], + )) + .await; assert_eq!(location(&no_cookie), "/?auth_error=invalid_state"); - let again = h.callback(&started, &format!("code=good-code&state={}", started.state)).await; - assert_eq!(location(&again), "/?auth_error=invalid_state", "a failed attempt burns the transaction"); + let again = h + .callback(&started, &format!("code=good-code&state={}", started.state)) + .await; + assert_eq!( + location(&again), + "/?auth_error=invalid_state", + "a failed attempt burns the transaction" + ); let started = h.start().await; - let wrong = Started { state: started.state.clone(), correlation: "__Host-tessera-oidc=forged".into() }; - assert_eq!(location(&h.callback(&wrong, &format!("code=good-code&state={}", started.state)).await), "/?auth_error=invalid_state"); + let wrong = Started { + state: started.state.clone(), + correlation: "__Host-tessera-oidc=forged".into(), + }; + assert_eq!( + location( + &h.callback(&wrong, &format!("code=good-code&state={}", started.state)) + .await + ), + "/?auth_error=invalid_state" + ); // Unknown, missing and mismatched state. let started = h.start().await; - assert_eq!(location(&h.callback(&started, "code=good-code&state=made-up").await), "/?auth_error=invalid_state"); - assert_eq!(location(&h.callback(&started, "code=good-code").await), "/?auth_error=invalid_state"); + assert_eq!( + location(&h.callback(&started, "code=good-code&state=made-up").await), + "/?auth_error=invalid_state" + ); + assert_eq!( + location(&h.callback(&started, "code=good-code").await), + "/?auth_error=invalid_state" + ); // Expired transaction. let started = h.start().await; - rusqlite::Connection::open(h.state.data_dir.join("tessera.db")).unwrap().execute("UPDATE oidc_login SET expires_at = 1", []).unwrap(); - assert_eq!(location(&h.callback(&started, &format!("code=good-code&state={}", started.state)).await), "/?auth_error=invalid_state"); + rusqlite::Connection::open(h.state.data_dir.join("tessera.db")) + .unwrap() + .execute("UPDATE oidc_login SET expires_at = 1", []) + .unwrap(); + assert_eq!( + location( + &h.callback(&started, &format!("code=good-code&state={}", started.state)) + .await + ), + "/?auth_error=invalid_state" + ); // The IdP reporting an error: shown as a fixed code, nothing echoed, transaction consumed. let started = h.start().await; - let denied = h.callback(&started, &format!("error=access_denied&error_description=secret-detail&state={}", started.state)).await; + let denied = h + .callback( + &started, + &format!( + "error=access_denied&error_description=secret-detail&state={}", + started.state + ), + ) + .await; assert_eq!(location(&denied), "/?auth_error=denied"); assert!(!format!("{:?}", denied.headers()).contains("secret-detail")); assert_eq!(h.count("oidc_login"), 0); @@ -484,7 +705,13 @@ async fn login_transactions_cannot_be_replayed_borrowed_or_forged() { // A wrong code is rejected by the IdP. let started = h.start().await; - assert_eq!(location(&h.callback(&started, &format!("code=bad-code&state={}", started.state)).await), "/?auth_error=failed"); + assert_eq!( + location( + &h.callback(&started, &format!("code=bad-code&state={}", started.state)) + .await + ), + "/?auth_error=failed" + ); assert_eq!(h.count("sessions"), 0); let failed: i64 = h.query("SELECT COUNT(*) FROM audit_events WHERE action='auth.login' AND outcome='failed' AND actor_id='anonymous'"); assert!(failed >= 6); @@ -499,10 +726,17 @@ async fn rotated_signing_keys_are_picked_up_but_refreshes_are_rate_limited() { // The IdP rotates: new key and kid, old key withdrawn. The cached key set is stale. *h.idp.jwks.lock().unwrap() = vec![("k2", 1)]; - h.mutate(|s| { s.signer = 1; s.kid = "k2"; }); + h.mutate(|s| { + s.signer = 1; + s.kid = "k2"; + }); tokio::time::sleep(Duration::from_millis(5)).await; let (after, _) = h.login().await; - assert_eq!(location(&after), "/", "refreshed once and verified with the new key"); + assert_eq!( + location(&after), + "/", + "refreshed once and verified with the new key" + ); assert_eq!(h.idp.hits("/jwks").await, 2); // With the default 60s gap, a flood of bad signatures cannot hammer the IdP. @@ -511,7 +745,9 @@ async fn rotated_signing_keys_are_picked_up_but_refreshes_are_rate_limited() { limited.mutate(|s| *s = Scenario::default()); let started = limited.start().await; limited.mutate(|s| s.signer = 2); - let r = limited.callback(&started, &format!("code=good-code&state={}", started.state)).await; + let r = limited + .callback(&started, &format!("code=good-code&state={}", started.state)) + .await; assert_eq!(location(&r), "/?auth_error=failed"); } assert!(limited.idp.hits("/.well-known/openid-configuration").await <= 2); @@ -532,21 +768,37 @@ async fn an_idp_outage_degrades_to_fixed_errors_and_never_a_session() { assert_eq!(location(&ok), "/"); h.mutate(|s| s.token_status = 500); let started = h.start().await; // metadata is cached, so /login still works - let response = h.callback(&started, &format!("code=good-code&state={}", started.state)).await; + let response = h + .callback(&started, &format!("code=good-code&state={}", started.state)) + .await; assert!(response.status().is_redirection()); assert!(location(&response).starts_with("/?auth_error=")); h.idp.server.reset().await; let started = h.start().await; - let response = h.callback(&started, &format!("code=good-code&state={}", started.state)).await; - assert!(location(&response).starts_with("/?auth_error="), "{}", location(&response)); + let response = h + .callback(&started, &format!("code=good-code&state={}", started.state)) + .await; + assert!( + location(&response).starts_with("/?auth_error="), + "{}", + location(&response) + ); } #[tokio::test] async fn oidc_endpoints_are_absent_when_oidc_is_not_configured() { let dir = tempfile::tempdir().unwrap(); - let state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault").await.unwrap(); + let state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") + .await + .unwrap(); let app = crate::api::router(state); - for uri in ["/api/v1/auth/oidc/login", "/api/v1/auth/oidc/callback?code=x&state=y"] { - assert_eq!(app.clone().oneshot(get(uri, &[])).await.unwrap().status(), StatusCode::NOT_FOUND); + for uri in [ + "/api/v1/auth/oidc/login", + "/api/v1/auth/oidc/callback?code=x&state=y", + ] { + assert_eq!( + app.clone().oneshot(get(uri, &[])).await.unwrap().status(), + StatusCode::NOT_FOUND + ); } } diff --git a/crates/tessera-hub/src/api/refresh.rs b/crates/tessera-hub/src/api/refresh.rs index b21be7d..40686a4 100644 --- a/crates/tessera-hub/src/api/refresh.rs +++ b/crates/tessera-hub/src/api/refresh.rs @@ -40,7 +40,12 @@ fn internal(error: impl std::fmt::Display) -> StatusCode { } fn reason(status: StatusCode, reason: &str) -> Response { - (status, no_store(), Json(serde_json::json!({ "reason": reason }))).into_response() + ( + status, + no_store(), + Json(serde_json::json!({ "reason": reason })), + ) + .into_response() } /// A run as its viewer may see it. Only administrators see who started it and the snapshot id. @@ -67,8 +72,15 @@ struct RunView { } fn view(state: &HubState, run: &RefreshRun, admin: bool) -> Result { - let Progress { capture_status, capture_phase, snapshot_taken_at, restore_status, restore_phase, source_name, target_name } = - state.db.refresh_progress(run).map_err(internal)?; + let Progress { + capture_status, + capture_phase, + snapshot_taken_at, + restore_status, + restore_phase, + source_name, + target_name, + } = state.db.refresh_progress(run).map_err(internal)?; Ok(RunView { id: run.id.clone(), relation_id: run.relation_id.clone(), @@ -99,7 +111,14 @@ fn can_see(state: &HubState, actor: &OperatorActor, run: &RefreshRun) -> Result< if actor.subject.admin || owns(actor, run) { return Ok(true); } - let granted = state.db.granted_relations(actor.subject.user_id.as_deref(), &actor.subject.groups, now()).map_err(internal)?; + let granted = state + .db + .granted_relations( + actor.subject.user_id.as_deref(), + &actor.subject.groups, + now(), + ) + .map_err(internal)?; Ok(granted.iter().any(|id| id == &run.relation_id)) } @@ -114,7 +133,10 @@ struct Start { } fn valid_key(key: &str) -> bool { - (1..=128).contains(&key.len()) && key.bytes().all(|b| b.is_ascii_alphanumeric() || b"-_.:".contains(&b)) + (1..=128).contains(&key.len()) + && key + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"-_.:".contains(&b)) } async fn start( @@ -133,7 +155,16 @@ async fn start( let authorized_by = if actor.subject.admin { "admin".to_string() } else { - match state.db.granting_relation_grant(actor.subject.user_id.as_deref(), &actor.subject.groups, &relation, now()).map_err(internal)? { + match state + .db + .granting_relation_grant( + actor.subject.user_id.as_deref(), + &actor.subject.groups, + &relation, + now(), + ) + .map_err(internal)? + { Some(grant) => format!("grant:{grant}"), None => return Err(StatusCode::NOT_FOUND), } @@ -141,8 +172,15 @@ async fn start( let started = state .db .create_refresh_run( - &relation, &body.confirmation, &actor.id(), actor.subject.user_id.as_deref(), &authorized_by, &body.idempotency_key, - state.refresh.ttl_secs, state.refresh.max_active, now(), + &relation, + &body.confirmation, + &actor.id(), + actor.subject.user_id.as_deref(), + &authorized_by, + &body.idempotency_key, + state.refresh.ttl_secs, + state.refresh.max_active, + now(), ) .map_err(internal)?; match started { @@ -150,13 +188,31 @@ async fn start( if created { crate::refresh::audit_run(&state, &run.id, "capturing"); } - let status = if created { StatusCode::ACCEPTED } else { StatusCode::OK }; - Ok((status, no_store(), Json(view(&state, &run, actor.subject.admin)?)).into_response()) + let status = if created { + StatusCode::ACCEPTED + } else { + StatusCode::OK + }; + Ok(( + status, + no_store(), + Json(view(&state, &run, actor.subject.admin)?), + ) + .into_response()) } Err(StartError::UnknownRelation) => Err(StatusCode::NOT_FOUND), - Err(StartError::Unusable(why)) => Ok((StatusCode::CONFLICT, no_store(), Json(serde_json::json!({"reason": "relation_unusable", "detail": why}))).into_response()), - Err(StartError::StaleConfirmation) => Ok(reason(StatusCode::CONFLICT, "stale_confirmation")), - Err(StartError::SourceUnavailable) => Ok(reason(StatusCode::CONFLICT, "source_unavailable")), + Err(StartError::Unusable(why)) => Ok(( + StatusCode::CONFLICT, + no_store(), + Json(serde_json::json!({"reason": "relation_unusable", "detail": why})), + ) + .into_response()), + Err(StartError::StaleConfirmation) => { + Ok(reason(StatusCode::CONFLICT, "stale_confirmation")) + } + Err(StartError::SourceUnavailable) => { + Ok(reason(StatusCode::CONFLICT, "source_unavailable")) + } Err(StartError::KeyReused) => Ok(reason(StatusCode::CONFLICT, "key_reused")), Err(StartError::TooManyRuns) => Ok(reason(StatusCode::TOO_MANY_REQUESTS, "too_many_runs")), Err(StartError::TargetBusy(id)) => { @@ -183,10 +239,17 @@ async fn list( let granted = super::gate::visible_relations(&state, &actor)?; let runs = match (&granted, actor.subject.admin) { (None, _) => state.db.refresh_runs(None, None, 50), - (Some(relations), _) => state.db.refresh_runs(actor.subject.user_id.as_deref(), Some(relations), 50), + (Some(relations), _) => { + state + .db + .refresh_runs(actor.subject.user_id.as_deref(), Some(relations), 50) + } } .map_err(internal)?; - let views = runs.iter().map(|run| view(&state, run, actor.subject.admin)).collect::, _>>()?; + let views = runs + .iter() + .map(|run| view(&state, run, actor.subject.admin)) + .collect::, _>>()?; Ok((no_store(), Json(views))) } @@ -197,10 +260,26 @@ async fn show( Path(id): Path, ) -> Result<(HeaderMap, Json), StatusCode> { let actor = authenticate(&state, peer, &headers, false)?; - let run = state.db.refresh_run(&id.to_string()).map_err(internal)?.filter(|run| can_see(&state, &actor, run).unwrap_or(false)); + let run = state + .db + .refresh_run(&id.to_string()) + .map_err(internal)? + .filter(|run| can_see(&state, &actor, run).unwrap_or(false)); let allowed = run.is_some(); - state.db.audit_event(&actor.principal, AuditAction::Authorization, AuditResource::RefreshRun(id), - if allowed { AuditOutcome::Allowed } else { AuditOutcome::Denied }, actor.request_id).map_err(internal)?; + state + .db + .audit_event( + &actor.principal, + AuditAction::Authorization, + AuditResource::RefreshRun(id), + if allowed { + AuditOutcome::Allowed + } else { + AuditOutcome::Denied + }, + actor.request_id, + ) + .map_err(internal)?; let run = run.ok_or(StatusCode::NOT_FOUND)?; Ok((no_store(), Json(view(&state, &run, actor.subject.admin)?))) } @@ -214,11 +293,26 @@ async fn cancel( let actor = authenticate(&state, peer, &headers, true)?; let run = state.db.refresh_run(&id.to_string()).map_err(internal)?; let (visible, allowed) = match &run { - Some(run) => (can_see(&state, &actor, run)?, actor.subject.admin || owns(&actor, run)), + Some(run) => ( + can_see(&state, &actor, run)?, + actor.subject.admin || owns(&actor, run), + ), None => (false, false), }; - state.db.audit_event(&actor.principal, AuditAction::Authorization, AuditResource::RefreshRun(id), - if allowed { AuditOutcome::Allowed } else { AuditOutcome::Denied }, actor.request_id).map_err(internal)?; + state + .db + .audit_event( + &actor.principal, + AuditAction::Authorization, + AuditResource::RefreshRun(id), + if allowed { + AuditOutcome::Allowed + } else { + AuditOutcome::Denied + }, + actor.request_id, + ) + .map_err(internal)?; if !visible { return Err(StatusCode::NOT_FOUND); } @@ -226,7 +320,11 @@ async fn cancel( // Someone who may see the run but did not start it and is not an administrator. return Err(StatusCode::FORBIDDEN); } - match state.db.cancel_refresh_run(&id.to_string(), now()).map_err(internal)? { + match state + .db + .cancel_refresh_run(&id.to_string(), now()) + .map_err(internal)? + { Ok(run) => { crate::refresh::audit_run(&state, &run.id, "cancelled"); Ok((no_store(), Json(view(&state, &run, actor.subject.admin)?)).into_response()) diff --git a/crates/tessera-hub/src/api/refresh_tests.rs b/crates/tessera-hub/src/api/refresh_tests.rs index 19b8056..2a3bca0 100644 --- a/crates/tessera-hub/src/api/refresh_tests.rs +++ b/crates/tessera-hub/src/api/refresh_tests.rs @@ -44,7 +44,9 @@ struct Lab { async fn lab_with(configure: impl FnOnce(&mut HubState)) -> Lab { let dir = tempfile::tempdir().unwrap(); - let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault").await.unwrap(); + let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") + .await + .unwrap(); state.admin.token = Some(ADMIN.into()); state.sessions = SessionGate::without_operator(state.db.clone()).with_oidc("refresh-fp"); configure(&mut state); @@ -52,26 +54,69 @@ async fn lab_with(configure: impl FnOnce(&mut HubState)) -> Lab { state .db .upsert_orbit(&crate::db::OrbitRow { - id: orbit, name: "prod-db".into(), provider: "wormhole".into(), provider_config: "{}".into(), schedule: None, - decay_preset: "week-of-dailies".into(), retention: None, dry_run: false, last_status: "idle".into(), + id: orbit, + name: "prod-db".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(AGENT, &outpost.to_string(), "agent"); + state + .db + .insert_test_credential(AGENT, &outpost.to_string(), "agent"); let application = Uuid::new_v4(); - let profile = CaptureProfile { application_id: application, orbit_id: orbit, outpost_id: outpost, format: CaptureFormat::PostgresCustom, schedule: None, retention: None }; + 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 target = RestoreTarget { - id: Uuid::new_v4(), application_id: application, outpost_id: outpost, name: "staging-db".into(), engine: Engine::Postgres, - identity: DatabaseIdentity { instance: "7300000000000000001".into(), database: "staging_app".into() }, + id: Uuid::new_v4(), + application_id: application, + outpost_id: outpost, + name: "staging-db".into(), + engine: Engine::Postgres, + identity: DatabaseIdentity { + instance: "7300000000000000001".into(), + database: "staging_app".into(), + }, }; assert!(state.db.register_restore_target(&target).unwrap()); - 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, false, "seed", now()).unwrap().unwrap(); + 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, false, "seed", now()) + .unwrap() + .unwrap(); let app = crate::api::router(state.clone()); - Lab { app, state, dir, orbit, application, outpost, target: target.id, relation: relation.id, relation_version: relation.version } + Lab { + app, + state, + dir, + orbit, + application, + outpost, + target: target.id, + relation: relation.id, + relation_version: relation.version, + } } async fn fresh() -> Lab { @@ -80,31 +125,73 @@ async fn fresh() -> Lab { impl Lab { fn person(&self, name: &str) -> Caller { - let user = self.state.db.upsert_user(ISSUER, name, name, now()).unwrap(); - let session = self.state.sessions.create_oidc(&user, name, false, &[], now()).unwrap(); - Caller { cookie: Some(format!("__Host-tessera-session={}", session.id)), csrf: Some(session.csrf), admin_token: false, user_id: Some(user) } + let user = self + .state + .db + .upsert_user(ISSUER, name, name, now()) + .unwrap(); + let session = self + .state + .sessions + .create_oidc(&user, name, false, &[], now()) + .unwrap(); + Caller { + cookie: Some(format!("__Host-tessera-session={}", session.id)), + csrf: Some(session.csrf), + admin_token: false, + user_id: Some(user), + } } /// A person holding `refresh.run` on the relation. fn refresher(&self, name: &str) -> (Caller, String) { let person = self.person(name); - let grant = self.state.db.add_relation_grant("user", person.user_id.as_ref().unwrap(), &self.relation, None, "test", now()).unwrap().unwrap(); + let grant = self + .state + .db + .add_relation_grant( + "user", + person.user_id.as_ref().unwrap(), + &self.relation, + None, + "test", + now(), + ) + .unwrap() + .unwrap(); (person, grant.id) } fn admin(&self) -> Caller { - Caller { cookie: None, csrf: None, admin_token: true, user_id: None } + Caller { + cookie: None, + csrf: None, + admin_token: true, + user_id: None, + } } async fn call(&self, request: Request) -> (StatusCode, Value) { let response = self.app.clone().oneshot(request).await.unwrap(); let status = response.status(); let bytes = to_bytes(response.into_body(), 1 << 24).await.unwrap(); - (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null)) + ( + status, + serde_json::from_slice(&bytes).unwrap_or(Value::Null), + ) } - async fn send(&self, caller: &Caller, method: &str, uri: &str, body: Option) -> (StatusCode, Value) { - let mut request = Request::builder().method(method).uri(uri).extension(ConnectInfo("127.0.0.1:4000".parse::().unwrap())); + async fn send( + &self, + caller: &Caller, + method: &str, + uri: &str, + body: Option, + ) -> (StatusCode, Value) { + let mut request = Request::builder() + .method(method) + .uri(uri) + .extension(ConnectInfo("127.0.0.1:4000".parse::().unwrap())); if let Some(cookie) = &caller.cookie { request = request.header(header::COOKIE, cookie); } @@ -117,7 +204,10 @@ impl Lab { } } let request = match body { - Some(json) => request.header(header::CONTENT_TYPE, "application/json").body(Body::from(json.to_string())).unwrap(), + Some(json) => request + .header(header::CONTENT_TYPE, "application/json") + .body(Body::from(json.to_string())) + .unwrap(), None => request.body(Body::empty()).unwrap(), }; self.call(request).await @@ -149,27 +239,57 @@ impl Lab { // ---- the agent, through the real Outpost endpoints ---- - fn agent_request(&self, method: &str, uri: &str, extra: &[(&str, String)], body: Option>) -> Request { - let mut request = Request::builder().method(method).uri(uri).header("x-tessera-upload-token", AGENT) - .extension(ConnectInfo("198.51.100.5:4000".parse::().unwrap())); + fn agent_request( + &self, + method: &str, + uri: &str, + extra: &[(&str, String)], + body: Option>, + ) -> Request { + let mut request = Request::builder() + .method(method) + .uri(uri) + .header("x-tessera-upload-token", AGENT) + .extension(ConnectInfo( + "198.51.100.5:4000".parse::().unwrap(), + )); for (name, value) in extra { request = request.header(*name, value); } match body { - Some(bytes) => request.header(header::CONTENT_LENGTH, bytes.len()).body(Body::from(bytes)).unwrap(), + Some(bytes) => request + .header(header::CONTENT_LENGTH, bytes.len()) + .body(Body::from(bytes)) + .unwrap(), None => request.body(Body::empty()).unwrap(), } } - async fn agent_json(&self, method: &str, uri: &str, extra: &[(&str, String)], body: Value) -> (StatusCode, Value) { - let mut request = self.agent_request(method, uri, extra, Some(body.to_string().into_bytes())); - request.headers_mut().insert(header::CONTENT_TYPE, "application/json".parse().unwrap()); + async fn agent_json( + &self, + method: &str, + uri: &str, + extra: &[(&str, String)], + body: Value, + ) -> (StatusCode, Value) { + let mut request = + self.agent_request(method, uri, extra, Some(body.to_string().into_bytes())); + request + .headers_mut() + .insert(header::CONTENT_TYPE, "application/json".parse().unwrap()); self.call(request).await } /// Run one whole capture as the agent would. `identity` is the source database's identity. async fn capture(&self, identity: &DatabaseIdentity, fail: bool) -> Option { - let (status, lease) = self.call(self.agent_request("POST", &format!("/api/v1/wormhole/capture/{}/claim", self.application), &[], None)).await; + let (status, lease) = self + .call(self.agent_request( + "POST", + &format!("/api/v1/wormhole/capture/{}/claim", self.application), + &[], + None, + )) + .await; assert_eq!(status, StatusCode::OK); if lease.is_null() { return None; @@ -187,24 +307,49 @@ impl Lab { return Some(Uuid::parse_str(&job).unwrap()); } assert_eq!(report("uploading").await, StatusCode::NO_CONTENT); - let payload = [b"PGDMP\x01\x0e\x00".as_slice(), format!("-- dump of {}", identity.database).as_bytes()].concat(); + let payload = [ + b"PGDMP\x01\x0e\x00".as_slice(), + format!("-- dump of {}", identity.database).as_bytes(), + ] + .concat(); let headers = [ ("x-tessera-lease-id", lease_id.clone()), ("x-tessera-sha256", hex::encode(Sha256::digest(&payload))), - ("x-tessera-source-identity", base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(serde_json::to_vec(identity).unwrap())), + ( + "x-tessera-source-identity", + base64::engine::general_purpose::URL_SAFE_NO_PAD + .encode(serde_json::to_vec(identity).unwrap()), + ), ]; - let (status, body) = self.call(self.agent_request("POST", &format!("/api/v1/wormhole/capture/{job}/payload"), &headers, Some(payload))).await; + let (status, body) = self + .call(self.agent_request( + "POST", + &format!("/api/v1/wormhole/capture/{job}/payload"), + &headers, + Some(payload), + )) + .await; assert_eq!(status, StatusCode::OK, "{body}"); Some(Uuid::parse_str(&job).unwrap()) } fn production_identity() -> DatabaseIdentity { - DatabaseIdentity { instance: "9100000000000000009".into(), database: "prod_app".into() } + DatabaseIdentity { + instance: "9100000000000000009".into(), + database: "prod_app".into(), + } } /// Claim the restore, pass checking and the safety backup, and stop just before apply. async fn restore_until_ready(&self) -> Option<(String, String)> { - let (status, lease) = self.call(self.agent_request("POST", &format!("/api/v1/wormhole/restore-targets/{}/claim", self.target), &[], None)).await; + let (status, lease) = self + .call(self.agent_request( + "POST", + &format!("/api/v1/wormhole/restore-targets/{}/claim", self.target), + &[], + None, + )) + .await; assert_eq!(status, StatusCode::OK); if lease.is_null() { return None; @@ -213,22 +358,57 @@ impl Lab { let token = lease["token"].as_str().unwrap().to_string(); let headers = [("x-tessera-restore-token", token.clone())]; for progress in ["checking", "safety"] { - let (status, _) = self.agent_json("POST", &format!("/api/v1/wormhole/restore/{job}/report"), &headers, json!(progress)).await; + let (status, _) = self + .agent_json( + "POST", + &format!("/api/v1/wormhole/restore/{job}/report"), + &headers, + json!(progress), + ) + .await; assert_eq!(status, StatusCode::NO_CONTENT, "report {progress}"); } - let safety = [b"PGDMP\x01\x0e\x00".as_slice(), b"-- safety copy of the target"].concat(); - let safety_headers = [("x-tessera-restore-token", token.clone()), ("x-tessera-sha256", hex::encode(Sha256::digest(&safety)))]; - let (status, body) = self.call(self.agent_request("POST", &format!("/api/v1/wormhole/restore/{job}/safety"), &safety_headers, Some(safety))).await; + let safety = [ + b"PGDMP\x01\x0e\x00".as_slice(), + b"-- safety copy of the target", + ] + .concat(); + let safety_headers = [ + ("x-tessera-restore-token", token.clone()), + ("x-tessera-sha256", hex::encode(Sha256::digest(&safety))), + ]; + let (status, body) = self + .call(self.agent_request( + "POST", + &format!("/api/v1/wormhole/restore/{job}/safety"), + &safety_headers, + Some(safety), + )) + .await; assert_eq!(status, StatusCode::OK, "{body}"); Some((job, token)) } async fn apply(&self, job: &str, token: &str) -> StatusCode { - self.call(self.agent_request("POST", &format!("/api/v1/wormhole/restore/{job}/apply"), &[("x-tessera-restore-token", token.to_string())], None)).await.0 + self.call(self.agent_request( + "POST", + &format!("/api/v1/wormhole/restore/{job}/apply"), + &[("x-tessera-restore-token", token.to_string())], + None, + )) + .await + .0 } async fn report_applied(&self, job: &str, token: &str) { - let (status, _) = self.agent_json("POST", &format!("/api/v1/wormhole/restore/{job}/report"), &[("x-tessera-restore-token", token.to_string())], json!("applied")).await; + let (status, _) = self + .agent_json( + "POST", + &format!("/api/v1/wormhole/restore/{job}/report"), + &[("x-tessera-restore-token", token.to_string())], + json!("applied"), + ) + .await; assert_eq!(status, StatusCode::NO_CONTENT); } @@ -241,13 +421,20 @@ impl Lab { } fn restore_status(&self, job: &str) -> String { - self.conn().query_row("SELECT status FROM restore_jobs WHERE id=?1", [job], |r| r.get(0)).unwrap() + self.conn() + .query_row("SELECT status FROM restore_jobs WHERE id=?1", [job], |r| { + r.get(0) + }) + .unwrap() } fn audit_actions(&self, run: &str) -> Vec { let conn = self.conn(); let mut stmt = conn.prepare("SELECT action FROM audit_events WHERE resource_type='refresh_run' AND resource_id=?1 AND action LIKE 'refresh.%' ORDER BY id").unwrap(); - stmt.query_map([run], |r| r.get(0)).unwrap().collect::>().unwrap() + stmt.query_map([run], |r| r.get(0)) + .unwrap() + .collect::>() + .unwrap() } } @@ -256,8 +443,14 @@ async fn a_refresh_captures_its_own_snapshot_and_restores_exactly_that_onto_the_ let lab = fresh().await; let (qa, _) = lab.refresher("qa-person"); // an older snapshot of the same source already exists; the run must not use it - let earlier = lab.start(&lab.admin(), "earlier").await.1["id"].as_str().unwrap().to_string(); - let first = lab.capture(&Lab::production_identity(), false).await.unwrap(); + let earlier = lab.start(&lab.admin(), "earlier").await.1["id"] + .as_str() + .unwrap() + .to_string(); + let first = lab + .capture(&Lab::production_identity(), false) + .await + .unwrap(); assert_eq!(lab.tick().await, 1); assert_eq!(lab.run(&earlier).status, "restoring"); let (job, token) = lab.restore_until_ready().await.unwrap(); @@ -265,41 +458,96 @@ async fn a_refresh_captures_its_own_snapshot_and_restores_exactly_that_onto_the_ lab.report_applied(&job, &token).await; lab.tick().await; assert_eq!(lab.run(&earlier).status, "completed"); - assert_eq!(lab.run(&earlier).snapshot_id.as_deref(), Some(first.to_string().as_str())); + assert_eq!( + lab.run(&earlier).snapshot_id.as_deref(), + Some(first.to_string().as_str()) + ); // now the QA person's own run let (status, started) = lab.start(&qa, "qa-1").await; assert_eq!(status, StatusCode::ACCEPTED, "{started}"); let run = started["id"].as_str().unwrap().to_string(); assert_eq!(started["status"], "capturing"); - assert!(started.get("requested_by").is_none() && started.get("snapshot_id").is_none(), "a refresher does not see who or which snapshot"); - assert_eq!(lab.tick().await, 0, "nothing to do until the capture has run"); + assert!( + started.get("requested_by").is_none() && started.get("snapshot_id").is_none(), + "a refresher does not see who or which snapshot" + ); + assert_eq!( + lab.tick().await, + 0, + "nothing to do until the capture has run" + ); assert_eq!(lab.restore_jobs(), 1); - let second = lab.capture(&Lab::production_identity(), false).await.unwrap(); + let second = lab + .capture(&Lab::production_identity(), false) + .await + .unwrap(); assert_ne!(first, second, "a new capture, not the old snapshot"); assert_eq!(lab.tick().await, 1); assert_eq!(lab.restore_jobs(), 2); let stored = lab.run(&run); - assert_eq!((stored.status.as_str(), stored.snapshot_id.as_deref()), ("restoring", Some(second.to_string().as_str()))); + assert_eq!( + (stored.status.as_str(), stored.snapshot_id.as_deref()), + ("restoring", Some(second.to_string().as_str())) + ); // the restore job belongs to this run, names the requester by stable id, and points at this run's snapshot - let (restore_snapshot, actor): (String, String) = - lab.conn().query_row("SELECT snapshot_id, actor FROM restore_jobs WHERE id=?1", [stored.restore_job_id.clone().unwrap()], |r| Ok((r.get(0)?, r.get(1)?))).unwrap(); + let (restore_snapshot, actor): (String, String) = lab + .conn() + .query_row( + "SELECT snapshot_id, actor FROM restore_jobs WHERE id=?1", + [stored.restore_job_id.clone().unwrap()], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .unwrap(); assert_eq!(restore_snapshot, second.to_string()); assert_eq!(actor, format!("oidc:{}", qa.user_id.clone().unwrap())); let (job, token) = lab.restore_until_ready().await.unwrap(); - assert_eq!(lab.apply(&job, &token).await, StatusCode::NO_CONTENT, "still authorised, so the agent may apply"); - assert_eq!(lab.run(&run).status, "restoring", "applying is the restore job's state; the run follows it"); + assert_eq!( + lab.apply(&job, &token).await, + StatusCode::NO_CONTENT, + "still authorised, so the agent may apply" + ); + assert_eq!( + lab.run(&run).status, + "restoring", + "applying is the restore job's state; the run follows it" + ); lab.report_applied(&job, &token).await; assert_eq!(lab.tick().await, 1); assert_eq!(lab.run(&run).status, "completed"); - assert_eq!(lab.audit_actions(&run), ["refresh.started", "refresh.restore_queued", "refresh.completed"]); + assert_eq!( + lab.audit_actions(&run), + [ + "refresh.started", + "refresh.restore_queued", + "refresh.completed" + ] + ); // the person can follow it, and sees the capture time but not where the database is - let (status, view) = lab.send(&qa, "GET", &format!("/api/v1/refresh-runs/{run}"), None).await; - assert_eq!((status, view["status"].clone(), view["source_name"].clone(), view["target_name"].clone()), (StatusCode::OK, json!("completed"), json!("prod-db"), json!("staging-db"))); + let (status, view) = lab + .send(&qa, "GET", &format!("/api/v1/refresh-runs/{run}"), None) + .await; + assert_eq!( + ( + status, + view["status"].clone(), + view["source_name"].clone(), + view["target_name"].clone() + ), + ( + StatusCode::OK, + json!("completed"), + json!("prod-db"), + json!("staging-db") + ) + ); assert!(view["snapshot_taken_at"].is_i64()); for secret in ["instance", "identity", "outpost", "7300000000000000001"] { - assert!(!view.to_string().contains(secret), "{secret} leaked: {view}"); + assert!( + !view.to_string().contains(secret), + "{secret} leaked: {view}" + ); } } @@ -311,19 +559,49 @@ async fn a_double_submit_is_one_run_and_two_keys_on_one_target_are_one_run_and_o let (status, first) = lab.start(&qa, "same-key").await; assert_eq!(status, StatusCode::ACCEPTED); let (status, again) = lab.start(&qa, "same-key").await; - assert_eq!((status, again["id"].clone()), (StatusCode::OK, first["id"].clone()), "the same key returns the same run"); - assert_eq!((lab.capture_jobs(), lab.scalar::("SELECT COUNT(*) FROM refresh_runs")), (1, 1)); + assert_eq!( + (status, again["id"].clone()), + (StatusCode::OK, first["id"].clone()), + "the same key returns the same run" + ); + assert_eq!( + ( + lab.capture_jobs(), + lab.scalar::("SELECT COUNT(*) FROM refresh_runs") + ), + (1, 1) + ); // another key from the same person: the target is busy, and they are told which run let (status, busy) = lab.start(&qa, "second-key").await; - assert_eq!((status, busy["reason"].clone(), busy["run_id"].clone()), (StatusCode::CONFLICT, json!("run_active"), first["id"].clone())); + assert_eq!( + (status, busy["reason"].clone(), busy["run_id"].clone()), + ( + StatusCode::CONFLICT, + json!("run_active"), + first["id"].clone() + ) + ); // another person is told it is busy, but not which run it is let (status, busy) = lab.start(&other, "theirs").await; - assert_eq!((status, busy["reason"].clone()), (StatusCode::CONFLICT, json!("run_active"))); - assert!(busy.get("run_id").is_none() || busy["run_id"] == first["id"], "a grant holder on the relation may see that run"); + assert_eq!( + (status, busy["reason"].clone()), + (StatusCode::CONFLICT, json!("run_active")) + ); + assert!( + busy.get("run_id").is_none() || busy["run_id"] == first["id"], + "a grant holder on the relation may see that run" + ); // the key belongs to the person who used it let (status, _) = lab.start(&other, "same-key").await; assert_eq!(status, StatusCode::CONFLICT); - assert_eq!((lab.capture_jobs(), lab.scalar::("SELECT COUNT(*) FROM refresh_runs")), (1, 1), "nothing extra was created"); + assert_eq!( + ( + lab.capture_jobs(), + lab.scalar::("SELECT COUNT(*) FROM refresh_runs") + ), + (1, 1), + "nothing extra was created" + ); // key hygiene let bad = lab.send(&qa, "POST", "/api/v1/refresh-runs", Some(json!({"relation_id": lab.relation, "confirmation": lab.confirmation(), "idempotency_key": "has space"}))).await.0; assert_eq!(bad, StatusCode::BAD_REQUEST); @@ -334,8 +612,14 @@ async fn a_failed_capture_ends_the_run_and_never_falls_back_to_an_older_snapshot let lab = fresh().await; let admin = lab.admin(); // an older, good snapshot exists - let earlier_run = lab.start(&admin, "older").await.1["id"].as_str().unwrap().to_string(); - let older = lab.capture(&Lab::production_identity(), false).await.unwrap(); + let earlier_run = lab.start(&admin, "older").await.1["id"] + .as_str() + .unwrap() + .to_string(); + let older = lab + .capture(&Lab::production_identity(), false) + .await + .unwrap(); lab.tick().await; let (job, token) = lab.restore_until_ready().await.unwrap(); lab.apply(&job, &token).await; @@ -343,18 +627,36 @@ async fn a_failed_capture_ends_the_run_and_never_falls_back_to_an_older_snapshot lab.tick().await; assert_eq!(lab.run(&earlier_run).status, "completed"); // the next capture fails - let run = lab.start(&admin, "doomed").await.1["id"].as_str().unwrap().to_string(); - lab.capture(&Lab::production_identity(), true).await.unwrap(); + let run = lab.start(&admin, "doomed").await.1["id"] + .as_str() + .unwrap() + .to_string(); + lab.capture(&Lab::production_identity(), true) + .await + .unwrap(); assert_eq!(lab.tick().await, 1); assert_eq!(lab.run(&run).status, "capture_failed"); - assert_eq!(lab.restore_jobs(), 1, "no restore was queued from the older snapshot"); + assert_eq!( + lab.restore_jobs(), + 1, + "no restore was queued from the older snapshot" + ); assert_eq!(lab.run(&run).restore_job_id, None); assert!(!lab.state.db.snapshot_in_restore(older).unwrap()); // the target is free again for a new run, which restores its own new capture - let next = lab.start(&admin, "retry").await.1["id"].as_str().unwrap().to_string(); - let newer = lab.capture(&Lab::production_identity(), false).await.unwrap(); + let next = lab.start(&admin, "retry").await.1["id"] + .as_str() + .unwrap() + .to_string(); + let newer = lab + .capture(&Lab::production_identity(), false) + .await + .unwrap(); lab.tick().await; - assert_eq!(lab.run(&next).snapshot_id.as_deref(), Some(newer.to_string().as_str())); + assert_eq!( + lab.run(&next).snapshot_id.as_deref(), + Some(newer.to_string().as_str()) + ); assert_ne!(newer, older); } @@ -368,26 +670,71 @@ enum Revoke { OutpostRevoked, } -const ALL_REVOKES: [Revoke; 5] = [Revoke::GrantDeleted, Revoke::UserDisabled, Revoke::RelationRetargeted, Revoke::TargetRelabelled, Revoke::OutpostRevoked]; +const ALL_REVOKES: [Revoke; 5] = [ + Revoke::GrantDeleted, + Revoke::UserDisabled, + Revoke::RelationRetargeted, + Revoke::TargetRelabelled, + Revoke::OutpostRevoked, +]; impl Lab { async fn revoke(&self, how: Revoke, person: &Caller, grant: &str) { match how { - Revoke::GrantDeleted => assert!(self.state.db.delete_relation_grant(&self.relation, grant).unwrap()), - Revoke::UserDisabled => assert!(self.state.db.set_user_active(person.user_id.as_ref().unwrap(), false).unwrap()), + Revoke::GrantDeleted => assert!(self + .state + .db + .delete_relation_grant(&self.relation, grant) + .unwrap()), + Revoke::UserDisabled => assert!(self + .state + .db + .set_user_active(person.user_id.as_ref().unwrap(), false) + .unwrap()), Revoke::RelationRetargeted => { let other = RestoreTarget { - id: Uuid::new_v4(), application_id: self.application, outpost_id: self.outpost, name: "another-staging".into(), engine: Engine::Postgres, - identity: DatabaseIdentity { instance: "7300000000000000002".into(), database: "other".into() }, + id: Uuid::new_v4(), + application_id: self.application, + outpost_id: self.outpost, + name: "another-staging".into(), + engine: Engine::Postgres, + identity: DatabaseIdentity { + instance: "7300000000000000002".into(), + database: "other".into(), + }, }; assert!(self.state.db.register_restore_target(&other).unwrap()); - self.state.db.set_target_environment(other.id, "staging", now()).unwrap(); - self.state.db.create_relation(self.orbit, other.id, Some(&self.relation), false, false, "admin", now()).unwrap().unwrap(); + self.state + .db + .set_target_environment(other.id, "staging", now()) + .unwrap(); + self.state + .db + .create_relation( + self.orbit, + other.id, + Some(&self.relation), + false, + false, + "admin", + now(), + ) + .unwrap() + .unwrap(); } Revoke::TargetRelabelled => { - assert!(self.state.db.set_target_environment(self.target, "production", now()).unwrap().is_some()); + assert!(self + .state + .db + .set_target_environment(self.target, "production", now()) + .unwrap() + .is_some()); } - Revoke::OutpostRevoked => assert!(self.state.db.revoke_outpost(&self.outpost.to_string(), now()).unwrap()), + Revoke::OutpostRevoked => assert!(self + .state + .db + .revoke_outpost(&self.outpost.to_string(), now()) + .unwrap()), } } } @@ -398,7 +745,10 @@ async fn losing_authorisation_stops_a_run_at_every_stage_before_anything_is_appl // stage 1: still capturing let lab = fresh().await; let (qa, grant) = lab.refresher("qa"); - let run = lab.start(&qa, "k").await.1["id"].as_str().unwrap().to_string(); + let run = lab.start(&qa, "k").await.1["id"] + .as_str() + .unwrap() + .to_string(); lab.revoke(how, &qa, &grant).await; lab.tick().await; assert_eq!(lab.run(&run).status, "blocked", "{how:?} while capturing"); @@ -417,12 +767,20 @@ async fn losing_authorisation_stops_a_run_at_every_stage_before_anything_is_appl async fn lab_for_stage(how: Revoke) -> Lab { let lab = fresh().await; let (qa, grant) = lab.refresher("qa"); - let run = lab.start(&qa, "k").await.1["id"].as_str().unwrap().to_string(); - lab.capture(&Lab::production_identity(), false).await.unwrap(); + let run = lab.start(&qa, "k").await.1["id"] + .as_str() + .unwrap() + .to_string(); + lab.capture(&Lab::production_identity(), false) + .await + .unwrap(); lab.revoke(how, &qa, &grant).await; lab.tick().await; let stored = lab.run(&run); - assert_eq!(stored.status, "blocked", "{how:?} after the capture, before the restore is queued"); + assert_eq!( + stored.status, "blocked", + "{how:?} after the capture, before the restore is queued" + ); assert_eq!(stored.restore_job_id, None); lab } @@ -430,14 +788,27 @@ async fn lab_for_stage(how: Revoke) -> Lab { async fn lab_for_queued(how: Revoke) -> Lab { let lab = fresh().await; let (qa, grant) = lab.refresher("qa"); - let run = lab.start(&qa, "k").await.1["id"].as_str().unwrap().to_string(); - lab.capture(&Lab::production_identity(), false).await.unwrap(); + let run = lab.start(&qa, "k").await.1["id"] + .as_str() + .unwrap() + .to_string(); + lab.capture(&Lab::production_identity(), false) + .await + .unwrap(); lab.tick().await; let job = lab.run(&run).restore_job_id.unwrap(); lab.revoke(how, &qa, &grant).await; lab.tick().await; - assert_eq!(lab.run(&run).status, "blocked", "{how:?} with the restore queued"); - assert_eq!(lab.restore_status(&job), "cancelled", "{how:?}: the queued restore was cancelled with it"); + assert_eq!( + lab.run(&run).status, + "blocked", + "{how:?} with the restore queued" + ); + assert_eq!( + lab.restore_status(&job), + "cancelled", + "{how:?}: the queued restore was cancelled with it" + ); // the agent finds nothing to do (or, when its Outpost was revoked, nothing at all) if !matches!(how, Revoke::OutpostRevoked) { assert!(lab.restore_until_ready().await.is_none()); @@ -446,22 +817,43 @@ async fn lab_for_queued(how: Revoke) -> Lab { } #[tokio::test] -async fn the_apply_permit_is_refused_and_the_restore_cancelled_when_authorisation_is_lost_after_the_safety_backup() { - for how in [Revoke::GrantDeleted, Revoke::UserDisabled, Revoke::RelationRetargeted, Revoke::TargetRelabelled] { +async fn the_apply_permit_is_refused_and_the_restore_cancelled_when_authorisation_is_lost_after_the_safety_backup( +) { + for how in [ + Revoke::GrantDeleted, + Revoke::UserDisabled, + Revoke::RelationRetargeted, + Revoke::TargetRelabelled, + ] { let lab = fresh().await; let (qa, grant) = lab.refresher("qa"); - let run = lab.start(&qa, "k").await.1["id"].as_str().unwrap().to_string(); - lab.capture(&Lab::production_identity(), false).await.unwrap(); + let run = lab.start(&qa, "k").await.1["id"] + .as_str() + .unwrap() + .to_string(); + lab.capture(&Lab::production_identity(), false) + .await + .unwrap(); lab.tick().await; let (job, token) = lab.restore_until_ready().await.unwrap(); // the safety backup is done and the agent is about to apply, and then access is taken away, with no tick in between lab.revoke(how, &qa, &grant).await; - assert_eq!(lab.apply(&job, &token).await, StatusCode::CONFLICT, "{how:?}: the agent must not be allowed to apply"); + assert_eq!( + lab.apply(&job, &token).await, + StatusCode::CONFLICT, + "{how:?}: the agent must not be allowed to apply" + ); assert_eq!(lab.restore_status(&job), "cancelled", "{how:?}"); assert_ne!(lab.restore_status(&job), "applying"); assert_eq!(lab.run(&run).status, "blocked", "{how:?}"); - assert!(lab.audit_actions(&run).contains(&"refresh.blocked".to_string()) || how_audited_later(&lab, &run).await, "{how:?}: audited"); - let refused: i64 = lab.scalar("SELECT COUNT(*) FROM audit_log WHERE event='restore.apply_refused'"); + assert!( + lab.audit_actions(&run) + .contains(&"refresh.blocked".to_string()) + || how_audited_later(&lab, &run).await, + "{how:?}: audited" + ); + let refused: i64 = + lab.scalar("SELECT COUNT(*) FROM audit_log WHERE event='restore.apply_refused'"); assert_eq!(refused, 1, "{how:?}"); } } @@ -471,7 +863,8 @@ async fn how_audited_later(lab: &Lab, run: &str) -> bool { lab.tick().await; let _ = lab.state.db.refresh_run(run); crate::refresh::audit_run(&lab.state, run, "blocked"); - lab.audit_actions(run).contains(&"refresh.blocked".to_string()) + lab.audit_actions(run) + .contains(&"refresh.blocked".to_string()) } #[tokio::test] @@ -479,15 +872,24 @@ async fn once_applying_has_started_nothing_cancels_it_and_the_run_finishes() { for how in ALL_REVOKES { let lab = fresh().await; let (qa, grant) = lab.refresher("qa"); - let run = lab.start(&qa, "k").await.1["id"].as_str().unwrap().to_string(); - lab.capture(&Lab::production_identity(), false).await.unwrap(); + let run = lab.start(&qa, "k").await.1["id"] + .as_str() + .unwrap() + .to_string(); + lab.capture(&Lab::production_identity(), false) + .await + .unwrap(); lab.tick().await; let (job, token) = lab.restore_until_ready().await.unwrap(); assert_eq!(lab.apply(&job, &token).await, StatusCode::NO_CONTENT); // authorisation is taken away while the restore is applying lab.revoke(how, &qa, &grant).await; lab.tick().await; - assert_eq!(lab.restore_status(&job), "applying", "{how:?}: a half-applied restore is finished, not abandoned"); + assert_eq!( + lab.restore_status(&job), + "applying", + "{how:?}: a half-applied restore is finished, not abandoned" + ); assert_eq!(lab.run(&run).status, "restoring", "{how:?}"); if !matches!(how, Revoke::OutpostRevoked) { lab.report_applied(&job, &token).await; @@ -495,7 +897,14 @@ async fn once_applying_has_started_nothing_cancels_it_and_the_run_finishes() { assert_eq!(lab.run(&run).status, "completed", "{how:?}"); } // and it can no longer be cancelled - let (status, body) = lab.send(&lab.admin(), "DELETE", &format!("/api/v1/refresh-runs/{run}"), None).await; + let (status, body) = lab + .send( + &lab.admin(), + "DELETE", + &format!("/api/v1/refresh-runs/{run}"), + None, + ) + .await; assert_eq!(status, StatusCode::CONFLICT, "{how:?}: {body}"); } } @@ -505,16 +914,48 @@ async fn restores_started_by_an_administrator_are_not_touched_by_any_of_this() { let lab = fresh().await; // a snapshot to restore, from a normal capture lab.start(&lab.admin(), "seed").await; - let snapshot = lab.capture(&Lab::production_identity(), false).await.unwrap(); - let manifest = lab.state.vault.read().await.get_snapshot(snapshot).unwrap().unwrap().manifest; + let snapshot = lab + .capture(&Lab::production_identity(), false) + .await + .unwrap(); + let manifest = lab + .state + .vault + .read() + .await + .get_snapshot(snapshot) + .unwrap() + .unwrap() + .manifest; let (_, artifact) = crate::api::artifact(&manifest).unwrap(); // an administrator queues a restore directly, as before M6 - let job = lab.state.db.enqueue_restore(snapshot, lab.application, lab.target, "admin:direct", &artifact, now()).unwrap().unwrap(); + let job = lab + .state + .db + .enqueue_restore( + snapshot, + lab.application, + lab.target, + "admin:direct", + &artifact, + now(), + ) + .unwrap() + .unwrap(); // the relation is ended and the target even relabelled: a refresh would be refused, an admin restore is not - assert!(lab.state.db.set_target_environment(lab.target, "production", now()).unwrap().is_some()); + assert!(lab + .state + .db + .set_target_environment(lab.target, "production", now()) + .unwrap() + .is_some()); let (restore, token) = lab.restore_until_ready().await.unwrap(); assert_eq!(restore, job.id.to_string()); - assert_eq!(lab.apply(&restore, &token).await, StatusCode::NO_CONTENT, "no run, no extra check"); + assert_eq!( + lab.apply(&restore, &token).await, + StatusCode::NO_CONTENT, + "no run, no extra check" + ); assert_eq!(lab.restore_status(&restore), "applying"); } @@ -522,44 +963,117 @@ async fn restores_started_by_an_administrator_are_not_touched_by_any_of_this() { async fn the_snapshot_is_pinned_from_the_start_and_released_when_the_run_ends() { let lab = fresh().await; let admin = lab.admin(); - let run = lab.start(&admin, "pin").await.1["id"].as_str().unwrap().to_string(); + let run = lab.start(&admin, "pin").await.1["id"] + .as_str() + .unwrap() + .to_string(); let capture = Uuid::parse_str(&lab.run(&run).capture_job_id).unwrap(); - assert!(lab.state.db.snapshot_in_restore(capture).unwrap(), "pinned the moment the run starts"); - lab.capture(&Lab::production_identity(), false).await.unwrap(); + assert!( + lab.state.db.snapshot_in_restore(capture).unwrap(), + "pinned the moment the run starts" + ); + lab.capture(&Lab::production_identity(), false) + .await + .unwrap(); // between the capture finishing and the restore being queued, retention and deletion must still leave it alone - let (status, _) = lab.send(&admin, "DELETE", &format!("/api/v1/snapshots/{capture}"), None).await; - assert_eq!(status, StatusCode::CONFLICT, "deleting a pinned snapshot is refused"); + let (status, _) = lab + .send( + &admin, + "DELETE", + &format!("/api/v1/snapshots/{capture}"), + None, + ) + .await; + assert_eq!( + status, + StatusCode::CONFLICT, + "deleting a pinned snapshot is refused" + ); lab.state.prune_orbit(lab.orbit).await.unwrap(); - assert!(lab.state.vault.read().await.get_snapshot(capture).unwrap().is_some(), "retention left it alone"); + assert!( + lab.state + .vault + .read() + .await + .get_snapshot(capture) + .unwrap() + .is_some(), + "retention left it alone" + ); lab.tick().await; assert!(lab.state.db.snapshot_in_restore(capture).unwrap()); // finishing the run (here: cancelling it) releases the pin - let (status, _) = lab.send(&admin, "DELETE", &format!("/api/v1/refresh-runs/{run}"), None).await; + let (status, _) = lab + .send( + &admin, + "DELETE", + &format!("/api/v1/refresh-runs/{run}"), + None, + ) + .await; assert_eq!(status, StatusCode::OK); - assert!(!lab.state.db.snapshot_in_restore(capture).unwrap(), "released"); + assert!( + !lab.state.db.snapshot_in_restore(capture).unwrap(), + "released" + ); } #[tokio::test] async fn a_run_expires_before_it_applies_but_never_while_applying() { - let lab = lab_with(|state| state.refresh = std::sync::Arc::new(crate::refresh::RefreshConfig { ttl_secs: 60, max_active: 4 })).await; + let lab = lab_with(|state| { + state.refresh = std::sync::Arc::new(crate::refresh::RefreshConfig { + ttl_secs: 60, + max_active: 4, + }) + }) + .await; let (qa, _) = lab.refresher("qa"); - let run = lab.start(&qa, "k").await.1["id"].as_str().unwrap().to_string(); + let run = lab.start(&qa, "k").await.1["id"] + .as_str() + .unwrap() + .to_string(); let stored = lab.run(&run); assert_eq!(stored.expires_at - stored.created_at, 60); // before the deadline nothing changes; after it the run is expired and no restore is ever queued - assert_eq!(lab.state.db.sync_refresh_run(&run, stored.created_at + 59).unwrap(), crate::db::refresh::Sync::Unchanged); - assert_eq!(lab.state.db.sync_refresh_run(&run, stored.expires_at).unwrap(), crate::db::refresh::Sync::Moved("expired".into())); + assert_eq!( + lab.state + .db + .sync_refresh_run(&run, stored.created_at + 59) + .unwrap(), + crate::db::refresh::Sync::Unchanged + ); + assert_eq!( + lab.state + .db + .sync_refresh_run(&run, stored.expires_at) + .unwrap(), + crate::db::refresh::Sync::Moved("expired".into()) + ); assert_eq!(lab.run(&run).status, "expired"); // a run that is already applying is not cut off by its deadline - let lab = lab_with(|state| state.refresh = std::sync::Arc::new(crate::refresh::RefreshConfig { ttl_secs: 60, max_active: 4 })).await; - let run = lab.start(&lab.admin(), "k").await.1["id"].as_str().unwrap().to_string(); - lab.capture(&Lab::production_identity(), false).await.unwrap(); + let lab = lab_with(|state| { + state.refresh = std::sync::Arc::new(crate::refresh::RefreshConfig { + ttl_secs: 60, + max_active: 4, + }) + }) + .await; + let run = lab.start(&lab.admin(), "k").await.1["id"] + .as_str() + .unwrap() + .to_string(); + lab.capture(&Lab::production_identity(), false) + .await + .unwrap(); lab.tick().await; let (job, token) = lab.restore_until_ready().await.unwrap(); assert_eq!(lab.apply(&job, &token).await, StatusCode::NO_CONTENT); let late = lab.run(&run).expires_at + 3600; - assert_eq!(lab.state.db.sync_refresh_run(&run, late).unwrap(), crate::db::refresh::Sync::Unchanged); + assert_eq!( + lab.state.db.sync_refresh_run(&run, late).unwrap(), + crate::db::refresh::Sync::Unchanged + ); assert_eq!(lab.run(&run).status, "restoring"); } @@ -570,50 +1084,122 @@ async fn a_stale_confirmation_a_retarget_and_a_busy_system_are_refused_with_a_re // the relation is retargeted between the person looking at it and pressing the button lab.revoke(Revoke::RelationRetargeted, &qa, &grant).await; let (status, _) = lab.start(&qa, "old-relation").await; - assert_eq!(status, StatusCode::NOT_FOUND, "the old relation no longer exists for them"); - let new = lab.state.db.relation_views(true, None, now()).unwrap().remove(0).relation; + assert_eq!( + status, + StatusCode::NOT_FOUND, + "the old relation no longer exists for them" + ); + let new = lab + .state + .db + .relation_views(true, None, now()) + .unwrap() + .remove(0) + .relation; let admin = lab.admin(); let (status, stale) = lab.send(&admin, "POST", "/api/v1/refresh-runs", Some(json!({"relation_id": new.id, "confirmation": lab.confirmation(), "idempotency_key": "stale"}))).await; - assert_eq!((status, stale["reason"].clone()), (StatusCode::CONFLICT, json!("stale_confirmation")), "the confirmation named version 1 and the target the person saw"); + assert_eq!( + (status, stale["reason"].clone()), + (StatusCode::CONFLICT, json!("stale_confirmation")), + "the confirmation named version 1 and the target the person saw" + ); assert_eq!(lab.scalar::("SELECT COUNT(*) FROM refresh_runs"), 0); // too many refreshes at once - let busy = lab_with(|state| state.refresh = std::sync::Arc::new(crate::refresh::RefreshConfig { ttl_secs: 3600, max_active: 0 })).await; + let busy = lab_with(|state| { + state.refresh = std::sync::Arc::new(crate::refresh::RefreshConfig { + ttl_secs: 3600, + max_active: 0, + }) + }) + .await; let (status, refusal) = busy.start(&busy.admin(), "k").await; - assert_eq!((status, refusal["reason"].clone()), (StatusCode::TOO_MANY_REQUESTS, json!("too_many_runs"))); + assert_eq!( + (status, refusal["reason"].clone()), + (StatusCode::TOO_MANY_REQUESTS, json!("too_many_runs")) + ); // a person without a grant gets 404, not a hint that the relation exists let stranger = busy.person("stranger"); assert_eq!(busy.start(&stranger, "k").await.0, StatusCode::NOT_FOUND); // an unusable relation is refused before anything is queued - busy.state.db.set_target_environment(busy.target, "production", now()).unwrap(); + busy.state + .db + .set_target_environment(busy.target, "production", now()) + .unwrap(); assert_eq!(busy.capture_jobs(), 0); } #[tokio::test] -async fn a_run_can_be_cancelled_by_its_owner_or_an_administrator_and_seen_only_by_those_with_a_reason() { +async fn a_run_can_be_cancelled_by_its_owner_or_an_administrator_and_seen_only_by_those_with_a_reason( +) { let lab = fresh().await; let (owner, _) = lab.refresher("owner"); let (colleague, _) = lab.refresher("colleague"); let stranger = lab.person("stranger"); - let run = lab.start(&owner, "k").await.1["id"].as_str().unwrap().to_string(); + let run = lab.start(&owner, "k").await.1["id"] + .as_str() + .unwrap() + .to_string(); let uri = format!("/api/v1/refresh-runs/{run}"); // visibility: owner, a grant holder on the relation, and an administrator; nobody else assert_eq!(lab.send(&owner, "GET", &uri, None).await.0, StatusCode::OK); - assert_eq!(lab.send(&colleague, "GET", &uri, None).await.0, StatusCode::OK); - assert_eq!(lab.send(&stranger, "GET", &uri, None).await.0, StatusCode::NOT_FOUND); + assert_eq!( + lab.send(&colleague, "GET", &uri, None).await.0, + StatusCode::OK + ); + assert_eq!( + lab.send(&stranger, "GET", &uri, None).await.0, + StatusCode::NOT_FOUND + ); let (_, admin_view) = lab.send(&lab.admin(), "GET", &uri, None).await; - assert!(admin_view["requested_by"].as_str().unwrap().starts_with("oidc:"), "an administrator sees who started it"); - assert!(lab.send(&colleague, "GET", &uri, None).await.1.get("requested_by").is_none()); + assert!( + admin_view["requested_by"] + .as_str() + .unwrap() + .starts_with("oidc:"), + "an administrator sees who started it" + ); + assert!(lab + .send(&colleague, "GET", &uri, None) + .await + .1 + .get("requested_by") + .is_none()); // lists - assert_eq!(lab.send(&colleague, "GET", "/api/v1/refresh-runs", None).await.1.as_array().unwrap().len(), 1); - assert_eq!(lab.send(&stranger, "GET", "/api/v1/refresh-runs", None).await.0, StatusCode::FORBIDDEN); + assert_eq!( + lab.send(&colleague, "GET", "/api/v1/refresh-runs", None) + .await + .1 + .as_array() + .unwrap() + .len(), + 1 + ); + assert_eq!( + lab.send(&stranger, "GET", "/api/v1/refresh-runs", None) + .await + .0, + StatusCode::FORBIDDEN + ); // cancelling: not by a colleague who merely holds a grant, not by a stranger - assert_eq!(lab.send(&colleague, "DELETE", &uri, None).await.0, StatusCode::FORBIDDEN); - assert_eq!(lab.send(&stranger, "DELETE", &uri, None).await.0, StatusCode::NOT_FOUND); + assert_eq!( + lab.send(&colleague, "DELETE", &uri, None).await.0, + StatusCode::FORBIDDEN + ); + assert_eq!( + lab.send(&stranger, "DELETE", &uri, None).await.0, + StatusCode::NOT_FOUND + ); assert_eq!(lab.run(&run).status, "capturing"); let (status, cancelled) = lab.send(&owner, "DELETE", &uri, None).await; - assert_eq!((status, cancelled["status"].clone()), (StatusCode::OK, json!("cancelled"))); - assert_eq!(lab.send(&owner, "DELETE", &uri, None).await.1["reason"], "too_late"); + assert_eq!( + (status, cancelled["status"].clone()), + (StatusCode::OK, json!("cancelled")) + ); + assert_eq!( + lab.send(&owner, "DELETE", &uri, None).await.1["reason"], + "too_late" + ); // the target is free again assert_eq!(lab.start(&colleague, "next").await.0, StatusCode::ACCEPTED); } @@ -622,55 +1208,139 @@ async fn a_run_can_be_cancelled_by_its_owner_or_an_administrator_and_seen_only_b async fn a_queued_restore_is_cancelled_with_its_run_and_every_step_is_safe_to_repeat() { let lab = fresh().await; let admin = lab.admin(); - let run = lab.start(&admin, "k").await.1["id"].as_str().unwrap().to_string(); - lab.capture(&Lab::production_identity(), false).await.unwrap(); + let run = lab.start(&admin, "k").await.1["id"] + .as_str() + .unwrap() + .to_string(); + lab.capture(&Lab::production_identity(), false) + .await + .unwrap(); // a crash after the capture and before the link: the pass can simply run again, any number of times assert_eq!(lab.tick().await, 1); assert_eq!((lab.tick().await, lab.tick().await), (0, 0)); assert_eq!(lab.restore_jobs(), 1, "exactly one restore"); let stored = lab.run(&run); - let manifest = lab.state.vault.read().await.get_snapshot(Uuid::parse_str(&stored.capture_job_id).unwrap()).unwrap().unwrap().manifest; + let manifest = lab + .state + .vault + .read() + .await + .get_snapshot(Uuid::parse_str(&stored.capture_job_id).unwrap()) + .unwrap() + .unwrap() + .manifest; let (_, artifact) = crate::api::artifact(&manifest).unwrap(); - assert_eq!(lab.state.db.enqueue_refresh_restore(&run, &artifact, false, now()).unwrap(), crate::db::refresh::Linked::NotReady, "a repeated link changes nothing"); + assert_eq!( + lab.state + .db + .enqueue_refresh_restore(&run, &artifact, false, now()) + .unwrap(), + crate::db::refresh::Linked::NotReady, + "a repeated link changes nothing" + ); assert_eq!(lab.restore_jobs(), 1); - assert_eq!(lab.state.db.sync_refresh_run(&run, now()).unwrap(), crate::db::refresh::Sync::Unchanged); + assert_eq!( + lab.state.db.sync_refresh_run(&run, now()).unwrap(), + crate::db::refresh::Sync::Unchanged + ); // cancelling before the agent claims it cancels the restore too let job = lab.run(&run).restore_job_id.unwrap(); - assert_eq!(lab.send(&admin, "DELETE", &format!("/api/v1/refresh-runs/{run}"), None).await.0, StatusCode::OK); + assert_eq!( + lab.send( + &admin, + "DELETE", + &format!("/api/v1/refresh-runs/{run}"), + None + ) + .await + .0, + StatusCode::OK + ); assert_eq!(lab.restore_status(&job), "cancelled"); assert!(lab.restore_until_ready().await.is_none()); } #[tokio::test] -async fn a_target_that_is_the_source_or_a_production_database_is_refused_when_the_snapshot_is_known() { +async fn a_target_that_is_the_source_or_a_production_database_is_refused_when_the_snapshot_is_known( +) { // the dump says it came from the very database the relation would overwrite let lab = fresh().await; - let run = lab.start(&lab.admin(), "k").await.1["id"].as_str().unwrap().to_string(); - lab.capture(&DatabaseIdentity { instance: "7300000000000000001".into(), database: "staging_app".into() }, false).await.unwrap(); + let run = lab.start(&lab.admin(), "k").await.1["id"] + .as_str() + .unwrap() + .to_string(); + lab.capture( + &DatabaseIdentity { + instance: "7300000000000000001".into(), + database: "staging_app".into(), + }, + false, + ) + .await + .unwrap(); lab.tick().await; let stored = lab.run(&run); // either rule may be the first to see it: the identity check against every captured source, or the restore's own source/target check assert_eq!(stored.status, "blocked"); - assert!(matches!(stored.blocked_reason.as_deref(), Some("target_rejected" | "target_matches_a_production_source")), "{:?}", stored.blocked_reason); + assert!( + matches!( + stored.blocked_reason.as_deref(), + Some("target_rejected" | "target_matches_a_production_source") + ), + "{:?}", + stored.blocked_reason + ); assert_eq!(lab.restore_jobs(), 0); // another orbit captured as production holds the very database this "staging" target points at let lab = fresh().await; let other = Uuid::new_v4(); - lab.state.db.upsert_orbit(&crate::db::OrbitRow { - id: other, name: "other-prod".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(); + lab.state + .db + .upsert_orbit(&crate::db::OrbitRow { + id: other, + name: "other-prod".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 manifest = tessera_core::manifest::SnapshotManifest { - snapshot_id: Uuid::new_v4(), orbit_id: other, orbit_name: "other-prod".into(), labels: vec![], provider: "postgres".into(), paths: vec![], + snapshot_id: Uuid::new_v4(), + orbit_id: other, + orbit_name: "other-prod".into(), + labels: vec![], + provider: "postgres".into(), + paths: vec![], restore_hints: json!({"format": "custom", "source_identity": {"instance": "7300000000000000001", "database": "staging_app"}}), }; - lab.state.vault.write().await.snapshot(manifest, b"PGDMP", false).unwrap(); - lab.state.db.set_orbit_environment(other, "production", now()).unwrap(); - let run = lab.start(&lab.admin(), "k").await.1["id"].as_str().unwrap().to_string(); - lab.capture(&Lab::production_identity(), false).await.unwrap(); + lab.state + .vault + .write() + .await + .snapshot(manifest, b"PGDMP", false) + .unwrap(); + lab.state + .db + .set_orbit_environment(other, "production", now()) + .unwrap(); + let run = lab.start(&lab.admin(), "k").await.1["id"] + .as_str() + .unwrap() + .to_string(); + lab.capture(&Lab::production_identity(), false) + .await + .unwrap(); lab.tick().await; - assert_eq!(lab.run(&run).blocked_reason.as_deref(), Some("target_matches_a_production_source")); + assert_eq!( + lab.run(&run).blocked_reason.as_deref(), + Some("target_matches_a_production_source") + ); assert_eq!(lab.restore_jobs(), 0); } @@ -678,17 +1348,50 @@ async fn a_target_that_is_the_source_or_a_production_database_is_refused_when_th async fn someone_who_may_only_refresh_gets_into_the_app_but_sees_nothing_else() { let lab = fresh().await; let nobody = lab.person("nobody"); - let status = lab.send(&nobody, "GET", "/api/v1/operator/session", None).await.1; - assert_eq!((status["authorized"].clone(), status["admin"].clone()), (json!(false), json!(false)), "no grant at all: closed"); + let status = lab + .send(&nobody, "GET", "/api/v1/operator/session", None) + .await + .1; + assert_eq!( + (status["authorized"].clone(), status["admin"].clone()), + (json!(false), json!(false)), + "no grant at all: closed" + ); let (qa, _) = lab.refresher("qa"); - let status = lab.send(&qa, "GET", "/api/v1/operator/session", None).await.1; - assert_eq!((status["authorized"].clone(), status["admin"].clone()), (json!(true), json!(false)), "a relation grant opens the app"); + let status = lab + .send(&qa, "GET", "/api/v1/operator/session", None) + .await + .1; + assert_eq!( + (status["authorized"].clone(), status["admin"].clone()), + (json!(true), json!(false)), + "a relation grant opens the app" + ); let me = lab.send(&qa, "GET", "/api/v1/me", None).await.1; assert_eq!(me["refresh_relations"], json!([lab.relation.clone()])); - assert_eq!(me["grants"].as_array().unwrap().len(), 0, "and carries no orbit permission"); + assert_eq!( + me["grants"].as_array().unwrap().len(), + 0, + "and carries no orbit permission" + ); // nothing about orbits, snapshots or restores is visible to them - for path in ["/api/v1/orbits", "/api/v1/snapshots", "/api/v1/capture-jobs", "/api/v1/restore-jobs", "/api/v1/relations"] { - assert_eq!(lab.send(&qa, "GET", path, None).await.0, StatusCode::FORBIDDEN, "{path}"); + for path in [ + "/api/v1/orbits", + "/api/v1/snapshots", + "/api/v1/capture-jobs", + "/api/v1/restore-jobs", + "/api/v1/relations", + ] { + assert_eq!( + lab.send(&qa, "GET", path, None).await.0, + StatusCode::FORBIDDEN, + "{path}" + ); } - assert_eq!(lab.send(&qa, "GET", "/api/v1/refresh-relations", None).await.0, StatusCode::OK); + assert_eq!( + lab.send(&qa, "GET", "/api/v1/refresh-relations", None) + .await + .0, + StatusCode::OK + ); } diff --git a/crates/tessera-hub/src/api/relations.rs b/crates/tessera-hub/src/api/relations.rs index 52b964d..38c227b 100644 --- a/crates/tessera-hub/src/api/relations.rs +++ b/crates/tessera-hub/src/api/relations.rs @@ -22,11 +22,20 @@ use uuid::Uuid; pub(super) fn routes() -> Router { Router::new() .route("/api/v1/orbits/:id/environment", put(set_orbit_environment)) - .route("/api/v1/restore-targets/:id/environment", put(set_target_environment)) + .route( + "/api/v1/restore-targets/:id/environment", + put(set_target_environment), + ) .route("/api/v1/relations", get(list).post(create)) .route("/api/v1/relations/:id", put(retarget).delete(deactivate)) - .route("/api/v1/relations/:id/access", get(list_access).post(grant_access)) - .route("/api/v1/relations/:id/access/:grant", axum::routing::delete(revoke_access)) + .route( + "/api/v1/relations/:id/access", + get(list_access).post(grant_access), + ) + .route( + "/api/v1/relations/:id/access/:grant", + axum::routing::delete(revoke_access), + ) .route("/api/v1/refresh-relations", get(mine)) } @@ -76,10 +85,23 @@ async fn set_orbit_environment( if !valid_environment(&body.environment) { return Err(StatusCode::BAD_REQUEST); } - if !state.db.set_orbit_environment(id, &body.environment, now()).map_err(internal)? { + if !state + .db + .set_orbit_environment(id, &body.environment, now()) + .map_err(internal)? + { return Err(StatusCode::NOT_FOUND); } - state.db.audit_event(&actor.principal, AuditAction::EnvironmentSet, AuditResource::Orbit(id), AuditOutcome::Succeeded, actor.request_id).map_err(internal)?; + state + .db + .audit_event( + &actor.principal, + AuditAction::EnvironmentSet, + AuditResource::Orbit(id), + AuditOutcome::Succeeded, + actor.request_id, + ) + .map_err(internal)?; Ok(StatusCode::NO_CONTENT) } @@ -100,14 +122,38 @@ async fn set_target_environment( if !valid_environment(&body.environment) { return Err(StatusCode::BAD_REQUEST); } - let ended = state.db.set_target_environment(id, &body.environment, now()).map_err(internal)?.ok_or(StatusCode::NOT_FOUND)?; - state.db.audit_event(&actor.principal, AuditAction::EnvironmentSet, AuditResource::RestoreTarget(id), AuditOutcome::Succeeded, actor.request_id).map_err(internal)?; + let ended = state + .db + .set_target_environment(id, &body.environment, now()) + .map_err(internal)? + .ok_or(StatusCode::NOT_FOUND)?; + state + .db + .audit_event( + &actor.principal, + AuditAction::EnvironmentSet, + AuditResource::RestoreTarget(id), + AuditOutcome::Succeeded, + actor.request_id, + ) + .map_err(internal)?; for relation in &ended { if let Ok(relation) = Uuid::parse_str(relation) { - state.db.audit_event(&actor.principal, AuditAction::RelationDeactivate, AuditResource::Relation(relation), AuditOutcome::Succeeded, actor.request_id).map_err(internal)?; + state + .db + .audit_event( + &actor.principal, + AuditAction::RelationDeactivate, + AuditResource::Relation(relation), + AuditOutcome::Succeeded, + actor.request_id, + ) + .map_err(internal)?; } } - Ok(Json(EnvironmentChange { ended_relations: ended })) + Ok(Json(EnvironmentChange { + ended_relations: ended, + })) } #[derive(Serialize)] @@ -154,8 +200,13 @@ async fn list( ) -> Result<(HeaderMap, Json), StatusCode> { admin_read(&state, peer, &headers)?; let (orbit_env, target_env) = state.db.environments().map_err(internal)?; - let profiles: std::collections::HashMap<_, _> = - state.db.capture_profiles().map_err(internal)?.into_iter().map(|p| (p.orbit_id, p)).collect(); + let profiles: std::collections::HashMap<_, _> = state + .db + .capture_profiles() + .map_err(internal)? + .into_iter() + .map(|p| (p.orbit_id, p)) + .collect(); let orbits = state .db .list_orbits() @@ -201,20 +252,43 @@ async fn list( outpost_active, }) .collect(); - let relations = state.db.relation_views(false, None, now()).map_err(internal)?; - Ok((no_store(), Json(Overview { relations, orbits, targets }))) + let relations = state + .db + .relation_views(false, None, now()) + .map_err(internal)?; + Ok(( + no_store(), + Json(Overview { + relations, + orbits, + targets, + }), + )) } /// What the snapshots say about a target: does its identity match a database that is captured as a /// production (or unlabelled) source, and has the source itself been seen at all? -pub(crate) async fn identity_facts(state: &HubState, source: Uuid, target: &DatabaseIdentity) -> Result<(bool, bool), StatusCode> { +pub(crate) async fn identity_facts( + state: &HubState, + source: Uuid, + target: &DatabaseIdentity, +) -> Result<(bool, bool), StatusCode> { let (orbit_env, _) = state.db.environments().map_err(internal)?; let vault = state.vault.read().await; let snapshots = vault.list_snapshots().map_err(internal)?; let (mut clash, mut verified) = (false, false); for snapshot in snapshots { - let Some(identity) = snapshot.manifest.restore_hints.get("source_identity").cloned() else { continue }; - let Ok(identity) = serde_json::from_value::(identity) else { continue }; + let Some(identity) = snapshot + .manifest + .restore_hints + .get("source_identity") + .cloned() + else { + continue; + }; + let Ok(identity) = serde_json::from_value::(identity) else { + continue; + }; let from = snapshot.manifest.orbit_id; if from == source { verified = true; @@ -222,7 +296,11 @@ pub(crate) async fn identity_facts(state: &HubState, source: Uuid, target: &Data if &identity == target { // A staging or development orbit that backs up the target itself is fine; anything else is // a database captured as production (or never classified) under a staging label. - let own_backup = from != source && matches!(orbit_env.get(&from.to_string()).map(String::as_str), Some("staging" | "development")); + let own_backup = from != source + && matches!( + orbit_env.get(&from.to_string()).map(String::as_str), + Some("staging" | "development") + ); if !own_backup { clash = true; } @@ -249,10 +327,31 @@ async fn create( return Ok(refused(Reject::UnknownTarget)); }; let (clash, verified) = identity_facts(&state, body.source_orbit_id, &target.identity).await?; - match state.db.create_relation(body.source_orbit_id, body.target_id, None, clash, verified, &actor.id(), now()).map_err(internal)? { + match state + .db + .create_relation( + body.source_orbit_id, + body.target_id, + None, + clash, + verified, + &actor.id(), + now(), + ) + .map_err(internal)? + { Ok(relation) => { let id = Uuid::parse_str(&relation.id).map_err(internal)?; - state.db.audit_event(&actor.principal, AuditAction::RelationCreate, AuditResource::Relation(id), AuditOutcome::Succeeded, actor.request_id).map_err(internal)?; + state + .db + .audit_event( + &actor.principal, + AuditAction::RelationCreate, + AuditResource::Relation(id), + AuditOutcome::Succeeded, + actor.request_id, + ) + .map_err(internal)?; Ok((StatusCode::CREATED, no_store(), Json(relation)).into_response()) } Err(reject) => Ok(refused(reject)), @@ -273,16 +372,42 @@ async fn retarget( Json(body): Json, ) -> Result { let actor = admin_write(&state, peer, &headers)?; - let old = state.db.relation(&id.to_string()).map_err(internal)?.filter(|r| r.active).ok_or(StatusCode::NOT_FOUND)?; + let old = state + .db + .relation(&id.to_string()) + .map_err(internal)? + .filter(|r| r.active) + .ok_or(StatusCode::NOT_FOUND)?; let source = Uuid::parse_str(&old.source_orbit_id).map_err(internal)?; let Some(target) = state.db.restore_target(body.target_id).map_err(internal)? else { return Ok(refused(Reject::UnknownTarget)); }; let (clash, verified) = identity_facts(&state, source, &target.identity).await?; - match state.db.create_relation(source, body.target_id, Some(&old.id), clash, verified, &actor.id(), now()).map_err(internal)? { + match state + .db + .create_relation( + source, + body.target_id, + Some(&old.id), + clash, + verified, + &actor.id(), + now(), + ) + .map_err(internal)? + { Ok(relation) => { let new_id = Uuid::parse_str(&relation.id).map_err(internal)?; - state.db.audit_event(&actor.principal, AuditAction::RelationRetarget, AuditResource::Relation(new_id), AuditOutcome::Succeeded, actor.request_id).map_err(internal)?; + state + .db + .audit_event( + &actor.principal, + AuditAction::RelationRetarget, + AuditResource::Relation(new_id), + AuditOutcome::Succeeded, + actor.request_id, + ) + .map_err(internal)?; Ok((StatusCode::CREATED, no_store(), Json(relation)).into_response()) } Err(reject) => Ok(refused(reject)), @@ -296,10 +421,29 @@ async fn deactivate( Path(id): Path, ) -> Result { let actor = admin_write(&state, peer, &headers)?; - let done = state.db.deactivate_relation(&id.to_string(), "deactivated_by_admin", now()).map_err(internal)?; - state.db.audit_event(&actor.principal, AuditAction::RelationDeactivate, AuditResource::Relation(id), - if done { AuditOutcome::Succeeded } else { AuditOutcome::Failed }, actor.request_id).map_err(internal)?; - if done { Ok(StatusCode::NO_CONTENT) } else { Err(StatusCode::NOT_FOUND) } + let done = state + .db + .deactivate_relation(&id.to_string(), "deactivated_by_admin", now()) + .map_err(internal)?; + state + .db + .audit_event( + &actor.principal, + AuditAction::RelationDeactivate, + AuditResource::Relation(id), + if done { + AuditOutcome::Succeeded + } else { + AuditOutcome::Failed + }, + actor.request_id, + ) + .map_err(internal)?; + if done { + Ok(StatusCode::NO_CONTENT) + } else { + Err(StatusCode::NOT_FOUND) + } } async fn list_access( @@ -309,8 +453,20 @@ async fn list_access( Path(id): Path, ) -> Result<(HeaderMap, Json>), StatusCode> { admin_read(&state, peer, &headers)?; - state.db.relation(&id.to_string()).map_err(internal)?.ok_or(StatusCode::NOT_FOUND)?; - Ok((no_store(), Json(state.db.relation_grants(&id.to_string()).map_err(internal)?))) + state + .db + .relation(&id.to_string()) + .map_err(internal)? + .ok_or(StatusCode::NOT_FOUND)?; + Ok(( + no_store(), + Json( + state + .db + .relation_grants(&id.to_string()) + .map_err(internal)?, + ), + )) } #[derive(Deserialize)] @@ -327,7 +483,14 @@ async fn grant_access( headers: HeaderMap, Path(id): Path, Json(body): Json, -) -> Result<(StatusCode, HeaderMap, Json), StatusCode> { +) -> Result< + ( + StatusCode, + HeaderMap, + Json, + ), + StatusCode, +> { let actor = admin_write(&state, peer, &headers)?; let now = now(); match body.principal_type.as_str() { @@ -338,7 +501,10 @@ async fn grant_access( } } "group" => { - if body.principal.is_empty() || body.principal.len() > 128 || body.principal.chars().any(char::is_control) { + if body.principal.is_empty() + || body.principal.len() > 128 + || body.principal.chars().any(char::is_control) + { return Err(StatusCode::BAD_REQUEST); } } @@ -347,18 +513,43 @@ async fn grant_access( 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)) + .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); } - state.db.relation(&id.to_string()).map_err(internal)?.filter(|r| r.active).ok_or(StatusCode::NOT_FOUND)?; + state + .db + .relation(&id.to_string()) + .map_err(internal)? + .filter(|r| r.active) + .ok_or(StatusCode::NOT_FOUND)?; let grant = state .db - .add_relation_grant(&body.principal_type, &body.principal, &id.to_string(), expires_at, &actor.id(), now) + .add_relation_grant( + &body.principal_type, + &body.principal, + &id.to_string(), + expires_at, + &actor.id(), + now, + ) .map_err(internal)? .ok_or(StatusCode::CONFLICT)?; - state.db.audit_event(&actor.principal, AuditAction::RelationGrantCreate, AuditResource::Relation(id), AuditOutcome::Succeeded, actor.request_id).map_err(internal)?; + state + .db + .audit_event( + &actor.principal, + AuditAction::RelationGrantCreate, + AuditResource::Relation(id), + AuditOutcome::Succeeded, + actor.request_id, + ) + .map_err(internal)?; Ok((StatusCode::CREATED, no_store(), Json(grant))) } @@ -369,10 +560,29 @@ async fn revoke_access( Path((id, grant)): Path<(Uuid, Uuid)>, ) -> Result { let actor = admin_write(&state, peer, &headers)?; - let removed = state.db.delete_relation_grant(&id.to_string(), &grant.to_string()).map_err(internal)?; - state.db.audit_event(&actor.principal, AuditAction::RelationGrantDelete, AuditResource::Relation(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) } + let removed = state + .db + .delete_relation_grant(&id.to_string(), &grant.to_string()) + .map_err(internal)?; + state + .db + .audit_event( + &actor.principal, + AuditAction::RelationGrantDelete, + AuditResource::Relation(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) + } } /// A relation as a refresher sees it: names and environments, never where the database is. @@ -395,7 +605,10 @@ async fn mine( ) -> Result<(HeaderMap, Json>), StatusCode> { let actor = authenticate(&state, peer, &headers, false)?; let granted = super::gate::visible_relations(&state, &actor)?; - let views = state.db.relation_views(true, granted.as_deref(), now()).map_err(internal)?; + let views = state + .db + .relation_views(true, granted.as_deref(), now()) + .map_err(internal)?; let list = views .into_iter() .map(|view| MyRelation { diff --git a/crates/tessera-hub/src/api/restore.rs b/crates/tessera-hub/src/api/restore.rs index 06793e0..06ad626 100644 --- a/crates/tessera-hub/src/api/restore.rs +++ b/crates/tessera-hub/src/api/restore.rs @@ -28,7 +28,10 @@ pub(super) fn routes() -> Router { Router::new() .route("/api/v1/restore-targets", post(register)) .route("/api/v1/capture-profiles/:id/restore-targets", get(targets)) - .route("/api/v1/snapshots/:id/restore-targets", get(snapshot_targets)) + .route( + "/api/v1/snapshots/:id/restore-targets", + get(snapshot_targets), + ) .route("/api/v1/restore-jobs", post(enqueue).get(recent)) .route("/api/v1/snapshots/:id/restore-jobs", get(history)) .route("/api/v1/restore-jobs/:id", get(job).delete(cancel)) @@ -56,7 +59,8 @@ async fn register( } let profiles = state.db.capture_profiles().map_err(internal)?; if !profiles.iter().any(|profile| { - profile.application_id == target.application_id && profile.format.engine() == Some(target.engine) + profile.application_id == target.application_id + && profile.format.engine() == Some(target.engine) }) { return Err(StatusCode::UNPROCESSABLE_ENTITY); } @@ -125,7 +129,10 @@ async fn snapshot_targets( } else { Some("Outpost is no longer paired") }; - SnapshotTarget { target, ineligible_reason } + SnapshotTarget { + target, + ineligible_reason, + } }) .collect(); Ok(Json(responses)) diff --git a/crates/tessera-hub/src/api/routes.rs b/crates/tessera-hub/src/api/routes.rs index c3d35b9..c38dd25 100644 --- a/crates/tessera-hub/src/api/routes.rs +++ b/crates/tessera-hub/src/api/routes.rs @@ -1,5 +1,5 @@ -use crate::db::OrbitRow; use crate::auth::{AuditAction, AuditOutcome, AuditResource, Permission, Principal, Subject}; +use crate::db::OrbitRow; use crate::state::{HubState, ManagedRetention}; use crate::upload::write_at; use axum::{ @@ -10,14 +10,14 @@ use axum::{ Json, Router, }; use base64::Engine; -use rand::Rng; -use tessera_core::OutpostSummary; use include_dir::{include_dir, Dir}; +use rand::Rng; use std::fs::{File, OpenOptions}; use std::net::SocketAddr; use tessera_core::decay::RetentionPolicy; use tessera_core::manifest::SnapshotManifest; use tessera_core::reconstitute::{ReconstituteSession, ReconstituteState, RECONSTITUTE_GRACE_SECS}; +use tessera_core::OutpostSummary; use tower_http::trace::TraceLayer; use utoipa::OpenApi; use uuid::Uuid; @@ -99,7 +99,10 @@ impl CaptureSnapshotSummary { _ => return None, }; Some(Self { - job_id, application_id, engine, format, + job_id, + application_id, + engine, + format, restore_ready: super::restore::artifact(manifest).is_some(), }) } @@ -131,10 +134,15 @@ impl From for OrbitResponse { "filesystem" => Some(OrbitSource::Filesystem), "postgres" | "database" => Some(OrbitSource::Database), "wormhole" => serde_json::from_str::(&row.provider_config) - .ok().and_then(|config| serde_json::from_value(config["source"].clone()).ok()), + .ok() + .and_then(|config| serde_json::from_value(config["source"].clone()).ok()), _ => None, }; - let access = if row.provider == "wormhole" { OrbitAccess::Outpost } else { OrbitAccess::Hub }; + let access = if row.provider == "wormhole" { + OrbitAccess::Outpost + } else { + OrbitAccess::Hub + }; Self { source, access, @@ -272,48 +280,89 @@ pub(super) fn authenticate( 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 = session.as_ref().map(|s| s.principal()).unwrap_or(Principal::Anonymous); + 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) + state + .db + .audit_event( + &attempted, + AuditAction::Authentication, + AuditResource::Api, + AuditOutcome::Denied, + request_id, + ) .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; } result } fn authenticate_inner( - state: &HubState, peer: SocketAddr, headers: &HeaderMap, mutation: bool, request_id: Uuid, + state: &HubState, + peer: SocketAddr, + headers: &HeaderMap, + mutation: bool, + request_id: Uuid, session: Option, ) -> Result { 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, + 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(configured_admin("api-token", Principal::Service("legacy-admin-token"))); + return Ok(configured_admin( + "api-token", + Principal::Service("legacy-admin-token"), + )); } if let Some(session) = session { if mutation { super::session::require_csrf(headers, &session.csrf.to_string())?; } - return Ok(OperatorActor { principal: session.principal(), subject: session.subject(), - name: session.actor, browser: true, request_id }); + 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(configured_admin("local-development", Principal::LocalDevelopment)); + 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 { +pub(super) fn admin_read( + state: &HubState, + peer: SocketAddr, + headers: &HeaderMap, +) -> Result { 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 { +pub(super) fn admin_write( + state: &HubState, + peer: SocketAddr, + headers: &HeaderMap, +) -> Result { let actor = authenticate(state, peer, headers, true)?; super::gate::admin_only(state, &actor)?; Ok(actor) @@ -335,7 +384,10 @@ pub fn router(state: HubState) -> Router { .route("/api/v1/wormhole/outposts", get(outposts)) .route("/api/v1/wormhole/pairing", post(pairing_start)) .route("/api/v1/wormhole/claim", post(pairing_claim)) - .route("/api/v1/wormhole/outposts/:id/rotate", post(rotate_outpost_token)) + .route( + "/api/v1/wormhole/outposts/:id/rotate", + post(rotate_outpost_token), + ) .route("/api/v1/wormhole/outposts/:id/revoke", post(revoke_outpost)) .route("/api/v1/wormhole/upload/init", post(wormhole_upload_init)) .route("/api/v1/wormhole/upload/chunk", post(wormhole_upload_chunk)) @@ -358,8 +410,7 @@ pub fn router(state: HubState) -> Router { get(|| async { Json(ApiDoc::openapi()) }), ); - api.fallback(spa_fallback) - .layer(TraceLayer::new_for_http()) + api.fallback(spa_fallback).layer(TraceLayer::new_for_http()) } #[utoipa::path(get, path = "/health", responses((status = 200, description = "ok")))] @@ -376,7 +427,9 @@ async fn list_snapshots( 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 snaps = vault + .list_snapshots() + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; let out = snaps .into_iter() .filter(|s| s.manifest.provider != "legacy-history") @@ -410,7 +463,11 @@ async fn list_orbits( .into_iter() .map(|profile| (profile.orbit_id, profile)) .collect(); - let rows = state.db.list_orbits().await.map_err(super::jobs::internal)?; + let rows = state + .db + .list_orbits() + .await + .map_err(super::jobs::internal)?; let responses = rows .into_iter() .filter(|row| visible.contains(row.id)) @@ -418,11 +475,13 @@ async fn list_orbits( let mut response = OrbitResponse::from(row); if let Some(profile) = profiles.get(&response.id) { response.application_id = Some(profile.application_id); - response.source = Some(if profile.format == tessera_core::job::CaptureFormat::Filesystem { - OrbitSource::Filesystem - } else { - OrbitSource::Database - }); + response.source = Some( + if profile.format == tessera_core::job::CaptureFormat::Filesystem { + OrbitSource::Filesystem + } else { + OrbitSource::Database + }, + ); response.capture_schedule = profile.schedule.clone(); (response.capture_retention, response.retention_source) = match ManagedRetention::resolve(profile, response.retention) { @@ -451,42 +510,63 @@ async fn create_orbit( let (decay_preset, retention) = retention_settings(req.decay_preset, req.retention)?; let (provider, config) = match (req.source, req.access, req.provider.as_deref()) { (Some(OrbitSource::Filesystem), Some(OrbitAccess::Hub), None) => { - let config: tessera_providers::FilesystemConfig = serde_json::from_value(req.provider_config.clone()) - .map_err(|_| (StatusCode::BAD_REQUEST, "invalid filesystem configuration"))?; + let config: tessera_providers::FilesystemConfig = + serde_json::from_value(req.provider_config.clone()) + .map_err(|_| (StatusCode::BAD_REQUEST, "invalid filesystem configuration"))?; if config.paths.is_empty() || config.paths.iter().any(|path| path.trim().is_empty()) { - return Err((StatusCode::BAD_REQUEST, "at least one filesystem path is required")); + return Err(( + StatusCode::BAD_REQUEST, + "at least one filesystem path is required", + )); } ("filesystem", req.provider_config) } (Some(OrbitSource::Database), Some(OrbitAccess::Hub), None) => { - let source: super::orbit::DatabaseSource = serde_json::from_value(req.provider_config.clone()) - .map_err(|_| (StatusCode::BAD_REQUEST, "invalid database configuration"))?; + let source: super::orbit::DatabaseSource = + serde_json::from_value(req.provider_config.clone()) + .map_err(|_| (StatusCode::BAD_REQUEST, "invalid database configuration"))?; if !source.valid_endpoint() { - return Err((StatusCode::BAD_REQUEST, "invalid database endpoint or password file path")); + return Err(( + StatusCode::BAD_REQUEST, + "invalid database endpoint or password file path", + )); } ("database", req.provider_config) } (Some(source), Some(OrbitAccess::Outpost), None) - if req.provider_config.as_object().is_some_and(|config| config.is_empty()) + if req + .provider_config + .as_object() + .is_some_and(|config| config.is_empty()) && !req.dry_run.unwrap_or(false) => { ("wormhole", serde_json::json!({ "source": source })) } - (None, None, Some("filesystem" | "postgres" | "wormhole")) => - (req.provider.as_deref().unwrap(), req.provider_config), + (None, None, Some("filesystem" | "postgres" | "wormhole")) => { + (req.provider.as_deref().unwrap(), req.provider_config) + } _ => return Err((StatusCode::BAD_REQUEST, "invalid backup source or access")), }; - let schedule = req.schedule.filter(|expression| !expression.trim().is_empty()); + let schedule = req + .schedule + .filter(|expression| !expression.trim().is_empty()); if let Some(expression) = &schedule { if provider == "wormhole" { - return Err((StatusCode::BAD_REQUEST, "set the schedule on the Outpost capture profile")); + return Err(( + StatusCode::BAD_REQUEST, + "set the schedule on the Outpost capture profile", + )); } crate::scheduler::orbit_schedule(expression) .map_err(|_| (StatusCode::BAD_REQUEST, "invalid cron schedule (UTC)"))?; } if provider == "postgres" { - tessera_providers::PostgresProvider::from_config(&config) - .map_err(|_| (StatusCode::BAD_REQUEST, "invalid PostgreSQL connection URL or dump format"))?; + tessera_providers::PostgresProvider::from_config(&config).map_err(|_| { + ( + StatusCode::BAD_REQUEST, + "invalid PostgreSQL connection URL or dump format", + ) + })?; } let row = OrbitRow { id: Uuid::new_v4(), @@ -567,16 +647,29 @@ async fn trigger_orbit( headers: HeaderMap, Path(id): Path, ) -> Result<(StatusCode, HeaderMap), (StatusCode, String)> { - 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()))? + 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); // 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()))?; + 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())); + return Err(( + StatusCode::CONFLICT, + "queue the capture through its Outpost profile or run the legacy agent".into(), + )); } let snapshot_id = crate::api::run_orbit_internal(state, orbit) .await @@ -611,8 +704,11 @@ async fn start_reconstitute( req.target_path.clone().into() }; let vault = state.vault.read().await; - if vault.get_snapshot(req.snapshot_id).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? - .is_none_or(|snapshot| snapshot.manifest.provider == "legacy-history") { + if vault + .get_snapshot(req.snapshot_id) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .is_none_or(|snapshot| snapshot.manifest.provider == "legacy-history") + { return Err(StatusCode::NOT_FOUND); } let session_id = Uuid::new_v4(); @@ -663,7 +759,10 @@ async fn start_reconstitute( ReconstituteState::Failed }; } - let _ = state_bg.db.audit("reconstitute.done", &format!("session={session_id}")).await; + let _ = state_bg + .db + .audit("reconstitute.done", &format!("session={session_id}")) + .await; }); Ok(Json(ReconstituteStartResponse { @@ -672,10 +771,15 @@ async fn start_reconstitute( })) } -fn browser_export_path(state: &HubState, requested: &str) -> Result { +fn browser_export_path( + state: &HubState, + requested: &str, +) -> Result { use std::path::{Component, Path}; let mut components = Path::new(requested).components(); - let Some(Component::Normal(name)) = components.next() else { return Err(StatusCode::BAD_REQUEST) }; + let Some(Component::Normal(name)) = components.next() else { + return Err(StatusCode::BAD_REQUEST); + }; if components.next().is_some() || name.len() > 255 { return Err(StatusCode::BAD_REQUEST); } @@ -691,7 +795,8 @@ fn browser_export_path(state: &HubState, requested: &str) -> Result (), Err(_) => return Err(StatusCode::INTERNAL_SERVER_ERROR), } - let metadata = std::fs::symlink_metadata(&directory).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let metadata = + std::fs::symlink_metadata(&directory).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; if !metadata.is_dir() { return Err(StatusCode::INTERNAL_SERVER_ERROR); } @@ -742,7 +847,11 @@ async fn outposts( headers: HeaderMap, ) -> Result>, StatusCode> { admin_read(&state, peer, &headers)?; - state.db.list_outposts().map(Json).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR) + state + .db + .list_outposts() + .map(Json) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR) } #[utoipa::path(post, path = "/api/v1/wormhole/pairing", responses((status = 200, body = PairingResponse)))] @@ -755,7 +864,9 @@ async fn pairing_start( const ALPHABET: &[u8] = b"23456789ABCDEFGHJKLMNPQRSTUVWXYZ"; let code: String = { let mut random = rand::thread_rng(); - (0..12).map(|_| ALPHABET[random.gen_range(0..ALPHABET.len())] as char).collect() + (0..12) + .map(|_| ALPHABET[random.gen_range(0..ALPHABET.len())] as char) + .collect() }; let expires = chrono::Utc::now() + chrono::Duration::minutes(10); // Only a digest of the code is stored, and no token exists yet: it is minted at claim. @@ -776,11 +887,18 @@ async fn pairing_claim( headers: HeaderMap, Json(req): Json, ) -> Result, StatusCode> { - let source = state.limits.source(peer.map(|ConnectInfo(addr)| addr), &headers); + let source = state + .limits + .source(peer.map(|ConnectInfo(addr)| addr), &headers); if !state.limits.claim_allowed(source) { if state.limits.audit_denial(source) { - let _ = state.db.audit_event(&Principal::Anonymous, AuditAction::OutpostPair, - AuditResource::Api, AuditOutcome::Denied, Uuid::new_v4()); + let _ = state.db.audit_event( + &Principal::Anonymous, + AuditAction::OutpostPair, + AuditResource::Api, + AuditOutcome::Denied, + Uuid::new_v4(), + ); } return Err(StatusCode::TOO_MANY_REQUESTS); } @@ -793,15 +911,26 @@ async fn pairing_claim( .claim_pairing(&req.code, name, chrono::Utc::now().timestamp()) .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; let Some(claimed) = claimed else { - let _ = state.db.audit_event(&Principal::Anonymous, AuditAction::OutpostPair, - AuditResource::Api, AuditOutcome::Failed, Uuid::new_v4()); + let _ = state.db.audit_event( + &Principal::Anonymous, + AuditAction::OutpostPair, + AuditResource::Api, + AuditOutcome::Failed, + Uuid::new_v4(), + ); return Err(StatusCode::GONE); }; - let outpost_id = Uuid::parse_str(&claimed.outpost_id).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let outpost_id = + Uuid::parse_str(&claimed.outpost_id).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; state .db - .audit_event(&Principal::Outpost(outpost_id), AuditAction::OutpostPair, - AuditResource::Outpost(outpost_id), AuditOutcome::Succeeded, Uuid::new_v4()) + .audit_event( + &Principal::Outpost(outpost_id), + AuditAction::OutpostPair, + AuditResource::Outpost(outpost_id), + AuditOutcome::Succeeded, + Uuid::new_v4(), + ) .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; let hub_url = std::env::var("TESSERA_PUBLIC_URL").unwrap_or_else(|_| { if state.wormhole_mtls { @@ -858,14 +987,27 @@ async fn rotate_outpost_token( .db .rotate_credential(&id.to_string(), grace * 60, now) .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; - let outcome = if issued.is_some() { AuditOutcome::Succeeded } else { AuditOutcome::Failed }; + let outcome = if issued.is_some() { + AuditOutcome::Succeeded + } else { + AuditOutcome::Failed + }; state .db - .audit_event(&actor.principal, AuditAction::CredentialRotate, AuditResource::Outpost(id), outcome, actor.request_id) + .audit_event( + &actor.principal, + AuditAction::CredentialRotate, + AuditResource::Outpost(id), + outcome, + actor.request_id, + ) .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; let issued = issued.ok_or(StatusCode::NOT_FOUND)?; let mut response_headers = HeaderMap::new(); - response_headers.insert(axum::http::header::CACHE_CONTROL, HeaderValue::from_static("no-store")); + response_headers.insert( + axum::http::header::CACHE_CONTROL, + HeaderValue::from_static("no-store"), + ); Ok(( response_headers, Json(RotateResponse { @@ -893,12 +1035,26 @@ async fn revoke_outpost( .db .revoke_outpost(&id.to_string(), chrono::Utc::now().timestamp()) .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; - let outcome = if known { AuditOutcome::Succeeded } else { AuditOutcome::Failed }; + let outcome = if known { + AuditOutcome::Succeeded + } else { + AuditOutcome::Failed + }; state .db - .audit_event(&actor.principal, AuditAction::CredentialRevoke, AuditResource::Outpost(id), outcome, actor.request_id) + .audit_event( + &actor.principal, + AuditAction::CredentialRevoke, + AuditResource::Outpost(id), + outcome, + actor.request_id, + ) .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; - if known { Ok(StatusCode::NO_CONTENT) } else { Err(StatusCode::NOT_FOUND) } + if known { + Ok(StatusCode::NO_CONTENT) + } else { + Err(StatusCode::NOT_FOUND) + } } #[derive(serde::Deserialize, utoipa::ToSchema)] @@ -919,21 +1075,56 @@ async fn bind_outpost( ) -> Result { 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)? { + if !state + .db + .bind_legacy_outpost(orbit, binding.outpost_id) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + { return Err(StatusCode::NOT_FOUND); } - state.db.audit("orbit.outpost_bound", &format!("actor={actor} orbit={orbit} outpost={}", binding.outpost_id)) - .await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; - state.db.audit_event(&actor.principal, AuditAction::OutpostBind, AuditResource::Orbit(orbit), - AuditOutcome::Succeeded, actor.request_id).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + state + .db + .audit( + "orbit.outpost_bound", + &format!("actor={actor} orbit={orbit} outpost={}", binding.outpost_id), + ) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + state + .db + .audit_event( + &actor.principal, + AuditAction::OutpostBind, + AuditResource::Orbit(orbit), + AuditOutcome::Succeeded, + actor.request_id, + ) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; Ok(StatusCode::NO_CONTENT) } -fn require_legacy_upload_owner(state: &HubState, orbit: Uuid, outpost: Uuid) -> Result<(), StatusCode> { - let allowed = state.db.legacy_upload_owned_by(orbit, outpost).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; - state.db.audit_event(&Principal::Outpost(outpost), AuditAction::Authorization, AuditResource::Orbit(orbit), - if allowed { AuditOutcome::Allowed } else { AuditOutcome::Denied }, Uuid::new_v4()) +fn require_legacy_upload_owner( + state: &HubState, + orbit: Uuid, + outpost: Uuid, +) -> Result<(), StatusCode> { + let allowed = state + .db + .legacy_upload_owned_by(orbit, outpost) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + state + .db + .audit_event( + &Principal::Outpost(outpost), + AuditAction::Authorization, + AuditResource::Orbit(orbit), + if allowed { + AuditOutcome::Allowed + } else { + AuditOutcome::Denied + }, + Uuid::new_v4(), + ) .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; if allowed { Ok(()) @@ -997,8 +1188,15 @@ async fn wormhole_upload_chunk( .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? .ok_or(StatusCode::NOT_FOUND)?; if session.outpost_id.as_deref() != Some(outpost.to_string().as_str()) { - state.db.audit_event(&Principal::Outpost(outpost), AuditAction::Authorization, - AuditResource::UploadSession(body.session_id), AuditOutcome::Denied, Uuid::new_v4()) + state + .db + .audit_event( + &Principal::Outpost(outpost), + AuditAction::Authorization, + AuditResource::UploadSession(body.session_id), + AuditOutcome::Denied, + Uuid::new_v4(), + ) .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; return Err(StatusCode::NOT_FOUND); } @@ -1016,6 +1214,7 @@ async fn wormhole_upload_chunk( } let mut file = OpenOptions::new() .create(true) + .truncate(false) // resumable upload: the part is written at offsets .read(true) .write(true) .open(&path) @@ -1042,7 +1241,9 @@ async fn wormhole_upload_chunk( let _ = state.db.mark_upload_unsealed(&body.session_id.to_string()); return Err(StatusCode::INTERNAL_SERVER_ERROR); } - if let Err(status) = seal_upload(&state, body.session_id, session.orbit_id, outpost, file).await { + if let Err(status) = + seal_upload(&state, body.session_id, session.orbit_id, outpost, file).await + { let _ = state.db.mark_upload_unsealed(&body.session_id.to_string()); return Err(status); } @@ -1068,7 +1269,10 @@ fn restrict_part(path: &std::path::Path) { let _ = path; } -pub(super) fn upload_token<'a>(state: &HubState, headers: &'a HeaderMap) -> Result<&'a str, StatusCode> { +pub(super) fn upload_token<'a>( + state: &HubState, + headers: &'a HeaderMap, +) -> Result<&'a str, StatusCode> { if !state.accept_plain_upload { return Err(StatusCode::FORBIDDEN); } @@ -1138,8 +1342,14 @@ async fn wormhole_restic_commit( } fn reject_managed_orbit(state: &HubState, orbit_id: Uuid) -> Result<(), StatusCode> { - if state.db.managed_orbit(orbit_id).map_err(super::jobs::internal)? - || state.db.restic_required(orbit_id).map_err(super::jobs::internal)? + if state + .db + .managed_orbit(orbit_id) + .map_err(super::jobs::internal)? + || state + .db + .restic_required(orbit_id) + .map_err(super::jobs::internal)? { return Err(StatusCode::FORBIDDEN); } @@ -1247,43 +1457,107 @@ mod tests { #[tokio::test] async fn legacy_uploads_are_owned_by_the_assigned_outpost() { let dir = tempfile::tempdir().unwrap(); - let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault").await.unwrap(); + let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") + .await + .unwrap(); state.accept_plain_upload = true; state.admin.token = Some("synthetic-admin".into()); let a = Uuid::new_v4(); let b = Uuid::new_v4(); for (id, token) in [(a, "outpost-a"), (b, "outpost-b")] { - state.db.insert_test_credential(token, &id.to_string(), "agent"); + state + .db + .insert_test_credential(token, &id.to_string(), "agent"); } let orbit = Uuid::new_v4(); - state.db.upsert_orbit(&OrbitRow { - id: orbit, name: "synthetic".into(), provider: "wormhole".into(), - provider_config: "{}".into(), schedule: None, decay_preset: "keep-all".into(), - retention: None, dry_run: false, last_status: "idle".into(), - }).await.unwrap(); + state + .db + .upsert_orbit(&OrbitRow { + id: orbit, + name: "synthetic".into(), + provider: "wormhole".into(), + provider_config: "{}".into(), + schedule: None, + decay_preset: "keep-all".into(), + retention: None, + dry_run: false, + last_status: "idle".into(), + }) + .await + .unwrap(); // Synthetic legacy sessions have no owner and must never be adopted. let old_session = Uuid::new_v4(); let conn = rusqlite::Connection::open(dir.path().join("tessera.db")).unwrap(); - conn.execute("INSERT INTO upload_sessions(id,orbit_id,total,created_at) VALUES (?1,?2,1,'2026')", - rusqlite::params![old_session.to_string(), orbit.to_string()]).unwrap(); + conn.execute( + "INSERT INTO upload_sessions(id,orbit_id,total,created_at) VALUES (?1,?2,1,'2026')", + rusqlite::params![old_session.to_string(), orbit.to_string()], + ) + .unwrap(); let app = router(state.clone()); let request = |path: &str, token: &str, body: serde_json::Value| { - Request::post(path).header(header::CONTENT_TYPE, "application/json") - .header("x-tessera-upload-token", token).body(Body::from(body.to_string())).unwrap() + Request::post(path) + .header(header::CONTENT_TYPE, "application/json") + .header("x-tessera-upload-token", token) + .body(Body::from(body.to_string())) + .unwrap() }; let init = serde_json::json!({"orbit_id":orbit,"total_bytes":2}); - assert_eq!(app.clone().oneshot(request("/api/v1/wormhole/upload/init", "outpost-a", init.clone())).await.unwrap().status(), StatusCode::NOT_FOUND); - let binding = |token: &str| Request::put(format!("/api/v1/orbits/{orbit}/outpost")) - .extension(ConnectInfo("127.0.0.1:9000".parse::().unwrap())) - .header(header::CONTENT_TYPE, "application/json") - .header(header::AUTHORIZATION, format!("Bearer {token}")) - .body(Body::from(serde_json::json!({"outpost_id":a}).to_string())).unwrap(); - assert_eq!(app.clone().oneshot(binding("outpost-a")).await.unwrap().status(), StatusCode::UNAUTHORIZED); - assert_eq!(app.clone().oneshot(binding("synthetic-admin")).await.unwrap().status(), StatusCode::NO_CONTENT); - assert_eq!(app.clone().oneshot(request("/api/v1/wormhole/upload/init", "outpost-b", init.clone())).await.unwrap().status(), StatusCode::NOT_FOUND); - let response = app.clone().oneshot(request("/api/v1/wormhole/upload/init", "outpost-a", init)).await.unwrap(); + assert_eq!( + app.clone() + .oneshot(request( + "/api/v1/wormhole/upload/init", + "outpost-a", + init.clone() + )) + .await + .unwrap() + .status(), + StatusCode::NOT_FOUND + ); + let binding = |token: &str| { + Request::put(format!("/api/v1/orbits/{orbit}/outpost")) + .extension(ConnectInfo("127.0.0.1:9000".parse::().unwrap())) + .header(header::CONTENT_TYPE, "application/json") + .header(header::AUTHORIZATION, format!("Bearer {token}")) + .body(Body::from(serde_json::json!({"outpost_id":a}).to_string())) + .unwrap() + }; + assert_eq!( + app.clone() + .oneshot(binding("outpost-a")) + .await + .unwrap() + .status(), + StatusCode::UNAUTHORIZED + ); + assert_eq!( + app.clone() + .oneshot(binding("synthetic-admin")) + .await + .unwrap() + .status(), + StatusCode::NO_CONTENT + ); + assert_eq!( + app.clone() + .oneshot(request( + "/api/v1/wormhole/upload/init", + "outpost-b", + init.clone() + )) + .await + .unwrap() + .status(), + StatusCode::NOT_FOUND + ); + let response = app + .clone() + .oneshot(request("/api/v1/wormhole/upload/init", "outpost-a", init)) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::OK); - let json: serde_json::Value = serde_json::from_slice(&to_bytes(response.into_body(), 1024).await.unwrap()).unwrap(); + let json: serde_json::Value = + serde_json::from_slice(&to_bytes(response.into_body(), 1024).await.unwrap()).unwrap(); let session = json["session_id"].as_str().unwrap(); for (id, token, expected) in [ (session, "outpost-b", StatusCode::NOT_FOUND), @@ -1292,30 +1566,90 @@ mod tests { (session, "outpost-a", StatusCode::NO_CONTENT), ] { let chunk = serde_json::json!({"session_id":id,"offset":0,"data_b64":"YQ=="}); - assert_eq!(app.clone().oneshot(request("/api/v1/wormhole/upload/chunk", token, chunk)).await.unwrap().status(), expected); + assert_eq!( + app.clone() + .oneshot(request("/api/v1/wormhole/upload/chunk", token, chunk)) + .await + .unwrap() + .status(), + expected + ); } // Foreign Outpost cannot send the final chunk (which would seal). let final_chunk = serde_json::json!({"session_id":session,"offset":1,"data_b64":"Yg=="}); - assert_eq!(app.clone().oneshot(request("/api/v1/wormhole/upload/chunk", "outpost-b", final_chunk.clone())).await.unwrap().status(), StatusCode::NOT_FOUND); - assert_eq!(app.clone().oneshot(request("/api/v1/wormhole/upload/chunk", "outpost-a", final_chunk)).await.unwrap().status(), StatusCode::NO_CONTENT); + assert_eq!( + app.clone() + .oneshot(request( + "/api/v1/wormhole/upload/chunk", + "outpost-b", + final_chunk.clone() + )) + .await + .unwrap() + .status(), + StatusCode::NOT_FOUND + ); + assert_eq!( + app.clone() + .oneshot(request( + "/api/v1/wormhole/upload/chunk", + "outpost-a", + final_chunk + )) + .await + .unwrap() + .status(), + StatusCode::NO_CONTENT + ); let foreign_commit = serde_json::json!({"orbit_id":orbit,"snapshot_id":"a".repeat(64)}); - assert_eq!(app.oneshot(request("/api/v1/wormhole/restic/commit", "outpost-b", foreign_commit)).await.unwrap().status(), StatusCode::NOT_FOUND); + assert_eq!( + app.oneshot(request( + "/api/v1/wormhole/restic/commit", + "outpost-b", + foreign_commit + )) + .await + .unwrap() + .status(), + StatusCode::NOT_FOUND + ); // Queue rebinding ahead of a former-owner commit while both wait on the vault. let guard = state.vault.read().await; let mut admin_headers = HeaderMap::new(); - admin_headers.insert(header::AUTHORIZATION, HeaderValue::from_static("Bearer synthetic-admin")); + admin_headers.insert( + header::AUTHORIZATION, + HeaderValue::from_static("Bearer synthetic-admin"), + ); let mut binding = Box::pin(bind_outpost( - ConnectInfo("127.0.0.1:9000".parse().unwrap()), State(state.clone()), - admin_headers, Path(orbit), Json(OutpostBinding { outpost_id: b }), + ConnectInfo("127.0.0.1:9000".parse().unwrap()), + State(state.clone()), + admin_headers, + Path(orbit), + Json(OutpostBinding { outpost_id: b }), )); use std::{future::Future, task::Poll}; - assert!(matches!(std::future::poll_fn(|cx| Poll::Ready(binding.as_mut().poll(cx))).await, Poll::Pending)); + assert!(matches!( + std::future::poll_fn(|cx| Poll::Ready(binding.as_mut().poll(cx))).await, + Poll::Pending + )); let mut owner_headers = HeaderMap::new(); - owner_headers.insert("x-tessera-upload-token", HeaderValue::from_static("outpost-a")); - let mut commit = Box::pin(wormhole_restic_commit(State(state.clone()), owner_headers, - Json(ResticCommit { orbit_id: orbit, snapshot_id: "a".repeat(64) }))); - assert!(matches!(std::future::poll_fn(|cx| Poll::Ready(commit.as_mut().poll(cx))).await, Poll::Pending)); + owner_headers.insert( + "x-tessera-upload-token", + HeaderValue::from_static("outpost-a"), + ); + let mut commit = Box::pin(wormhole_restic_commit( + State(state.clone()), + owner_headers, + Json(ResticCommit { + orbit_id: orbit, + snapshot_id: "a".repeat(64), + }), + )); + assert!(matches!( + std::future::poll_fn(|cx| Poll::Ready(commit.as_mut().poll(cx))).await, + Poll::Pending + )); drop(guard); assert_eq!(binding.await.unwrap(), StatusCode::NO_CONTENT); assert_eq!(commit.await.err(), Some(StatusCode::NOT_FOUND)); @@ -1334,7 +1668,9 @@ mod tests { #[tokio::test] async fn orbit_creation_validates_cron_and_direct_run_preserves_wormhole_status() { let dir = tempfile::tempdir().unwrap(); - let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "test-vault").await.unwrap(); + let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "test-vault") + .await + .unwrap(); state.admin.token = Some("fixture-admin".into()); state.accept_plain_upload = true; let app = router(state.clone()); @@ -1361,22 +1697,36 @@ mod tests { let rows = state.db.list_orbits().await.unwrap(); assert_eq!(rows.len(), 2); let orbit = rows.iter().find(|row| row.provider == "wormhole").unwrap(); - let response = app.clone().oneshot(post( - &format!("/api/v1/orbits/{}/run", orbit.id), serde_json::Value::Null, - )).await.unwrap(); + let response = app + .clone() + .oneshot(post( + &format!("/api/v1/orbits/{}/run", orbit.id), + serde_json::Value::Null, + )) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::CONFLICT); assert_eq!(state.db.list_orbits().await.unwrap()[1].last_status, "idle"); let outpost = Uuid::new_v4(); - state.db.insert_test_credential("fixture-token", &outpost.to_string(), "agent"); + state + .db + .insert_test_credential("fixture-token", &outpost.to_string(), "agent"); assert!(state.db.bind_legacy_outpost(orbit.id, outpost).unwrap()); { let conn = rusqlite::Connection::open(dir.path().join("tessera.db")).unwrap(); - conn.execute("UPDATE outposts SET last_seen = NULL", []).unwrap(); + conn.execute("UPDATE outposts SET last_seen = NULL", []) + .unwrap(); } - let response = app.oneshot(post("/api/v1/wormhole/upload/init", serde_json::json!({ - "orbit_id": orbit.id, "total_bytes": 42 - }))).await.unwrap(); + let response = app + .oneshot(post( + "/api/v1/wormhole/upload/init", + serde_json::json!({ + "orbit_id": orbit.id, "total_bytes": 42 + }), + )) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::OK); assert!(state.db.list_outposts().unwrap()[0].last_seen.is_some()); } @@ -1384,15 +1734,37 @@ mod tests { #[tokio::test] async fn new_orbits_validate_source_access_and_keep_provider_internal() { let dir = tempfile::tempdir().unwrap(); - let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "test-vault").await.unwrap(); + let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "test-vault") + .await + .unwrap(); state.admin.token = Some("fixture-admin".into()); let app = router(state); for (source, access, config, expected) in [ - ("filesystem", "hub", serde_json::json!({"paths": ["/data/source"]}), StatusCode::OK), - ("filesystem", "hub", serde_json::json!({"paths": []}), StatusCode::BAD_REQUEST), - ("filesystem", "outpost", serde_json::json!({}), StatusCode::OK), + ( + "filesystem", + "hub", + serde_json::json!({"paths": ["/data/source"]}), + StatusCode::OK, + ), + ( + "filesystem", + "hub", + serde_json::json!({"paths": []}), + StatusCode::BAD_REQUEST, + ), + ( + "filesystem", + "outpost", + serde_json::json!({}), + StatusCode::OK, + ), ("database", "outpost", serde_json::json!({}), StatusCode::OK), - ("vm", "outpost", serde_json::json!({}), StatusCode::UNPROCESSABLE_ENTITY), + ( + "vm", + "outpost", + serde_json::json!({}), + StatusCode::UNPROCESSABLE_ENTITY, + ), ] { let request = Request::post("/api/v1/orbits") .extension(ConnectInfo("127.0.0.1:1234".parse::().unwrap())) @@ -1404,7 +1776,9 @@ mod tests { let response = app.clone().oneshot(request).await.unwrap(); assert_eq!(response.status(), expected); if expected == StatusCode::OK { - let body = axum::body::to_bytes(response.into_body(), 65536).await.unwrap(); + let body = axum::body::to_bytes(response.into_body(), 65536) + .await + .unwrap(); let orbit: serde_json::Value = serde_json::from_slice(&body).unwrap(); assert_eq!(orbit["source"], source); assert_eq!(orbit["access"], access); @@ -1445,12 +1819,18 @@ mod tests { ("GET", "/api/v1/orbits", Body::empty()), ("GET", "/api-doc/openapi.json", Body::empty()), ] { - let response = app.clone().oneshot(request(method, path, body)).await.unwrap(); + let response = app + .clone() + .oneshot(request(method, path, body)) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::OK); let bytes = to_bytes(response.into_body(), 100_000).await.unwrap(); let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); let orbit = match path { - "/api-doc/openapi.json" => &json["components"]["schemas"]["OrbitResponse"]["properties"], + "/api-doc/openapi.json" => { + &json["components"]["schemas"]["OrbitResponse"]["properties"] + } _ if method == "GET" => &json[0], _ => &json, }; diff --git a/crates/tessera-hub/src/api/session.rs b/crates/tessera-hub/src/api/session.rs index 1158adc..99de2fd 100644 --- a/crates/tessera-hub/src/api/session.rs +++ b/crates/tessera-hub/src/api/session.rs @@ -32,7 +32,10 @@ pub(super) fn routes() -> Router { .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)) + .route( + "/api/v1/me/preferences", + get(preferences).put(set_preferences), + ) } async fn status( @@ -52,8 +55,11 @@ async fn status( // someone who may only refresh a staging database still gets in, to that one screen || state.db.granted_relations(Some(&session.user_id), &session.groups, now).is_ok_and(|r| !r.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() + 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()); ( no_store(), @@ -104,10 +110,17 @@ async fn me( } else { state .db - .grants_of(actor.subject.user_id.as_deref(), &actor.subject.groups, chrono::Utc::now().timestamp()) + .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 }) + .map(|(permission, orbit_id)| MyGrant { + permission, + orbit_id, + }) .collect() }; let mut capabilities: Vec = if actor.subject.admin { @@ -123,12 +136,25 @@ async fn me( } else { state .db - .granted_relations(actor.subject.user_id.as_deref(), &actor.subject.groups, chrono::Utc::now().timestamp()) + .granted_relations( + actor.subject.user_id.as_deref(), + &actor.subject.groups, + chrono::Utc::now().timestamp(), + ) .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? }; Ok(( no_store(), - Json(Me { id, kind, auth_method, display_name: actor.name.clone(), admin: actor.subject.admin, capabilities, grants, refresh_relations }), + Json(Me { + id, + kind, + auth_method, + display_name: actor.name.clone(), + admin: actor.subject.admin, + capabilities, + grants, + refresh_relations, + }), )) } @@ -149,10 +175,16 @@ async fn preferences( ) -> Result<(HeaderMap, Json), 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)?, + 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(); + let look = stored + .get("look") + .filter(|value| LOOKS.contains(&value.as_str())) + .cloned(); Ok((no_store(), Json(Preferences { look }))) } @@ -169,12 +201,19 @@ async fn set_preferences( Json(body): Json, ) -> Result { let actor = super::routes::authenticate(&state, peer, &headers, true)?; - let user = actor.subject.user_id.as_deref().ok_or(StatusCode::NOT_FOUND)?; + 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)?; + state + .db + .set_preference(user, "look", &look, chrono::Utc::now().timestamp()) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; } Ok(StatusCode::NO_CONTENT) } @@ -191,15 +230,25 @@ async fn login( let source = state.limits.source(Some(peer), &headers); if !state.limits.login_allowed(source) { if state.limits.audit_denial(source) { - let _ = state.db.audit_event(&Principal::Anonymous, AuditAction::Login, AuditResource::Session, - AuditOutcome::Denied, uuid::Uuid::new_v4()); + let _ = state.db.audit_event( + &Principal::Anonymous, + AuditAction::Login, + AuditResource::Session, + AuditOutcome::Denied, + uuid::Uuid::new_v4(), + ); } return Err(StatusCode::TOO_MANY_REQUESTS); } if input.password.is_empty() || input.password.len() > 1024 { return Err(StatusCode::UNAUTHORIZED); } - let permit = state.limits.argon2.clone().try_acquire_owned().map_err(|_| StatusCode::TOO_MANY_REQUESTS)?; + let permit = state + .limits + .argon2 + .clone() + .try_acquire_owned() + .map_err(|_| StatusCode::TOO_MANY_REQUESTS)?; let gate = state.sessions.clone(); let attempt = tokio::task::spawn_blocking(move || { let _permit = permit; // released when hashing is done, not when the handler returns @@ -208,10 +257,21 @@ async fn login( .await .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; let (principal, outcome) = match &attempt { - Ok(session) => (Principal::Emergency(session.actor.clone()), AuditOutcome::Succeeded), + Ok(session) => ( + Principal::Emergency(session.actor.clone()), + AuditOutcome::Succeeded, + ), Err(_) => (Principal::Anonymous, AuditOutcome::Failed), }; - state.db.audit_event(&principal, AuditAction::Login, AuditResource::Session, outcome, uuid::Uuid::new_v4()) + state + .db + .audit_event( + &principal, + AuditAction::Login, + AuditResource::Session, + outcome, + uuid::Uuid::new_v4(), + ) .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; let session = attempt?; state @@ -220,7 +280,10 @@ async fn login( .await .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; let mut headers = no_store(); - headers.insert(header::SET_COOKIE, session_cookie(Some(&session.id.to_string()))?); + headers.insert( + header::SET_COOKIE, + session_cookie(Some(&session.id.to_string()))?, + ); Ok(( headers, Json(Status { @@ -245,8 +308,15 @@ async fn logout( .ok_or(StatusCode::UNAUTHORIZED)?; require_csrf(&headers, &session.csrf.to_string())?; state.sessions.remove(session.id); - state.db.audit_event(&session.principal(), AuditAction::Logout, - AuditResource::Session, AuditOutcome::Succeeded, uuid::Uuid::new_v4()) + state + .db + .audit_event( + &session.principal(), + AuditAction::Logout, + AuditResource::Session, + AuditOutcome::Succeeded, + uuid::Uuid::new_v4(), + ) .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; state .db @@ -425,7 +495,12 @@ mod tests { "SELECT group_concat(actor_id || action || coalesce(resource_id,'') || auth_method) FROM audit_events", [], |row| row.get(0), ).unwrap(); - for secret in ["fixture-operator-password", "fixture-api-token", "Bearer", "wrong"] { + for secret in [ + "fixture-operator-password", + "fixture-api-token", + "Bearer", + "wrong", + ] { assert!(!values.contains(secret)); } } @@ -441,7 +516,13 @@ mod tests { let peer = || ConnectInfo("127.0.0.1:1234".parse::().unwrap()); let anonymous = app .clone() - .oneshot(Request::builder().uri("/api/v1/me").extension(peer()).body(Body::empty()).unwrap()) + .oneshot( + Request::builder() + .uri("/api/v1/me") + .extension(peer()) + .body(Body::empty()) + .unwrap(), + ) .await .unwrap(); assert_eq!(anonymous.status(), StatusCode::UNAUTHORIZED); @@ -459,7 +540,12 @@ mod tests { .await .unwrap(); let cookie = HeaderValue::from_str( - login.headers()[header::SET_COOKIE].to_str().unwrap().split(';').next().unwrap(), + login.headers()[header::SET_COOKIE] + .to_str() + .unwrap() + .split(';') + .next() + .unwrap(), ) .unwrap(); let me = app diff --git a/crates/tessera-hub/src/auth.rs b/crates/tessera-hub/src/auth.rs index cc11929..11f8d85 100644 --- a/crates/tessera-hub/src/auth.rs +++ b/crates/tessera-hub/src/auth.rs @@ -174,8 +174,18 @@ impl Permission { pub fn parse(text: &str) -> Option { [ - Self::OrbitRead, Self::SnapshotRead, Self::CaptureRun, Self::SnapshotDownload, Self::OrbitManage, - Self::OutpostManage, Self::RetentionManage, Self::SnapshotDelete, Self::RecoveryManage, Self::AccessManage, Self::RelationManage, Self::RefreshRun, + Self::OrbitRead, + Self::SnapshotRead, + Self::CaptureRun, + Self::SnapshotDownload, + Self::OrbitManage, + Self::OutpostManage, + Self::RetentionManage, + Self::SnapshotDelete, + Self::RecoveryManage, + Self::AccessManage, + Self::RelationManage, + Self::RefreshRun, ] .into_iter() .find(|permission| permission.as_str() == text) @@ -183,7 +193,10 @@ impl Permission { /// May be given to a non-administrator through a grant. pub fn grantable(self) -> bool { - matches!(self, Self::OrbitRead | Self::SnapshotRead | Self::CaptureRun | Self::SnapshotDownload) + matches!( + self, + Self::OrbitRead | Self::SnapshotRead | Self::CaptureRun | Self::SnapshotDownload + ) } } diff --git a/crates/tessera-hub/src/db.rs b/crates/tessera-hub/src/db.rs index 5067888..a05e2b3 100644 --- a/crates/tessera-hub/src/db.rs +++ b/crates/tessera-hub/src/db.rs @@ -1,12 +1,12 @@ -mod jobs; -mod restore; -mod audit; -pub mod sessions; -pub(crate) mod oidc_login; -pub(crate) mod credentials; pub(crate) mod access; -pub(crate) mod relations; +mod audit; +pub(crate) mod credentials; +mod jobs; +pub(crate) mod oidc_login; pub(crate) mod refresh; +pub(crate) mod relations; +mod restore; +pub mod sessions; pub(crate) use restore::restore_target_mismatch; use anyhow::Result; @@ -93,7 +93,12 @@ impl Db { "INTEGER NOT NULL DEFAULT 0", )?; ensure_column(&conn, "orbits", "retention", "TEXT")?; - ensure_column(&conn, "orbits", "outpost_id", "TEXT REFERENCES outposts(id)")?; + ensure_column( + &conn, + "orbits", + "outpost_id", + "TEXT REFERENCES outposts(id)", + )?; credentials::migrate(&conn)?; jobs::migrate(&conn)?; restore::migrate(&conn)?; @@ -229,7 +234,10 @@ impl Db { WHERE id = ?2 AND outpost_id = ?3 AND provider = 'wormhole' AND dry_run = 0", params![id, orbit_id, outpost_id.to_string(), total], )?; - anyhow::ensure!(inserted == 1, "Outpost assignment changed during upload initialization"); + anyhow::ensure!( + inserted == 1, + "Outpost assignment changed during upload initialization" + ); Ok(()) } @@ -247,18 +255,29 @@ impl Db { Ok(self.conn.lock().unwrap().query_row( "SELECT EXISTS(SELECT 1 FROM orbits WHERE id=?1 AND outpost_id=?2 AND provider='wormhole' AND dry_run=0)", - params![orbit.to_string(), outpost.to_string()], |row| row.get(0), + params![orbit.to_string(), outpost.to_string()], + |row| row.get(0), )?) } pub fn list_outposts(&self) -> Result> { let conn = self.conn.lock().unwrap(); - let mut stmt = conn.prepare("SELECT id, name, last_seen, pairing_state FROM outposts ORDER BY name, id")?; + let mut stmt = conn + .prepare("SELECT id, name, last_seen, pairing_state FROM outposts ORDER BY name, id")?; let rows = stmt.query_map([], |row| { let id = Uuid::parse_str(&row.get::<_, String>(0)?).map_err(|err| { - rusqlite::Error::FromSqlConversionFailure(0, rusqlite::types::Type::Text, Box::new(err)) + rusqlite::Error::FromSqlConversionFailure( + 0, + rusqlite::types::Type::Text, + Box::new(err), + ) })?; - Ok(OutpostSummary { id, name: row.get(1)?, last_seen: row.get(2)?, pairing_state: row.get(3)? }) + Ok(OutpostSummary { + id, + name: row.get(1)?, + last_seen: row.get(2)?, + pairing_state: row.get(3)?, + }) })?; Ok(rows.collect::>()?) } @@ -372,7 +391,10 @@ fn ensure_column(conn: &Connection, table: &str, column: &str, decl: &str) -> Re return Ok(()); } } - conn.execute(&format!("ALTER TABLE {table} ADD COLUMN {column} {decl}"), [])?; + conn.execute( + &format!("ALTER TABLE {table} ADD COLUMN {column} {decl}"), + [], + )?; Ok(()) } diff --git a/crates/tessera-hub/src/db/access.rs b/crates/tessera-hub/src/db/access.rs index 6b037ae..1645e58 100644 --- a/crates/tessera-hub/src/db/access.rs +++ b/crates/tessera-hub/src/db/access.rs @@ -107,7 +107,12 @@ impl Db { } pub fn delete_grant(&self, id: &str) -> Result { - Ok(self.conn.lock().unwrap().execute("DELETE FROM access_grants WHERE id=?1", params![id])? == 1) + Ok(self + .conn + .lock() + .unwrap() + .execute("DELETE FROM access_grants WHERE id=?1", params![id])? + == 1) } pub fn list_grants(&self) -> Result> { @@ -135,7 +140,14 @@ impl Db { } /// Does the subject hold `permission` on `orbit` (a global grant counts)? - pub fn has_permission(&self, user: Option<&str>, groups: &[String], permission: &str, orbit: &str, now: i64) -> Result { + pub fn has_permission( + &self, + user: Option<&str>, + groups: &[String], + permission: &str, + orbit: &str, + now: i64, + ) -> Result { let conn = self.conn.lock().unwrap(); Ok(conn.query_row( &format!( @@ -147,12 +159,20 @@ impl Db { )?) } - pub fn permitted_orbits(&self, user: Option<&str>, groups: &[String], permission: &str, now: i64) -> Result { + pub fn permitted_orbits( + &self, + user: Option<&str>, + groups: &[String], + permission: &str, + now: i64, + ) -> Result { let conn = self.conn.lock().unwrap(); let mut stmt = conn.prepare(&format!( "SELECT scope_type, scope_id FROM access_grants WHERE permission=?1 AND {LIVE}" ))?; - let rows = stmt.query_map(params![permission, now, user, groups_json(groups)], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?; + let rows = stmt.query_map(params![permission, now, user, groups_json(groups)], |r| { + Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)) + })?; let mut out = Permitted::default(); for row in rows { let (scope, id) = row?; @@ -166,17 +186,23 @@ impl Db { } /// Live grants of one subject, for `/me`. - pub fn grants_of(&self, user: Option<&str>, groups: &[String], now: i64) -> Result)>> { + pub fn grants_of( + &self, + user: Option<&str>, + groups: &[String], + now: i64, + ) -> Result)>> { let conn = self.conn.lock().unwrap(); - let mut stmt = conn.prepare(&format!( - "SELECT permission, scope_type, scope_id FROM access_grants WHERE (expires_at IS NULL OR expires_at > ?1) + let mut stmt = conn.prepare("SELECT permission, scope_type, scope_id FROM access_grants WHERE (expires_at IS NULL OR expires_at > ?1) AND ((principal_type='user' AND principal=?2) OR (principal_type='group' AND principal IN (SELECT value FROM json_each(?3)))) - ORDER BY permission, scope_id" - ).replace("?1", "?1"))?; + ORDER BY permission, scope_id")?; let rows = stmt.query_map(params![now, user, groups_json(groups)], |r| { let scope_type: String = r.get(1)?; let scope_id: String = r.get(2)?; - Ok((r.get::<_, String>(0)?, (scope_type == "orbit").then_some(scope_id))) + Ok(( + r.get::<_, String>(0)?, + (scope_type == "orbit").then_some(scope_id), + )) })?; Ok(rows.collect::>()?) } @@ -200,14 +226,21 @@ impl Db { } pub fn user_exists(&self, id: &str) -> Result { - Ok(self.conn.lock().unwrap().query_row("SELECT EXISTS(SELECT 1 FROM users WHERE id=?1)", params![id], |r| r.get(0))?) + Ok(self.conn.lock().unwrap().query_row( + "SELECT EXISTS(SELECT 1 FROM users WHERE id=?1)", + params![id], + |r| r.get(0), + )?) } /// Enable or disable a user. Disabling also ends every session at once. pub fn set_user_active(&self, id: &str, active: bool) -> Result { let mut conn = self.conn.lock().unwrap(); let tx = conn.transaction()?; - let changed = tx.execute("UPDATE users SET active=?2, generation=generation+1 WHERE id=?1", params![id, active])? == 1; + let changed = tx.execute( + "UPDATE users SET active=?2, generation=generation+1 WHERE id=?1", + params![id, active], + )? == 1; if changed && !active { tx.execute("DELETE FROM sessions WHERE user_id=?1", params![id])?; } @@ -219,7 +252,9 @@ impl Db { pub fn preferences(&self, user: &str) -> Result> { let conn = self.conn.lock().unwrap(); let mut stmt = conn.prepare("SELECT key, value FROM user_preferences WHERE user_id=?1")?; - let rows = stmt.query_map(params![user], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?; + let rows = stmt.query_map(params![user], |r| { + Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)) + })?; Ok(rows.collect::>()?) } @@ -233,14 +268,22 @@ impl Db { } pub fn orbit_exists(&self, id: &str) -> Result { - Ok(self.conn.lock().unwrap().query_row("SELECT EXISTS(SELECT 1 FROM orbits WHERE id=?1)", params![id], |r| r.get(0))?) + Ok(self.conn.lock().unwrap().query_row( + "SELECT EXISTS(SELECT 1 FROM orbits WHERE id=?1)", + params![id], + |r| r.get(0), + )?) } /// The orbit an application (capture profile) belongs to. pub fn orbit_of_application(&self, application: Uuid) -> Result> { let conn = self.conn.lock().unwrap(); let orbit: Option = conn - .query_row("SELECT orbit_id FROM capture_profiles WHERE application_id=?1", params![application.to_string()], |r| r.get(0)) + .query_row( + "SELECT orbit_id FROM capture_profiles WHERE application_id=?1", + params![application.to_string()], + |r| r.get(0), + ) .optional()?; Ok(orbit.and_then(|id| Uuid::parse_str(&id).ok())) } @@ -257,45 +300,108 @@ mod tests { (dir, db) } - fn grant<'a>(kind: &'a str, who: &'a str, permission: &'a str, orbit: Option<&'a str>, expires: Option) -> NewGrant<'a> { - NewGrant { principal_type: kind, principal: who, permission, orbit, expires_at: expires, created_by: "test" } + fn grant<'a>( + kind: &'a str, + who: &'a str, + permission: &'a str, + orbit: Option<&'a str>, + expires: Option, + ) -> NewGrant<'a> { + NewGrant { + principal_type: kind, + principal: who, + permission, + orbit, + expires_at: expires, + created_by: "test", + } } #[tokio::test] async fn a_grant_applies_to_its_user_scope_and_permission_only() { let (_d, db) = db().await; - db.add_grant(&grant("user", "u1", "orbit.read", Some("orbit-a"), None), 10).unwrap().unwrap(); - let has = |user: &str, perm: &str, orbit: &str| db.has_permission(Some(user), &[], perm, orbit, 20).unwrap(); + db.add_grant( + &grant("user", "u1", "orbit.read", Some("orbit-a"), None), + 10, + ) + .unwrap() + .unwrap(); + let has = |user: &str, perm: &str, orbit: &str| { + db.has_permission(Some(user), &[], perm, orbit, 20).unwrap() + }; assert!(has("u1", "orbit.read", "orbit-a")); assert!(!has("u1", "orbit.read", "orbit-b"), "other orbit"); assert!(!has("u1", "snapshot.read", "orbit-a"), "other permission"); assert!(!has("u2", "orbit.read", "orbit-a"), "other user"); - assert!(!has("u1", "orbit.", "orbit-a") && !has("u1", "orbit", "orbit-a"), "never by prefix"); - assert!(!db.has_permission(None, &[], "orbit.read", "orbit-a", 20).unwrap(), "no user, no groups"); + assert!( + !has("u1", "orbit.", "orbit-a") && !has("u1", "orbit", "orbit-a"), + "never by prefix" + ); + assert!( + !db.has_permission(None, &[], "orbit.read", "orbit-a", 20) + .unwrap(), + "no user, no groups" + ); } #[tokio::test] async fn a_global_grant_covers_every_orbit_and_a_group_grant_covers_its_members() { let (_d, db) = db().await; - db.add_grant(&grant("group", "qa", "capture.run", None, None), 10).unwrap().unwrap(); + db.add_grant(&grant("group", "qa", "capture.run", None, None), 10) + .unwrap() + .unwrap(); let qa = vec!["qa".to_string()]; - assert!(db.has_permission(Some("anyone"), &qa, "capture.run", "any-orbit", 11).unwrap()); - assert!(!db.has_permission(Some("anyone"), &["devs".to_string()], "capture.run", "any-orbit", 11).unwrap()); - assert!(!db.has_permission(Some("anyone"), &[], "capture.run", "any-orbit", 11).unwrap(), "claim missing = no groups"); - let p = db.permitted_orbits(Some("anyone"), &qa, "capture.run", 11).unwrap(); + assert!(db + .has_permission(Some("anyone"), &qa, "capture.run", "any-orbit", 11) + .unwrap()); + assert!(!db + .has_permission( + Some("anyone"), + &["devs".to_string()], + "capture.run", + "any-orbit", + 11 + ) + .unwrap()); + assert!( + !db.has_permission(Some("anyone"), &[], "capture.run", "any-orbit", 11) + .unwrap(), + "claim missing = no groups" + ); + let p = db + .permitted_orbits(Some("anyone"), &qa, "capture.run", 11) + .unwrap(); assert!(p.everywhere && p.orbits.is_empty()); } #[tokio::test] async fn expired_and_deleted_grants_stop_applying_on_the_next_check() { let (_d, db) = db().await; - let timed = db.add_grant(&grant("user", "u1", "orbit.read", Some("o"), Some(100)), 10).unwrap().unwrap(); - assert!(db.has_permission(Some("u1"), &[], "orbit.read", "o", 99).unwrap()); - assert!(!db.has_permission(Some("u1"), &[], "orbit.read", "o", 100).unwrap(), "expiry is exclusive"); - let forever = db.add_grant(&grant("user", "u1", "snapshot.read", Some("o"), None), 10).unwrap().unwrap(); - assert!(db.has_permission(Some("u1"), &[], "snapshot.read", "o", 1_000_000).unwrap()); + let timed = db + .add_grant(&grant("user", "u1", "orbit.read", Some("o"), Some(100)), 10) + .unwrap() + .unwrap(); + assert!(db + .has_permission(Some("u1"), &[], "orbit.read", "o", 99) + .unwrap()); + assert!( + !db.has_permission(Some("u1"), &[], "orbit.read", "o", 100) + .unwrap(), + "expiry is exclusive" + ); + let forever = db + .add_grant(&grant("user", "u1", "snapshot.read", Some("o"), None), 10) + .unwrap() + .unwrap(); + assert!(db + .has_permission(Some("u1"), &[], "snapshot.read", "o", 1_000_000) + .unwrap()); assert!(db.delete_grant(&forever.id).unwrap()); - assert!(!db.has_permission(Some("u1"), &[], "snapshot.read", "o", 11).unwrap(), "revoked at once"); + assert!( + !db.has_permission(Some("u1"), &[], "snapshot.read", "o", 11) + .unwrap(), + "revoked at once" + ); assert!(!db.delete_grant(&forever.id).unwrap()); let _ = timed; } @@ -303,13 +409,26 @@ mod tests { #[tokio::test] async fn duplicates_are_ignored_and_the_list_filters_by_permission() { let (_d, db) = db().await; - assert!(db.add_grant(&grant("user", "u1", "orbit.read", Some("a"), None), 1).unwrap().is_some()); - assert!(db.add_grant(&grant("user", "u1", "orbit.read", Some("a"), None), 2).unwrap().is_none()); - db.add_grant(&grant("user", "u1", "orbit.read", Some("b"), None), 1).unwrap(); - db.add_grant(&grant("user", "u1", "capture.run", Some("c"), None), 1).unwrap(); - let p = db.permitted_orbits(Some("u1"), &[], "orbit.read", 5).unwrap(); + assert!(db + .add_grant(&grant("user", "u1", "orbit.read", Some("a"), None), 1) + .unwrap() + .is_some()); + assert!(db + .add_grant(&grant("user", "u1", "orbit.read", Some("a"), None), 2) + .unwrap() + .is_none()); + db.add_grant(&grant("user", "u1", "orbit.read", Some("b"), None), 1) + .unwrap(); + db.add_grant(&grant("user", "u1", "capture.run", Some("c"), None), 1) + .unwrap(); + let p = db + .permitted_orbits(Some("u1"), &[], "orbit.read", 5) + .unwrap(); assert!(!p.everywhere); - assert_eq!(p.orbits, ["a".to_string(), "b".to_string()].into_iter().collect()); + assert_eq!( + p.orbits, + ["a".to_string(), "b".to_string()].into_iter().collect() + ); assert_eq!(db.list_grants().unwrap().len(), 3); assert_eq!(db.grants_of(Some("u1"), &[], 5).unwrap().len(), 3); } @@ -317,13 +436,20 @@ mod tests { #[tokio::test] async fn disabling_a_user_ends_their_sessions_and_blocks_new_ones() { let (_d, db) = db().await; - let user = db.upsert_user("https://idp.example", "sub", "Sam", 1).unwrap(); - db.create_session("s1", &user, "oidc", None, false, &[], 1).unwrap(); + let user = db + .upsert_user("https://idp.example", "sub", "Sam", 1) + .unwrap(); + db.create_session("s1", &user, "oidc", None, false, &[], 1) + .unwrap(); assert!(db.set_user_active(&user, false).unwrap()); assert!(db.lookup_session("s1", 2).unwrap().is_none()); - assert!(!db.create_session("s2", &user, "oidc", None, false, &[], 2).unwrap()); + assert!(!db + .create_session("s2", &user, "oidc", None, false, &[], 2) + .unwrap()); assert!(db.set_user_active(&user, true).unwrap()); - assert!(db.create_session("s3", &user, "oidc", None, false, &[], 3).unwrap()); + assert!(db + .create_session("s3", &user, "oidc", None, false, &[], 3) + .unwrap()); assert!(!db.set_user_active("missing", false).unwrap()); } } diff --git a/crates/tessera-hub/src/db/credentials.rs b/crates/tessera-hub/src/db/credentials.rs index 4d2f3c3..d72e2ad 100644 --- a/crates/tessera-hub/src/db/credentials.rs +++ b/crates/tessera-hub/src/db/credentials.rs @@ -90,7 +90,16 @@ fn migrate_legacy(conn: &Connection) -> Result<()> { let mut codes = 0; let rows: Vec<(String, String, String, String, Option, String)> = { let mut stmt = conn.prepare("SELECT token, outpost_id, code, state, outpost_name, expires_at FROM wormhole_tokens")?; - let mapped = stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?)))?; + let mapped = stmt.query_map([], |r| { + Ok(( + r.get(0)?, + r.get(1)?, + r.get(2)?, + r.get(3)?, + r.get(4)?, + r.get(5)?, + )) + })?; mapped.collect::>()? }; for (token, outpost, code, state, name, expires) in rows { @@ -106,7 +115,9 @@ fn migrate_legacy(conn: &Connection) -> Result<()> { )?; active += 1; } else if state == "code_shown" { - let expires_at = chrono::DateTime::parse_from_rfc3339(&expires).map(|t| t.timestamp()).unwrap_or(0); + let expires_at = chrono::DateTime::parse_from_rfc3339(&expires) + .map(|t| t.timestamp()) + .unwrap_or(0); conn.execute( "INSERT OR IGNORE INTO pairing_codes(code_digest,outpost_id,expires_at) VALUES (?1,?2,?3)", params![digest("pairing-code", &code), outpost, expires_at], @@ -139,7 +150,10 @@ fn migrate_legacy(conn: &Connection) -> Result<()> { impl Db { pub fn insert_pairing(&self, outpost_id: &str, code: &str, expires_at: i64) -> Result<()> { let conn = self.conn.lock().unwrap(); - conn.execute("DELETE FROM pairing_codes WHERE expires_at <= ?1 OR consumed_at IS NOT NULL", params![expires_at - 86_400])?; + conn.execute( + "DELETE FROM pairing_codes WHERE expires_at <= ?1 OR consumed_at IS NOT NULL", + params![expires_at - 86_400], + )?; conn.execute( "INSERT INTO pairing_codes(code_digest, outpost_id, expires_at) VALUES (?1, ?2, ?3)", params![digest("pairing-code", code), outpost_id, expires_at], @@ -150,7 +164,12 @@ impl Db { /// Consume a pairing code and mint the upload token. The single UPDATE … /// RETURNING is what makes a code usable once; the `Db` mutex additionally /// serialises callers. The token exists in clear only in the return value. - pub fn claim_pairing(&self, code: &str, outpost_name: &str, now: i64) -> Result> { + pub fn claim_pairing( + &self, + code: &str, + outpost_name: &str, + now: i64, + ) -> Result> { let mut conn = self.conn.lock().unwrap(); let tx = conn.transaction()?; let outpost: Option = tx @@ -162,7 +181,9 @@ impl Db { |row| row.get(0), ) .optional()?; - let Some(outpost) = outpost else { return Ok(None) }; + let Some(outpost) = outpost else { + return Ok(None); + }; let token = new_token(); let expires_at = now + lifetime_secs(); tx.execute( @@ -176,7 +197,12 @@ impl Db { params![Uuid::new_v4().to_string(), outpost, digest("outpost-token", &token), now, expires_at], )?; tx.commit()?; - Ok(Some(Issued { token, outpost_id: outpost, expires_at, previous_valid_until: None })) + Ok(Some(Issued { + token, + outpost_id: outpost, + expires_at, + previous_valid_until: None, + })) } /// The Outpost a presented token belongs to, if it is active and unexpired. @@ -196,7 +222,12 @@ impl Db { /// working for `grace_secs` (0 = they stop immediately), so an operator has a /// bounded window to put the new token on the agent. Returns `None` for an /// unknown or revoked Outpost: it must be paired again. - pub fn rotate_credential(&self, outpost: &str, grace_secs: i64, now: i64) -> Result> { + pub fn rotate_credential( + &self, + outpost: &str, + grace_secs: i64, + now: i64, + ) -> Result> { let mut conn = self.conn.lock().unwrap(); let tx = conn.transaction()?; let paired: bool = tx.query_row( @@ -238,7 +269,10 @@ impl Db { "UPDATE outpost_credentials SET state='revoked', revoked_at=?2 WHERE outpost_id=?1 AND state='active'", params![outpost, now], )?; - let known = tx.execute("UPDATE outposts SET pairing_state='revoked' WHERE id=?1", params![outpost])? == 1; + let known = tx.execute( + "UPDATE outposts SET pairing_state='revoked' WHERE id=?1", + params![outpost], + )? == 1; // Anything that overwrites through, or reads from, this Outpost must stop working with it. tx.execute( "UPDATE orbit_relations SET active=0, deactivated_at=?2, deactivated_reason='outpost_revoked' @@ -296,7 +330,9 @@ mod tests { } fn contains(haystack: &[u8], needle: &str) -> bool { - haystack.windows(needle.len()).any(|w| w == needle.as_bytes()) + haystack + .windows(needle.len()) + .any(|w| w == needle.as_bytes()) } #[tokio::test] @@ -304,14 +340,31 @@ mod tests { let (_dir, db, path) = db().await; let outpost = Uuid::new_v4().to_string(); db.insert_pairing(&outpost, "ABCDEFGH2345", 10_000).unwrap(); - let issued = db.claim_pairing("ABCDEFGH2345", "agent", 100).unwrap().unwrap(); + let issued = db + .claim_pairing("ABCDEFGH2345", "agent", 100) + .unwrap() + .unwrap(); assert_eq!(issued.token.len(), 64); - assert_eq!(db.upload_token_outpost(&issued.token, 101).unwrap().as_deref(), Some(outpost.as_str())); + assert_eq!( + db.upload_token_outpost(&issued.token, 101) + .unwrap() + .as_deref(), + Some(outpost.as_str()) + ); drop(db); let bytes = disk_bytes(&path); - assert!(contains(&bytes, "agent"), "sanity: the scan really reads the database file"); - assert!(!contains(&bytes, &issued.token), "token in the database file"); - assert!(!contains(&bytes, "ABCDEFGH2345"), "pairing code in the database file"); + assert!( + contains(&bytes, "agent"), + "sanity: the scan really reads the database file" + ); + assert!( + !contains(&bytes, &issued.token), + "token in the database file" + ); + assert!( + !contains(&bytes, "ABCDEFGH2345"), + "pairing code in the database file" + ); } #[tokio::test] @@ -321,9 +374,15 @@ mod tests { db.insert_pairing(&outpost, "CODE-ONE", 1_000).unwrap(); assert!(db.claim_pairing("WRONG", "a", 10).unwrap().is_none()); assert!(db.claim_pairing("CODE-ONE", "a", 10).unwrap().is_some()); - assert!(db.claim_pairing("CODE-ONE", "a", 11).unwrap().is_none(), "replay"); + assert!( + db.claim_pairing("CODE-ONE", "a", 11).unwrap().is_none(), + "replay" + ); db.insert_pairing(&outpost, "CODE-TWO", 1_000).unwrap(); - assert!(db.claim_pairing("CODE-TWO", "a", 1_000).unwrap().is_none(), "expired at its deadline"); + assert!( + db.claim_pairing("CODE-TWO", "a", 1_000).unwrap().is_none(), + "expired at its deadline" + ); } #[tokio::test] @@ -331,14 +390,19 @@ mod tests { // The Db mutex serialises these, so this shows the statement is atomic // (one consumer per code), not that SQLite arbitrates a race. let (_dir, db, _) = db().await; - db.insert_pairing(&Uuid::new_v4().to_string(), "RACE-CODE", 1_000_000).unwrap(); + db.insert_pairing(&Uuid::new_v4().to_string(), "RACE-CODE", 1_000_000) + .unwrap(); let handles: Vec<_> = (0..8) .map(|_| { let db = db.clone(); std::thread::spawn(move || db.claim_pairing("RACE-CODE", "a", 5).unwrap().is_some()) }) .collect(); - let winners = handles.into_iter().map(|h| h.join().unwrap()).filter(|won| *won).count(); + let winners = handles + .into_iter() + .map(|h| h.join().unwrap()) + .filter(|won| *won) + .count(); assert_eq!(winners, 1); } @@ -348,12 +412,31 @@ mod tests { let outpost = Uuid::new_v4().to_string(); db.insert_pairing(&outpost, "C", 1_000).unwrap(); let issued = db.claim_pairing("C", "agent", 10).unwrap().unwrap(); - assert!(db.upload_token_outpost(&issued.token, issued.expires_at - 1).unwrap().is_some()); - assert!(db.upload_token_outpost(&issued.token, issued.expires_at).unwrap().is_none(), "expiry"); - assert!(db.upload_token_outpost(&issued.token, 20).unwrap().is_some()); + assert!(db + .upload_token_outpost(&issued.token, issued.expires_at - 1) + .unwrap() + .is_some()); + assert!( + db.upload_token_outpost(&issued.token, issued.expires_at) + .unwrap() + .is_none(), + "expiry" + ); + assert!(db + .upload_token_outpost(&issued.token, 20) + .unwrap() + .is_some()); assert!(db.revoke_outpost(&outpost, 21).unwrap()); - assert!(db.upload_token_outpost(&issued.token, 22).unwrap().is_none(), "revoked"); - assert!(db.rotate_credential(&outpost, 60, 23).unwrap().is_none(), "a revoked Outpost must be paired again"); + assert!( + db.upload_token_outpost(&issued.token, 22) + .unwrap() + .is_none(), + "revoked" + ); + assert!( + db.rotate_credential(&outpost, 60, 23).unwrap().is_none(), + "a revoked Outpost must be paired again" + ); assert!(!db.revoke_outpost(&Uuid::new_v4().to_string(), 1).unwrap()); } @@ -366,16 +449,38 @@ mod tests { let second = db.rotate_credential(&outpost, 300, 100).unwrap().unwrap(); assert_eq!(second.previous_valid_until, Some(400)); assert_ne!(first.token, second.token); - assert!(db.upload_token_outpost(&first.token, 399).unwrap().is_some(), "old token inside the grace window"); - assert!(db.upload_token_outpost(&first.token, 400).unwrap().is_none(), "and not after it"); - assert!(db.upload_token_outpost(&second.token, 400).unwrap().is_some()); + assert!( + db.upload_token_outpost(&first.token, 399) + .unwrap() + .is_some(), + "old token inside the grace window" + ); + assert!( + db.upload_token_outpost(&first.token, 400) + .unwrap() + .is_none(), + "and not after it" + ); + assert!(db + .upload_token_outpost(&second.token, 400) + .unwrap() + .is_some()); // grace 0 cuts the old token at once let third = db.rotate_credential(&outpost, 0, 500).unwrap().unwrap(); assert_eq!(third.previous_valid_until, None); - assert!(db.upload_token_outpost(&second.token, 500).unwrap().is_none()); - assert!(db.upload_token_outpost(&third.token, 500).unwrap().is_some()); + assert!(db + .upload_token_outpost(&second.token, 500) + .unwrap() + .is_none()); + assert!(db + .upload_token_outpost(&third.token, 500) + .unwrap() + .is_some()); // an unknown outpost cannot be rotated into existence - assert!(db.rotate_credential(&Uuid::new_v4().to_string(), 0, 1).unwrap().is_none()); + assert!(db + .rotate_credential(&Uuid::new_v4().to_string(), 0, 1) + .unwrap() + .is_none()); } /// A pre-M4 database: clear-text tokens and codes in `wormhole_tokens`. @@ -403,31 +508,68 @@ mod tests { let now = chrono::Utc::now().timestamp(); // the paired agent keeps working with its existing token assert_eq!( - db.upload_token_outpost("LEGACY-ACTIVE-TOKEN-0001", now).unwrap().as_deref(), + db.upload_token_outpost("LEGACY-ACTIVE-TOKEN-0001", now) + .unwrap() + .as_deref(), Some("11111111-1111-1111-1111-111111111111") ); - assert!(db.upload_token_outpost("LEGACY-ACTIVE-TOKEN-0001", now + lifetime_secs() + 10).unwrap().is_none()); + assert!(db + .upload_token_outpost("LEGACY-ACTIVE-TOKEN-0001", now + lifetime_secs() + 10) + .unwrap() + .is_none()); // an unclaimed code can still be claimed once, but its pre-minted token is gone - let claimed = db.claim_pairing("LEGACYCODE2", "new-agent", now).unwrap().unwrap(); + let claimed = db + .claim_pairing("LEGACYCODE2", "new-agent", now) + .unwrap() + .unwrap(); assert_ne!(claimed.token, "PREMINTED-TOKEN-0002"); - assert!(db.upload_token_outpost("PREMINTED-TOKEN-0002", now).unwrap().is_none()); - assert!(db.claim_pairing("LEGACYCODE3", "late-agent", now).unwrap().is_none(), "expired code stays expired"); + assert!(db + .upload_token_outpost("PREMINTED-TOKEN-0002", now) + .unwrap() + .is_none()); + assert!( + db.claim_pairing("LEGACYCODE3", "late-agent", now) + .unwrap() + .is_none(), + "expired code stays expired" + ); // the old table and every clear-text copy are gone, including freed pages - let exists: bool = db.conn.lock().unwrap() - .query_row("SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE name='wormhole_tokens')", [], |r| r.get(0)).unwrap(); + let exists: bool = db + .conn + .lock() + .unwrap() + .query_row( + "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE name='wormhole_tokens')", + [], + |r| r.get(0), + ) + .unwrap(); assert!(!exists); let state: String = db.conn.lock().unwrap() .query_row("SELECT pairing_state FROM outposts WHERE id='11111111-1111-1111-1111-111111111111'", [], |r| r.get(0)).unwrap(); assert_eq!(state, "active"); drop(db); let bytes = disk_bytes(&path); - assert!(contains(&bytes, "old-agent") || contains(&bytes, "new-agent"), "sanity: the scan really reads the database file"); - for secret in ["LEGACY-ACTIVE-TOKEN-0001", "PREMINTED-TOKEN-0002", "PREMINTED-TOKEN-0003", "LEGACYCODE1", "LEGACYCODE2", "LEGACYCODE3"] { + assert!( + contains(&bytes, "old-agent") || contains(&bytes, "new-agent"), + "sanity: the scan really reads the database file" + ); + for secret in [ + "LEGACY-ACTIVE-TOKEN-0001", + "PREMINTED-TOKEN-0002", + "PREMINTED-TOKEN-0003", + "LEGACYCODE1", + "LEGACYCODE2", + "LEGACYCODE3", + ] { assert!(!contains(&bytes, secret), "{secret} still on disk"); } // migrating again changes nothing let again = Db::connect(&path).await.unwrap(); again.migrate().await.unwrap(); - assert!(again.upload_token_outpost("LEGACY-ACTIVE-TOKEN-0001", now).unwrap().is_some()); + assert!(again + .upload_token_outpost("LEGACY-ACTIVE-TOKEN-0001", now) + .unwrap() + .is_some()); } } diff --git a/crates/tessera-hub/src/db/jobs.rs b/crates/tessera-hub/src/db/jobs.rs index 10222fc..7261b34 100644 --- a/crates/tessera-hub/src/db/jobs.rs +++ b/crates/tessera-hub/src/db/jobs.rs @@ -182,9 +182,14 @@ impl Db { SELECT application_id FROM capture_profiles WHERE orbit_id IN (SELECT value FROM json_each(?4)))) ORDER BY j.created_at DESC, j.rowid DESC LIMIT ?3" ))?; - let restriction = orbits.map(|ids| serde_json::to_string(ids)).transpose()?; + let restriction = orbits.map(serde_json::to_string).transpose()?; let rows = stmt.query_map( - params![application.map(|id| id.to_string()), status, limit, restriction], + params![ + application.map(|id| id.to_string()), + status, + limit, + restriction + ], read_job, )?; Ok(rows.collect::>()?) @@ -419,7 +424,12 @@ impl Db { /// Queue a capture for a managed application whose Outpost is usable. Returns the job id, or /// `None` when there is no such profile or its Outpost has no usable credential. Takes a plain /// connection so a refresh run can queue the capture in the same transaction as the run itself. -pub(super) fn insert_capture_job(conn: &Connection, application_id: Uuid, actor: &str, now: i64) -> Result> { +pub(super) fn insert_capture_job( + conn: &Connection, + application_id: Uuid, + actor: &str, + now: i64, +) -> Result> { let id = Uuid::new_v4(); let changed = conn.execute( "INSERT INTO capture_jobs (id, application_id, actor, created_at, updated_at) @@ -611,12 +621,23 @@ mod tests { let lease = db.claim_capture(outpost, app, now).unwrap().unwrap(); assert_eq!(db.list_orbits().await.unwrap()[0].last_status, "running"); for progress in [CaptureProgress::Dumping, progress] { - assert!(db.report_capture(outpost, job.id, CaptureReport { - lease_id: lease.lease_id, progress, - }, now).unwrap()); + assert!(db + .report_capture( + outpost, + job.id, + CaptureReport { + lease_id: lease.lease_id, + progress, + }, + now + ) + .unwrap()); } if expected == "completed" { - assert!(db.publish_capture(outpost, job.id, lease.lease_id, false, |_| Ok(())).unwrap().is_some()); + assert!(db + .publish_capture(outpost, job.id, lease.lease_id, false, |_| Ok(())) + .unwrap() + .is_some()); } assert_eq!(db.list_orbits().await.unwrap()[0].last_status, expected); } diff --git a/crates/tessera-hub/src/db/oidc_login.rs b/crates/tessera-hub/src/db/oidc_login.rs index 81f6461..97d57ee 100644 --- a/crates/tessera-hub/src/db/oidc_login.rs +++ b/crates/tessera-hub/src/db/oidc_login.rs @@ -22,9 +22,19 @@ pub(super) fn migrate(conn: &Connection) -> Result<()> { impl Db { /// Store a transaction. Returns false when too many are pending. - pub fn begin_oidc_login(&self, state: &str, browser: &str, nonce: &str, verifier: &str, now: i64) -> Result { + pub fn begin_oidc_login( + &self, + state: &str, + browser: &str, + nonce: &str, + verifier: &str, + now: i64, + ) -> Result { let conn = self.conn.lock().unwrap(); - conn.execute("DELETE FROM oidc_login WHERE expires_at <= ?1", params![now])?; + conn.execute( + "DELETE FROM oidc_login WHERE expires_at <= ?1", + params![now], + )?; let pending: i64 = conn.query_row("SELECT COUNT(*) FROM oidc_login", [], |r| r.get(0))?; if pending >= MAX_PENDING { return Ok(false); @@ -40,7 +50,12 @@ impl Db { /// including one from a browser that does not hold the correlation cookie, /// so a leaked `state` cannot be retried. Returns `(nonce, verifier)` only /// for the right browser, before expiry, exactly once. - pub fn consume_oidc_login(&self, state: &str, browser: Option<&str>, now: i64) -> Result> { + pub fn consume_oidc_login( + &self, + state: &str, + browser: Option<&str>, + now: i64, + ) -> Result> { let conn = self.conn.lock().unwrap(); let row: Option<(String, String, String, i64)> = conn .query_row( @@ -50,7 +65,8 @@ impl Db { ) .optional()?; Ok(row.and_then(|(bound, nonce, verifier, expires)| { - (browser.is_some_and(|b| session_digest(b) == bound) && expires > now).then_some((nonce, verifier)) + (browser.is_some_and(|b| session_digest(b) == bound) && expires > now) + .then_some((nonce, verifier)) })) } } @@ -70,30 +86,65 @@ mod tests { async fn a_transaction_is_single_use_and_bound_to_its_browser() { let (_dir, db) = db().await; assert!(db.begin_oidc_login("s1", "b1", "n", "v", 100).unwrap()); - assert_eq!(db.consume_oidc_login("s1", Some("b1"), 101).unwrap(), Some(("n".into(), "v".into()))); - assert_eq!(db.consume_oidc_login("s1", Some("b1"), 102).unwrap(), None, "replay"); + assert_eq!( + db.consume_oidc_login("s1", Some("b1"), 101).unwrap(), + Some(("n".into(), "v".into())) + ); + assert_eq!( + db.consume_oidc_login("s1", Some("b1"), 102).unwrap(), + None, + "replay" + ); db.begin_oidc_login("s2", "b2", "n", "v", 100).unwrap(); - assert_eq!(db.consume_oidc_login("s2", Some("other"), 101).unwrap(), None, "wrong browser"); - assert_eq!(db.consume_oidc_login("s2", Some("b2"), 102).unwrap(), None, "burned by the failed attempt"); + assert_eq!( + db.consume_oidc_login("s2", Some("other"), 101).unwrap(), + None, + "wrong browser" + ); + assert_eq!( + db.consume_oidc_login("s2", Some("b2"), 102).unwrap(), + None, + "burned by the failed attempt" + ); db.begin_oidc_login("s3", "b3", "n", "v", 100).unwrap(); - assert_eq!(db.consume_oidc_login("s3", None, 101).unwrap(), None, "no cookie"); + assert_eq!( + db.consume_oidc_login("s3", None, 101).unwrap(), + None, + "no cookie" + ); db.begin_oidc_login("s4", "b4", "n", "v", 100).unwrap(); - assert_eq!(db.consume_oidc_login("s4", Some("b4"), 100 + TTL_SECS).unwrap(), None, "expired"); + assert_eq!( + db.consume_oidc_login("s4", Some("b4"), 100 + TTL_SECS) + .unwrap(), + None, + "expired" + ); } #[tokio::test] async fn only_digests_of_state_and_browser_are_keys_and_pending_rows_are_capped() { let (_dir, db) = db().await; - db.begin_oidc_login("raw-state", "raw-browser", "n", "v", 1).unwrap(); + db.begin_oidc_login("raw-state", "raw-browser", "n", "v", 1) + .unwrap(); let (state, browser): (String, String) = db - .conn.lock().unwrap() - .query_row("SELECT state_digest,browser_digest FROM oidc_login", [], |r| Ok((r.get(0)?, r.get(1)?))) + .conn + .lock() + .unwrap() + .query_row( + "SELECT state_digest,browser_digest FROM oidc_login", + [], + |r| Ok((r.get(0)?, r.get(1)?)), + ) .unwrap(); assert!(!state.contains("raw-state") && !browser.contains("raw-browser")); for i in 0..MAX_PENDING { let _ = db.begin_oidc_login(&format!("s{i}"), "b", "n", "v", 1); } - assert!(!db.begin_oidc_login("one-too-many", "b", "n", "v", 1).unwrap()); - assert!(db.begin_oidc_login("after-expiry", "b", "n", "v", 1 + TTL_SECS).unwrap()); + assert!(!db + .begin_oidc_login("one-too-many", "b", "n", "v", 1) + .unwrap()); + assert!(db + .begin_oidc_login("after-expiry", "b", "n", "v", 1 + TTL_SECS) + .unwrap()); } } diff --git a/crates/tessera-hub/src/db/refresh.rs b/crates/tessera-hub/src/db/refresh.rs index 88c2b26..9c1137d 100644 --- a/crates/tessera-hub/src/db/refresh.rs +++ b/crates/tessera-hub/src/db/refresh.rs @@ -43,10 +43,23 @@ const COLUMNS: &str = "id,relation_id,relation_version,source_orbit_id,source_ap fn read_run(r: &rusqlite::Row<'_>) -> rusqlite::Result { Ok(RefreshRun { - id: r.get(0)?, relation_id: r.get(1)?, relation_version: r.get(2)?, source_orbit_id: r.get(3)?, source_application_id: r.get(4)?, - target_id: r.get(5)?, requester: r.get(6)?, requester_user_id: r.get(7)?, authorized_by: r.get(8)?, status: r.get(9)?, - blocked_reason: r.get(10)?, capture_job_id: r.get(11)?, snapshot_id: r.get(12)?, restore_job_id: r.get(13)?, - created_at: r.get(14)?, updated_at: r.get(15)?, expires_at: r.get(16)?, + id: r.get(0)?, + relation_id: r.get(1)?, + relation_version: r.get(2)?, + source_orbit_id: r.get(3)?, + source_application_id: r.get(4)?, + target_id: r.get(5)?, + requester: r.get(6)?, + requester_user_id: r.get(7)?, + authorized_by: r.get(8)?, + status: r.get(9)?, + blocked_reason: r.get(10)?, + capture_job_id: r.get(11)?, + snapshot_id: r.get(12)?, + restore_job_id: r.get(13)?, + created_at: r.get(14)?, + updated_at: r.get(15)?, + expires_at: r.get(16)?, }) } @@ -105,25 +118,52 @@ pub(super) fn migrate(conn: &Connection) -> Result<()> { } fn get(conn: &Connection, id: &str) -> Result> { - Ok(conn.query_row(&format!("SELECT {COLUMNS} FROM refresh_runs WHERE id=?1"), params![id], read_run).optional()?) + Ok(conn + .query_row( + &format!("SELECT {COLUMNS} FROM refresh_runs WHERE id=?1"), + params![id], + read_run, + ) + .optional()?) } /// The run that owns a restore job, if the job was queued by a refresh. Admin restores have none. pub(super) fn run_for_restore(conn: &Connection, restore_job: &str) -> Result> { - Ok(conn.query_row(&format!("SELECT {COLUMNS} FROM refresh_runs WHERE restore_job_id=?1"), params![restore_job], read_run).optional()?) + Ok(conn + .query_row( + &format!("SELECT {COLUMNS} FROM refresh_runs WHERE restore_job_id=?1"), + params![restore_job], + read_run, + ) + .optional()?) } fn relation_of(conn: &Connection, id: &str) -> Result> { - Ok(conn.query_row(&format!("SELECT {RELATION_COLUMNS} FROM orbit_relations WHERE id=?1"), params![id], read_relation).optional()?) + Ok(conn + .query_row( + &format!("SELECT {RELATION_COLUMNS} FROM orbit_relations WHERE id=?1"), + params![id], + read_relation, + ) + .optional()?) } fn names(conn: &Connection, relation: &Relation) -> rusqlite::Result<(String, String)> { let source: String = conn - .query_row("SELECT name FROM orbits WHERE id=?1", params![relation.source_orbit_id], |r| r.get(0)) + .query_row( + "SELECT name FROM orbits WHERE id=?1", + params![relation.source_orbit_id], + |r| r.get(0), + ) .optional()? .unwrap_or_default(); - let target_profile: Option = - conn.query_row("SELECT profile FROM restore_targets WHERE id=?1", params![relation.target_id], |r| r.get(0)).optional()?; + let target_profile: Option = conn + .query_row( + "SELECT profile FROM restore_targets WHERE id=?1", + params![relation.target_id], + |r| r.get(0), + ) + .optional()?; let target = target_profile .and_then(|p| serde_json::from_str::(&p).ok()) .and_then(|p| p["name"].as_str().map(str::to_string)) @@ -133,8 +173,14 @@ fn names(conn: &Connection, relation: &Relation) -> rusqlite::Result<(String, St /// Why this run must not go on, if anything has changed since it was started. Nothing here is cached: /// the relation, the requester and the grant that authorised the run are read again each time. -pub(super) fn invalid_reason(conn: &Connection, run: &RefreshRun, now: i64) -> Result> { - let Some(relation) = relation_of(conn, &run.relation_id)? else { return Ok(Some("relation_ended")) }; +pub(super) fn invalid_reason( + conn: &Connection, + run: &RefreshRun, + now: i64, +) -> Result> { + let Some(relation) = relation_of(conn, &run.relation_id)? else { + return Ok(Some("relation_ended")); + }; if !relation.active { return Ok(Some("relation_ended")); } @@ -142,7 +188,11 @@ pub(super) fn invalid_reason(conn: &Connection, run: &RefreshRun, now: i64) -> R return Ok(Some("relation_unusable")); } if let Some(user) = &run.requester_user_id { - let active: bool = conn.query_row("SELECT EXISTS(SELECT 1 FROM users WHERE id=?1 AND active=1)", params![user], |r| r.get(0))?; + let active: bool = conn.query_row( + "SELECT EXISTS(SELECT 1 FROM users WHERE id=?1 AND active=1)", + params![user], + |r| r.get(0), + )?; if !active { return Ok(Some("user_disabled")); } @@ -163,7 +213,13 @@ pub(super) fn invalid_reason(conn: &Connection, run: &RefreshRun, now: i64) -> R Ok(None) } -fn finish(conn: &Connection, run: &str, status: &str, reason: Option<&str>, now: i64) -> Result<()> { +fn finish( + conn: &Connection, + run: &str, + status: &str, + reason: Option<&str>, + now: i64, +) -> Result<()> { conn.execute( "UPDATE refresh_runs SET status=?2, blocked_reason=?3, updated_at=?4 WHERE id=?1 AND status IN ('capturing','restoring','recovery_required')", params![run, status, reason, now], @@ -180,11 +236,27 @@ pub(super) fn block(conn: &Connection, run: &RefreshRun, reason: &str, now: i64) params![job, now], )?; } - finish(conn, &run.id, if reason == "expired" { "expired" } else { "blocked" }, Some(reason), now) + finish( + conn, + &run.id, + if reason == "expired" { + "expired" + } else { + "blocked" + }, + Some(reason), + now, + ) } fn restore_status(conn: &Connection, job: &str) -> Result> { - Ok(conn.query_row("SELECT status FROM restore_jobs WHERE id=?1", params![job], |r| r.get(0)).optional()?) + Ok(conn + .query_row( + "SELECT status FROM restore_jobs WHERE id=?1", + params![job], + |r| r.get(0), + ) + .optional()?) } impl Db { @@ -210,9 +282,15 @@ impl Db { .query_row(&format!("SELECT {COLUMNS} FROM refresh_runs WHERE requester=?1 AND idempotency_key=?2"), params![requester, idempotency_key], read_run) .optional()?; if let Some(run) = existing { - return Ok(if run.relation_id == relation_id { Ok((run, false)) } else { Err(StartError::KeyReused) }); + return Ok(if run.relation_id == relation_id { + Ok((run, false)) + } else { + Err(StartError::KeyReused) + }); } - let Some(relation) = relation_of(&tx, relation_id)?.filter(|r| r.active) else { return Ok(Err(StartError::UnknownRelation)) }; + let Some(relation) = relation_of(&tx, relation_id)?.filter(|r| r.active) else { + return Ok(Err(StartError::UnknownRelation)); + }; if let Some(reason) = unusable(&tx, &relation, now)? { return Ok(Err(StartError::Unusable(reason))); } @@ -231,7 +309,8 @@ impl Db { return Ok(Err(StartError::TooManyRuns)); } let application = Uuid::parse_str(&relation.source_application_id)?; - let Some(capture) = super::jobs::insert_capture_job(&tx, application, requester, now)? else { + let Some(capture) = super::jobs::insert_capture_job(&tx, application, requester, now)? + else { return Ok(Err(StartError::SourceUnavailable)); }; let id = Uuid::new_v4().to_string(); @@ -258,19 +337,28 @@ impl Db { pub fn active_refresh_runs(&self) -> Result> { let conn = self.conn.lock().unwrap(); let mut stmt = conn.prepare(&format!("SELECT {COLUMNS} FROM refresh_runs WHERE status IN ('capturing','restoring','recovery_required') ORDER BY created_at"))?; - let rows = stmt.query_map([], read_run)?.collect::>()?; + let rows = stmt + .query_map([], read_run)? + .collect::>()?; Ok(rows) } /// Recent runs (all of them, or only those of one requester / a set of relations), newest first. - pub fn refresh_runs(&self, requester_user: Option<&str>, relations: Option<&[String]>, limit: i64) -> Result> { + pub fn refresh_runs( + &self, + requester_user: Option<&str>, + relations: Option<&[String]>, + limit: i64, + ) -> Result> { let conn = self.conn.lock().unwrap(); let mut stmt = conn.prepare(&format!( "SELECT {COLUMNS} FROM refresh_runs WHERE (?1 IS NULL AND ?2 IS NULL) OR requester_user_id = ?1 OR relation_id IN (SELECT value FROM json_each(?2)) ORDER BY created_at DESC, rowid DESC LIMIT ?3" ))?; let relations_json = relations.map(serde_json::to_string).transpose()?; - let rows = stmt.query_map(params![requester_user, relations_json, limit], read_run)?.collect::>()?; + let rows = stmt + .query_map(params![requester_user, relations_json, limit], read_run)? + .collect::>()?; Ok(rows) } @@ -278,10 +366,20 @@ impl Db { pub fn refresh_progress(&self, run: &RefreshRun) -> Result { let conn = self.conn.lock().unwrap(); let capture: Option<(String, String, i64)> = conn - .query_row("SELECT status, phase, updated_at FROM capture_jobs WHERE id=?1", params![run.capture_job_id], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?))) + .query_row( + "SELECT status, phase, updated_at FROM capture_jobs WHERE id=?1", + params![run.capture_job_id], + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)), + ) .optional()?; let restore: Option<(String, String)> = match &run.restore_job_id { - Some(job) => conn.query_row("SELECT status, phase FROM restore_jobs WHERE id=?1", params![job], |r| Ok((r.get(0)?, r.get(1)?))).optional()?, + Some(job) => conn + .query_row( + "SELECT status, phase FROM restore_jobs WHERE id=?1", + params![job], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .optional()?, None => None, }; let relation = relation_of(&conn, &run.relation_id)?; @@ -311,18 +409,32 @@ impl Db { /// Queue the restore of the run's own snapshot. Everything is checked again inside the transaction, the /// restore job is linked only if the run does not have one yet, and a second call changes nothing. - pub fn enqueue_refresh_restore(&self, id: &str, artifact: &RestoreArtifact, identity_clash: bool, now: i64) -> Result { + pub fn enqueue_refresh_restore( + &self, + id: &str, + artifact: &RestoreArtifact, + identity_clash: bool, + now: i64, + ) -> Result { let mut conn = self.conn.lock().unwrap(); let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?; let outcome = (|| -> Result { - let Some(run) = get(&tx, id)? else { return Ok(Linked::NotReady) }; + let Some(run) = get(&tx, id)? else { + return Ok(Linked::NotReady); + }; if run.status != "capturing" || run.restore_job_id.is_some() { return Ok(Linked::NotReady); } let capture: Option<(String, Option)> = tx - .query_row("SELECT status, snapshot_id FROM capture_jobs WHERE id=?1", params![run.capture_job_id], |r| Ok((r.get(0)?, r.get(1)?))) + .query_row( + "SELECT status, snapshot_id FROM capture_jobs WHERE id=?1", + params![run.capture_job_id], + |r| Ok((r.get(0)?, r.get(1)?)), + ) .optional()?; - let Some((status, Some(snapshot))) = capture.filter(|c| c.0 == "completed") else { return Ok(Linked::NotReady) }; + let Some((status, Some(snapshot))) = capture.filter(|c| c.0 == "completed") else { + return Ok(Linked::NotReady); + }; let _ = status; if let Some(reason) = invalid_reason(&tx, &run, now)? { block(&tx, &run, reason, now)?; @@ -334,7 +446,13 @@ impl Db { } let snapshot = Uuid::parse_str(&snapshot)?; let job = super::restore::enqueue_restore_in( - &tx, snapshot, Uuid::parse_str(&run.source_application_id)?, Uuid::parse_str(&run.target_id)?, &run.requester, artifact, now, + &tx, + snapshot, + Uuid::parse_str(&run.source_application_id)?, + Uuid::parse_str(&run.target_id)?, + &run.requester, + artifact, + now, )?; let Some(job) = job else { block(&tx, &run, "target_rejected", now)?; @@ -366,17 +484,25 @@ impl Db { } /// Cancel a run before anything has been applied. `Err` carries why it could not be. - pub fn cancel_refresh_run(&self, id: &str, now: i64) -> Result> { + pub fn cancel_refresh_run( + &self, + id: &str, + now: i64, + ) -> Result> { let mut conn = self.conn.lock().unwrap(); let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?; let result = (|| -> Result> { - let Some(run) = get(&tx, id)? else { return Ok(Err(CancelError::Unknown)) }; + let Some(run) = get(&tx, id)? else { + return Ok(Err(CancelError::Unknown)); + }; if !ACTIVE.contains(&run.status.as_str()) || run.status == "recovery_required" { return Ok(Err(CancelError::TooLate)); } if let Some(job) = &run.restore_job_id { match restore_status(&tx, job)?.as_deref() { - Some("applying") | Some("recovery_required") | Some("completed") => return Ok(Err(CancelError::TooLate)), + Some("applying") | Some("recovery_required") | Some("completed") => { + return Ok(Err(CancelError::TooLate)) + } _ => {} } } @@ -426,7 +552,9 @@ pub struct Progress { } fn sync_in(tx: &Transaction<'_>, id: &str, now: i64) -> Result { - let Some(run) = get(tx, id)? else { return Ok(Sync::Unchanged) }; + let Some(run) = get(tx, id)? else { + return Ok(Sync::Unchanged); + }; if !ACTIVE.contains(&run.status.as_str()) { return Ok(Sync::Unchanged); } @@ -435,11 +563,21 @@ fn sync_in(tx: &Transaction<'_>, id: &str, now: i64) -> Result { None => None, }; // Until the restore starts applying, any change in what authorised the run stops it. - let past_the_point_of_no_return = matches!(restore.as_deref(), Some("applying" | "recovery_required" | "completed" | "failed" | "reconciled")); + let past_the_point_of_no_return = matches!( + restore.as_deref(), + Some("applying" | "recovery_required" | "completed" | "failed" | "reconciled") + ); if !past_the_point_of_no_return { if let Some(reason) = invalid_reason(tx, &run, now)? { block(tx, &run, reason, now)?; - return Ok(Sync::Moved(if reason == "expired" { "expired" } else { "blocked" }.into())); + return Ok(Sync::Moved( + if reason == "expired" { + "expired" + } else { + "blocked" + } + .into(), + )); } } let move_to = |status: &str| -> Result { @@ -449,11 +587,19 @@ fn sync_in(tx: &Transaction<'_>, id: &str, now: i64) -> Result { match run.status.as_str() { "capturing" => { let capture: Option<(String, Option)> = tx - .query_row("SELECT status, snapshot_id FROM capture_jobs WHERE id=?1", params![run.capture_job_id], |r| Ok((r.get(0)?, r.get(1)?))) + .query_row( + "SELECT status, snapshot_id FROM capture_jobs WHERE id=?1", + params![run.capture_job_id], + |r| Ok((r.get(0)?, r.get(1)?)), + ) .optional()?; match capture { Some((status, _)) if status == "failed" => move_to("capture_failed"), - Some((status, Some(snapshot))) if status == "completed" && run.restore_job_id.is_none() => Ok(Sync::NeedRestore(snapshot)), + Some((status, Some(snapshot))) + if status == "completed" && run.restore_job_id.is_none() => + { + Ok(Sync::NeedRestore(snapshot)) + } None => move_to("capture_failed"), _ => Ok(Sync::Unchanged), } diff --git a/crates/tessera-hub/src/db/relations.rs b/crates/tessera-hub/src/db/relations.rs index 840a32e..684cf8e 100644 --- a/crates/tessera-hub/src/db/relations.rs +++ b/crates/tessera-hub/src/db/relations.rs @@ -138,7 +138,10 @@ pub(super) fn migrate(conn: &Connection) -> Result<()> { } fn engine_of_profile(profile: &str) -> Option { - serde_json::from_str::(profile).ok()?.format.engine() + serde_json::from_str::(profile) + .ok()? + .format + .engine() } pub(super) fn read_relation(r: &rusqlite::Row<'_>) -> rusqlite::Result { @@ -173,18 +176,37 @@ fn outpost_active(conn: &Connection, outpost: &str, now: i64) -> rusqlite::Resul } /// Why a relation cannot be used right now, if it cannot. -pub(super) fn unusable(conn: &Connection, relation: &Relation, now: i64) -> rusqlite::Result> { +pub(super) fn unusable( + conn: &Connection, + relation: &Relation, + now: i64, +) -> rusqlite::Result> { if !relation.active { return Ok(Some("deactivated")); } - let target_env: Option = - conn.query_row("SELECT environment FROM target_environments WHERE target_id=?1", params![relation.target_id], |r| r.get(0)).optional()?; + let target_env: Option = conn + .query_row( + "SELECT environment FROM target_environments WHERE target_id=?1", + params![relation.target_id], + |r| r.get(0), + ) + .optional()?; if !matches!(target_env.as_deref(), Some("staging" | "development")) { return Ok(Some("target_environment")); } let outposts: (Option, Option) = ( - conn.query_row("SELECT outpost_id FROM restore_targets WHERE id=?1", params![relation.target_id], |r| r.get(0)).optional()?, - conn.query_row("SELECT outpost_id FROM capture_profiles WHERE application_id=?1", params![relation.source_application_id], |r| r.get(0)).optional()?, + conn.query_row( + "SELECT outpost_id FROM restore_targets WHERE id=?1", + params![relation.target_id], + |r| r.get(0), + ) + .optional()?, + conn.query_row( + "SELECT outpost_id FROM capture_profiles WHERE application_id=?1", + params![relation.source_application_id], + |r| r.get(0), + ) + .optional()?, ); for outpost in [outposts.0, outposts.1] { match outpost { @@ -198,7 +220,11 @@ pub(super) fn unusable(conn: &Connection, relation: &Relation, now: i64) -> rusq impl Db { pub fn set_orbit_environment(&self, orbit: Uuid, environment: &str, now: i64) -> Result { let conn = self.conn.lock().unwrap(); - let exists: bool = conn.query_row("SELECT EXISTS(SELECT 1 FROM orbits WHERE id=?1)", params![orbit.to_string()], |r| r.get(0))?; + let exists: bool = conn.query_row( + "SELECT EXISTS(SELECT 1 FROM orbits WHERE id=?1)", + params![orbit.to_string()], + |r| r.get(0), + )?; if !exists { return Ok(false); } @@ -212,10 +238,19 @@ impl Db { /// Label a restore target. Labelling it production ends every active relation into it in the same /// transaction. Returns the ids of the relations that were ended, or `None` for an unknown target. - pub fn set_target_environment(&self, target: Uuid, environment: &str, now: i64) -> Result>> { + pub fn set_target_environment( + &self, + target: Uuid, + environment: &str, + now: i64, + ) -> Result>> { let mut conn = self.conn.lock().unwrap(); let tx = conn.transaction()?; - let exists: bool = tx.query_row("SELECT EXISTS(SELECT 1 FROM restore_targets WHERE id=?1)", params![target.to_string()], |r| r.get(0))?; + let exists: bool = tx.query_row( + "SELECT EXISTS(SELECT 1 FROM restore_targets WHERE id=?1)", + params![target.to_string()], + |r| r.get(0), + )?; if !exists { return Ok(None); } @@ -226,8 +261,11 @@ impl Db { )?; let mut ended = Vec::new(); if !matches!(environment, "staging" | "development") { - let mut stmt = tx.prepare("SELECT id FROM orbit_relations WHERE target_id=?1 AND active=1")?; - ended = stmt.query_map(params![target.to_string()], |r| r.get::<_, String>(0))?.collect::>()?; + let mut stmt = + tx.prepare("SELECT id FROM orbit_relations WHERE target_id=?1 AND active=1")?; + ended = stmt + .query_map(params![target.to_string()], |r| r.get::<_, String>(0))? + .collect::>()?; drop(stmt); tx.execute( "UPDATE orbit_relations SET active=0, deactivated_at=?2, deactivated_reason='target_relabelled' WHERE target_id=?1 AND active=1", @@ -255,7 +293,11 @@ impl Db { let mut conn = self.conn.lock().unwrap(); let tx = conn.transaction()?; let result = (|| -> Result> { - let orbit_known: bool = tx.query_row("SELECT EXISTS(SELECT 1 FROM orbits WHERE id=?1)", params![source_orbit.to_string()], |r| r.get(0))?; + let orbit_known: bool = tx.query_row( + "SELECT EXISTS(SELECT 1 FROM orbits WHERE id=?1)", + params![source_orbit.to_string()], + |r| r.get(0), + )?; if !orbit_known { return Ok(Err(Reject::UnknownSource)); } @@ -266,10 +308,18 @@ impl Db { |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)), ) .optional()?; - let Some((application, source_outpost, profile_json)) = profile else { return Ok(Err(Reject::SourceNotManaged)) }; - let Some(engine) = engine_of_profile(&profile_json) else { return Ok(Err(Reject::SourceNotRestoreReady)) }; + let Some((application, source_outpost, profile_json)) = profile else { + return Ok(Err(Reject::SourceNotManaged)); + }; + let Some(engine) = engine_of_profile(&profile_json) else { + return Ok(Err(Reject::SourceNotRestoreReady)); + }; let source_env: Option = tx - .query_row("SELECT environment FROM orbit_environments WHERE orbit_id=?1", params![source_orbit.to_string()], |r| r.get(0)) + .query_row( + "SELECT environment FROM orbit_environments WHERE orbit_id=?1", + params![source_orbit.to_string()], + |r| r.get(0), + ) .optional()?; if source_env.is_none() { return Ok(Err(Reject::SourceEnvironmentUnset)); @@ -281,9 +331,16 @@ impl Db { |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)), ) .optional()?; - let Some((target_application, target_outpost, identity, target_profile)) = target_row else { return Ok(Err(Reject::UnknownTarget)) }; + let Some((target_application, target_outpost, identity, target_profile)) = target_row + else { + return Ok(Err(Reject::UnknownTarget)); + }; let target_env: Option = tx - .query_row("SELECT environment FROM target_environments WHERE target_id=?1", params![target.to_string()], |r| r.get(0)) + .query_row( + "SELECT environment FROM target_environments WHERE target_id=?1", + params![target.to_string()], + |r| r.get(0), + ) .optional()?; match target_env.as_deref() { None => return Ok(Err(Reject::TargetEnvironmentUnset)), @@ -293,19 +350,27 @@ impl Db { if target_application != application { return Ok(Err(Reject::ApplicationMismatch)); } - let target_engine = serde_json::from_str::(&target_profile).ok().map(|t| t.engine); + let target_engine = + serde_json::from_str::(&target_profile) + .ok() + .map(|t| t.engine); if target_engine != Some(engine) { return Ok(Err(Reject::EngineMismatch)); } // The table keeps `(engine, identity)`; the relation records just the identity it was checked against. - let identity = serde_json::from_str::<(Engine, tessera_core::restore::DatabaseIdentity)>(&identity) + let identity = + serde_json::from_str::<(Engine, tessera_core::restore::DatabaseIdentity)>( + &identity, + ) .ok() .and_then(|(_, identity)| serde_json::to_string(&identity).ok()) .unwrap_or(identity); if identity_clash { return Ok(Err(Reject::TargetMatchesSource)); } - if !outpost_active(&tx, &source_outpost, now)? || !outpost_active(&tx, &target_outpost, now)? { + if !outpost_active(&tx, &source_outpost, now)? + || !outpost_active(&tx, &target_outpost, now)? + { return Ok(Err(Reject::OutpostInactive)); } let (lineage, version) = match replace { @@ -313,8 +378,14 @@ impl Db { let found: Option<(String, i64)> = tx .query_row("SELECT lineage, version FROM orbit_relations WHERE id=?1 AND source_orbit_id=?2 AND active=1", params![old, source_orbit.to_string()], |r| Ok((r.get(0)?, r.get(1)?))) .optional()?; - let Some((lineage, version)) = found else { return Ok(Err(Reject::UnknownSource)) }; - let next: i64 = tx.query_row("SELECT MAX(version) FROM orbit_relations WHERE lineage=?1", params![lineage], |r| r.get(0))?; + let Some((lineage, version)) = found else { + return Ok(Err(Reject::UnknownSource)); + }; + let next: i64 = tx.query_row( + "SELECT MAX(version) FROM orbit_relations WHERE lineage=?1", + params![lineage], + |r| r.get(0), + )?; tx.execute( "UPDATE orbit_relations SET active=0, deactivated_at=?2, deactivated_reason='replaced' WHERE id=?1", params![old, now], @@ -332,10 +403,18 @@ impl Db { ); match inserted { Ok(_) => {} - Err(rusqlite::Error::SqliteFailure(error, _)) if error.code == rusqlite::ErrorCode::ConstraintViolation => return Ok(Err(Reject::Duplicate)), + Err(rusqlite::Error::SqliteFailure(error, _)) + if error.code == rusqlite::ErrorCode::ConstraintViolation => + { + return Ok(Err(Reject::Duplicate)) + } Err(error) => return Err(error.into()), } - let relation = tx.query_row(&format!("SELECT {RELATION_COLUMNS} FROM orbit_relations WHERE id=?1"), params![id], read_relation)?; + let relation = tx.query_row( + &format!("SELECT {RELATION_COLUMNS} FROM orbit_relations WHERE id=?1"), + params![id], + read_relation, + )?; Ok(Ok(relation)) })()?; if result.is_ok() { @@ -352,37 +431,68 @@ impl Db { } pub fn relation(&self, id: &str) -> Result> { - Ok(self.conn.lock().unwrap() - .query_row(&format!("SELECT {RELATION_COLUMNS} FROM orbit_relations WHERE id=?1"), params![id], read_relation) + Ok(self + .conn + .lock() + .unwrap() + .query_row( + &format!("SELECT {RELATION_COLUMNS} FROM orbit_relations WHERE id=?1"), + params![id], + read_relation, + ) .optional()?) } /// Relations with names and live usability. `only` restricts to a set of ids (for a non-administrator). - pub fn relation_views(&self, active_only: bool, only: Option<&[String]>, now: i64) -> Result> { + pub fn relation_views( + &self, + active_only: bool, + only: Option<&[String]>, + now: i64, + ) -> Result> { let conn = self.conn.lock().unwrap(); let mut stmt = conn.prepare(&format!( "SELECT {RELATION_COLUMNS} FROM orbit_relations WHERE (?1 = 0 OR active = 1) AND (?2 IS NULL OR id IN (SELECT value FROM json_each(?2))) ORDER BY created_at DESC, version DESC" ))?; let restriction = only.map(serde_json::to_string).transpose()?; - let relations: Vec = stmt.query_map(params![active_only, restriction], read_relation)?.collect::>()?; + let relations: Vec = stmt + .query_map(params![active_only, restriction], read_relation)? + .collect::>()?; drop(stmt); let mut out = Vec::new(); for relation in relations { let name = |sql: &str, id: &str| -> rusqlite::Result { - Ok(conn.query_row(sql, params![id], |r| r.get::<_, String>(0)).optional()?.unwrap_or_default()) + Ok(conn + .query_row(sql, params![id], |r| r.get::<_, String>(0)) + .optional()? + .unwrap_or_default()) }; let environment = |sql: &str, id: &str| -> rusqlite::Result> { - conn.query_row(sql, params![id], |r| r.get::<_, String>(0)).optional() + conn.query_row(sql, params![id], |r| r.get::<_, String>(0)) + .optional() }; let reason = unusable(&conn, &relation, now)?; out.push(RelationView { - source_name: name("SELECT name FROM orbits WHERE id=?1", &relation.source_orbit_id)?, - source_environment: environment("SELECT environment FROM orbit_environments WHERE orbit_id=?1", &relation.source_orbit_id)?, - target_name: serde_json::from_str::( - &name("SELECT profile FROM restore_targets WHERE id=?1", &relation.target_id)?, - ).ok().and_then(|p| p["name"].as_str().map(str::to_string)).unwrap_or_default(), - target_environment: environment("SELECT environment FROM target_environments WHERE target_id=?1", &relation.target_id)?, + source_name: name( + "SELECT name FROM orbits WHERE id=?1", + &relation.source_orbit_id, + )?, + source_environment: environment( + "SELECT environment FROM orbit_environments WHERE orbit_id=?1", + &relation.source_orbit_id, + )?, + target_name: serde_json::from_str::(&name( + "SELECT profile FROM restore_targets WHERE id=?1", + &relation.target_id, + )?) + .ok() + .and_then(|p| p["name"].as_str().map(str::to_string)) + .unwrap_or_default(), + target_environment: environment( + "SELECT environment FROM target_environments WHERE target_id=?1", + &relation.target_id, + )?, usable: reason.is_none(), unusable_reason: reason, relation, @@ -391,21 +501,32 @@ impl Db { Ok(out) } - pub fn environments(&self) -> Result<(std::collections::HashMap, std::collections::HashMap)> { + pub fn environments( + &self, + ) -> Result<( + std::collections::HashMap, + std::collections::HashMap, + )> { let conn = self.conn.lock().unwrap(); let read = |sql: &str| -> rusqlite::Result> { let mut stmt = conn.prepare(sql)?; - let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?; + let rows = + stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?; rows.collect() }; - Ok((read("SELECT orbit_id, environment FROM orbit_environments")?, read("SELECT target_id, environment FROM target_environments")?)) + Ok(( + read("SELECT orbit_id, environment FROM orbit_environments")?, + read("SELECT target_id, environment FROM target_environments")?, + )) } /// Every registered restore target, with whether its Outpost can be used right now. pub fn all_restore_targets(&self, now: i64) -> Result> { let conn = self.conn.lock().unwrap(); let mut stmt = conn.prepare("SELECT profile FROM restore_targets ORDER BY id")?; - let profiles: Vec = stmt.query_map([], |r| r.get(0))?.collect::>()?; + let profiles: Vec = stmt + .query_map([], |r| r.get(0))? + .collect::>()?; drop(stmt); let mut out = Vec::new(); for profile in profiles { @@ -418,14 +539,27 @@ impl Db { } pub fn restore_target(&self, id: Uuid) -> Result> { - let profile: Option = self.conn.lock().unwrap() - .query_row("SELECT profile FROM restore_targets WHERE id=?1", params![id.to_string()], |r| r.get(0)) + let profile: Option = self + .conn + .lock() + .unwrap() + .query_row( + "SELECT profile FROM restore_targets WHERE id=?1", + params![id.to_string()], + |r| r.get(0), + ) .optional()?; Ok(profile.and_then(|p| serde_json::from_str(&p).ok())) } /// The grant that currently lets this subject use the relation, if any: its id, for recording on a run. - pub fn granting_relation_grant(&self, user: Option<&str>, groups: &[String], relation: &str, now: i64) -> Result> { + pub fn granting_relation_grant( + &self, + user: Option<&str>, + groups: &[String], + relation: &str, + now: i64, + ) -> Result> { let conn = self.conn.lock().unwrap(); let groups_json = serde_json::to_string(groups)?; Ok(conn @@ -441,9 +575,21 @@ impl Db { // ---- grants of the refresh permission, one relation at a time ---- - pub fn add_relation_grant(&self, principal_type: &str, principal: &str, relation: &str, expires_at: Option, created_by: &str, now: i64) -> Result> { + pub fn add_relation_grant( + &self, + principal_type: &str, + principal: &str, + relation: &str, + expires_at: Option, + created_by: &str, + now: i64, + ) -> Result> { let conn = self.conn.lock().unwrap(); - let active: bool = conn.query_row("SELECT EXISTS(SELECT 1 FROM orbit_relations WHERE id=?1 AND active=1)", params![relation], |r| r.get(0))?; + let active: bool = conn.query_row( + "SELECT EXISTS(SELECT 1 FROM orbit_relations WHERE id=?1 AND active=1)", + params![relation], + |r| r.get(0), + )?; if !active { return Ok(None); } @@ -453,25 +599,47 @@ impl Db { params![id, principal_type, principal, relation, expires_at, created_by, now], )?; Ok((inserted == 1).then(|| RelationGrant { - id, principal_type: principal_type.into(), principal: principal.into(), relation_id: relation.into(), expires_at, created_by: created_by.into(), created_at: now, + id, + principal_type: principal_type.into(), + principal: principal.into(), + relation_id: relation.into(), + expires_at, + created_by: created_by.into(), + created_at: now, })) } pub fn delete_relation_grant(&self, relation: &str, grant: &str) -> Result { - Ok(self.conn.lock().unwrap().execute("DELETE FROM relation_grants WHERE id=?1 AND relation_id=?2", params![grant, relation])? == 1) + Ok(self.conn.lock().unwrap().execute( + "DELETE FROM relation_grants WHERE id=?1 AND relation_id=?2", + params![grant, relation], + )? == 1) } pub fn relation_grants(&self, relation: &str) -> Result> { let conn = self.conn.lock().unwrap(); let mut stmt = conn.prepare("SELECT id,principal_type,principal,relation_id,expires_at,created_by,created_at FROM relation_grants WHERE relation_id=?1 ORDER BY principal_type, principal")?; - let rows = stmt.query_map(params![relation], |r| Ok(RelationGrant { - id: r.get(0)?, principal_type: r.get(1)?, principal: r.get(2)?, relation_id: r.get(3)?, expires_at: r.get(4)?, created_by: r.get(5)?, created_at: r.get(6)?, - }))?; + let rows = stmt.query_map(params![relation], |r| { + Ok(RelationGrant { + id: r.get(0)?, + principal_type: r.get(1)?, + principal: r.get(2)?, + relation_id: r.get(3)?, + expires_at: r.get(4)?, + created_by: r.get(5)?, + created_at: r.get(6)?, + }) + })?; Ok(rows.collect::>()?) } /// Ids of the active relations this subject may use. Read live on every request. - pub fn granted_relations(&self, user: Option<&str>, groups: &[String], now: i64) -> Result> { + pub fn granted_relations( + &self, + user: Option<&str>, + groups: &[String], + now: i64, + ) -> Result> { let conn = self.conn.lock().unwrap(); let mut stmt = conn.prepare( "SELECT DISTINCT g.relation_id FROM relation_grants g JOIN orbit_relations r ON r.id = g.relation_id AND r.active = 1 @@ -479,7 +647,9 @@ impl Db { AND ((g.principal_type='user' AND g.principal=?2) OR (g.principal_type='group' AND g.principal IN (SELECT value FROM json_each(?3))))", )?; let groups_json = serde_json::to_string(groups)?; - let rows = stmt.query_map(params![now, user, groups_json], |r| r.get::<_, String>(0))?.collect::>>()?; + let rows = stmt + .query_map(params![now, user, groups_json], |r| r.get::<_, String>(0))? + .collect::>>()?; Ok(rows) } } @@ -506,8 +676,15 @@ mod tests { async fn orbit(db: &Db, name: &str) -> Uuid { let id = Uuid::new_v4(); db.upsert_orbit(&OrbitRow { - id, 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(), + id, + 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(); @@ -516,15 +693,36 @@ mod tests { fn profile(db: &Db, orbit: Uuid, outpost: Uuid, format: CaptureFormat) -> Uuid { let application = Uuid::new_v4(); - let profile = CaptureProfile { application_id: application, orbit_id: orbit, outpost_id: outpost, format, schedule: None, retention: None }; + let profile = CaptureProfile { + application_id: application, + orbit_id: orbit, + outpost_id: outpost, + format, + schedule: None, + retention: None, + }; assert!(db.register_capture_profile(&profile, now()).unwrap()); application } - fn target(db: &Db, application: Uuid, outpost: Uuid, engine: Engine, instance: &str, name: &str) -> Uuid { + fn target( + db: &Db, + application: Uuid, + outpost: Uuid, + engine: Engine, + instance: &str, + name: &str, + ) -> Uuid { let target = RestoreTarget { - id: Uuid::new_v4(), application_id: application, outpost_id: outpost, name: name.into(), engine, - identity: DatabaseIdentity { instance: instance.into(), database: "app".into() }, + id: Uuid::new_v4(), + application_id: application, + outpost_id: outpost, + name: name.into(), + engine, + identity: DatabaseIdentity { + instance: instance.into(), + database: "app".into(), + }, }; assert!(db.register_restore_target(&target).unwrap()); target.id @@ -538,141 +736,347 @@ mod tests { db.insert_test_credential("token", &outpost.to_string(), "agent"); let orbit = orbit(&db, "prod-db").await; let application = profile(&db, orbit, outpost, CaptureFormat::PostgresCustom); - let target = target(&db, application, outpost, Engine::Postgres, "111", "staging-db"); - db.set_orbit_environment(orbit, "production", now()).unwrap(); + let target = target( + &db, + application, + outpost, + Engine::Postgres, + "111", + "staging-db", + ); + db.set_orbit_environment(orbit, "production", now()) + .unwrap(); db.set_target_environment(target, "staging", now()).unwrap(); - Fixture { db, orbit, application, outpost, target, _dir: dir } + Fixture { + db, + orbit, + application, + outpost, + target, + _dir: dir, + } } fn make(f: &Fixture) -> std::result::Result { - f.db.create_relation(f.orbit, f.target, None, false, true, "admin", now()).unwrap() + f.db.create_relation(f.orbit, f.target, None, false, true, "admin", now()) + .unwrap() } #[tokio::test] async fn a_valid_relation_is_created_in_one_direction_and_only_once() { let f = fixture().await; let relation = make(&f).unwrap(); - assert_eq!((relation.version, relation.active, relation.engine.as_str()), (1, true, "postgres")); + assert_eq!( + (relation.version, relation.active, relation.engine.as_str()), + (1, true, "postgres") + ); assert_eq!(relation.target_identity["instance"], "111"); - assert_eq!(make(&f).err(), Some(Reject::Duplicate), "one active relation per source and target"); + assert_eq!( + make(&f).err(), + Some(Reject::Duplicate), + "one active relation per source and target" + ); // not symmetric: the target is not a source, and a production-labelled database can never be a target let reverse_source = orbit(&f.db, "staging-orbit").await; - assert_eq!(f.db.create_relation(reverse_source, f.target, None, false, true, "admin", now()).unwrap().err(), Some(Reject::SourceNotManaged)); + assert_eq!( + f.db.create_relation(reverse_source, f.target, None, false, true, "admin", now()) + .unwrap() + .err(), + Some(Reject::SourceNotManaged) + ); } #[tokio::test] async fn every_rule_has_its_own_refusal() { let f = fixture().await; let now = now(); - let try_with = |source: Uuid, target: Uuid, clash: bool| f.db.create_relation(source, target, None, clash, true, "admin", now).unwrap().err(); - assert_eq!(try_with(Uuid::new_v4(), f.target, false), Some(Reject::UnknownSource)); - assert_eq!(try_with(f.orbit, Uuid::new_v4(), false), Some(Reject::UnknownTarget)); - assert_eq!(try_with(f.orbit, f.target, true), Some(Reject::TargetMatchesSource), "the target is a production database under another label"); + let try_with = |source: Uuid, target: Uuid, clash: bool| { + f.db.create_relation(source, target, None, clash, true, "admin", now) + .unwrap() + .err() + }; + assert_eq!( + try_with(Uuid::new_v4(), f.target, false), + Some(Reject::UnknownSource) + ); + assert_eq!( + try_with(f.orbit, Uuid::new_v4(), false), + Some(Reject::UnknownTarget) + ); + assert_eq!( + try_with(f.orbit, f.target, true), + Some(Reject::TargetMatchesSource), + "the target is a production database under another label" + ); // a source that is not managed, or whose format cannot be restored let plain = orbit(&f.db, "plain").await; - assert_eq!(try_with(plain, f.target, false), Some(Reject::SourceNotManaged)); + assert_eq!( + try_with(plain, f.target, false), + Some(Reject::SourceNotManaged) + ); let files = orbit(&f.db, "files").await; profile(&f.db, files, f.outpost, CaptureFormat::Filesystem); - f.db.set_orbit_environment(files, "production", now).unwrap(); - assert_eq!(try_with(files, f.target, false), Some(Reject::SourceNotRestoreReady)); + f.db.set_orbit_environment(files, "production", now) + .unwrap(); + assert_eq!( + try_with(files, f.target, false), + Some(Reject::SourceNotRestoreReady) + ); // environments are never assumed let unset = orbit(&f.db, "unset").await; let unset_app = profile(&f.db, unset, f.outpost, CaptureFormat::PostgresSql); - let unset_target = target(&f.db, unset_app, f.outpost, Engine::Postgres, "222", "other"); - assert_eq!(try_with(unset, unset_target, false), Some(Reject::SourceEnvironmentUnset)); - f.db.set_orbit_environment(unset, "production", now).unwrap(); - assert_eq!(try_with(unset, unset_target, false), Some(Reject::TargetEnvironmentUnset), "an unlabelled target fails closed"); - f.db.set_target_environment(unset_target, "production", now).unwrap(); - assert_eq!(try_with(unset, unset_target, false), Some(Reject::TargetIsProduction)); + let unset_target = target( + &f.db, + unset_app, + f.outpost, + Engine::Postgres, + "222", + "other", + ); + assert_eq!( + try_with(unset, unset_target, false), + Some(Reject::SourceEnvironmentUnset) + ); + f.db.set_orbit_environment(unset, "production", now) + .unwrap(); + assert_eq!( + try_with(unset, unset_target, false), + Some(Reject::TargetEnvironmentUnset), + "an unlabelled target fails closed" + ); + f.db.set_target_environment(unset_target, "production", now) + .unwrap(); + assert_eq!( + try_with(unset, unset_target, false), + Some(Reject::TargetIsProduction) + ); // a target belongs to the application it was registered for, and the engines must agree - let wrong_app = target(&f.db, unset_app, f.outpost, Engine::Postgres, "333", "for-another-app"); - f.db.set_target_environment(wrong_app, "staging", now).unwrap(); - assert_eq!(try_with(f.orbit, wrong_app, false), Some(Reject::ApplicationMismatch)); - let mysql = target(&f.db, f.application, f.outpost, Engine::Mysql, &Uuid::new_v4().to_string(), "mysql-staging"); + let wrong_app = target( + &f.db, + unset_app, + f.outpost, + Engine::Postgres, + "333", + "for-another-app", + ); + f.db.set_target_environment(wrong_app, "staging", now) + .unwrap(); + assert_eq!( + try_with(f.orbit, wrong_app, false), + Some(Reject::ApplicationMismatch) + ); + let mysql = target( + &f.db, + f.application, + f.outpost, + Engine::Mysql, + &Uuid::new_v4().to_string(), + "mysql-staging", + ); f.db.set_target_environment(mysql, "staging", now).unwrap(); - assert_eq!(try_with(f.orbit, mysql, false), Some(Reject::EngineMismatch)); - assert!(f.db.relation_views(false, None, now).unwrap().is_empty(), "no refused request stored anything"); + assert_eq!( + try_with(f.orbit, mysql, false), + Some(Reject::EngineMismatch) + ); + assert!( + f.db.relation_views(false, None, now).unwrap().is_empty(), + "no refused request stored anything" + ); } #[tokio::test] async fn an_expired_or_revoked_outpost_is_refused() { let f = fixture().await; let far = now() + crate::db::credentials::lifetime_secs() + 10; - assert_eq!(f.db.create_relation(f.orbit, f.target, None, false, true, "admin", far).unwrap().err(), Some(Reject::OutpostInactive), "credential expired"); + assert_eq!( + f.db.create_relation(f.orbit, f.target, None, false, true, "admin", far) + .unwrap() + .err(), + Some(Reject::OutpostInactive), + "credential expired" + ); assert!(f.db.revoke_outpost(&f.outpost.to_string(), now()).unwrap()); - assert_eq!(make(&f).err(), Some(Reject::OutpostInactive), "credential revoked"); + assert_eq!( + make(&f).err(), + Some(Reject::OutpostInactive), + "credential revoked" + ); } #[tokio::test] async fn retargeting_makes_a_new_version_and_grants_do_not_follow() { let f = fixture().await; let first = make(&f).unwrap(); - f.db.add_relation_grant("user", "qa-user", &first.id, None, "admin", now()).unwrap().unwrap(); - assert_eq!(f.db.granted_relations(Some("qa-user"), &[], now()).unwrap(), [first.id.clone()]); - let other = target(&f.db, f.application, f.outpost, Engine::Postgres, "444", "second-staging"); - f.db.set_target_environment(other, "development", now()).unwrap(); - let second = f.db.create_relation(f.orbit, other, Some(&first.id), false, true, "admin", now()).unwrap().unwrap(); - assert_eq!((second.version, second.lineage.as_str()), (2, first.lineage.as_str())); + f.db.add_relation_grant("user", "qa-user", &first.id, None, "admin", now()) + .unwrap() + .unwrap(); + assert_eq!( + f.db.granted_relations(Some("qa-user"), &[], now()).unwrap(), + std::slice::from_ref(&first.id) + ); + let other = target( + &f.db, + f.application, + f.outpost, + Engine::Postgres, + "444", + "second-staging", + ); + f.db.set_target_environment(other, "development", now()) + .unwrap(); + let second = + f.db.create_relation(f.orbit, other, Some(&first.id), false, true, "admin", now()) + .unwrap() + .unwrap(); + assert_eq!( + (second.version, second.lineage.as_str()), + (2, first.lineage.as_str()) + ); assert_ne!(second.id, first.id); let old = f.db.relation(&first.id).unwrap().unwrap(); - assert_eq!((old.active, old.deactivated_reason.as_deref()), (false, Some("replaced"))); - assert!(f.db.granted_relations(Some("qa-user"), &[], now()).unwrap().is_empty(), "the new database starts with no access"); - assert!(f.db.add_relation_grant("user", "qa-user", &first.id, None, "admin", now()).unwrap().is_none(), "no grants on a deactivated relation"); + assert_eq!( + (old.active, old.deactivated_reason.as_deref()), + (false, Some("replaced")) + ); + assert!( + f.db.granted_relations(Some("qa-user"), &[], now()) + .unwrap() + .is_empty(), + "the new database starts with no access" + ); + assert!( + f.db.add_relation_grant("user", "qa-user", &first.id, None, "admin", now()) + .unwrap() + .is_none(), + "no grants on a deactivated relation" + ); // retargeting something that is not an active relation of this source changes nothing - assert!(f.db.create_relation(f.orbit, other, Some(&first.id), false, true, "admin", now()).unwrap().is_err()); + assert!(f + .db + .create_relation(f.orbit, other, Some(&first.id), false, true, "admin", now()) + .unwrap() + .is_err()); } #[tokio::test] async fn relabelling_the_target_as_production_ends_its_relations_at_once() { let f = fixture().await; let relation = make(&f).unwrap(); - f.db.add_relation_grant("user", "qa-user", &relation.id, None, "admin", now()).unwrap().unwrap(); + f.db.add_relation_grant("user", "qa-user", &relation.id, None, "admin", now()) + .unwrap() + .unwrap(); assert!(f.db.relation_views(true, None, now()).unwrap()[0].usable); - let ended = f.db.set_target_environment(f.target, "production", now()).unwrap().unwrap(); - assert_eq!(ended, [relation.id.clone()]); + let ended = + f.db.set_target_environment(f.target, "production", now()) + .unwrap() + .unwrap(); + assert_eq!(ended, std::slice::from_ref(&relation.id)); let stored = f.db.relation(&relation.id).unwrap().unwrap(); - assert_eq!((stored.active, stored.deactivated_reason.as_deref()), (false, Some("target_relabelled"))); - assert!(f.db.granted_relations(Some("qa-user"), &[], now()).unwrap().is_empty()); + assert_eq!( + (stored.active, stored.deactivated_reason.as_deref()), + (false, Some("target_relabelled")) + ); + assert!(f + .db + .granted_relations(Some("qa-user"), &[], now()) + .unwrap() + .is_empty()); assert_eq!(make(&f).err(), Some(Reject::TargetIsProduction)); - assert!(f.db.set_target_environment(Uuid::new_v4(), "staging", now()).unwrap().is_none()); + assert!(f + .db + .set_target_environment(Uuid::new_v4(), "staging", now()) + .unwrap() + .is_none()); } #[tokio::test] - async fn revoking_an_outpost_ends_relations_through_it_and_a_lapsed_credential_makes_one_unusable() { + async fn revoking_an_outpost_ends_relations_through_it_and_a_lapsed_credential_makes_one_unusable( + ) { let f = fixture().await; let relation = make(&f).unwrap(); let view = &f.db.relation_views(true, None, now()).unwrap()[0]; assert!(view.usable && view.source_name == "prod-db" && view.target_name == "staging-db"); - assert_eq!((view.source_environment.as_deref(), view.target_environment.as_deref()), (Some("production"), Some("staging"))); + assert_eq!( + ( + view.source_environment.as_deref(), + view.target_environment.as_deref() + ), + (Some("production"), Some("staging")) + ); // the credential simply expires: still "active" in the table, but not usable let late = now() + crate::db::credentials::lifetime_secs() + 10; let stale = &f.db.relation_views(true, None, late).unwrap()[0]; - assert_eq!((stale.usable, stale.unusable_reason), (false, Some("outpost_inactive"))); + assert_eq!( + (stale.usable, stale.unusable_reason), + (false, Some("outpost_inactive")) + ); assert!(f.db.revoke_outpost(&f.outpost.to_string(), now()).unwrap()); let stored = f.db.relation(&relation.id).unwrap().unwrap(); - assert_eq!((stored.active, stored.deactivated_reason.as_deref()), (false, Some("outpost_revoked"))); + assert_eq!( + (stored.active, stored.deactivated_reason.as_deref()), + (false, Some("outpost_revoked")) + ); assert!(f.db.relation_views(true, None, now()).unwrap().is_empty()); - assert_eq!(f.db.relation_views(false, None, now()).unwrap()[0].unusable_reason, Some("deactivated")); + assert_eq!( + f.db.relation_views(false, None, now()).unwrap()[0].unusable_reason, + Some("deactivated") + ); } #[tokio::test] async fn relation_grants_apply_to_people_and_groups_until_they_expire_or_are_removed() { let f = fixture().await; let relation = make(&f).unwrap(); - let user = f.db.add_relation_grant("user", "u1", &relation.id, Some(100), "admin", 10).unwrap().unwrap(); - f.db.add_relation_grant("group", "qa", &relation.id, None, "admin", 10).unwrap().unwrap(); - assert!(f.db.add_relation_grant("user", "u1", &relation.id, None, "admin", 10).unwrap().is_none(), "duplicate"); - assert_eq!(f.db.granted_relations(Some("u1"), &[], 99).unwrap().len(), 1); - assert!(f.db.granted_relations(Some("u1"), &[], 100).unwrap().is_empty(), "expiry is exclusive"); - assert_eq!(f.db.granted_relations(Some("someone"), &["qa".to_string()], 100).unwrap().len(), 1, "group member"); - assert!(f.db.granted_relations(Some("someone"), &[], 100).unwrap().is_empty(), "a missing groups claim grants nothing"); + let user = + f.db.add_relation_grant("user", "u1", &relation.id, Some(100), "admin", 10) + .unwrap() + .unwrap(); + f.db.add_relation_grant("group", "qa", &relation.id, None, "admin", 10) + .unwrap() + .unwrap(); + assert!( + f.db.add_relation_grant("user", "u1", &relation.id, None, "admin", 10) + .unwrap() + .is_none(), + "duplicate" + ); + assert_eq!( + f.db.granted_relations(Some("u1"), &[], 99).unwrap().len(), + 1 + ); + assert!( + f.db.granted_relations(Some("u1"), &[], 100) + .unwrap() + .is_empty(), + "expiry is exclusive" + ); + assert_eq!( + f.db.granted_relations(Some("someone"), &["qa".to_string()], 100) + .unwrap() + .len(), + 1, + "group member" + ); + assert!( + f.db.granted_relations(Some("someone"), &[], 100) + .unwrap() + .is_empty(), + "a missing groups claim grants nothing" + ); assert!(f.db.delete_relation_grant(&relation.id, &user.id).unwrap()); - assert!(!f.db.delete_relation_grant("other-relation", &user.id).unwrap(), "a grant is only removed through its own relation"); + assert!( + !f.db + .delete_relation_grant("other-relation", &user.id) + .unwrap(), + "a grant is only removed through its own relation" + ); assert_eq!(f.db.relation_grants(&relation.id).unwrap().len(), 1); - let only = f.db.relation_views(true, Some(&["nope".to_string()]), now()).unwrap(); + let only = + f.db.relation_views(true, Some(&["nope".to_string()]), now()) + .unwrap(); assert!(only.is_empty(), "restricting to other ids returns nothing"); } @@ -682,6 +1086,10 @@ mod tests { make(&f).unwrap(); f.db.migrate().await.unwrap(); f.db.migrate().await.unwrap(); - assert_eq!(f.db.relation_views(true, None, now()).unwrap().len(), 1, "existing data survives a re-run"); + assert_eq!( + f.db.relation_views(true, None, now()).unwrap().len(), + 1, + "existing data survives a re-run" + ); } } diff --git a/crates/tessera-hub/src/db/restore.rs b/crates/tessera-hub/src/db/restore.rs index a53fc27..966ae80 100644 --- a/crates/tessera-hub/src/db/restore.rs +++ b/crates/tessera-hub/src/db/restore.rs @@ -101,18 +101,27 @@ impl Db { } pub fn restore_targets(&self, application: Uuid) -> Result> { - Ok(self.restore_targets_with_activity(application)? - .into_iter().map(|(target, _)| target).collect()) + Ok(self + .restore_targets_with_activity(application)? + .into_iter() + .map(|(target, _)| target) + .collect()) } - pub fn restore_targets_with_activity(&self, application: Uuid) -> Result> { + pub fn restore_targets_with_activity( + &self, + application: Uuid, + ) -> Result> { let conn = self.conn.lock().unwrap(); let mut stmt = conn.prepare( "SELECT t.profile, EXISTS (SELECT 1 FROM outpost_credentials WHERE outpost_id = t.outpost_id AND state = 'active' AND expires_at > ?2) FROM restore_targets t WHERE t.application_id = ?1 ORDER BY t.id", )?; - let rows = stmt.query_map(params![application.to_string(), chrono::Utc::now().timestamp()], |row| Ok((json(row, 0)?, row.get(1)?)))?; + let rows = stmt.query_map( + params![application.to_string(), chrono::Utc::now().timestamp()], + |row| Ok((json(row, 0)?, row.get(1)?)), + )?; Ok(rows.collect::>()?) } @@ -284,7 +293,11 @@ impl Db { if let Some(reason) = super::refresh::invalid_reason(&tx, &run, now)? { super::refresh::block(&tx, &run, reason, now)?; tx.execute("UPDATE restore_jobs SET status='cancelled', phase='cancelled', updated_at=?2 WHERE id=?1 AND status='running'", params![id.to_string(), now])?; - audit(&tx, "restore.apply_refused", &format!("job={id} run={} reason={reason}", run.id))?; + audit( + &tx, + "restore.apply_refused", + &format!("job={id} run={} reason={reason}", run.id), + )?; tx.commit()?; return Ok(false); } @@ -385,35 +398,35 @@ pub(super) fn enqueue_restore_in( artifact: &RestoreArtifact, now: i64, ) -> Result> { - let registered: Option = tx.query_row( + let registered: Option = tx.query_row( "SELECT t.profile FROM restore_targets t WHERE t.id = ?1 AND t.application_id = ?2 AND EXISTS (SELECT 1 FROM outpost_credentials WHERE outpost_id = t.outpost_id AND state = 'active' AND expires_at > ?3)", params![target.to_string(), application.to_string(), now], |row| json(row, 0), ).optional()?; - let Some(registered) = registered else { - return Ok(None); - }; - if restore_target_mismatch(®istered, artifact).is_some() { - return Ok(None); - } - let id = Uuid::new_v4(); - tx.execute( + let Some(registered) = registered else { + return Ok(None); + }; + if restore_target_mismatch(®istered, artifact).is_some() { + return Ok(None); + } + let id = Uuid::new_v4(); + tx.execute( "INSERT INTO restore_jobs(id, snapshot_id, target_id, actor, artifact, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6)", params![id.to_string(), snapshot.to_string(), target.to_string(), actor, serde_json::to_string(artifact)?, now], )?; - audit( - &tx, - "restore.queued", - &format!("actor={actor} job={id} snapshot={snapshot} target={target}"), - )?; - let job = tx.query_row( - &format!("{VIEW} WHERE j.id = ?1"), - [id.to_string()], - read_job, - )?; + audit( + tx, + "restore.queued", + &format!("actor={actor} job={id} snapshot={snapshot} target={target}"), + )?; + let job = tx.query_row( + &format!("{VIEW} WHERE j.id = ?1"), + [id.to_string()], + read_job, + )?; Ok(Some(job)) } @@ -520,11 +533,24 @@ mod tests { database: "source".into(), }, }; - let registered = db.restore_targets_with_activity(app).unwrap().pop().unwrap(); + let registered = db + .restore_targets_with_activity(app) + .unwrap() + .pop() + .unwrap(); assert!(registered.1); - let same_source = RestoreArtifact { identity: registered.0.identity.clone(), ..artifact.clone() }; - assert_eq!(restore_target_mismatch(®istered.0, &same_source), Some("Target is the source database")); - assert!(db.enqueue_restore(snapshot, app, target, "fixture", &same_source, 100).unwrap().is_none()); + let same_source = RestoreArtifact { + identity: registered.0.identity.clone(), + ..artifact.clone() + }; + assert_eq!( + restore_target_mismatch(®istered.0, &same_source), + Some("Target is the source database") + ); + assert!(db + .enqueue_restore(snapshot, app, target, "fixture", &same_source, 100) + .unwrap() + .is_none()); let job = db .enqueue_restore(snapshot, app, target, "fixture", &artifact, 100) .unwrap() @@ -580,7 +606,10 @@ mod tests { let interrupted = db.restore_job(job.id, late).unwrap().unwrap(); assert_eq!(interrupted.status, "recovery_required"); let recent = db.restore_recent(10, late).unwrap(); - assert_eq!(recent.iter().map(|item| item.id).collect::>(), vec![next.id, job.id]); + assert_eq!( + recent.iter().map(|item| item.id).collect::>(), + vec![next.id, job.id] + ); assert_eq!(db.restore_recent(1, late).unwrap().len(), 1); assert_eq!(interrupted.safety_snapshot_id, Some(safety)); assert!(db.snapshot_in_restore(snapshot).unwrap()); diff --git a/crates/tessera-hub/src/db/sessions.rs b/crates/tessera-hub/src/db/sessions.rs index ff2f5fd..09c3c81 100644 --- a/crates/tessera-hub/src/db/sessions.rs +++ b/crates/tessera-hub/src/db/sessions.rs @@ -68,7 +68,13 @@ pub(super) fn migrate(conn: &Connection) -> Result<()> { impl Db { /// Find or create the user for a stable `(issuer, subject)` identity. - pub fn upsert_user(&self, issuer: &str, subject: &str, display_name: &str, now: i64) -> Result { + pub fn upsert_user( + &self, + issuer: &str, + subject: &str, + display_name: &str, + now: i64, + ) -> Result { let conn = self.conn.lock().unwrap(); conn.execute( "INSERT INTO users(id,issuer,subject,display_name,created_at,last_login_at) @@ -85,6 +91,7 @@ impl Db { /// Create a session for an active user. Returns false when the user is /// missing or inactive. Expired rows are purged opportunistically. + #[allow(clippy::too_many_arguments)] pub fn create_session( &self, id: &str, @@ -96,7 +103,10 @@ impl Db { now: i64, ) -> Result { let conn = self.conn.lock().unwrap(); - conn.execute("DELETE FROM sessions WHERE expires_at <= ?1 OR last_seen + ?2 <= ?1", params![now, IDLE_SECS])?; + conn.execute( + "DELETE FROM sessions WHERE expires_at <= ?1 OR last_seen + ?2 <= ?1", + params![now, IDLE_SECS], + )?; let inserted = conn.execute( "INSERT INTO sessions(token_digest,user_id,generation,auth_method,credential_fp,auth_time,created_at,last_seen,expires_at,admin,groups) SELECT ?1, id, generation, ?3, ?4, ?5, ?5, ?5, ?6, ?7, ?8 FROM users WHERE id=?2 AND active=1", @@ -134,15 +144,23 @@ impl Db { }, ) .optional()?; - let Some((session, last_seen)) = found else { return Ok(None) }; + let Some((session, last_seen)) = found else { + return Ok(None); + }; if now - last_seen >= TOUCH_AFTER_SECS { - conn.execute("UPDATE sessions SET last_seen=?2 WHERE token_digest=?1", params![digest, now])?; + conn.execute( + "UPDATE sessions SET last_seen=?2 WHERE token_digest=?1", + params![digest, now], + )?; } Ok(Some(session)) } pub fn revoke_session(&self, id: &str) -> Result<()> { - self.conn.lock().unwrap().execute("DELETE FROM sessions WHERE token_digest=?1", params![session_digest(id)])?; + self.conn.lock().unwrap().execute( + "DELETE FROM sessions WHERE token_digest=?1", + params![session_digest(id)], + )?; Ok(()) } @@ -151,7 +169,10 @@ impl Db { pub fn revoke_user_sessions(&self, user_id: &str) -> Result { let mut conn = self.conn.lock().unwrap(); let tx = conn.transaction()?; - tx.execute("UPDATE users SET generation=generation+1 WHERE id=?1", params![user_id])?; + tx.execute( + "UPDATE users SET generation=generation+1 WHERE id=?1", + params![user_id], + )?; let removed = tx.execute("DELETE FROM sessions WHERE user_id=?1", params![user_id])?; tx.commit()?; Ok(removed) @@ -159,12 +180,20 @@ impl Db { #[cfg(test)] pub fn expire_all_sessions(&self) { - self.conn.lock().unwrap().execute("UPDATE sessions SET expires_at=0", []).unwrap(); + self.conn + .lock() + .unwrap() + .execute("UPDATE sessions SET expires_at=0", []) + .unwrap(); } #[cfg(test)] pub fn session_rows(&self) -> i64 { - self.conn.lock().unwrap().query_row("SELECT COUNT(*) FROM sessions", [], |r| r.get(0)).unwrap() + self.conn + .lock() + .unwrap() + .query_row("SELECT COUNT(*) FROM sessions", [], |r| r.get(0)) + .unwrap() } } @@ -182,30 +211,54 @@ mod tests { #[tokio::test] async fn idle_and_absolute_deadlines_use_the_supplied_clock() { let (_dir, db) = db().await; - let user = db.upsert_user("local:emergency", "ops", "ops", 1000).unwrap(); - assert!(db.create_session("a", &user, "password", Some("fp"), true, &[], 1000).unwrap()); - assert!(db.lookup_session("a", 1000 + IDLE_SECS - 1).unwrap().is_some()); + let user = db + .upsert_user("local:emergency", "ops", "ops", 1000) + .unwrap(); + assert!(db + .create_session("a", &user, "password", Some("fp"), true, &[], 1000) + .unwrap()); + assert!(db + .lookup_session("a", 1000 + IDLE_SECS - 1) + .unwrap() + .is_some()); // sliding: the touch above moved last_seen, so a request just inside the // new idle window is still fine, one beyond it is not - assert!(db.lookup_session("a", 1000 + 2 * IDLE_SECS - 2).unwrap().is_some()); - assert!(db.lookup_session("a", 1000 + 3 * IDLE_SECS).unwrap().is_none()); - assert!(db.create_session("b", &user, "password", None, true, &[], 5000).unwrap()); + assert!(db + .lookup_session("a", 1000 + 2 * IDLE_SECS - 2) + .unwrap() + .is_some()); + assert!(db + .lookup_session("a", 1000 + 3 * IDLE_SECS) + .unwrap() + .is_none()); + assert!(db + .create_session("b", &user, "password", None, true, &[], 5000) + .unwrap()); let mut now = 5000; while now + IDLE_SECS - 10 < 5000 + ABSOLUTE_SECS { now += IDLE_SECS - 10; - assert!(db.lookup_session("b", now).unwrap().is_some(), "active at {now}"); + assert!( + db.lookup_session("b", now).unwrap().is_some(), + "active at {now}" + ); } // keeps being used, yet the absolute deadline still ends it - assert!(db.lookup_session("b", 5000 + ABSOLUTE_SECS).unwrap().is_none()); + assert!(db + .lookup_session("b", 5000 + ABSOLUTE_SECS) + .unwrap() + .is_none()); } #[tokio::test] async fn only_a_digest_is_stored_and_csrf_is_not_the_key() { let (_dir, db) = db().await; let user = db.upsert_user("local:emergency", "ops", "ops", 1).unwrap(); - db.create_session("raw-session-id", &user, "password", None, true, &[], 1).unwrap(); + db.create_session("raw-session-id", &user, "password", None, true, &[], 1) + .unwrap(); let conn = db.conn.lock().unwrap(); - let key: String = conn.query_row("SELECT token_digest FROM sessions", [], |r| r.get(0)).unwrap(); + let key: String = conn + .query_row("SELECT token_digest FROM sessions", [], |r| r.get(0)) + .unwrap(); assert_ne!(key, "raw-session-id"); assert_eq!(key, session_digest("raw-session-id")); assert_ne!(key, csrf_token("raw-session-id")); @@ -218,48 +271,81 @@ mod tests { #[tokio::test] async fn revoked_sessions_cannot_be_resurrected_by_a_late_touch() { let (_dir, db) = db().await; - let user = db.upsert_user("local:emergency", "ops", "ops", 1000).unwrap(); - db.create_session("a", &user, "password", None, true, &[], 1000).unwrap(); + let user = db + .upsert_user("local:emergency", "ops", "ops", 1000) + .unwrap(); + db.create_session("a", &user, "password", None, true, &[], 1000) + .unwrap(); db.revoke_session("a").unwrap(); - assert!(db.lookup_session("a", 1000 + 2 * TOUCH_AFTER_SECS).unwrap().is_none()); + assert!(db + .lookup_session("a", 1000 + 2 * TOUCH_AFTER_SECS) + .unwrap() + .is_none()); assert_eq!(db.session_rows(), 0); } #[tokio::test] async fn per_user_revoke_ends_all_sessions_and_allows_a_new_login() { let (_dir, db) = db().await; - let one = db.upsert_user("https://idp.example", "alice", "Alice", 10).unwrap(); - let two = db.upsert_user("https://idp.example", "bob", "Bob", 10).unwrap(); + let one = db + .upsert_user("https://idp.example", "alice", "Alice", 10) + .unwrap(); + let two = db + .upsert_user("https://idp.example", "bob", "Bob", 10) + .unwrap(); for id in ["a1", "a2"] { - db.create_session(id, &one, "oidc", None, true, &[], 10).unwrap(); + db.create_session(id, &one, "oidc", None, true, &[], 10) + .unwrap(); } - db.create_session("b1", &two, "oidc", None, true, &[], 10).unwrap(); + db.create_session("b1", &two, "oidc", None, true, &[], 10) + .unwrap(); assert_eq!(db.revoke_user_sessions(&one).unwrap(), 2); assert!(db.lookup_session("a1", 11).unwrap().is_none()); assert!(db.lookup_session("a2", 11).unwrap().is_none()); assert!(db.lookup_session("b1", 11).unwrap().is_some()); - assert!(db.create_session("a3", &one, "oidc", None, true, &[], 12).unwrap()); + assert!(db + .create_session("a3", &one, "oidc", None, true, &[], 12) + .unwrap()); assert!(db.lookup_session("a3", 13).unwrap().is_some()); } #[tokio::test] async fn inactive_users_have_no_valid_or_new_sessions() { let (_dir, db) = db().await; - let user = db.upsert_user("https://idp.example", "carol", "Carol", 10).unwrap(); - db.create_session("c1", &user, "oidc", None, true, &[], 10).unwrap(); - db.conn.lock().unwrap().execute("UPDATE users SET active=0 WHERE id=?1", params![user]).unwrap(); + let user = db + .upsert_user("https://idp.example", "carol", "Carol", 10) + .unwrap(); + db.create_session("c1", &user, "oidc", None, true, &[], 10) + .unwrap(); + db.conn + .lock() + .unwrap() + .execute("UPDATE users SET active=0 WHERE id=?1", params![user]) + .unwrap(); assert!(db.lookup_session("c1", 11).unwrap().is_none()); - assert!(!db.create_session("c2", &user, "oidc", None, true, &[], 11).unwrap()); - assert!(!db.create_session("c3", "no-such-user", "oidc", None, true, &[], 11).unwrap()); + assert!(!db + .create_session("c2", &user, "oidc", None, true, &[], 11) + .unwrap()); + assert!(!db + .create_session("c3", "no-such-user", "oidc", None, true, &[], 11) + .unwrap()); } #[tokio::test] async fn issuer_and_subject_identify_the_user_not_the_display_name() { let (_dir, db) = db().await; - let first = db.upsert_user("https://idp.example", "sub-1", "Sam", 1).unwrap(); - let again = db.upsert_user("https://idp.example", "sub-1", "Samuel", 2).unwrap(); - let other_subject = db.upsert_user("https://idp.example", "sub-2", "Sam", 3).unwrap(); - let other_issuer = db.upsert_user("https://other.example", "sub-1", "Sam", 4).unwrap(); + let first = db + .upsert_user("https://idp.example", "sub-1", "Sam", 1) + .unwrap(); + let again = db + .upsert_user("https://idp.example", "sub-1", "Samuel", 2) + .unwrap(); + let other_subject = db + .upsert_user("https://idp.example", "sub-2", "Sam", 3) + .unwrap(); + let other_issuer = db + .upsert_user("https://other.example", "sub-1", "Sam", 4) + .unwrap(); assert_eq!(first, again); assert_ne!(first, other_subject); assert_ne!(first, other_issuer); @@ -272,13 +358,20 @@ mod tests { { let db = Db::connect(&path).await.unwrap(); db.migrate().await.unwrap(); - let user = db.upsert_user("local:emergency", "ops", "ops", 1000).unwrap(); - db.create_session("live", &user, "password", Some("fp"), true, &[], 1000).unwrap(); - db.create_session("old", &user, "password", Some("fp"), true, &[], 1000).unwrap(); + let user = db + .upsert_user("local:emergency", "ops", "ops", 1000) + .unwrap(); + db.create_session("live", &user, "password", Some("fp"), true, &[], 1000) + .unwrap(); + db.create_session("old", &user, "password", Some("fp"), true, &[], 1000) + .unwrap(); } let db = Db::connect(&path).await.unwrap(); db.migrate().await.unwrap(); assert!(db.lookup_session("live", 1000 + 60).unwrap().is_some()); - assert!(db.lookup_session("old", 1000 + ABSOLUTE_SECS + 1).unwrap().is_none()); + assert!(db + .lookup_session("old", 1000 + ABSOLUTE_SECS + 1) + .unwrap() + .is_none()); } } diff --git a/crates/tessera-hub/src/exports.rs b/crates/tessera-hub/src/exports.rs index 1153779..002e241 100644 --- a/crates/tessera-hub/src/exports.rs +++ b/crates/tessera-hub/src/exports.rs @@ -31,7 +31,15 @@ pub struct Plan { fn plan_of(extension: &'static str, compress: bool) -> Plan { let gz = extension.ends_with("gz"); - Plan { extension, compress, content_type: if gz || compress { "application/gzip" } else { "application/octet-stream" } } + Plan { + extension, + compress, + content_type: if gz || compress { + "application/gzip" + } else { + "application/octet-stream" + }, + } } /// Decide the delivery from the manifest `restore_hints` and the first bytes of the exported file. @@ -92,20 +100,32 @@ pub enum Refused { impl ExportGate { pub fn new(concurrency: usize, min_free: u64) -> Self { - Self { permits: Arc::new(Semaphore::new(concurrency)), min_free } + Self { + permits: Arc::new(Semaphore::new(concurrency)), + min_free, + } } pub fn from_env() -> Self { - let number = |name: &str| std::env::var(name).ok().and_then(|v| v.trim().parse::().ok()); + let number = |name: &str| { + std::env::var(name) + .ok() + .and_then(|v| v.trim().parse::().ok()) + }; Self::new( - number("TESSERA_EXPORT_CONCURRENCY").map_or(DEFAULT_CONCURRENCY, |n| n.clamp(1, 64) as usize), + number("TESSERA_EXPORT_CONCURRENCY") + .map_or(DEFAULT_CONCURRENCY, |n| n.clamp(1, 64) as usize), number("TESSERA_EXPORT_MIN_FREE_BYTES").unwrap_or(DEFAULT_MARGIN), ) } /// Admit one export of about `size` bytes into `dir`. The permit lives as long as the response body. pub fn admit(&self, dir: &std::path::Path, size: u64) -> Result { - let permit = self.permits.clone().try_acquire_owned().map_err(|_| Refused::Busy)?; + let permit = self + .permits + .clone() + .try_acquire_owned() + .map_err(|_| Refused::Busy)?; match free_bytes(dir) { // `size` is the snapshot's recorded size; when a producer did not record one it is 0 and the margin alone applies. Some(free) if free < size.saturating_add(self.min_free) => Err(Refused::NoSpace), @@ -128,7 +148,9 @@ fn free_bytes(_dir: &std::path::Path) -> Option { /// Remove export directories a crash left behind. Only directories with our own prefix, only directly /// inside `data_dir`; run before the listener starts. Older `.tmp*` leftovers are deliberately not touched. pub fn sweep_stale(data_dir: &std::path::Path) -> usize { - let Ok(entries) = std::fs::read_dir(data_dir) else { return 0 }; + let Ok(entries) = std::fs::read_dir(data_dir) else { + return 0; + }; let mut removed = 0; for entry in entries.flatten() { let name = entry.file_name(); @@ -156,8 +178,26 @@ pub struct Guarded { } impl Guarded { - pub fn new(inner: S, permit: OwnedSemaphorePermit, dir: tempfile::TempDir, db: Db, principal: Principal, snapshot: Uuid, request: Uuid) -> Self { - Self { inner: Box::pin(inner), _permit: permit, _dir: dir, db, principal, snapshot, request, completed: false, failed: false } + pub fn new( + inner: S, + permit: OwnedSemaphorePermit, + dir: tempfile::TempDir, + db: Db, + principal: Principal, + snapshot: Uuid, + request: Uuid, + ) -> Self { + Self { + inner: Box::pin(inner), + _permit: permit, + _dir: dir, + db, + principal, + snapshot, + request, + completed: false, + failed: false, + } } } @@ -183,7 +223,13 @@ impl Drop for Guarded { } else { (AuditAction::ExportDisconnected, AuditOutcome::Failed) }; - if let Err(error) = self.db.audit_event(&self.principal, action, AuditResource::Snapshot(self.snapshot), outcome, self.request) { + if let Err(error) = self.db.audit_event( + &self.principal, + action, + AuditResource::Snapshot(self.snapshot), + outcome, + self.request, + ) { tracing::error!("could not audit the end of an export: {error:#}"); } } @@ -204,25 +250,117 @@ mod tests { fn every_producer_of_a_snapshot_gets_the_right_delivery() { let gz = [0x1f, 0x8b, 8, 0]; let cases: Vec<(&str, serde_json::Value, Vec, &str, bool)> = vec![ - ("hub database orbit, postgres plain SQL", json!({"engine": "postgres", "format": "plain"}), b"-- PostgreSQL dump\n".to_vec(), "sql.gz", true), - ("hub database orbit, mysql plain SQL", json!({"engine": "mysql", "format": "plain"}), b"-- MySQL dump\n".to_vec(), "sql.gz", true), - ("agent capture, postgres custom", json!({"engine": "postgres", "format": "custom", "sha256": "x"}), b"PGDMP\x01\x0e\x00".to_vec(), "dump", false), - ("hub postgres provider, custom", json!({"format": "custom", "restore_command_hint": "pg_restore"}), b"PGDMP\x01".to_vec(), "dump", false), - ("restic filesystem, tar by hint", json!({"format": "tar"}), ustar(), "tar.gz", true), - ("restic filesystem snapshot with no hint but a tar payload", serde_json::Value::Null, ustar(), "tar.gz", true), - ("hub filesystem orbit archive", json!({"paths": [], "format": "tessera-fs-v1"}), b"a/b\0\x03\0\0\0\0\0\0\0xyz".to_vec(), "tessera-fs.gz", true), - ("sqlite database", json!({"format": "sqlite"}), b"SQLite format 3\0....".to_vec(), "sqlite.gz", true), - ("SQL that is already gzip", json!({"format": "sql_gzip"}), gz.to_vec(), "sql.gz", false), - ("hint says plain SQL but the file is gzip: no double compression", json!({"format": "plain"}), gz.to_vec(), "sql.gz", false), - ("a tar that is already gzip", json!({"format": "tar"}), gz.to_vec(), "tar.gz", false), - ("zstd payload", serde_json::Value::Null, vec![0x28, 0xb5, 0x2f, 0xfd, 0], "zst", false), - ("legacy wormhole commit with no hints", serde_json::Value::Null, b"opaque payload".to_vec(), "dump.gz", true), - ("demo seed", json!({"demo": true}), b"demo".to_vec(), "dump.gz", true), + ( + "hub database orbit, postgres plain SQL", + json!({"engine": "postgres", "format": "plain"}), + b"-- PostgreSQL dump\n".to_vec(), + "sql.gz", + true, + ), + ( + "hub database orbit, mysql plain SQL", + json!({"engine": "mysql", "format": "plain"}), + b"-- MySQL dump\n".to_vec(), + "sql.gz", + true, + ), + ( + "agent capture, postgres custom", + json!({"engine": "postgres", "format": "custom", "sha256": "x"}), + b"PGDMP\x01\x0e\x00".to_vec(), + "dump", + false, + ), + ( + "hub postgres provider, custom", + json!({"format": "custom", "restore_command_hint": "pg_restore"}), + b"PGDMP\x01".to_vec(), + "dump", + false, + ), + ( + "restic filesystem, tar by hint", + json!({"format": "tar"}), + ustar(), + "tar.gz", + true, + ), + ( + "restic filesystem snapshot with no hint but a tar payload", + serde_json::Value::Null, + ustar(), + "tar.gz", + true, + ), + ( + "hub filesystem orbit archive", + json!({"paths": [], "format": "tessera-fs-v1"}), + b"a/b\0\x03\0\0\0\0\0\0\0xyz".to_vec(), + "tessera-fs.gz", + true, + ), + ( + "sqlite database", + json!({"format": "sqlite"}), + b"SQLite format 3\0....".to_vec(), + "sqlite.gz", + true, + ), + ( + "SQL that is already gzip", + json!({"format": "sql_gzip"}), + gz.to_vec(), + "sql.gz", + false, + ), + ( + "hint says plain SQL but the file is gzip: no double compression", + json!({"format": "plain"}), + gz.to_vec(), + "sql.gz", + false, + ), + ( + "a tar that is already gzip", + json!({"format": "tar"}), + gz.to_vec(), + "tar.gz", + false, + ), + ( + "zstd payload", + serde_json::Value::Null, + vec![0x28, 0xb5, 0x2f, 0xfd, 0], + "zst", + false, + ), + ( + "legacy wormhole commit with no hints", + serde_json::Value::Null, + b"opaque payload".to_vec(), + "dump.gz", + true, + ), + ( + "demo seed", + json!({"demo": true}), + b"demo".to_vec(), + "dump.gz", + true, + ), ]; for (name, hints, head, extension, compress) in cases { let got = plan(&hints, &head); - assert_eq!((got.extension, got.compress), (extension, compress), "{name}"); - let ct = if extension.ends_with("gz") { "application/gzip" } else { "application/octet-stream" }; + assert_eq!( + (got.extension, got.compress), + (extension, compress), + "{name}" + ); + let ct = if extension.ends_with("gz") { + "application/gzip" + } else { + "application/octet-stream" + }; assert_eq!(got.content_type, ct, "{name}"); } } @@ -235,10 +373,19 @@ mod tests { make("tessera-export-bbbb"); make("vault"); make(".tmpXYZ"); - std::fs::write(dir.path().join("tessera-export-file"), b"a file, not a directory").unwrap(); + std::fs::write( + dir.path().join("tessera-export-file"), + b"a file, not a directory", + ) + .unwrap(); std::fs::create_dir_all(dir.path().join("vault/tessera-export-nested")).unwrap(); assert_eq!(sweep_stale(dir.path()), 2); - for kept in ["vault", ".tmpXYZ", "tessera-export-file", "vault/tessera-export-nested"] { + for kept in [ + "vault", + ".tmpXYZ", + "tessera-export-file", + "vault/tessera-export-nested", + ] { assert!(dir.path().join(kept).exists(), "{kept} must survive"); } assert!(!dir.path().join("tessera-export-aaaa").exists()); @@ -248,12 +395,30 @@ mod tests { fn admission_is_bounded_by_concurrency_and_by_free_disk() { let dir = tempfile::tempdir().unwrap(); let gate = ExportGate::new(1, 0); - let held = gate.admit(dir.path(), 1).ok().expect("first export is admitted"); - assert!(matches!(gate.admit(dir.path(), 1), Err(Refused::Busy)), "second export is refused at once"); + let held = gate + .admit(dir.path(), 1) + .ok() + .expect("first export is admitted"); + assert!( + matches!(gate.admit(dir.path(), 1), Err(Refused::Busy)), + "second export is refused at once" + ); drop(held); - assert!(gate.admit(dir.path(), 1).is_ok(), "the permit comes back when the first ends"); + assert!( + gate.admit(dir.path(), 1).is_ok(), + "the permit comes back when the first ends" + ); let greedy = ExportGate::new(4, u64::MAX / 2); - assert!(matches!(greedy.admit(dir.path(), 10), Err(Refused::NoSpace))); - assert!(matches!(ExportGate::new(4, 0).admit(dir.path(), u64::MAX), Err(Refused::NoSpace)), "a snapshot bigger than the disk"); + assert!(matches!( + greedy.admit(dir.path(), 10), + Err(Refused::NoSpace) + )); + assert!( + matches!( + ExportGate::new(4, 0).admit(dir.path(), u64::MAX), + Err(Refused::NoSpace) + ), + "a snapshot bigger than the disk" + ); } } diff --git a/crates/tessera-hub/src/limits.rs b/crates/tessera-hub/src/limits.rs index 4709f5a..2a9699c 100644 --- a/crates/tessera-hub/src/limits.rs +++ b/crates/tessera-hub/src/limits.rs @@ -7,7 +7,10 @@ //! their /64. State is in memory and per hub process: it resets on restart and //! is not shared between replicas. use axum::http::HeaderMap; -use governor::{clock::DefaultClock, state::keyed::DefaultKeyedStateStore, state::InMemoryState, state::NotKeyed, Quota, RateLimiter}; +use governor::{ + clock::DefaultClock, state::keyed::DefaultKeyedStateStore, state::InMemoryState, + state::NotKeyed, Quota, RateLimiter, +}; use std::net::{IpAddr, Ipv6Addr, SocketAddr}; use std::num::NonZeroU32; use std::sync::atomic::{AtomicU64, Ordering}; @@ -82,7 +85,11 @@ impl Limits { let mut proxies = Vec::new(); if let Ok(list) = std::env::var("TESSERA_TRUSTED_PROXIES") { for item in list.split(',').map(str::trim).filter(|s| !s.is_empty()) { - proxies.push(item.parse::().map_err(|_| anyhow::anyhow!("TESSERA_TRUSTED_PROXIES: invalid IP {item}"))?); + proxies.push( + item.parse::().map_err(|_| { + anyhow::anyhow!("TESSERA_TRUSTED_PROXIES: invalid IP {item}") + })?, + ); } } Ok(Self::new(LimitConfig::default(), proxies)) @@ -91,7 +98,9 @@ impl Limits { /// The rate-limit key for a request. `None` peer (should not happen) maps to /// one strict shared bucket instead of bypassing limits. pub fn source(&self, peer: Option, headers: &HeaderMap) -> IpAddr { - let Some(peer) = peer else { return IpAddr::V6(Ipv6Addr::UNSPECIFIED) }; + let Some(peer) = peer else { + return IpAddr::V6(Ipv6Addr::UNSPECIFIED); + }; let mut client = peer.ip(); if self.trusted_proxies.contains(&client) { let forwarded: Vec<&str> = headers @@ -182,7 +191,10 @@ mod tests { } fn limits(proxies: &[&str]) -> Limits { - Limits::new(LimitConfig::default(), proxies.iter().map(|p| p.parse().unwrap()).collect()) + Limits::new( + LimitConfig::default(), + proxies.iter().map(|p| p.parse().unwrap()).collect(), + ) } #[test] @@ -202,14 +214,30 @@ mod tests { fn forwarded_for_is_ignored_unless_the_peer_is_a_trusted_proxy() { let l = limits(&["10.0.0.1"]); let spoof = headers("198.51.100.9"); - assert_eq!(l.source(peer("203.0.113.7"), &spoof), "203.0.113.7".parse::().unwrap(), "untrusted peer cannot choose its key"); - assert_eq!(l.source(peer("10.0.0.1"), &spoof), "198.51.100.9".parse::().unwrap()); + assert_eq!( + l.source(peer("203.0.113.7"), &spoof), + "203.0.113.7".parse::().unwrap(), + "untrusted peer cannot choose its key" + ); + assert_eq!( + l.source(peer("10.0.0.1"), &spoof), + "198.51.100.9".parse::().unwrap() + ); // client-supplied prefix is ignored: walk right to left, skipping trusted hops let chain = headers("1.1.1.1, 198.51.100.9, 10.0.0.1"); - assert_eq!(l.source(peer("10.0.0.1"), &chain), "198.51.100.9".parse::().unwrap()); + assert_eq!( + l.source(peer("10.0.0.1"), &chain), + "198.51.100.9".parse::().unwrap() + ); // junk or missing header falls back to the proxy itself - assert_eq!(l.source(peer("10.0.0.1"), &headers("not-an-ip")), "10.0.0.1".parse::().unwrap()); - assert_eq!(l.source(peer("10.0.0.1"), &HeaderMap::new()), "10.0.0.1".parse::().unwrap()); + assert_eq!( + l.source(peer("10.0.0.1"), &headers("not-an-ip")), + "10.0.0.1".parse::().unwrap() + ); + assert_eq!( + l.source(peer("10.0.0.1"), &HeaderMap::new()), + "10.0.0.1".parse::().unwrap() + ); } #[test] @@ -220,8 +248,14 @@ mod tests { let c = l.source(peer("2001:db8:1:3::1"), &HeaderMap::new()); assert_eq!(a, b); assert_ne!(a, c); - assert_eq!(l.source(peer("::ffff:192.0.2.5"), &HeaderMap::new()), "192.0.2.5".parse::().unwrap()); - assert_eq!(l.source(None, &HeaderMap::new()), IpAddr::V6(Ipv6Addr::UNSPECIFIED)); + assert_eq!( + l.source(peer("::ffff:192.0.2.5"), &HeaderMap::new()), + "192.0.2.5".parse::().unwrap() + ); + assert_eq!( + l.source(None, &HeaderMap::new()), + IpAddr::V6(Ipv6Addr::UNSPECIFIED) + ); } #[test] diff --git a/crates/tessera-hub/src/main.rs b/crates/tessera-hub/src/main.rs index 59db3af..373826c 100644 --- a/crates/tessera-hub/src/main.rs +++ b/crates/tessera-hub/src/main.rs @@ -1,6 +1,6 @@ mod admin; -mod auth; mod api; +mod auth; mod db; mod exports; mod limits; diff --git a/crates/tessera-hub/src/mtls.rs b/crates/tessera-hub/src/mtls.rs index b100833..61220d4 100644 --- a/crates/tessera-hub/src/mtls.rs +++ b/crates/tessera-hub/src/mtls.rs @@ -34,15 +34,12 @@ pub fn from_env() -> Result> { if !enabled { return Ok(None); } - let cert = std::env::var("TESSERA_WORMHOLE_CERT").context( - "TESSERA_WORMHOLE_CERT is required when TESSERA_WORMHOLE_MTLS is enabled", - )?; - let key = std::env::var("TESSERA_WORMHOLE_KEY").context( - "TESSERA_WORMHOLE_KEY is required when TESSERA_WORMHOLE_MTLS is enabled", - )?; - let ca = std::env::var("TESSERA_WORMHOLE_CLIENT_CA").context( - "TESSERA_WORMHOLE_CLIENT_CA is required when TESSERA_WORMHOLE_MTLS is enabled", - )?; + let cert = std::env::var("TESSERA_WORMHOLE_CERT") + .context("TESSERA_WORMHOLE_CERT is required when TESSERA_WORMHOLE_MTLS is enabled")?; + let key = std::env::var("TESSERA_WORMHOLE_KEY") + .context("TESSERA_WORMHOLE_KEY is required when TESSERA_WORMHOLE_MTLS is enabled")?; + let ca = std::env::var("TESSERA_WORMHOLE_CLIENT_CA") + .context("TESSERA_WORMHOLE_CLIENT_CA is required when TESSERA_WORMHOLE_MTLS is enabled")?; let listen = std::env::var("TESSERA_WORMHOLE_LISTEN") .unwrap_or_else(|_| "127.0.0.1:8788".into()) .parse() @@ -111,7 +108,9 @@ impl Service> for HyperApp { let mut request = request.map(Body::new); // The TLS listener has no `into_make_service_with_connect_info`; supply the peer here // so handlers that rate limit by source see the real address. - request.extensions_mut().insert(axum::extract::ConnectInfo(self.1)); + request + .extensions_mut() + .insert(axum::extract::ConnectInfo(self.1)); Box::pin(async move { Ok(app .oneshot(request) @@ -135,7 +134,9 @@ pub fn load_key(path: &Path) -> Result> { pub fn load_ca(path: &Path) -> Result { let mut roots = RootCertStore::empty(); for cert in load_certs(path)? { - roots.add(cert).map_err(|error| anyhow::anyhow!("client CA: {error}"))?; + roots + .add(cert) + .map_err(|error| anyhow::anyhow!("client CA: {error}"))?; } if roots.is_empty() { anyhow::bail!("client CA file contained no certificates"); @@ -146,7 +147,9 @@ pub fn load_ca(path: &Path) -> Result { #[cfg(test)] mod tests { use super::*; - use rcgen::{BasicConstraints, CertificateParams, DnType, ExtendedKeyUsagePurpose, IsCa, KeyPair}; + use rcgen::{ + BasicConstraints, CertificateParams, DnType, ExtendedKeyUsagePurpose, IsCa, KeyPair, + }; /// Agents reach pairing and upload routes over mTLS. Those handlers rate limit /// by source, which needs the peer address; this proves it is supplied on that @@ -156,10 +159,15 @@ mod tests { let ca_key = KeyPair::generate().unwrap(); let mut ca_params = CertificateParams::new(vec![]).unwrap(); ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); - ca_params.distinguished_name.push(DnType::CommonName, "tessera-test-ca"); + ca_params + .distinguished_name + .push(DnType::CommonName, "tessera-test-ca"); let ca = ca_params.self_signed(&ca_key).unwrap(); let server_key = KeyPair::generate().unwrap(); - let server = CertificateParams::new(vec!["localhost".into()]).unwrap().signed_by(&server_key, &ca, &ca_key).unwrap(); + let server = CertificateParams::new(vec!["localhost".into()]) + .unwrap() + .signed_by(&server_key, &ca, &ca_key) + .unwrap(); let client_key = KeyPair::generate().unwrap(); let mut client_params = CertificateParams::new(vec!["agent".into()]).unwrap(); client_params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth]; @@ -181,11 +189,19 @@ mod tests { key: load_key(&write("server.key", server_key.serialize_pem())).unwrap(), client_ca: load_ca(&write("ca.pem", ca.pem())).unwrap(), }; - let mut state = crate::state::HubState::bootstrap(dir.path().join("hub").to_str().unwrap(), "synthetic-vault").await.unwrap(); + let mut state = crate::state::HubState::bootstrap( + dir.path().join("hub").to_str().unwrap(), + "synthetic-vault", + ) + .await + .unwrap(); state.admin.token = Some("synthetic-admin".into()); tokio::spawn(mtls_serve(mtls, crate::api::router(state))); - let identity = openidconnect::reqwest::Identity::from_pem(format!("{}{}", client.pem(), client_key.serialize_pem()).as_bytes()).unwrap(); + let identity = openidconnect::reqwest::Identity::from_pem( + format!("{}{}", client.pem(), client_key.serialize_pem()).as_bytes(), + ) + .unwrap(); let trusted = openidconnect::reqwest::Certificate::from_pem(ca.pem().as_bytes()).unwrap(); let with_cert = openidconnect::reqwest::Client::builder() .add_root_certificate(trusted.clone()) @@ -197,7 +213,14 @@ mod tests { let body = serde_json::json!({}); let mut answer = None; for _ in 0..50 { - match with_cert.post(&url).header("x-tessera-admin-token", "synthetic-admin").header("content-type", "application/json").body(body.to_string()).send().await { + match with_cert + .post(&url) + .header("x-tessera-admin-token", "synthetic-admin") + .header("content-type", "application/json") + .body(body.to_string()) + .send() + .await + { Ok(response) => { answer = Some(response.status().as_u16()); break; @@ -205,15 +228,27 @@ mod tests { Err(_) => tokio::time::sleep(std::time::Duration::from_millis(100)).await, } } - assert_eq!(answer, Some(200), "a handler that requires ConnectInfo ran, so the peer address was supplied"); + assert_eq!( + answer, + Some(200), + "a handler that requires ConnectInfo ran, so the peer address was supplied" + ); // without a client certificate the TLS handshake itself is refused - let anonymous = openidconnect::reqwest::Client::builder().add_root_certificate(trusted).build().unwrap(); - assert!(anonymous.post(&url).header("x-tessera-admin-token", "synthetic-admin").header("content-type", "application/json").body(body.to_string()).send().await.is_err()); + let anonymous = openidconnect::reqwest::Client::builder() + .add_root_certificate(trusted) + .build() + .unwrap(); + assert!(anonymous + .post(&url) + .header("x-tessera-admin-token", "synthetic-admin") + .header("content-type", "application/json") + .body(body.to_string()) + .send() + .await + .is_err()); } - fn mtls_serve(mtls: WormholeMtls, app: Router) -> impl Future { - async move { - let _ = serve(mtls, app).await; - } + async fn mtls_serve(mtls: WormholeMtls, app: Router) { + let _ = serve(mtls, app).await; } } diff --git a/crates/tessera-hub/src/oidc.rs b/crates/tessera-hub/src/oidc.rs index c6ce51a..16310b0 100644 --- a/crates/tessera-hub/src/oidc.rs +++ b/crates/tessera-hub/src/oidc.rs @@ -6,9 +6,7 @@ //! from verified claims to a Tessera identity. Tokens never leave this module: //! the caller only receives an [`Identity`]. use anyhow::{bail, Context, Result}; -use openidconnect::core::{ - CoreAuthenticationFlow, CoreClient, CoreProviderMetadata, -}; +use openidconnect::core::{CoreAuthenticationFlow, CoreClient, CoreProviderMetadata}; use openidconnect::reqwest; use openidconnect::{ AccessTokenHash, AuthorizationCode, ClientId, ClientSecret, CsrfToken, EndpointMaybeSet, @@ -54,11 +52,27 @@ impl OidcConfig { /// A plain-http issuer is only accepted for a loopback host while /// `TESSERA_LOCAL_DEVELOPMENT` is on. pub fn from_env(local_development: bool) -> Result> { - let var = |name: &str| std::env::var(name).ok().map(|v| v.trim().to_string()).filter(|v| !v.is_empty()); - let Some(issuer) = var("TESSERA_OIDC_ISSUER") else { return Ok(None) }; - let need = |name: &str| var(name).with_context(|| format!("{name} is required when TESSERA_OIDC_ISSUER is set")); + let var = |name: &str| { + std::env::var(name) + .ok() + .map(|v| v.trim().to_string()) + .filter(|v| !v.is_empty()) + }; + let Some(issuer) = var("TESSERA_OIDC_ISSUER") else { + return Ok(None); + }; + let need = |name: &str| { + var(name).with_context(|| format!("{name} is required when TESSERA_OIDC_ISSUER is set")) + }; let list = |name: &str| -> BTreeSet { - var(name).map(|v| v.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect()).unwrap_or_default() + var(name) + .map(|v| { + v.split(',') + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + .collect() + }) + .unwrap_or_default() }; let config = Self { issuer, @@ -76,9 +90,16 @@ impl OidcConfig { pub fn validate(&self, allow_loopback_http: bool) -> Result<()> { check_url("TESSERA_OIDC_ISSUER", &self.issuer, allow_loopback_http)?; - check_url("TESSERA_OIDC_REDIRECT_URL", &self.redirect_url, allow_loopback_http)?; + check_url( + "TESSERA_OIDC_REDIRECT_URL", + &self.redirect_url, + allow_loopback_http, + )?; let redirect = url_parts(&self.redirect_url)?; - if redirect.path() != CALLBACK_PATH || redirect.query().is_some() || redirect.fragment().is_some() { + if redirect.path() != CALLBACK_PATH + || redirect.query().is_some() + || redirect.fragment().is_some() + { bail!("TESSERA_OIDC_REDIRECT_URL must end with exactly {CALLBACK_PATH}"); } if self.admin_subjects.is_empty() && self.admin_groups.is_empty() { @@ -126,7 +147,10 @@ impl OidcConfig { /// A missing or malformed group claim never grants anything. pub fn is_admin(&self, identity: &Identity) -> bool { self.admin_subjects.contains(&identity.subject) - || identity.groups.iter().any(|group| self.admin_groups.contains(group)) + || identity + .groups + .iter() + .any(|group| self.admin_groups.contains(group)) } } @@ -191,7 +215,9 @@ impl OidcProvider { .timeout(Duration::from_secs(15)); if let Some(path) = &config.ca_file { let pem = std::fs::read(path).with_context(|| format!("read {}", path.display()))?; - builder = builder.add_root_certificate(reqwest::Certificate::from_pem(&pem).context("TESSERA_OIDC_CA_FILE")?); + builder = builder.add_root_certificate( + reqwest::Certificate::from_pem(&pem).context("TESSERA_OIDC_CA_FILE")?, + ); } Ok(Self { http: builder.build().context("build OIDC HTTP client")?, @@ -209,7 +235,11 @@ impl OidcProvider { } async fn discover(&self) -> Result { - let metadata = CoreProviderMetadata::discover_async(IssuerUrl::new(self.config.issuer.clone())?, &self.http).await?; + let metadata = CoreProviderMetadata::discover_async( + IssuerUrl::new(self.config.issuer.clone())?, + &self.http, + ) + .await?; Ok(CoreClient::from_provider_metadata( metadata, ClientId::new(self.config.client_id.clone()), @@ -234,14 +264,23 @@ impl OidcProvider { } let mut last_attempt = self.refresh.lock().await; // Someone else may have refreshed while we waited for the lock. - let cached = self.cache.read().await.as_ref().map(|c| (c.client.clone(), c.fetched_at)); + let cached = self + .cache + .read() + .await + .as_ref() + .map(|c| (c.client.clone(), c.fetched_at)); if let Some((client, at)) = &cached { if fresh(*at) && !force { return Ok(client.clone()); } } // Without any cached client, retry sooner so recovery after an outage is quick. - let gap = if cached.is_some() { self.min_refresh } else { self.min_refresh.min(Duration::from_secs(5)) }; + let gap = if cached.is_some() { + self.min_refresh + } else { + self.min_refresh.min(Duration::from_secs(5)) + }; if last_attempt.is_some_and(|t| t.elapsed() < gap) { return cached.map(|(c, _)| c).ok_or(OidcError::Unavailable); } @@ -249,7 +288,10 @@ impl OidcProvider { match self.discover().await { Ok(client) => { let client = Arc::new(client); - *self.cache.write().await = Some(Cached { client: client.clone(), fetched_at: Instant::now() }); + *self.cache.write().await = Some(Cached { + client: client.clone(), + fetched_at: Instant::now(), + }); Ok(client) } Err(error) => { @@ -265,7 +307,11 @@ impl OidcProvider { let client = self.client(false).await?; let (challenge, verifier) = PkceCodeChallenge::new_random_sha256(); let (url, state, nonce) = client - .authorize_url(CoreAuthenticationFlow::AuthorizationCode, CsrfToken::new_random, Nonce::new_random) + .authorize_url( + CoreAuthenticationFlow::AuthorizationCode, + CsrfToken::new_random, + Nonce::new_random, + ) .add_scope(Scope::new("profile".into())) .set_pkce_challenge(challenge) .url(); @@ -279,7 +325,12 @@ impl OidcProvider { /// Exchange the code and verify the ID token. Details go to the log; the /// caller only sees `Unavailable` or `Rejected`. - pub async fn finish(&self, code: &str, nonce: &str, verifier: &str) -> Result { + pub async fn finish( + &self, + code: &str, + nonce: &str, + verifier: &str, + ) -> Result { let client = self.client(false).await?; let response = client .exchange_code(AuthorizationCode::new(code.to_string())) @@ -301,7 +352,13 @@ impl OidcProvider { let nonce = Nonce::new(nonce.to_string()); let mut client = client; for attempt in 0..2 { - match verify(&client, id_token, response.access_token(), &nonce, &self.config.groups_claim) { + match verify( + &client, + id_token, + response.access_token(), + &nonce, + &self.config.groups_claim, + ) { Ok(identity) => return Ok(identity), // Keys may have rotated since the last fetch: refresh once and retry. Err(Verify::Signature) if attempt == 0 => client = self.client(true).await?, @@ -329,7 +386,10 @@ fn verify( let verifier = client.id_token_verifier(); let claims = id_token.claims(&verifier, nonce).map_err(|error| { tracing::warn!("OIDC ID token rejected: {error}"); - if matches!(error, openidconnect::ClaimsVerificationError::SignatureVerification(_)) { + if matches!( + error, + openidconnect::ClaimsVerificationError::SignatureVerification(_) + ) { Verify::Signature } else { Verify::Other @@ -354,7 +414,12 @@ fn verify( let display_name = claims .preferred_username() .map(|n| n.as_str().to_string()) - .or_else(|| claims.name().and_then(|n| n.get(None)).map(|n| n.as_str().to_string())) + .or_else(|| { + claims + .name() + .and_then(|n| n.get(None)) + .map(|n| n.as_str().to_string()) + }) .unwrap_or_else(|| subject.clone()) .chars() .take(128) @@ -362,19 +427,31 @@ fn verify( // The signature was verified by `claims()` above, so reading one more // claim from the same token is safe. Missing or malformed means no groups. let groups = groups_from_token(&id_token.to_string(), groups_claim); - Ok(Identity { issuer: claims.issuer().as_str().to_string(), subject, display_name, groups }) + Ok(Identity { + issuer: claims.issuer().as_str().to_string(), + subject, + display_name, + groups, + }) } fn groups_from_token(jwt: &str, claim: &str) -> Vec { use base64::Engine; - let Some(payload) = jwt.split('.').nth(1) else { return vec![] }; - let Ok(bytes) = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(payload) else { return vec![] }; - let Ok(value) = serde_json::from_slice::(&bytes) else { return vec![] }; + let Some(payload) = jwt.split('.').nth(1) else { + return vec![]; + }; + let Ok(bytes) = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(payload) else { + return vec![]; + }; + let Ok(value) = serde_json::from_slice::(&bytes) else { + return vec![]; + }; match value.get(claim) { Some(serde_json::Value::String(one)) => vec![one.clone()], - Some(serde_json::Value::Array(items)) => { - items.iter().filter_map(|item| item.as_str().map(str::to_string)).collect() - } + Some(serde_json::Value::Array(items)) => items + .iter() + .filter_map(|item| item.as_str().map(str::to_string)) + .collect(), _ => vec![], } } @@ -384,7 +461,12 @@ mod tests { use super::*; fn config() -> OidcConfig { - let mut config = OidcConfig::new("https://idp.example/realm", "tessera", "secret", "https://hub.example/api/v1/auth/oidc/callback"); + let mut config = OidcConfig::new( + "https://idp.example/realm", + "tessera", + "secret", + "https://hub.example/api/v1/auth/oidc/callback", + ); config.admin_subjects.insert("admin-sub".into()); config } @@ -395,12 +477,21 @@ mod tests { assert!(c.validate(false).is_ok()); c.issuer = "http://idp.example".into(); assert!(c.validate(false).is_err()); - assert!(c.validate(true).is_err(), "non-loopback http stays rejected"); + assert!( + c.validate(true).is_err(), + "non-loopback http stays rejected" + ); c.issuer = "http://localhost:8080/realms/t".into(); assert!(c.validate(false).is_err()); - assert!(c.validate(true).is_ok(), "loopback http issuer in local development"); + assert!( + c.validate(true).is_ok(), + "loopback http issuer in local development" + ); c.redirect_url = "http://hub.example/api/v1/auth/oidc/callback".into(); - assert!(c.validate(true).is_err(), "non-loopback http redirect stays rejected"); + assert!( + c.validate(true).is_err(), + "non-loopback http redirect stays rejected" + ); c.redirect_url = "http://localhost:8787/api/v1/auth/oidc/callback".into(); assert!(c.validate(true).is_ok()); assert!(c.validate(false).is_err()); @@ -433,8 +524,14 @@ mod tests { assert!(c.is_admin(&id("admin-sub", &[]))); assert!(c.is_admin(&id("someone", &["tessera-admins"]))); assert!(!c.is_admin(&id("someone", &["other"]))); - assert!(!c.is_admin(&id("someone", &[])), "missing groups claim grants nothing"); - assert!(!c.is_admin(&id("operator", &[])), "display name is not an identifier"); + assert!( + !c.is_admin(&id("someone", &[])), + "missing groups claim grants nothing" + ); + assert!( + !c.is_admin(&id("operator", &[])), + "display name is not an identifier" + ); } #[test] @@ -455,9 +552,20 @@ mod tests { #[test] fn groups_accept_a_string_or_array_and_ignore_anything_else() { use base64::Engine; - let jwt = |json: &str| format!("h.{}.s", base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(json)); - assert_eq!(groups_from_token(&jwt(r#"{"groups":["a","b"]}"#), "groups"), ["a", "b"]); - assert_eq!(groups_from_token(&jwt(r#"{"groups":"solo"}"#), "groups"), ["solo"]); + let jwt = |json: &str| { + format!( + "h.{}.s", + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(json) + ) + }; + assert_eq!( + groups_from_token(&jwt(r#"{"groups":["a","b"]}"#), "groups"), + ["a", "b"] + ); + assert_eq!( + groups_from_token(&jwt(r#"{"groups":"solo"}"#), "groups"), + ["solo"] + ); assert!(groups_from_token(&jwt(r#"{"groups":{"a":1}}"#), "groups").is_empty()); assert!(groups_from_token(&jwt(r#"{"groups":[1,null]}"#), "groups").is_empty()); assert!(groups_from_token(&jwt(r#"{"other":["a"]}"#), "groups").is_empty()); diff --git a/crates/tessera-hub/src/refresh.rs b/crates/tessera-hub/src/refresh.rs index 6ffcfcb..7266727 100644 --- a/crates/tessera-hub/src/refresh.rs +++ b/crates/tessera-hub/src/refresh.rs @@ -22,10 +22,19 @@ pub struct RefreshConfig { impl RefreshConfig { pub fn from_env() -> Self { - let number = |name: &str| std::env::var(name).ok().and_then(|v| v.trim().parse::().ok()); + let number = |name: &str| { + std::env::var(name) + .ok() + .and_then(|v| v.trim().parse::().ok()) + }; Self { - ttl_secs: number("TESSERA_REFRESH_TTL_MINUTES").filter(|m| (1..=1440).contains(m)).unwrap_or(DEFAULT_TTL_MINUTES) * 60, - max_active: number("TESSERA_REFRESH_MAX_ACTIVE").filter(|m| (1..=64).contains(m)).unwrap_or(DEFAULT_MAX_ACTIVE), + ttl_secs: number("TESSERA_REFRESH_TTL_MINUTES") + .filter(|m| (1..=1440).contains(m)) + .unwrap_or(DEFAULT_TTL_MINUTES) + * 60, + max_active: number("TESSERA_REFRESH_MAX_ACTIVE") + .filter(|m| (1..=64).contains(m)) + .unwrap_or(DEFAULT_MAX_ACTIVE), } } } @@ -54,7 +63,13 @@ pub fn audit_name(status: &str) -> (&'static str, AuditOutcome) { pub fn audit_run(state: &HubState, run: &str, status: &str) { let (action, outcome) = audit_name(status); if let Ok(id) = Uuid::parse_str(run) { - if let Err(error) = state.db.audit_event(&Principal::Service("refresh"), AuditAction::RefreshEvent(action), AuditResource::RefreshRun(id), outcome, Uuid::new_v4()) { + if let Err(error) = state.db.audit_event( + &Principal::Service("refresh"), + AuditAction::RefreshEvent(action), + AuditResource::RefreshRun(id), + outcome, + Uuid::new_v4(), + ) { tracing::error!("could not audit refresh run {run}: {error:#}"); } } @@ -83,11 +98,21 @@ pub async fn tick(state: &HubState) -> anyhow::Result { /// Read the run's own snapshot and queue its restore. Idempotent: a second call finds the job already linked. async fn queue_restore(state: &HubState, run: &RefreshRun, snapshot: &str) -> anyhow::Result { let snapshot_id = Uuid::parse_str(snapshot)?; - let manifest = state.vault.read().await.get_snapshot(snapshot_id)?.map(|s| s.manifest); - let artifact = manifest.as_ref().and_then(|m| crate::api::artifact(m)).map(|(_, artifact)| artifact); + let manifest = state + .vault + .read() + .await + .get_snapshot(snapshot_id)? + .map(|s| s.manifest); + let artifact = manifest + .as_ref() + .and_then(crate::api::artifact) + .map(|(_, artifact)| artifact); let Some(artifact) = artifact else { // The snapshot is missing or lacks what a restore needs (format, checksum, source identity). - state.db.block_refresh_run(&run.id, "snapshot_not_restorable", now())?; + state + .db + .block_refresh_run(&run.id, "snapshot_not_restorable", now())?; audit_run(state, &run.id, "blocked"); return Ok(true); }; @@ -95,11 +120,17 @@ async fn queue_restore(state: &HubState, run: &RefreshRun, snapshot: &str) -> an let clash = match target { Some(target) => { let source = Uuid::parse_str(&run.source_orbit_id)?; - crate::api::identity_facts(state, source, &target.identity).await.map_err(|status| anyhow::anyhow!("identity check failed: {status}"))?.0 + crate::api::identity_facts(state, source, &target.identity) + .await + .map_err(|status| anyhow::anyhow!("identity check failed: {status}"))? + .0 } None => true, }; - match state.db.enqueue_refresh_restore(&run.id, &artifact, clash, now())? { + match state + .db + .enqueue_refresh_restore(&run.id, &artifact, clash, now())? + { Linked::Queued(_) => { audit_run(state, &run.id, "restoring"); Ok(true) diff --git a/crates/tessera-hub/src/state.rs b/crates/tessera-hub/src/state.rs index 927b279..a595246 100644 --- a/crates/tessera-hub/src/state.rs +++ b/crates/tessera-hub/src/state.rs @@ -75,11 +75,16 @@ impl HubState { reconstitute_sessions: Arc::new(RwLock::new(HashMap::new())), active_orbits: Arc::new(Mutex::new(HashSet::new())), admin, - sessions: SessionGate::from_env(db.clone(), oidc_config.as_ref().map(|c| c.fingerprint()))?, + sessions: SessionGate::from_env( + db.clone(), + oidc_config.as_ref().map(|c| c.fingerprint()), + )?, limits: Arc::new(crate::limits::Limits::from_env()?), exports: Arc::new(crate::exports::ExportGate::from_env()), refresh: Arc::new(crate::refresh::RefreshConfig::from_env()), - oidc: oidc_config.map(|c| crate::oidc::OidcProvider::new(c).map(Arc::new)).transpose()?, + oidc: oidc_config + .map(|c| crate::oidc::OidcProvider::new(c).map(Arc::new)) + .transpose()?, wormhole_mtls: false, accept_plain_upload: true, }) @@ -221,7 +226,10 @@ impl HubState { }; let mut deletable = Vec::new(); for id in expired { - if !active_exports.contains(&id) && !db.offsite_pending(id)? && !db.snapshot_in_restore(id)? { + if !active_exports.contains(&id) + && !db.offsite_pending(id)? + && !db.snapshot_in_restore(id)? + { deletable.push(id); } } diff --git a/crates/tessera-hub/src/upload.rs b/crates/tessera-hub/src/upload.rs index 883378f..dae77a5 100644 --- a/crates/tessera-hub/src/upload.rs +++ b/crates/tessera-hub/src/upload.rs @@ -26,9 +26,9 @@ pub fn contiguous_from_zero(ranges: &[ByteRange]) -> u64 { } pub fn write_at(file: &mut File, offset: u64, data: &[u8], total: u64) -> io::Result { - let end = offset.checked_add(data.len() as u64).ok_or_else(|| { - io::Error::new(io::ErrorKind::InvalidInput, "chunk offset overflows") - })?; + let end = offset + .checked_add(data.len() as u64) + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "chunk offset overflows"))?; if end > total { return Err(io::Error::new( io::ErrorKind::InvalidInput, @@ -47,10 +47,7 @@ mod tests { #[test] fn out_of_order_chunks_cover_the_object() { - assert_eq!( - contiguous_from_zero(&[ByteRange { start: 4, end: 8 }]), - 0 - ); + assert_eq!(contiguous_from_zero(&[ByteRange { start: 4, end: 8 }]), 0); assert_eq!( contiguous_from_zero(&[ ByteRange { start: 4, end: 8 }, diff --git a/crates/tessera-providers/src/lib.rs b/crates/tessera-providers/src/lib.rs index 28d9520..c39f0ad 100644 --- a/crates/tessera-providers/src/lib.rs +++ b/crates/tessera-providers/src/lib.rs @@ -30,12 +30,15 @@ pub struct CaptureResult { pub restore_hints: Value, } -pub fn provider_from_config(kind: &ProviderKind, config: &Value) -> Result> { +pub fn provider_from_config( + kind: &ProviderKind, + config: &Value, +) -> Result> { match kind { ProviderKind::Filesystem => Ok(Box::new(FilesystemProvider::from_config(config)?)), ProviderKind::Postgres => Ok(Box::new(PostgresProvider::from_config(config)?)), - ProviderKind::Command => anyhow::bail!( - "command provider is outside this release; use filesystem or postgres" - ), + ProviderKind::Command => { + anyhow::bail!("command provider is outside this release; use filesystem or postgres") + } } } diff --git a/crates/tessera-providers/src/postgres.rs b/crates/tessera-providers/src/postgres.rs index 8bb1261..86b08bd 100644 --- a/crates/tessera-providers/src/postgres.rs +++ b/crates/tessera-providers/src/postgres.rs @@ -72,7 +72,12 @@ impl PostgresSource { self.dump_archive(file, "custom", true).await } - async fn dump_archive(&self, file: fs::File, format: &str, preserve_permissions: bool) -> Result<()> { + async fn dump_archive( + &self, + file: fs::File, + format: &str, + preserve_permissions: bool, + ) -> Result<()> { let mut args = dump_args(format)?; if !preserve_permissions { args.extend(["--no-owner".into(), "--no-acl".into()]); diff --git a/crates/tessera-store/src/crypto.rs b/crates/tessera-store/src/crypto.rs index e44354c..7b9ffa1 100644 --- a/crates/tessera-store/src/crypto.rs +++ b/crates/tessera-store/src/crypto.rs @@ -43,7 +43,7 @@ impl VaultKey { if let Some(parent) = salt_path.parent() { fs::create_dir_all(parent)?; } - fs::write(salt_path, &salt)?; + fs::write(salt_path, salt)?; restrict_secret_file(salt_path)?; let spec = KdfSpec::argon2id(); fs::write(&marker, serde_json::to_vec_pretty(&spec)?)?; diff --git a/crates/tessera-store/src/vault.rs b/crates/tessera-store/src/vault.rs index fe3d83b..9c0f11d 100644 --- a/crates/tessera-store/src/vault.rs +++ b/crates/tessera-store/src/vault.rs @@ -14,7 +14,8 @@ use tessera_core::decay::{ use tessera_core::manifest::SnapshotManifest; use uuid::Uuid; -const RESTIC_CONFIG: &str = "{\n \"version\": 2,\n \"id\": \"tessera-restic-layout-v1\",\n \"tessera\": true\n}\n"; +const RESTIC_CONFIG: &str = + "{\n \"version\": 2,\n \"id\": \"tessera-restic-layout-v1\",\n \"tessera\": true\n}\n"; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct StoredSnapshot { @@ -173,11 +174,15 @@ impl Vault { restic_id: &str, ) -> Result { let config = self.outpost_config(manifest.orbit_id)?; - anyhow::ensure!(config.outpost_id == outpost_id, "repository belongs to another outpost"); + anyhow::ensure!( + config.outpost_id == outpost_id, + "repository belongs to another outpost" + ); let repo = self.outpost_repository(manifest.orbit_id, config); let id = manifest.snapshot_id; let expected_path = (manifest.provider != "filesystem").then_some(restic::PAYLOAD); - let summary = repo.snapshot_summary(restic_id, Some(&restic::tessera_tag(id)), expected_path)?; + let summary = + repo.snapshot_summary(restic_id, Some(&restic::tessera_tag(id)), expected_path)?; Ok(StoredSnapshot { id, taken_at: Utc::now(), @@ -310,7 +315,13 @@ impl Vault { repo.init() .context("opening the deduplicated vault (restic must be on PATH)")?; let mut cmd = repo.command(); - cmd.args(["backup", "--json", "--quiet", "--tag", &restic::tessera_tag(manifest.snapshot_id)]); + cmd.args([ + "backup", + "--json", + "--quiet", + "--tag", + &restic::tessera_tag(manifest.snapshot_id), + ]); if dry_run { cmd.arg("--dry-run"); } @@ -339,7 +350,10 @@ impl Vault { } pub fn import_legacy_payload( - &self, manifest: SnapshotManifest, payload: File, taken_at: chrono::DateTime, + &self, + manifest: SnapshotManifest, + payload: File, + taken_at: chrono::DateTime, ) -> Result { let id = manifest.snapshot_id; let receipts = self.root.join("keys/legacy-imports"); @@ -351,7 +365,8 @@ impl Vault { } let snapshots = self.root.join("snapshots"); let already_imported = || -> Result { - Ok(self.has_published_snapshot(id)? || snapshots.join(format!("{id}.expired")).try_exists()?) + Ok(self.has_published_snapshot(id)? + || snapshots.join(format!("{id}.expired")).try_exists()?) }; let imported = if already_imported()? { false @@ -378,18 +393,32 @@ impl Vault { } pub fn legacy_import_exists(&self, id: Uuid) -> Result { - Ok(self.root.join("keys/legacy-imports").join(id.to_string()).try_exists()?) + Ok(self + .root + .join("keys/legacy-imports") + .join(id.to_string()) + .try_exists()?) } - pub fn verify_prepared_payload(&self, snap: &StoredSnapshot, expected: &[u8; 32]) -> Result<()> { + pub fn verify_prepared_payload( + &self, + snap: &StoredSnapshot, + expected: &[u8; 32], + ) -> Result<()> { use sha2::{Digest, Sha256}; - let id = snap.tree_root.strip_prefix(restic::PREFIX).context("prepared payload is missing")?; + let id = snap + .tree_root + .strip_prefix(restic::PREFIX) + .context("prepared payload is missing")?; let mut file = tempfile::tempfile()?; self.restic.dump(id, restic::PAYLOAD, file.try_clone()?)?; file.seek(SeekFrom::Start(0))?; let mut digest = Sha256::new(); std::io::copy(&mut file, &mut digest)?; - anyhow::ensure!(digest.finalize()[..] == expected[..], "stored payload checksum mismatch"); + anyhow::ensure!( + digest.finalize()[..] == expected[..], + "stored payload checksum mismatch" + ); Ok(()) } @@ -405,7 +434,11 @@ impl Vault { } pub fn has_published_snapshot(&self, id: Uuid) -> Result { - Ok(self.root.join("snapshots").join(format!("{id}.json.enc")).try_exists()?) + Ok(self + .root + .join("snapshots") + .join(format!("{id}.json.enc")) + .try_exists()?) } fn index_path(&self) -> PathBuf { @@ -552,15 +585,33 @@ impl Vault { } pub fn prepare_offsite_copy(&self, id: Uuid) -> Result { - let snapshot = self.read_snapshot_file(&self.root.join("snapshots").join(format!("{id}.json.enc")))?; - anyhow::ensure!(snapshot.manifest.restore_hints.get("job_id").is_some(), "snapshot is not a capture job"); - let (source, restic_id) = if let Some(id) = snapshot.tree_root.strip_prefix(restic::OUTPOST_PREFIX) { - let orbit = snapshot.manifest.orbit_id; - (self.outpost_repository(orbit, self.outpost_config(orbit)?), id) - } else { - (self.restic.clone(), snapshot.tree_root.strip_prefix(restic::PREFIX).context("capture Restic snapshot missing")?) - }; - Ok(crate::OffsiteCopy { snapshot: id, source, restic_id: restic_id.to_owned() }) + let snapshot = + self.read_snapshot_file(&self.root.join("snapshots").join(format!("{id}.json.enc")))?; + anyhow::ensure!( + snapshot.manifest.restore_hints.get("job_id").is_some(), + "snapshot is not a capture job" + ); + let (source, restic_id) = + if let Some(id) = snapshot.tree_root.strip_prefix(restic::OUTPOST_PREFIX) { + let orbit = snapshot.manifest.orbit_id; + ( + self.outpost_repository(orbit, self.outpost_config(orbit)?), + id, + ) + } else { + ( + self.restic.clone(), + snapshot + .tree_root + .strip_prefix(restic::PREFIX) + .context("capture Restic snapshot missing")?, + ) + }; + Ok(crate::OffsiteCopy { + snapshot: id, + source, + restic_id: restic_id.to_owned(), + }) } pub fn get_snapshot(&self, id: Uuid) -> Result> { @@ -574,7 +625,9 @@ impl Vault { } pub fn restore_snapshot(&self, id: Uuid, dest: &Path) -> Result { - let snap = self.get_snapshot(id)?.context("snapshot metadata not found")?; + let snap = self + .get_snapshot(id)? + .context("snapshot metadata not found")?; let parent = dest .parent() .filter(|p| !p.as_os_str().is_empty()) @@ -583,7 +636,11 @@ impl Vault { let mut temp = tempfile::NamedTempFile::new_in(parent)?; if let Some(id) = snap.tree_root.strip_prefix(restic::OUTPOST_PREFIX) { let orbit_id = snap.manifest.orbit_id; - let path = if snap.manifest.restore_hints["format"] == "tar" { "/" } else { restic::PAYLOAD }; + let path = if snap.manifest.restore_hints["format"] == "tar" { + "/" + } else { + restic::PAYLOAD + }; self.outpost_repository(orbit_id, self.outpost_config(orbit_id)?) .dump(id, path, temp.reopen()?)?; } else if let Some(id) = snap.tree_root.strip_prefix(restic::PREFIX) { @@ -682,9 +739,14 @@ impl Vault { pub fn prune_with_decay(&mut self, preset: &str) -> Result> { let snaps = self.list_snapshots()?; - self.prune_snapshots(preset, None, snaps.into_iter() - .filter(|snapshot| snapshot.manifest.provider != "legacy-history" - && snapshot.manifest.restore_hints.get("job_id").is_none())) + self.prune_snapshots( + preset, + None, + snaps.into_iter().filter(|snapshot| { + snapshot.manifest.provider != "legacy-history" + && snapshot.manifest.restore_hints.get("job_id").is_none() + }), + ) } pub fn prune_orbit_with_decay( @@ -829,9 +891,7 @@ mod tests { paths: vec![], restore_hints: serde_json::json!({}), }; - let snap = vault - .snapshot(manifest, b"payload bytes", false) - .unwrap(); + let snap = vault.snapshot(manifest, b"payload bytes", false).unwrap(); let list = vault.list_snapshots().unwrap(); assert_eq!(list.len(), 1); assert_eq!(list[0].id, snap.id); @@ -918,7 +978,9 @@ mod tests { new_data_chunks: None, }; fs::write( - dir.path().join("snapshots").join(format!("{legacy_id}.json")), + dir.path() + .join("snapshots") + .join(format!("{legacy_id}.json")), serde_json::to_string(&legacy).unwrap(), ) .unwrap();