chore: rustfmt the workspace and make clippy -D warnings pass

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-14 19:19:21 +07:00
parent d7fe99edd7
commit f13f0e6953
46 changed files with 6606 additions and 1496 deletions

View File

@@ -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<i64> {
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<BrowserSession> {
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"));

View File

@@ -21,7 +21,10 @@ pub(super) fn routes() -> Router<HubState> {
.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<Permission> = match (&body.role, &body.permission) {
(Some(name), None) => role(name).ok_or(StatusCode::BAD_REQUEST)?.to_vec(),
(None, Some(name)) => vec![Permission::parse(name).filter(|p| p.grantable()).ok_or(StatusCode::BAD_REQUEST)?],
(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<crate::db::access::UserRow, StatusCode> {
let user = state.db.list_users().map_err(internal)?.into_iter().find(|u| u.id == id.to_string()).ok_or(StatusCode::NOT_FOUND)?;
fn target_user(
state: &HubState,
actor: &super::routes::OperatorActor,
id: Uuid,
) -> Result<crate::db::access::UserRow, StatusCode> {
let user = state
.db
.list_users()
.map_err(internal)?
.into_iter()
.find(|u| u.id == id.to_string())
.ok_or(StatusCode::NOT_FOUND)?;
if actor.subject.user_id.as_deref() == Some(user.id.as_str()) || user.is_emergency {
return Err(StatusCode::CONFLICT);
}
@@ -207,10 +264,19 @@ async fn set_user(
) -> Result<StatusCode, StatusCode> {
let actor = admin_write(&state, peer, &headers)?;
let user = target_user(&state, &actor, id)?;
state.db.set_user_active(&user.id, body.active).map_err(internal)?;
state
.db
.audit_event(&actor.principal, AuditAction::UserState, AuditResource::User(id), AuditOutcome::Succeeded, actor.request_id)
.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<Uuid>,
) -> Result<StatusCode, StatusCode> {
let actor = admin_write(&state, peer, &headers)?;
let user = state.db.list_users().map_err(internal)?.into_iter().find(|u| u.id == id.to_string()).ok_or(StatusCode::NOT_FOUND)?;
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)
}

File diff suppressed because it is too large Load Diff

View File

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

View File

@@ -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

View File

@@ -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<Value>) -> Request<Body> {
fn request(
method: &str,
uri: &str,
peer: &str,
auth: Option<&str>,
body: Option<Value>,
) -> Request<Body> {
let mut builder = Request::builder()
.method(method)
.uri(uri)
.extension(ConnectInfo(format!("{peer}:4000").parse::<SocketAddr>().unwrap()));
.extension(ConnectInfo(
format!("{peer}:4000").parse::<SocketAddr>().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<Body>, token: &str) -> Request<Body> {
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<Body>) -> 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<T: rusqlite::types::FromSql>(&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::<Result<_, _>>().unwrap()
stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))
.unwrap()
.collect::<Result<_, _>>()
.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));
}

View File

@@ -23,7 +23,9 @@ struct Harness {
async fn harness_with(gate: Option<ExportGate>) -> 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::<Result<_, _>>().unwrap()
stmt.query_map([snapshot.to_string()], |r| Ok((r.get(0)?, r.get(1)?)))
.unwrap()
.collect::<Result<_, _>>()
.unwrap()
}
}
async fn gunzip(bytes: &[u8]) -> Vec<u8> {
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<u8> {
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<u8>, &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<u8> = line.iter().copied().cycle().take(24 * 1024 * 1024).collect();
let id = h.snapshot(serde_json::json!({"format": "plain"}), &payload).await;
let payload: Vec<u8> = 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());

View File

@@ -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<bool, StatusCode> {
permission.grantable().then(|| {
state
.db
.has_permission(actor.subject.user_id.as_deref(), &actor.subject.groups, permission.as_str(), &orbit.to_string(), now())
.map_err(internal)
})
.unwrap_or(Ok(false))
if 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<Option<Vec<String>>, StatusCode> {
pub(super) fn visible_relations(
state: &HubState,
actor: &OperatorActor,
) -> Result<Option<Vec<String>>, 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<Visible, StatusCode> {
pub(super) fn visible(
state: &HubState,
actor: &OperatorActor,
permission: Permission,
) -> Result<Visible, StatusCode> {
if actor.subject.admin {
audit(state, actor, AuditResource::Api, true)?;
return Ok(Visible::All);
@@ -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<String>| -> HashSet<Uuid> { 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<String>| -> HashSet<Uuid> {
set.iter()
.filter_map(|id| Uuid::parse_str(id).ok())
.collect()
};
let result = match wanted {
None if read.everywhere => Visible::All,
None => Visible::Only(parse(&read.orbits)),
@@ -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)
}
}

View File

@@ -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<CaptureJob, StatusCode> {
fn job_in_scope(
state: &HubState,
actor: &super::routes::OperatorActor,
id: Uuid,
) -> Result<CaptureJob, StatusCode> {
let job = state.db.capture_job(id).map_err(internal)?;
match job {
Some(job) => {
@@ -186,10 +199,18 @@ async fn claim(
Path(application): Path<Uuid>,
) -> Result<Json<Option<CaptureLease>>, 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<ResticCaptureCommit>,
) -> Result<Json<serde_json::Value>, 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<Uuid, Sta
use crate::auth::{AuditAction, AuditOutcome, AuditResource, Principal};
let result = authenticate_outpost(state, headers);
let (actor, resource, outcome) = match result {
Ok(id) => (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
}

View File

@@ -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;

View File

@@ -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<String> {
.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<ConnectInfo<SocketAddr>>, State(state): State<HubState>, headers: HeaderMap) -> Response {
let Some(oidc) = state.oidc.clone() else { return StatusCode::NOT_FOUND.into_response() };
async fn login(
peer: Option<ConnectInfo<SocketAddr>>,
State(state): State<HubState>,
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<ConnectInfo<SocketAddr>>, State(state): State<HubSta
Err(_) => 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<CallbackQuery>,
) -> 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<crate::admin::BrowserSession, &'static str> {
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<String> = identity.groups.iter().filter(|g| !g.is_empty() && g.len() <= 128).take(64).cloned().collect();
let groups: Vec<String> = identity
.groups
.iter()
.filter(|g| !g.is_empty() && g.len() <= 128)
.take(64)
.cloned()
.collect();
let now = now();
let session = state
.db
.upsert_user(&identity.issuer, &identity.subject, &identity.display_name, now)
.map_err(anyhow::Error::from)
.and_then(|user_id| state.sessions.create_oidc(&user_id, &identity.display_name, admin, &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

View File

@@ -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::<Sha256>::new(keys()[signer].clone()).sign(signing_input.as_bytes()).to_bytes()),
"RS256" => b64(SigningKey::<Sha256>::new(keys()[signer].clone())
.sign(signing_input.as_bytes())
.to_bytes()),
"HS256" => {
let mut mac = Hmac::<Sha256>::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<String, String> =
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<Value> = 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<Value> = 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<Body> {
let mut request = Request::builder().uri(uri).extension(ConnectInfo("127.0.0.1:9000".parse::<SocketAddr>().unwrap()));
let mut request = Request::builder()
.uri(uri)
.extension(ConnectInfo("127.0.0.1:9000".parse::<SocketAddr>().unwrap()));
if !cookies.is_empty() {
request = request.header(header::COOKIE, cookies.join("; "));
}
@@ -235,7 +283,12 @@ fn get(uri: &str, cookies: &[String]) -> Request<Body> {
}
fn set_cookies(response: &Response<Body>) -> Vec<String> {
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<Body>) -> 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<String, String> = target.query_pairs().into_owned().collect();
assert!(target
.as_str()
.starts_with(&format!("{}/authorize", self.idp.issuer())));
let q: std::collections::HashMap<String, String> =
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<Body> {
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<Body>, 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<T: rusqlite::types::FromSql>(&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<Body>) -> 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::<SocketAddr>().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<dyn Fn(&mut Scenario)>)> = 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<dyn Fn(&mut Scenario)>);
let cases: Vec<Case> = 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
);
}
}

View File

@@ -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<RunView, StatusCode> {
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::<Result<Vec<_>, _>>()?;
let views = runs
.iter()
.map(|run| view(&state, run, actor.subject.admin))
.collect::<Result<Vec<_>, _>>()?;
Ok((no_store(), Json(views)))
}
@@ -197,10 +260,26 @@ async fn show(
Path(id): Path<Uuid>,
) -> Result<(HeaderMap, Json<RunView>), 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())

File diff suppressed because it is too large Load Diff

View File

@@ -22,11 +22,20 @@ use uuid::Uuid;
pub(super) fn routes() -> Router<HubState> {
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<Overview>), 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::<DatabaseIdentity>(identity) else { continue };
let Some(identity) = snapshot
.manifest
.restore_hints
.get("source_identity")
.cloned()
else {
continue;
};
let Ok(identity) = serde_json::from_value::<DatabaseIdentity>(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<Retarget>,
) -> Result<Response, StatusCode> {
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<Uuid>,
) -> Result<StatusCode, StatusCode> {
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<Uuid>,
) -> Result<(HeaderMap, Json<Vec<crate::db::relations::RelationGrant>>), 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<Uuid>,
Json(body): Json<NewAccess>,
) -> Result<(StatusCode, HeaderMap, Json<crate::db::relations::RelationGrant>), StatusCode> {
) -> Result<
(
StatusCode,
HeaderMap,
Json<crate::db::relations::RelationGrant>,
),
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<StatusCode, StatusCode> {
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<Vec<MyRelation>>), 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 {

View File

@@ -28,7 +28,10 @@ pub(super) fn routes() -> Router<HubState> {
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))

View File

@@ -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<OrbitRow> for OrbitResponse {
"filesystem" => Some(OrbitSource::Filesystem),
"postgres" | "database" => Some(OrbitSource::Database),
"wormhole" => serde_json::from_str::<serde_json::Value>(&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<crate::admin::BrowserSession>,
) -> Result<OperatorActor, StatusCode> {
let configured_admin = |name: &str, principal: Principal| OperatorActor {
name: name.into(), browser: false, principal,
subject: Subject { user_id: None, groups: vec![], admin: true }, request_id,
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<OperatorActor, StatusCode> {
pub(super) fn admin_read(
state: &HubState,
peer: SocketAddr,
headers: &HeaderMap,
) -> Result<OperatorActor, StatusCode> {
let actor = authenticate(state, peer, headers, false)?;
super::gate::admin_only(state, &actor)?;
Ok(actor)
}
pub(super) fn admin_write(state: &HubState, peer: SocketAddr, headers: &HeaderMap) -> Result<OperatorActor, StatusCode> {
pub(super) fn admin_write(
state: &HubState,
peer: SocketAddr,
headers: &HeaderMap,
) -> Result<OperatorActor, StatusCode> {
let actor = authenticate(state, peer, headers, true)?;
super::gate::admin_only(state, &actor)?;
Ok(actor)
@@ -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<Uuid>,
) -> 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<std::path::PathBuf, StatusCode> {
fn browser_export_path(
state: &HubState,
requested: &str,
) -> Result<std::path::PathBuf, StatusCode> {
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<std::path::P
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => (),
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<Json<Vec<OutpostSummary>>, 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<ClaimRequest>,
) -> Result<Json<ClaimResponse>, 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<StatusCode, StatusCode> {
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::<SocketAddr>().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::<SocketAddr>().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::<SocketAddr>().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,
};

View File

@@ -32,7 +32,10 @@ pub(super) fn routes() -> Router<HubState> {
.route("/api/v1/operator/session", get(status).delete(logout))
.route("/api/v1/operator/login", post(login))
.route("/api/v1/me", get(me))
.route("/api/v1/me/preferences", get(preferences).put(set_preferences))
.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<String> = 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<Preferences>), StatusCode> {
let actor = super::routes::authenticate(&state, peer, &headers, false)?;
let stored = match actor.subject.user_id.as_deref() {
Some(user) => state.db.preferences(user).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
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<SetPreferences>,
) -> Result<StatusCode, StatusCode> {
let actor = super::routes::authenticate(&state, peer, &headers, true)?;
let user = actor.subject.user_id.as_deref().ok_or(StatusCode::NOT_FOUND)?;
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::<SocketAddr>().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

View File

@@ -174,8 +174,18 @@ impl Permission {
pub fn parse(text: &str) -> Option<Self> {
[
Self::OrbitRead, Self::SnapshotRead, Self::CaptureRun, Self::SnapshotDownload, Self::OrbitManage,
Self::OutpostManage, Self::RetentionManage, Self::SnapshotDelete, Self::RecoveryManage, Self::AccessManage, 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
)
}
}

View File

@@ -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<Vec<OutpostSummary>> {
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::<rusqlite::Result<_>>()?)
}
@@ -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(())
}

View File

@@ -107,7 +107,12 @@ impl Db {
}
pub fn delete_grant(&self, id: &str) -> Result<bool> {
Ok(self.conn.lock().unwrap().execute("DELETE FROM access_grants WHERE id=?1", params![id])? == 1)
Ok(self
.conn
.lock()
.unwrap()
.execute("DELETE FROM access_grants WHERE id=?1", params![id])?
== 1)
}
pub fn list_grants(&self) -> Result<Vec<Grant>> {
@@ -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<bool> {
pub fn has_permission(
&self,
user: Option<&str>,
groups: &[String],
permission: &str,
orbit: &str,
now: i64,
) -> Result<bool> {
let conn = self.conn.lock().unwrap();
Ok(conn.query_row(
&format!(
@@ -147,12 +159,20 @@ impl Db {
)?)
}
pub fn permitted_orbits(&self, user: Option<&str>, groups: &[String], permission: &str, now: i64) -> Result<Permitted> {
pub fn permitted_orbits(
&self,
user: Option<&str>,
groups: &[String],
permission: &str,
now: i64,
) -> Result<Permitted> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(&format!(
"SELECT scope_type, scope_id FROM access_grants WHERE permission=?1 AND {LIVE}"
))?;
let rows = stmt.query_map(params![permission, now, user, groups_json(groups)], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
let 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<Vec<(String, Option<String>)>> {
pub fn grants_of(
&self,
user: Option<&str>,
groups: &[String],
now: i64,
) -> Result<Vec<(String, Option<String>)>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(&format!(
"SELECT permission, scope_type, scope_id FROM access_grants WHERE (expires_at IS NULL OR expires_at > ?1)
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::<rusqlite::Result<_>>()?)
}
@@ -200,14 +226,21 @@ impl Db {
}
pub fn user_exists(&self, id: &str) -> Result<bool> {
Ok(self.conn.lock().unwrap().query_row("SELECT EXISTS(SELECT 1 FROM users WHERE id=?1)", params![id], |r| r.get(0))?)
Ok(self.conn.lock().unwrap().query_row(
"SELECT EXISTS(SELECT 1 FROM users WHERE id=?1)",
params![id],
|r| r.get(0),
)?)
}
/// Enable or disable a user. Disabling also ends every session at once.
pub fn set_user_active(&self, id: &str, active: bool) -> Result<bool> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction()?;
let changed = tx.execute("UPDATE users SET active=?2, generation=generation+1 WHERE id=?1", params![id, active])? == 1;
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<std::collections::BTreeMap<String, String>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare("SELECT key, value FROM user_preferences WHERE user_id=?1")?;
let rows = stmt.query_map(params![user], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
let rows = stmt.query_map(params![user], |r| {
Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))
})?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
@@ -233,14 +268,22 @@ impl Db {
}
pub fn orbit_exists(&self, id: &str) -> Result<bool> {
Ok(self.conn.lock().unwrap().query_row("SELECT EXISTS(SELECT 1 FROM orbits WHERE id=?1)", params![id], |r| r.get(0))?)
Ok(self.conn.lock().unwrap().query_row(
"SELECT EXISTS(SELECT 1 FROM orbits WHERE id=?1)",
params![id],
|r| r.get(0),
)?)
}
/// The orbit an application (capture profile) belongs to.
pub fn orbit_of_application(&self, application: Uuid) -> Result<Option<Uuid>> {
let conn = self.conn.lock().unwrap();
let orbit: Option<String> = conn
.query_row("SELECT orbit_id FROM capture_profiles WHERE application_id=?1", params![application.to_string()], |r| r.get(0))
.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<i64>) -> 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<i64>,
) -> NewGrant<'a> {
NewGrant {
principal_type: kind,
principal: who,
permission,
orbit,
expires_at: expires,
created_by: "test",
}
}
#[tokio::test]
async fn a_grant_applies_to_its_user_scope_and_permission_only() {
let (_d, db) = db().await;
db.add_grant(&grant("user", "u1", "orbit.read", Some("orbit-a"), None), 10).unwrap().unwrap();
let has = |user: &str, perm: &str, orbit: &str| db.has_permission(Some(user), &[], perm, orbit, 20).unwrap();
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());
}
}

View File

@@ -90,7 +90,16 @@ fn migrate_legacy(conn: &Connection) -> Result<()> {
let mut codes = 0;
let rows: Vec<(String, String, String, String, Option<String>, 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::<rusqlite::Result<_>>()?
};
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<Option<Issued>> {
pub fn claim_pairing(
&self,
code: &str,
outpost_name: &str,
now: i64,
) -> Result<Option<Issued>> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction()?;
let outpost: Option<String> = 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<Option<Issued>> {
pub fn rotate_credential(
&self,
outpost: &str,
grace_secs: i64,
now: i64,
) -> Result<Option<Issued>> {
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());
}
}

View File

@@ -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::<rusqlite::Result<_>>()?)
@@ -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<Option<Uuid>> {
pub(super) fn insert_capture_job(
conn: &Connection,
application_id: Uuid,
actor: &str,
now: i64,
) -> Result<Option<Uuid>> {
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);
}

View File

@@ -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<bool> {
pub fn begin_oidc_login(
&self,
state: &str,
browser: &str,
nonce: &str,
verifier: &str,
now: i64,
) -> Result<bool> {
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<Option<(String, String)>> {
pub fn consume_oidc_login(
&self,
state: &str,
browser: Option<&str>,
now: i64,
) -> Result<Option<(String, String)>> {
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());
}
}

View File

@@ -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<RefreshRun> {
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<Option<RefreshRun>> {
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<Option<RefreshRun>> {
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<Option<Relation>> {
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<String> =
conn.query_row("SELECT profile FROM restore_targets WHERE id=?1", params![relation.target_id], |r| r.get(0)).optional()?;
let target_profile: Option<String> = 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::<serde_json::Value>(&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<Option<&'static str>> {
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<Option<&'static str>> {
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<Option<String>> {
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<Vec<RefreshRun>> {
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::<rusqlite::Result<_>>()?;
let rows = stmt
.query_map([], read_run)?
.collect::<rusqlite::Result<_>>()?;
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<Vec<RefreshRun>> {
pub fn refresh_runs(
&self,
requester_user: Option<&str>,
relations: Option<&[String]>,
limit: i64,
) -> Result<Vec<RefreshRun>> {
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::<rusqlite::Result<_>>()?;
let rows = stmt
.query_map(params![requester_user, relations_json, limit], read_run)?
.collect::<rusqlite::Result<_>>()?;
Ok(rows)
}
@@ -278,10 +366,20 @@ impl Db {
pub fn refresh_progress(&self, run: &RefreshRun) -> Result<Progress> {
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<Linked> {
pub fn enqueue_refresh_restore(
&self,
id: &str,
artifact: &RestoreArtifact,
identity_clash: bool,
now: i64,
) -> Result<Linked> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
let outcome = (|| -> Result<Linked> {
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<String>)> = 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<std::result::Result<RefreshRun, CancelError>> {
pub fn cancel_refresh_run(
&self,
id: &str,
now: i64,
) -> Result<std::result::Result<RefreshRun, CancelError>> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
let result = (|| -> Result<std::result::Result<RefreshRun, CancelError>> {
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<Sync> {
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<Sync> {
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<Sync> {
@@ -449,11 +587,19 @@ fn sync_in(tx: &Transaction<'_>, id: &str, now: i64) -> Result<Sync> {
match run.status.as_str() {
"capturing" => {
let capture: Option<(String, Option<String>)> = 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),
}

View File

@@ -138,7 +138,10 @@ pub(super) fn migrate(conn: &Connection) -> Result<()> {
}
fn engine_of_profile(profile: &str) -> Option<Engine> {
serde_json::from_str::<tessera_core::job::CaptureProfile>(profile).ok()?.format.engine()
serde_json::from_str::<tessera_core::job::CaptureProfile>(profile)
.ok()?
.format
.engine()
}
pub(super) fn read_relation(r: &rusqlite::Row<'_>) -> rusqlite::Result<Relation> {
@@ -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<Option<&'static str>> {
pub(super) fn unusable(
conn: &Connection,
relation: &Relation,
now: i64,
) -> rusqlite::Result<Option<&'static str>> {
if !relation.active {
return Ok(Some("deactivated"));
}
let target_env: Option<String> =
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<String> = 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<String>, Option<String>) = (
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<bool> {
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<Option<Vec<String>>> {
pub fn set_target_environment(
&self,
target: Uuid,
environment: &str,
now: i64,
) -> Result<Option<Vec<String>>> {
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::<rusqlite::Result<_>>()?;
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::<rusqlite::Result<_>>()?;
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<std::result::Result<Relation, Reject>> {
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<String> = 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<String> = 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::<tessera_core::restore::RestoreTarget>(&target_profile).ok().map(|t| t.engine);
let target_engine =
serde_json::from_str::<tessera_core::restore::RestoreTarget>(&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<Option<Relation>> {
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<Vec<RelationView>> {
pub fn relation_views(
&self,
active_only: bool,
only: Option<&[String]>,
now: i64,
) -> Result<Vec<RelationView>> {
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<Relation> = stmt.query_map(params![active_only, restriction], read_relation)?.collect::<rusqlite::Result<_>>()?;
let relations: Vec<Relation> = stmt
.query_map(params![active_only, restriction], read_relation)?
.collect::<rusqlite::Result<_>>()?;
drop(stmt);
let mut out = Vec::new();
for relation in relations {
let name = |sql: &str, id: &str| -> rusqlite::Result<String> {
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<Option<String>> {
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::<serde_json::Value>(
&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::<serde_json::Value>(&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<String, String>, std::collections::HashMap<String, String>)> {
pub fn environments(
&self,
) -> Result<(
std::collections::HashMap<String, String>,
std::collections::HashMap<String, String>,
)> {
let conn = self.conn.lock().unwrap();
let read = |sql: &str| -> rusqlite::Result<std::collections::HashMap<String, String>> {
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<Vec<(RestoreTarget, bool)>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare("SELECT profile FROM restore_targets ORDER BY id")?;
let profiles: Vec<String> = stmt.query_map([], |r| r.get(0))?.collect::<rusqlite::Result<_>>()?;
let profiles: Vec<String> = stmt
.query_map([], |r| r.get(0))?
.collect::<rusqlite::Result<_>>()?;
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<Option<RestoreTarget>> {
let profile: Option<String> = 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<String> = 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<Option<String>> {
pub fn granting_relation_grant(
&self,
user: Option<&str>,
groups: &[String],
relation: &str,
now: i64,
) -> Result<Option<String>> {
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<i64>, created_by: &str, now: i64) -> Result<Option<RelationGrant>> {
pub fn add_relation_grant(
&self,
principal_type: &str,
principal: &str,
relation: &str,
expires_at: Option<i64>,
created_by: &str,
now: i64,
) -> Result<Option<RelationGrant>> {
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<bool> {
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<Vec<RelationGrant>> {
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::<rusqlite::Result<_>>()?)
}
/// 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<Vec<String>> {
pub fn granted_relations(
&self,
user: Option<&str>,
groups: &[String],
now: i64,
) -> Result<Vec<String>> {
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::<rusqlite::Result<Vec<_>>>()?;
let rows = stmt
.query_map(params![now, user, groups_json], |r| r.get::<_, String>(0))?
.collect::<rusqlite::Result<Vec<_>>>()?;
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<Relation, Reject> {
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"
);
}
}

View File

@@ -101,18 +101,27 @@ impl Db {
}
pub fn restore_targets(&self, application: Uuid) -> Result<Vec<RestoreTarget>> {
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<Vec<(RestoreTarget, bool)>> {
pub fn restore_targets_with_activity(
&self,
application: Uuid,
) -> Result<Vec<(RestoreTarget, bool)>> {
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::<rusqlite::Result<_>>()?)
}
@@ -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<Option<RestoreJob>> {
let registered: Option<RestoreTarget> = tx.query_row(
let registered: Option<RestoreTarget> = 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(&registered, 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(&registered, 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(&registered.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(&registered.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<_>>(), vec![next.id, job.id]);
assert_eq!(
recent.iter().map(|item| item.id).collect::<Vec<_>>(),
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());

View File

@@ -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<String> {
pub fn upsert_user(
&self,
issuer: &str,
subject: &str,
display_name: &str,
now: i64,
) -> Result<String> {
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<bool> {
let conn = self.conn.lock().unwrap();
conn.execute("DELETE FROM sessions WHERE expires_at <= ?1 OR last_seen + ?2 <= ?1", params![now, IDLE_SECS])?;
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<usize> {
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());
}
}

View File

@@ -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::<u64>().ok());
let number = |name: &str| {
std::env::var(name)
.ok()
.and_then(|v| v.trim().parse::<u64>().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<OwnedSemaphorePermit, Refused> {
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<u64> {
/// 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<S> {
}
impl<S> Guarded<S> {
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<S> Drop for Guarded<S> {
} 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<u8>, &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"
);
}
}

View File

@@ -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::<IpAddr>().map_err(|_| anyhow::anyhow!("TESSERA_TRUSTED_PROXIES: invalid IP {item}"))?);
proxies.push(
item.parse::<IpAddr>().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<SocketAddr>, 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::<IpAddr>().unwrap(), "untrusted peer cannot choose its key");
assert_eq!(l.source(peer("10.0.0.1"), &spoof), "198.51.100.9".parse::<IpAddr>().unwrap());
assert_eq!(
l.source(peer("203.0.113.7"), &spoof),
"203.0.113.7".parse::<IpAddr>().unwrap(),
"untrusted peer cannot choose its key"
);
assert_eq!(
l.source(peer("10.0.0.1"), &spoof),
"198.51.100.9".parse::<IpAddr>().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::<IpAddr>().unwrap());
assert_eq!(
l.source(peer("10.0.0.1"), &chain),
"198.51.100.9".parse::<IpAddr>().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::<IpAddr>().unwrap());
assert_eq!(l.source(peer("10.0.0.1"), &HeaderMap::new()), "10.0.0.1".parse::<IpAddr>().unwrap());
assert_eq!(
l.source(peer("10.0.0.1"), &headers("not-an-ip")),
"10.0.0.1".parse::<IpAddr>().unwrap()
);
assert_eq!(
l.source(peer("10.0.0.1"), &HeaderMap::new()),
"10.0.0.1".parse::<IpAddr>().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::<IpAddr>().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::<IpAddr>().unwrap()
);
assert_eq!(
l.source(None, &HeaderMap::new()),
IpAddr::V6(Ipv6Addr::UNSPECIFIED)
);
}
#[test]

View File

@@ -1,6 +1,6 @@
mod admin;
mod auth;
mod api;
mod auth;
mod db;
mod exports;
mod limits;

View File

@@ -34,15 +34,12 @@ pub fn from_env() -> Result<Option<WormholeMtls>> {
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<Request<Incoming>> 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<PrivateKeyDer<'static>> {
pub fn load_ca(path: &Path) -> Result<RootCertStore> {
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<RootCertStore> {
#[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<Output = ()> {
async move {
let _ = serve(mtls, app).await;
}
async fn mtls_serve(mtls: WormholeMtls, app: Router) {
let _ = serve(mtls, app).await;
}
}

View File

@@ -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<Option<Self>> {
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<String> {
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<Client> {
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<Identity, OidcError> {
pub async fn finish(
&self,
code: &str,
nonce: &str,
verifier: &str,
) -> Result<Identity, OidcError> {
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<String> {
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::<serde_json::Value>(&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::<serde_json::Value>(&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());

View File

@@ -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::<i64>().ok());
let number = |name: &str| {
std::env::var(name)
.ok()
.and_then(|v| v.trim().parse::<i64>().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<usize> {
/// 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<bool> {
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)

View File

@@ -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);
}
}

View File

@@ -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<ByteRange> {
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 },