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