feat: add managed database capture and operator restore
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>
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
use crate::db::OrbitRow;
|
||||
use crate::state::HubState;
|
||||
use crate::state::{HubState, ManagedRetention};
|
||||
use crate::upload::write_at;
|
||||
use axum::{
|
||||
extract::{ConnectInfo, Path, State},
|
||||
@@ -9,6 +9,8 @@ use axum::{
|
||||
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;
|
||||
@@ -39,8 +41,11 @@ static WEB_DIST: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/../../web/dist");
|
||||
),
|
||||
components(schemas(
|
||||
SnapshotSummary,
|
||||
OrbitRow,
|
||||
CaptureSnapshotSummary,
|
||||
OrbitResponse,
|
||||
CreateOrbitRequest,
|
||||
OrbitSource,
|
||||
OrbitAccess,
|
||||
RetentionUpdate,
|
||||
RetentionPolicy,
|
||||
ReconstituteRequest,
|
||||
@@ -62,14 +67,107 @@ struct SnapshotSummary {
|
||||
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: String,
|
||||
provider: Option<String>,
|
||||
source: Option<OrbitSource>,
|
||||
access: Option<OrbitAccess>,
|
||||
provider_config: serde_json::Value,
|
||||
schedule: Option<String>,
|
||||
decay_preset: Option<String>,
|
||||
@@ -133,12 +231,53 @@ struct ReconstituteStartResponse {
|
||||
session: ReconstituteSession,
|
||||
}
|
||||
|
||||
fn require_admin(
|
||||
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> {
|
||||
state.admin.authorize(peer, headers)
|
||||
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 {
|
||||
@@ -153,6 +292,7 @@ pub fn router(state: HubState) -> Router {
|
||||
"/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))
|
||||
@@ -161,6 +301,10 @@ pub fn router(state: HubState) -> Router {
|
||||
"/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(
|
||||
@@ -188,10 +332,12 @@ async fn list_snapshots(
|
||||
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,
|
||||
@@ -201,36 +347,103 @@ async fn list_snapshots(
|
||||
Ok(Json(out))
|
||||
}
|
||||
|
||||
#[utoipa::path(get, path = "/api/v1/orbits", responses((status = 200, body = [OrbitRow])))]
|
||||
#[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<OrbitRow>>, StatusCode> {
|
||||
) -> Result<Json<Vec<OrbitResponse>>, StatusCode> {
|
||||
require_admin(&state, peer, &headers)?;
|
||||
state
|
||||
let profiles: std::collections::HashMap<_, _> = state
|
||||
.db
|
||||
.list_orbits()
|
||||
.await
|
||||
.map(Json)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
|
||||
.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 = OrbitRow)))]
|
||||
#[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<OrbitRow>, (StatusCode, &'static str)> {
|
||||
require_admin(&state, peer, &headers).map_err(|status| (status, "unauthorized"))?;
|
||||
) -> 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: req.provider,
|
||||
provider_config: serde_json::to_string(&req.provider_config).unwrap_or_else(|_| "{}".into()),
|
||||
schedule: req.schedule,
|
||||
provider: provider.to_owned(),
|
||||
provider_config: config.to_string(),
|
||||
schedule,
|
||||
decay_preset,
|
||||
retention,
|
||||
dry_run: req.dry_run.unwrap_or(false),
|
||||
@@ -241,7 +454,7 @@ async fn create_orbit(
|
||||
.upsert_orbit(&row)
|
||||
.await
|
||||
.map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "could not save orbit"))?;
|
||||
Ok(Json(row))
|
||||
Ok(Json(row.into()))
|
||||
}
|
||||
|
||||
fn retention_settings(
|
||||
@@ -274,7 +487,7 @@ async fn update_orbit_retention(
|
||||
Path(id): Path<Uuid>,
|
||||
Json(req): Json<RetentionUpdate>,
|
||||
) -> Result<StatusCode, (StatusCode, &'static str)> {
|
||||
require_admin(&state, peer, &headers).map_err(|status| (status, "unauthorized"))?;
|
||||
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,
|
||||
@@ -297,15 +510,23 @@ async fn update_orbit_retention(
|
||||
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")))))]
|
||||
#[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(&state, peer, &headers).map_err(|status| (status, "unauthorized".into()))?;
|
||||
let snapshot_id = crate::api::run_orbit_internal(state, id)
|
||||
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");
|
||||
@@ -331,7 +552,17 @@ async fn start_reconstitute(
|
||||
headers: HeaderMap,
|
||||
Json(req): Json<ReconstituteRequest>,
|
||||
) -> Result<Json<ReconstituteStartResponse>, StatusCode> {
|
||||
require_admin(&state, peer, &headers)?;
|
||||
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,
|
||||
@@ -344,9 +575,9 @@ async fn start_reconstitute(
|
||||
.write()
|
||||
.await
|
||||
.insert(session_id, session.clone());
|
||||
drop(vault);
|
||||
|
||||
let state_bg = state.clone();
|
||||
let target = req.target_path;
|
||||
tokio::spawn(async move {
|
||||
for remaining in (0..RECONSTITUTE_GRACE_SECS).rev() {
|
||||
{
|
||||
@@ -371,14 +602,7 @@ async fn start_reconstitute(
|
||||
s.state = ReconstituteState::Restoring;
|
||||
s.seconds_remaining = 0;
|
||||
}
|
||||
let dest = std::path::PathBuf::from(&target);
|
||||
let result = {
|
||||
let vault = state_bg.vault.clone().read_owned().await;
|
||||
tokio::task::spawn_blocking(move || vault.restore_snapshot(req.snapshot_id, &dest))
|
||||
.await
|
||||
.map_err(anyhow::Error::from)
|
||||
.and_then(|result| result)
|
||||
};
|
||||
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() {
|
||||
@@ -396,6 +620,39 @@ async fn start_reconstitute(
|
||||
}))
|
||||
}
|
||||
|
||||
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>,
|
||||
@@ -413,7 +670,7 @@ async fn abort_reconstitute(
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
require_admin(&state, peer, &headers)?;
|
||||
require_admin_mutation(&state, peer, &headers)?;
|
||||
let mut map = state.reconstitute_sessions.write().await;
|
||||
if let Some(s) = map.get_mut(&id) {
|
||||
if matches!(
|
||||
@@ -427,23 +684,27 @@ async fn abort_reconstitute(
|
||||
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(&state, peer, &headers)?;
|
||||
let code: String = (0..6)
|
||||
.map(|_| {
|
||||
let n = rand::random::<u8>() % 36;
|
||||
if n < 10 {
|
||||
(b'0' + n) as char
|
||||
} else {
|
||||
(b'A' + n - 10) as char
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
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());
|
||||
@@ -467,10 +728,14 @@ 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, &req.outpost_name, &now)
|
||||
.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(|_| {
|
||||
@@ -482,7 +747,7 @@ async fn pairing_claim(
|
||||
});
|
||||
state
|
||||
.db
|
||||
.audit("wormhole.paired", &req.outpost_name)
|
||||
.audit("wormhole.paired", name)
|
||||
.await
|
||||
.ok();
|
||||
let outpost_id = Uuid::parse_str(&claimed.1).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
@@ -499,7 +764,8 @@ async fn wormhole_upload_init(
|
||||
headers: axum::http::HeaderMap,
|
||||
Json(body): Json<UploadInit>,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
verify_upload_token(&state, &headers)?;
|
||||
super::jobs::outpost(&state, &headers)?;
|
||||
reject_managed_orbit(&state, body.orbit_id)?;
|
||||
if state
|
||||
.vault
|
||||
.read()
|
||||
@@ -538,12 +804,13 @@ async fn wormhole_upload_chunk(
|
||||
headers: axum::http::HeaderMap,
|
||||
Json(body): Json<UploadChunk>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
verify_upload_token(&state, &headers)?;
|
||||
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);
|
||||
}
|
||||
@@ -608,16 +875,7 @@ fn restrict_part(path: &std::path::Path) {
|
||||
let _ = path;
|
||||
}
|
||||
|
||||
fn verify_upload_token(state: &HubState, headers: &HeaderMap) -> Result<(), StatusCode> {
|
||||
let token = upload_token(state, headers)?;
|
||||
if state.upload_token_valid(token) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(StatusCode::UNAUTHORIZED)
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -633,13 +891,7 @@ async fn wormhole_restic_commit(
|
||||
headers: HeaderMap,
|
||||
Json(body): Json<ResticCommit>,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let token = upload_token(&state, &headers)?;
|
||||
let outpost_id = state
|
||||
.db
|
||||
.upload_token_outpost(token)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.and_then(|id| Uuid::parse_str(&id).ok())
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
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);
|
||||
}
|
||||
@@ -653,6 +905,7 @@ async fn wormhole_restic_commit(
|
||||
.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(),
|
||||
@@ -689,6 +942,15 @@ async fn wormhole_restic_commit(
|
||||
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,
|
||||
@@ -715,6 +977,7 @@ async fn seal_upload(
|
||||
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)?
|
||||
@@ -776,3 +1039,142 @@ fn content_type(path: &str) -> &'static str {
|
||||
"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"]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user