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:
@@ -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
@@ -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();
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
@@ -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 {
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user