PostgreSQL and MySQL backups run through paired outposts, with operator sign-in, off-site copies, and legacy import. Retention stays on each orbit, so the unused retention console is removed. Co-authored-by: Cursor <cursoragent@cursor.com>
1181 lines
42 KiB
Rust
1181 lines
42 KiB
Rust
use crate::db::OrbitRow;
|
|
use crate::state::{HubState, ManagedRetention};
|
|
use crate::upload::write_at;
|
|
use axum::{
|
|
extract::{ConnectInfo, Path, State},
|
|
http::{header, HeaderMap, HeaderValue, StatusCode, Uri},
|
|
response::IntoResponse,
|
|
routing::{get, post, put},
|
|
Json, Router,
|
|
};
|
|
use base64::Engine;
|
|
use rand::Rng;
|
|
use tessera_core::OutpostSummary;
|
|
use include_dir::{include_dir, Dir};
|
|
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 tower_http::trace::TraceLayer;
|
|
use utoipa::OpenApi;
|
|
use uuid::Uuid;
|
|
|
|
static WEB_DIST: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/../../web/dist");
|
|
|
|
#[derive(OpenApi)]
|
|
#[openapi(
|
|
paths(
|
|
health,
|
|
list_snapshots,
|
|
list_orbits,
|
|
create_orbit,
|
|
update_orbit_retention,
|
|
trigger_orbit,
|
|
start_reconstitute,
|
|
pairing_start,
|
|
pairing_claim,
|
|
wormhole_upload_init,
|
|
wormhole_upload_chunk,
|
|
wormhole_restic_commit,
|
|
),
|
|
components(schemas(
|
|
SnapshotSummary,
|
|
CaptureSnapshotSummary,
|
|
OrbitResponse,
|
|
CreateOrbitRequest,
|
|
OrbitSource,
|
|
OrbitAccess,
|
|
RetentionUpdate,
|
|
RetentionPolicy,
|
|
ReconstituteRequest,
|
|
ReconstituteSession,
|
|
PairingResponse,
|
|
ClaimRequest,
|
|
ClaimResponse,
|
|
UploadInit,
|
|
UploadChunk,
|
|
ResticCommit,
|
|
))
|
|
)]
|
|
struct ApiDoc;
|
|
|
|
#[derive(serde::Serialize, utoipa::ToSchema)]
|
|
struct SnapshotSummary {
|
|
id: Uuid,
|
|
orbit_id: Uuid,
|
|
taken_at: chrono::DateTime<chrono::Utc>,
|
|
orbit_name: String,
|
|
size_bytes: u64,
|
|
capture: Option<CaptureSnapshotSummary>,
|
|
stored_bytes: Option<u64>,
|
|
new_data_chunks: Option<u64>,
|
|
}
|
|
|
|
#[derive(serde::Serialize, utoipa::ToSchema)]
|
|
struct CaptureSnapshotSummary {
|
|
job_id: Uuid,
|
|
application_id: Uuid,
|
|
engine: &'static str,
|
|
format: &'static str,
|
|
restore_ready: bool,
|
|
}
|
|
|
|
impl CaptureSnapshotSummary {
|
|
fn from_manifest(manifest: &SnapshotManifest) -> Option<Self> {
|
|
let hints = &manifest.restore_hints;
|
|
let job_id = Uuid::parse_str(hints.get("job_id")?.as_str()?).ok()?;
|
|
let application_id = Uuid::parse_str(hints.get("application_id")?.as_str()?).ok()?;
|
|
let (engine, format) = match (manifest.provider.as_str(), hints.get("format")?.as_str()?) {
|
|
("postgres", "custom") => ("postgres", "custom"),
|
|
("postgres", "plain") => ("postgres", "plain"),
|
|
("mysql", "plain") => ("mysql", "plain"),
|
|
_ => return None,
|
|
};
|
|
Some(Self {
|
|
job_id, application_id, engine, format,
|
|
restore_ready: super::restore::artifact(manifest).is_some(),
|
|
})
|
|
}
|
|
}
|
|
|
|
#[derive(serde::Serialize, utoipa::ToSchema)]
|
|
struct OrbitResponse {
|
|
id: Uuid,
|
|
name: String,
|
|
provider: String,
|
|
source: Option<OrbitSource>,
|
|
access: OrbitAccess,
|
|
schedule: Option<String>,
|
|
decay_preset: String,
|
|
retention: Option<RetentionPolicy>,
|
|
dry_run: bool,
|
|
last_status: String,
|
|
application_id: Option<Uuid>,
|
|
#[schema(value_type = Option<Object>)]
|
|
capture_schedule: Option<tessera_core::job::CaptureSchedule>,
|
|
#[schema(value_type = Option<Object>)]
|
|
capture_retention: Option<tessera_core::decay::CaptureRetention>,
|
|
retention_source: &'static str,
|
|
}
|
|
|
|
impl From<OrbitRow> for OrbitResponse {
|
|
fn from(row: OrbitRow) -> Self {
|
|
let source = match row.provider.as_str() {
|
|
"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()),
|
|
_ => None,
|
|
};
|
|
let access = if row.provider == "wormhole" { OrbitAccess::Outpost } else { OrbitAccess::Hub };
|
|
Self {
|
|
source,
|
|
access,
|
|
id: row.id,
|
|
name: row.name,
|
|
provider: row.provider,
|
|
schedule: row.schedule,
|
|
decay_preset: row.decay_preset,
|
|
retention: row.retention,
|
|
dry_run: row.dry_run,
|
|
last_status: row.last_status,
|
|
application_id: None,
|
|
capture_schedule: None,
|
|
capture_retention: None,
|
|
retention_source: "orbit",
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Copy, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
|
|
#[serde(rename_all = "snake_case")]
|
|
enum OrbitSource {
|
|
Filesystem,
|
|
Database,
|
|
}
|
|
|
|
#[derive(serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
|
|
#[serde(rename_all = "snake_case")]
|
|
enum OrbitAccess {
|
|
Hub,
|
|
Outpost,
|
|
}
|
|
|
|
#[derive(serde::Deserialize, utoipa::ToSchema)]
|
|
struct CreateOrbitRequest {
|
|
name: String,
|
|
provider: Option<String>,
|
|
source: Option<OrbitSource>,
|
|
access: Option<OrbitAccess>,
|
|
provider_config: serde_json::Value,
|
|
schedule: Option<String>,
|
|
decay_preset: Option<String>,
|
|
retention: Option<RetentionPolicy>,
|
|
dry_run: Option<bool>,
|
|
}
|
|
|
|
#[derive(serde::Deserialize, utoipa::ToSchema)]
|
|
struct RetentionUpdate {
|
|
decay_preset: Option<String>,
|
|
retention: Option<RetentionPolicy>,
|
|
}
|
|
|
|
#[derive(serde::Deserialize, utoipa::ToSchema)]
|
|
struct ReconstituteRequest {
|
|
snapshot_id: Uuid,
|
|
target_path: String,
|
|
}
|
|
|
|
#[derive(serde::Serialize, utoipa::ToSchema)]
|
|
struct PairingResponse {
|
|
code: String,
|
|
expires_at: chrono::DateTime<chrono::Utc>,
|
|
}
|
|
|
|
#[derive(serde::Deserialize, utoipa::ToSchema)]
|
|
struct ClaimRequest {
|
|
code: String,
|
|
outpost_name: String,
|
|
}
|
|
|
|
#[derive(serde::Serialize, utoipa::ToSchema)]
|
|
struct ClaimResponse {
|
|
outpost_id: Uuid,
|
|
upload_token: String,
|
|
hub_url: String,
|
|
}
|
|
|
|
#[derive(serde::Deserialize, utoipa::ToSchema)]
|
|
struct UploadInit {
|
|
orbit_id: Uuid,
|
|
total_bytes: Option<u64>,
|
|
}
|
|
|
|
#[derive(serde::Deserialize, utoipa::ToSchema)]
|
|
struct UploadChunk {
|
|
session_id: Uuid,
|
|
offset: u64,
|
|
data_b64: String,
|
|
}
|
|
|
|
#[derive(serde::Deserialize, utoipa::ToSchema)]
|
|
struct ResticCommit {
|
|
orbit_id: Uuid,
|
|
snapshot_id: String,
|
|
}
|
|
|
|
#[derive(serde::Serialize, utoipa::ToSchema)]
|
|
struct ReconstituteStartResponse {
|
|
session_id: Uuid,
|
|
session: ReconstituteSession,
|
|
}
|
|
|
|
pub(super) struct OperatorActor {
|
|
pub(super) name: String,
|
|
browser: bool,
|
|
}
|
|
|
|
impl std::fmt::Display for OperatorActor {
|
|
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
self.name.fmt(formatter)
|
|
}
|
|
}
|
|
|
|
pub(super) fn require_admin(
|
|
state: &HubState,
|
|
peer: SocketAddr,
|
|
headers: &HeaderMap,
|
|
) -> Result<(), StatusCode> {
|
|
authorize_operator(state, peer, headers, false).map(|_| ())
|
|
}
|
|
|
|
pub(super) fn require_admin_mutation(
|
|
state: &HubState,
|
|
peer: SocketAddr,
|
|
headers: &HeaderMap,
|
|
) -> Result<OperatorActor, StatusCode> {
|
|
authorize_operator(state, peer, headers, true)
|
|
}
|
|
|
|
fn authorize_operator(
|
|
state: &HubState,
|
|
peer: SocketAddr,
|
|
headers: &HeaderMap,
|
|
mutation: bool,
|
|
) -> Result<OperatorActor, StatusCode> {
|
|
if state.admin.token.is_some() && state.admin.authorize(peer, headers).is_ok() {
|
|
return Ok(OperatorActor { name: "api-token".into(), browser: false });
|
|
}
|
|
if let Some(session) = state.sessions.active(headers) {
|
|
if mutation {
|
|
super::session::require_csrf(headers, &session.csrf.to_string())?;
|
|
}
|
|
return Ok(OperatorActor { name: session.actor, browser: true });
|
|
}
|
|
if !state.sessions.enabled() {
|
|
state.admin.authorize(peer, headers)?;
|
|
return Ok(OperatorActor { name: "loopback".into(), browser: false });
|
|
}
|
|
Err(StatusCode::UNAUTHORIZED)
|
|
}
|
|
|
|
pub fn router(state: HubState) -> Router {
|
|
let api = Router::new()
|
|
.route("/health", get(health))
|
|
.route("/api/v1/snapshots", get(list_snapshots))
|
|
.route("/api/v1/orbits", get(list_orbits).post(create_orbit))
|
|
.route("/api/v1/orbits/:id/retention", put(update_orbit_retention))
|
|
.route("/api/v1/orbits/:id/run", post(trigger_orbit))
|
|
.route("/api/v1/reconstitute", post(start_reconstitute))
|
|
.route(
|
|
"/api/v1/reconstitute/:id",
|
|
get(reconstitute_status).delete(abort_reconstitute),
|
|
)
|
|
.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/upload/init", post(wormhole_upload_init))
|
|
.route("/api/v1/wormhole/upload/chunk", post(wormhole_upload_chunk))
|
|
.route(
|
|
"/api/v1/wormhole/restic/commit",
|
|
post(wormhole_restic_commit),
|
|
)
|
|
.merge(super::jobs::routes())
|
|
.merge(super::catalog::routes())
|
|
.merge(super::session::routes())
|
|
.merge(super::restore::routes())
|
|
.with_state(state);
|
|
|
|
let api = api.route(
|
|
"/api-doc/openapi.json",
|
|
get(|| async { Json(ApiDoc::openapi()) }),
|
|
);
|
|
|
|
api.fallback(spa_fallback)
|
|
.layer(TraceLayer::new_for_http())
|
|
}
|
|
|
|
#[utoipa::path(get, path = "/health", responses((status = 200, description = "ok")))]
|
|
async fn health() -> &'static str {
|
|
"vault online"
|
|
}
|
|
|
|
#[utoipa::path(get, path = "/api/v1/snapshots", responses((status = 200, body = [SnapshotSummary])))]
|
|
async fn list_snapshots(
|
|
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
|
State(state): State<HubState>,
|
|
headers: HeaderMap,
|
|
) -> Result<Json<Vec<SnapshotSummary>>, StatusCode> {
|
|
require_admin(&state, peer, &headers)?;
|
|
let vault = state.vault.read().await;
|
|
let snaps = vault.list_snapshots().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
let out = snaps
|
|
.into_iter()
|
|
.filter(|s| s.manifest.provider != "legacy-history")
|
|
.map(|s| SnapshotSummary {
|
|
id: s.id,
|
|
orbit_id: s.manifest.orbit_id,
|
|
taken_at: s.taken_at,
|
|
capture: CaptureSnapshotSummary::from_manifest(&s.manifest),
|
|
orbit_name: s.manifest.orbit_name,
|
|
size_bytes: s.size_bytes,
|
|
stored_bytes: s.stored_bytes,
|
|
new_data_chunks: s.new_data_chunks,
|
|
})
|
|
.collect();
|
|
Ok(Json(out))
|
|
}
|
|
|
|
#[utoipa::path(get, path = "/api/v1/orbits", responses((status = 200, body = [OrbitResponse])))]
|
|
async fn list_orbits(
|
|
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
|
State(state): State<HubState>,
|
|
headers: HeaderMap,
|
|
) -> Result<Json<Vec<OrbitResponse>>, StatusCode> {
|
|
require_admin(&state, peer, &headers)?;
|
|
let profiles: std::collections::HashMap<_, _> = state
|
|
.db
|
|
.capture_profiles()
|
|
.map_err(super::jobs::internal)?
|
|
.into_iter()
|
|
.map(|profile| (profile.orbit_id, profile))
|
|
.collect();
|
|
let rows = state.db.list_orbits().await.map_err(super::jobs::internal)?;
|
|
let responses = rows
|
|
.into_iter()
|
|
.map(|row| {
|
|
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.capture_schedule = profile.schedule.clone();
|
|
(response.capture_retention, response.retention_source) =
|
|
match ManagedRetention::resolve(profile, response.retention) {
|
|
ManagedRetention::Orbit(_) => (None, "orbit"),
|
|
ManagedRetention::Profile(policy) => (Some(policy), "profile"),
|
|
ManagedRetention::Default(policy) => (Some(policy), "default"),
|
|
};
|
|
}
|
|
response
|
|
})
|
|
.collect();
|
|
Ok(Json(responses))
|
|
}
|
|
|
|
#[utoipa::path(post, path = "/api/v1/orbits", request_body = CreateOrbitRequest, responses((status = 200, body = OrbitResponse), (status = 400)))]
|
|
async fn create_orbit(
|
|
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
|
State(state): State<HubState>,
|
|
headers: HeaderMap,
|
|
Json(req): Json<CreateOrbitRequest>,
|
|
) -> Result<Json<OrbitResponse>, (StatusCode, &'static str)> {
|
|
require_admin_mutation(&state, peer, &headers).map_err(|status| (status, "unauthorized"))?;
|
|
if req.name.trim().is_empty() {
|
|
return Err((StatusCode::BAD_REQUEST, "orbit name is required"));
|
|
}
|
|
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"))?;
|
|
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"));
|
|
}
|
|
("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"))?;
|
|
if !source.valid_endpoint() {
|
|
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())
|
|
&& !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),
|
|
_ => return Err((StatusCode::BAD_REQUEST, "invalid backup source or access")),
|
|
};
|
|
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"));
|
|
}
|
|
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"))?;
|
|
}
|
|
let row = OrbitRow {
|
|
id: Uuid::new_v4(),
|
|
name: req.name,
|
|
provider: provider.to_owned(),
|
|
provider_config: config.to_string(),
|
|
schedule,
|
|
decay_preset,
|
|
retention,
|
|
dry_run: req.dry_run.unwrap_or(false),
|
|
last_status: "idle".into(),
|
|
};
|
|
state
|
|
.db
|
|
.upsert_orbit(&row)
|
|
.await
|
|
.map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "could not save orbit"))?;
|
|
Ok(Json(row.into()))
|
|
}
|
|
|
|
fn retention_settings(
|
|
preset: Option<String>,
|
|
retention: Option<RetentionPolicy>,
|
|
) -> Result<(String, Option<RetentionPolicy>), (StatusCode, &'static str)> {
|
|
if preset.is_some() && retention.is_some() {
|
|
return Err((
|
|
StatusCode::BAD_REQUEST,
|
|
"choose a preset or custom retention",
|
|
));
|
|
}
|
|
if retention.is_some_and(|policy| !policy.has_tiers()) {
|
|
return Err((
|
|
StatusCode::BAD_REQUEST,
|
|
"set at least one retention count above zero",
|
|
));
|
|
}
|
|
Ok((
|
|
preset.unwrap_or_else(|| "week-of-dailies".into()),
|
|
retention,
|
|
))
|
|
}
|
|
|
|
#[utoipa::path(put, path = "/api/v1/orbits/{id}/retention", params(("id" = Uuid, Path, description = "orbit id")), request_body = RetentionUpdate, responses((status = 204), (status = 400), (status = 404)))]
|
|
async fn update_orbit_retention(
|
|
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
|
State(state): State<HubState>,
|
|
headers: HeaderMap,
|
|
Path(id): Path<Uuid>,
|
|
Json(req): Json<RetentionUpdate>,
|
|
) -> Result<StatusCode, (StatusCode, &'static str)> {
|
|
require_admin_mutation(&state, peer, &headers).map_err(|status| (status, "unauthorized"))?;
|
|
if req.decay_preset.is_none() && req.retention.is_none() {
|
|
return Err((
|
|
StatusCode::BAD_REQUEST,
|
|
"choose a preset or custom retention",
|
|
));
|
|
}
|
|
let (preset, retention) = retention_settings(req.decay_preset, req.retention)?;
|
|
let saved = state
|
|
.db
|
|
.set_orbit_retention(id, &preset, retention.as_ref())
|
|
.map_err(|_| {
|
|
(
|
|
StatusCode::INTERNAL_SERVER_ERROR,
|
|
"could not save retention",
|
|
)
|
|
})?;
|
|
if !saved {
|
|
return Err((StatusCode::NOT_FOUND, "orbit not found"));
|
|
}
|
|
Ok(StatusCode::NO_CONTENT)
|
|
}
|
|
|
|
#[utoipa::path(post, path = "/api/v1/orbits/{id}/run", params(("id" = Uuid, Path, description = "orbit id")), responses((status = 204, headers(("X-Tessera-Snapshot-Id" = Uuid, description = "New retained snapshot ID when a capture writes to the vault"))), (status = 404), (status = 409)))]
|
|
async fn trigger_orbit(
|
|
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
|
State(state): State<HubState>,
|
|
headers: HeaderMap,
|
|
Path(id): Path<Uuid>,
|
|
) -> Result<(StatusCode, HeaderMap), (StatusCode, String)> {
|
|
require_admin_mutation(&state, peer, &headers).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)
|
|
.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()));
|
|
}
|
|
let snapshot_id = crate::api::run_orbit_internal(state, orbit)
|
|
.await
|
|
.map_err(|error| {
|
|
tracing::warn!(orbit_id = %id, %error, "capture did not complete");
|
|
(StatusCode::INTERNAL_SERVER_ERROR, error.to_string())
|
|
})?;
|
|
let mut headers = HeaderMap::new();
|
|
if let Some(snapshot_id) = snapshot_id {
|
|
let value = HeaderValue::from_str(&snapshot_id.to_string()).map_err(|_| {
|
|
(
|
|
StatusCode::INTERNAL_SERVER_ERROR,
|
|
"snapshot id header".into(),
|
|
)
|
|
})?;
|
|
headers.insert("x-tessera-snapshot-id", value);
|
|
}
|
|
Ok((StatusCode::NO_CONTENT, headers))
|
|
}
|
|
|
|
#[utoipa::path(post, path = "/api/v1/reconstitute", request_body = ReconstituteRequest, responses((status = 200, body = ReconstituteStartResponse)))]
|
|
async fn start_reconstitute(
|
|
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
|
State(state): State<HubState>,
|
|
headers: HeaderMap,
|
|
Json(req): Json<ReconstituteRequest>,
|
|
) -> Result<Json<ReconstituteStartResponse>, StatusCode> {
|
|
let actor = require_admin_mutation(&state, peer, &headers)?;
|
|
let destination = if actor.browser {
|
|
browser_export_path(&state, &req.target_path)?
|
|
} else {
|
|
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") {
|
|
return Err(StatusCode::NOT_FOUND);
|
|
}
|
|
let session_id = Uuid::new_v4();
|
|
let session = ReconstituteSession {
|
|
snapshot_id: req.snapshot_id,
|
|
target: req.target_path.clone(),
|
|
state: ReconstituteState::Countdown,
|
|
seconds_remaining: RECONSTITUTE_GRACE_SECS,
|
|
};
|
|
state
|
|
.reconstitute_sessions
|
|
.write()
|
|
.await
|
|
.insert(session_id, session.clone());
|
|
drop(vault);
|
|
|
|
let state_bg = state.clone();
|
|
tokio::spawn(async move {
|
|
for remaining in (0..RECONSTITUTE_GRACE_SECS).rev() {
|
|
{
|
|
let mut map = state_bg.reconstitute_sessions.write().await;
|
|
if let Some(s) = map.get_mut(&session_id) {
|
|
if s.state == ReconstituteState::Aborted {
|
|
return;
|
|
}
|
|
s.seconds_remaining = remaining;
|
|
}
|
|
}
|
|
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
|
|
}
|
|
{
|
|
let mut map = state_bg.reconstitute_sessions.write().await;
|
|
let Some(s) = map.get_mut(&session_id) else {
|
|
return;
|
|
};
|
|
if s.state == ReconstituteState::Aborted {
|
|
return;
|
|
}
|
|
s.state = ReconstituteState::Restoring;
|
|
s.seconds_remaining = 0;
|
|
}
|
|
let result = state_bg.export_snapshot(req.snapshot_id, destination).await;
|
|
let mut map = state_bg.reconstitute_sessions.write().await;
|
|
if let Some(s) = map.get_mut(&session_id) {
|
|
s.state = if result.is_ok() {
|
|
ReconstituteState::Completed
|
|
} else {
|
|
ReconstituteState::Failed
|
|
};
|
|
}
|
|
let _ = state_bg.db.audit("reconstitute.done", &format!("session={session_id}")).await;
|
|
});
|
|
|
|
Ok(Json(ReconstituteStartResponse {
|
|
session_id,
|
|
session,
|
|
}))
|
|
}
|
|
|
|
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) };
|
|
if components.next().is_some() || name.len() > 255 {
|
|
return Err(StatusCode::BAD_REQUEST);
|
|
}
|
|
let directory = state.data_dir.join("exports");
|
|
let mut builder = std::fs::DirBuilder::new();
|
|
#[cfg(unix)]
|
|
{
|
|
use std::os::unix::fs::DirBuilderExt;
|
|
builder.mode(0o700);
|
|
}
|
|
match builder.create(&directory) {
|
|
Ok(()) => (),
|
|
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)?;
|
|
if !metadata.is_dir() {
|
|
return Err(StatusCode::INTERNAL_SERVER_ERROR);
|
|
}
|
|
#[cfg(unix)]
|
|
{
|
|
use std::os::unix::fs::PermissionsExt;
|
|
if metadata.permissions().mode() & 0o077 != 0 {
|
|
return Err(StatusCode::INTERNAL_SERVER_ERROR);
|
|
}
|
|
}
|
|
Ok(directory.join(name))
|
|
}
|
|
|
|
async fn reconstitute_status(
|
|
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
|
State(state): State<HubState>,
|
|
headers: HeaderMap,
|
|
Path(id): Path<Uuid>,
|
|
) -> Result<Json<ReconstituteSession>, StatusCode> {
|
|
require_admin(&state, peer, &headers)?;
|
|
let map = state.reconstitute_sessions.read().await;
|
|
map.get(&id).cloned().map(Json).ok_or(StatusCode::NOT_FOUND)
|
|
}
|
|
|
|
async fn abort_reconstitute(
|
|
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
|
State(state): State<HubState>,
|
|
headers: HeaderMap,
|
|
Path(id): Path<Uuid>,
|
|
) -> Result<StatusCode, StatusCode> {
|
|
require_admin_mutation(&state, peer, &headers)?;
|
|
let mut map = state.reconstitute_sessions.write().await;
|
|
if let Some(s) = map.get_mut(&id) {
|
|
if matches!(
|
|
s.state,
|
|
ReconstituteState::Countdown | ReconstituteState::Confirming
|
|
) {
|
|
s.state = ReconstituteState::Aborted;
|
|
return Ok(StatusCode::NO_CONTENT);
|
|
}
|
|
}
|
|
Err(StatusCode::BAD_REQUEST)
|
|
}
|
|
|
|
async fn outposts(
|
|
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
|
State(state): State<HubState>,
|
|
headers: HeaderMap,
|
|
) -> Result<Json<Vec<OutpostSummary>>, StatusCode> {
|
|
require_admin(&state, peer, &headers)?;
|
|
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)))]
|
|
async fn pairing_start(
|
|
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
|
State(state): State<HubState>,
|
|
headers: HeaderMap,
|
|
) -> Result<Json<PairingResponse>, StatusCode> {
|
|
require_admin_mutation(&state, peer, &headers)?;
|
|
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()
|
|
};
|
|
let expires = chrono::Utc::now() + chrono::Duration::minutes(10);
|
|
let outpost_id = Uuid::new_v4();
|
|
let upload_token = hex::encode(Uuid::new_v4().as_bytes());
|
|
state
|
|
.db
|
|
.insert_wormhole_token(
|
|
&upload_token,
|
|
&outpost_id.to_string(),
|
|
&code,
|
|
&expires.to_rfc3339(),
|
|
)
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
Ok(Json(PairingResponse {
|
|
code,
|
|
expires_at: expires,
|
|
}))
|
|
}
|
|
|
|
#[utoipa::path(post, path = "/api/v1/wormhole/claim", request_body = ClaimRequest, responses((status = 200, body = ClaimResponse)))]
|
|
async fn pairing_claim(
|
|
State(state): State<HubState>,
|
|
Json(req): Json<ClaimRequest>,
|
|
) -> Result<Json<ClaimResponse>, StatusCode> {
|
|
let name = req.outpost_name.trim();
|
|
if name.is_empty() || name.len() > 128 || name.chars().any(char::is_control) {
|
|
return Err(StatusCode::BAD_REQUEST);
|
|
}
|
|
let now = chrono::Utc::now().to_rfc3339();
|
|
let claimed = state
|
|
.db
|
|
.claim_wormhole_code(&req.code, name, &now)
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
|
.ok_or(StatusCode::GONE)?;
|
|
let hub_url = std::env::var("TESSERA_PUBLIC_URL").unwrap_or_else(|_| {
|
|
if state.wormhole_mtls {
|
|
"https://127.0.0.1:8788".into()
|
|
} else {
|
|
"http://127.0.0.1:8787".into()
|
|
}
|
|
});
|
|
state
|
|
.db
|
|
.audit("wormhole.paired", name)
|
|
.await
|
|
.ok();
|
|
let outpost_id = Uuid::parse_str(&claimed.1).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
Ok(Json(ClaimResponse {
|
|
outpost_id,
|
|
upload_token: claimed.0,
|
|
hub_url,
|
|
}))
|
|
}
|
|
|
|
#[utoipa::path(post, path = "/api/v1/wormhole/upload/init", request_body = UploadInit, responses((status = 200)))]
|
|
async fn wormhole_upload_init(
|
|
State(state): State<HubState>,
|
|
headers: axum::http::HeaderMap,
|
|
Json(body): Json<UploadInit>,
|
|
) -> Result<Json<serde_json::Value>, StatusCode> {
|
|
super::jobs::outpost(&state, &headers)?;
|
|
reject_managed_orbit(&state, body.orbit_id)?;
|
|
if state
|
|
.vault
|
|
.read()
|
|
.await
|
|
.outpost_repository_configured(body.orbit_id)
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
|
{
|
|
return Err(StatusCode::FORBIDDEN);
|
|
}
|
|
let total = body.total_bytes.ok_or(StatusCode::BAD_REQUEST)?;
|
|
let session_id = Uuid::new_v4();
|
|
state
|
|
.db
|
|
.insert_upload_session(
|
|
&session_id.to_string(),
|
|
&body.orbit_id.to_string(),
|
|
Some(i64::try_from(total).map_err(|_| StatusCode::BAD_REQUEST)?),
|
|
)
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
if total == 0 {
|
|
let seal = state
|
|
.db
|
|
.record_range(&session_id.to_string(), 0, 0, 0)
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
if seal {
|
|
let file = tempfile::tempfile().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
seal_upload(&state, session_id, body.orbit_id, file).await?;
|
|
}
|
|
}
|
|
Ok(Json(serde_json::json!({ "session_id": session_id })))
|
|
}
|
|
|
|
#[utoipa::path(post, path = "/api/v1/wormhole/upload/chunk", request_body = UploadChunk, responses((status = 204)))]
|
|
async fn wormhole_upload_chunk(
|
|
State(state): State<HubState>,
|
|
headers: axum::http::HeaderMap,
|
|
Json(body): Json<UploadChunk>,
|
|
) -> Result<StatusCode, StatusCode> {
|
|
super::jobs::outpost(&state, &headers)?;
|
|
let session = state
|
|
.db
|
|
.upload_session(&body.session_id.to_string())
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
|
.ok_or(StatusCode::NOT_FOUND)?;
|
|
reject_managed_orbit(&state, session.orbit_id)?;
|
|
if session.sealed {
|
|
return Err(StatusCode::CONFLICT);
|
|
}
|
|
let data = base64::engine::general_purpose::STANDARD
|
|
.decode(&body.data_b64)
|
|
.map_err(|_| StatusCode::BAD_REQUEST)?;
|
|
let path = upload_part_path(&state, body.session_id);
|
|
if let Some(parent) = path.parent() {
|
|
std::fs::create_dir_all(parent).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
}
|
|
let mut file = OpenOptions::new()
|
|
.create(true)
|
|
.read(true)
|
|
.write(true)
|
|
.open(&path)
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
restrict_part(&path);
|
|
let range = write_at(&mut file, body.offset, &data, session.total).map_err(|error| {
|
|
if error.kind() == std::io::ErrorKind::InvalidInput {
|
|
StatusCode::BAD_REQUEST
|
|
} else {
|
|
StatusCode::INTERNAL_SERVER_ERROR
|
|
}
|
|
})?;
|
|
let seal = state
|
|
.db
|
|
.record_range(
|
|
&body.session_id.to_string(),
|
|
range.start,
|
|
range.end,
|
|
session.total,
|
|
)
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
if seal {
|
|
if !matches!(file.metadata(), Ok(metadata) if metadata.len() == session.total) {
|
|
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, file).await {
|
|
let _ = state.db.mark_upload_unsealed(&body.session_id.to_string());
|
|
return Err(status);
|
|
}
|
|
let _ = std::fs::remove_file(&path);
|
|
}
|
|
Ok(StatusCode::NO_CONTENT)
|
|
}
|
|
|
|
fn upload_part_path(state: &HubState, session_id: Uuid) -> std::path::PathBuf {
|
|
state
|
|
.data_dir
|
|
.join("wormhole")
|
|
.join(format!("{session_id}.part"))
|
|
}
|
|
|
|
fn restrict_part(path: &std::path::Path) {
|
|
#[cfg(unix)]
|
|
{
|
|
use std::os::unix::fs::PermissionsExt;
|
|
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
|
|
}
|
|
#[cfg(not(unix))]
|
|
let _ = path;
|
|
}
|
|
|
|
pub(super) fn upload_token<'a>(state: &HubState, headers: &'a HeaderMap) -> Result<&'a str, StatusCode> {
|
|
if !state.accept_plain_upload {
|
|
return Err(StatusCode::FORBIDDEN);
|
|
}
|
|
headers
|
|
.get("x-tessera-upload-token")
|
|
.and_then(|v| v.to_str().ok())
|
|
.ok_or(StatusCode::UNAUTHORIZED)
|
|
}
|
|
|
|
#[utoipa::path(post, path = "/api/v1/wormhole/restic/commit", request_body = ResticCommit, responses((status = 200)))]
|
|
async fn wormhole_restic_commit(
|
|
State(state): State<HubState>,
|
|
headers: HeaderMap,
|
|
Json(body): Json<ResticCommit>,
|
|
) -> Result<Json<serde_json::Value>, StatusCode> {
|
|
let outpost_id = super::jobs::outpost(&state, &headers)?;
|
|
if body.snapshot_id.len() != 64 || !body.snapshot_id.bytes().all(|b| b.is_ascii_hexdigit()) {
|
|
return Err(StatusCode::BAD_REQUEST);
|
|
}
|
|
let orbit = state
|
|
.db
|
|
.list_orbits()
|
|
.await
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
|
.into_iter()
|
|
.find(|orbit| orbit.id == body.orbit_id && orbit.provider == "wormhole" && !orbit.dry_run)
|
|
.ok_or(StatusCode::NOT_FOUND)?;
|
|
let orbit_id = orbit.id;
|
|
let mut vault = state.vault.clone().write_owned().await;
|
|
reject_managed_orbit(&state, orbit_id)?;
|
|
let (snapshot, created) = tokio::task::spawn_blocking(move || {
|
|
let manifest = SnapshotManifest {
|
|
snapshot_id: Uuid::nil(),
|
|
orbit_id,
|
|
orbit_name: orbit.name,
|
|
labels: vec!["wormhole".into()],
|
|
provider: orbit.provider,
|
|
paths: vec![],
|
|
restore_hints: serde_json::Value::Null,
|
|
};
|
|
vault.register_outpost_snapshot(manifest, outpost_id, &body.snapshot_id)
|
|
})
|
|
.await
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
|
.map_err(|error| {
|
|
tracing::error!(%orbit_id, %error, "could not register Restic snapshot");
|
|
StatusCode::INTERNAL_SERVER_ERROR
|
|
})?
|
|
.ok_or(StatusCode::FORBIDDEN)?;
|
|
if created {
|
|
if let Err(error) = state.prune_orbit(orbit_id).await {
|
|
tracing::warn!(%orbit_id, %error, "could not apply Wormhole retention");
|
|
}
|
|
}
|
|
state
|
|
.db
|
|
.set_orbit_status(orbit_id, "completed")
|
|
.await
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
let _ = state
|
|
.db
|
|
.audit("wormhole.restic.committed", &format!("snapshot={snapshot}"))
|
|
.await;
|
|
Ok(Json(serde_json::json!({ "snapshot_id": snapshot })))
|
|
}
|
|
|
|
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)?
|
|
{
|
|
return Err(StatusCode::FORBIDDEN);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
async fn seal_upload(
|
|
state: &HubState,
|
|
session_id: Uuid,
|
|
orbit_id: Uuid,
|
|
payload: File,
|
|
) -> Result<(), StatusCode> {
|
|
let orbits = state
|
|
.db
|
|
.list_orbits()
|
|
.await
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
let orbit = orbits.into_iter().find(|orbit| orbit.id == orbit_id);
|
|
let orbit_name = orbit
|
|
.as_ref()
|
|
.map(|orbit| orbit.name.clone())
|
|
.unwrap_or_else(|| orbit_id.to_string());
|
|
let manifest = SnapshotManifest {
|
|
snapshot_id: Uuid::new_v4(),
|
|
orbit_id,
|
|
orbit_name,
|
|
labels: vec!["wormhole".into()],
|
|
provider: "wormhole".into(),
|
|
paths: vec![],
|
|
restore_hints: serde_json::json!({ "session_id": session_id }),
|
|
};
|
|
let vault = state.vault.clone().read_owned().await;
|
|
reject_managed_orbit(state, orbit_id)?;
|
|
if vault
|
|
.outpost_repository_configured(orbit_id)
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
|
{
|
|
return Err(StatusCode::FORBIDDEN);
|
|
}
|
|
let snap_id = tokio::task::spawn_blocking(move || {
|
|
Ok::<_, anyhow::Error>(vault.snapshot_payload(manifest, payload, false)?.id)
|
|
})
|
|
.await
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
|
.map_err(|error| {
|
|
tracing::error!(%session_id, %error, "could not seal Wormhole snapshot");
|
|
StatusCode::INTERNAL_SERVER_ERROR
|
|
})?;
|
|
if let Err(error) = state.prune_orbit(orbit_id).await {
|
|
tracing::warn!(%orbit_id, %error, "could not apply Wormhole retention");
|
|
}
|
|
let _ = state
|
|
.db
|
|
.audit("wormhole.sealed", &format!("snapshot={snap_id}"))
|
|
.await;
|
|
Ok(())
|
|
}
|
|
|
|
async fn spa_fallback(uri: Uri) -> impl IntoResponse {
|
|
let mut path = uri.path().trim_start_matches('/').to_string();
|
|
if path.is_empty() {
|
|
path = "index.html".into();
|
|
}
|
|
if let Some(file) = WEB_DIST.get_file(&path) {
|
|
let ct = content_type(&path);
|
|
return (
|
|
StatusCode::OK,
|
|
[(header::CONTENT_TYPE, ct)],
|
|
file.contents(),
|
|
)
|
|
.into_response();
|
|
}
|
|
if let Some(index) = WEB_DIST.get_file("index.html") {
|
|
return (
|
|
StatusCode::OK,
|
|
[(header::CONTENT_TYPE, "text/html")],
|
|
index.contents(),
|
|
)
|
|
.into_response();
|
|
}
|
|
(StatusCode::NOT_FOUND, "not found").into_response()
|
|
}
|
|
|
|
fn content_type(path: &str) -> &'static str {
|
|
if path.ends_with(".js") {
|
|
"application/javascript"
|
|
} else if path.ends_with(".css") {
|
|
"text/css"
|
|
} else if path.ends_with(".svg") {
|
|
"image/svg+xml"
|
|
} else {
|
|
"text/html"
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use axum::body::{to_bytes, Body};
|
|
use axum::http::Request;
|
|
use tower::ServiceExt;
|
|
|
|
#[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();
|
|
state.admin.token = None;
|
|
state.accept_plain_upload = true;
|
|
let app = router(state.clone());
|
|
let post = |path: &str, body: serde_json::Value| {
|
|
Request::post(path)
|
|
.extension(ConnectInfo("127.0.0.1:1234".parse::<SocketAddr>().unwrap()))
|
|
.header(header::CONTENT_TYPE, "application/json")
|
|
.header("x-tessera-upload-token", "fixture-token")
|
|
.body(Body::from(body.to_string()))
|
|
.unwrap()
|
|
};
|
|
for (provider, schedule, expected) in [
|
|
("filesystem", Some("bad cron"), StatusCode::BAD_REQUEST),
|
|
("postgres", None, StatusCode::BAD_REQUEST),
|
|
("filesystem", Some("0 2 * * *"), StatusCode::OK),
|
|
("wormhole", None, StatusCode::OK),
|
|
] {
|
|
let response = app.clone().oneshot(post("/api/v1/orbits", serde_json::json!({
|
|
"name": provider, "provider": provider, "provider_config": {}, "schedule": schedule
|
|
}))).await.unwrap();
|
|
assert_eq!(response.status(), expected);
|
|
}
|
|
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();
|
|
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_wormhole_token("fixture-token", &outpost.to_string(), "fixture-code", "9999").unwrap();
|
|
state.db.claim_wormhole_code("fixture-code", "fixture", "2026").unwrap().unwrap();
|
|
{
|
|
let conn = rusqlite::Connection::open(dir.path().join("tessera.db")).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();
|
|
assert_eq!(response.status(), StatusCode::OK);
|
|
assert!(state.db.list_outposts().unwrap()[0].last_seen.is_some());
|
|
}
|
|
|
|
#[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();
|
|
state.admin.token = None;
|
|
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),
|
|
("database", "outpost", serde_json::json!({}), StatusCode::OK),
|
|
("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()))
|
|
.header(header::CONTENT_TYPE, "application/json")
|
|
.body(Body::from(serde_json::json!({
|
|
"name": "test", "source": source, "access": access, "provider_config": config,
|
|
}).to_string())).unwrap();
|
|
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 orbit: serde_json::Value = serde_json::from_slice(&body).unwrap();
|
|
assert_eq!(orbit["source"], source);
|
|
assert_eq!(orbit["access"], access);
|
|
assert!(orbit.get("provider_config").is_none());
|
|
}
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn orbit_responses_and_schema_hide_provider_config() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "test-vault")
|
|
.await
|
|
.unwrap();
|
|
state.admin.token = None;
|
|
let app = router(state.clone());
|
|
let input = serde_json::json!({
|
|
"name": "billing",
|
|
"provider": "postgres",
|
|
"provider_config": {
|
|
"connection_url": "postgres://user:synthetic-password@db/billing",
|
|
"token": "synthetic-token",
|
|
"secret_ref": "synthetic-reference",
|
|
}
|
|
});
|
|
let request = |method: &str, uri: &str, body: Body| {
|
|
Request::builder()
|
|
.method(method)
|
|
.uri(uri)
|
|
.extension(ConnectInfo("127.0.0.1:1234".parse::<SocketAddr>().unwrap()))
|
|
.header(header::CONTENT_TYPE, "application/json")
|
|
.body(body)
|
|
.unwrap()
|
|
};
|
|
for (method, path, body) in [
|
|
("POST", "/api/v1/orbits", Body::from(input.to_string())),
|
|
("GET", "/api/v1/orbits", Body::empty()),
|
|
("GET", "/api-doc/openapi.json", Body::empty()),
|
|
] {
|
|
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"],
|
|
_ if method == "GET" => &json[0],
|
|
_ => &json,
|
|
};
|
|
assert!(orbit.get("id").is_some());
|
|
assert!(orbit.get("provider_config").is_none());
|
|
assert!(!String::from_utf8_lossy(&bytes).contains("synthetic-"));
|
|
}
|
|
let rows = state.db.list_orbits().await.unwrap();
|
|
assert_eq!(
|
|
serde_json::from_str::<serde_json::Value>(&rows[0].provider_config).unwrap(),
|
|
input["provider_config"]
|
|
);
|
|
}
|
|
}
|