779 lines
25 KiB
Rust
779 lines
25 KiB
Rust
use crate::db::OrbitRow;
|
|
use crate::state::HubState;
|
|
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 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,
|
|
OrbitRow,
|
|
CreateOrbitRequest,
|
|
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,
|
|
stored_bytes: Option<u64>,
|
|
new_data_chunks: Option<u64>,
|
|
}
|
|
|
|
#[derive(serde::Deserialize, utoipa::ToSchema)]
|
|
struct CreateOrbitRequest {
|
|
name: String,
|
|
provider: String,
|
|
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,
|
|
}
|
|
|
|
fn require_admin(
|
|
state: &HubState,
|
|
peer: SocketAddr,
|
|
headers: &HeaderMap,
|
|
) -> Result<(), StatusCode> {
|
|
state.admin.authorize(peer, headers)
|
|
}
|
|
|
|
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/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),
|
|
)
|
|
.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()
|
|
.map(|s| SnapshotSummary {
|
|
id: s.id,
|
|
orbit_id: s.manifest.orbit_id,
|
|
taken_at: s.taken_at,
|
|
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 = [OrbitRow])))]
|
|
async fn list_orbits(
|
|
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
|
State(state): State<HubState>,
|
|
headers: HeaderMap,
|
|
) -> Result<Json<Vec<OrbitRow>>, StatusCode> {
|
|
require_admin(&state, peer, &headers)?;
|
|
state
|
|
.db
|
|
.list_orbits()
|
|
.await
|
|
.map(Json)
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
|
|
}
|
|
|
|
#[utoipa::path(post, path = "/api/v1/orbits", request_body = CreateOrbitRequest, responses((status = 200, body = OrbitRow)))]
|
|
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"))?;
|
|
let (decay_preset, retention) = retention_settings(req.decay_preset, req.retention)?;
|
|
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,
|
|
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))
|
|
}
|
|
|
|
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(&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")))))]
|
|
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)
|
|
.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> {
|
|
require_admin(&state, peer, &headers)?;
|
|
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());
|
|
|
|
let state_bg = state.clone();
|
|
let target = req.target_path;
|
|
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 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 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,
|
|
}))
|
|
}
|
|
|
|
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(&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)
|
|
}
|
|
|
|
#[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();
|
|
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 now = chrono::Utc::now().to_rfc3339();
|
|
let claimed = state
|
|
.db
|
|
.claim_wormhole_code(&req.code, &req.outpost_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", &req.outpost_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> {
|
|
verify_upload_token(&state, &headers)?;
|
|
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> {
|
|
verify_upload_token(&state, &headers)?;
|
|
let session = state
|
|
.db
|
|
.upload_session(&body.session_id.to_string())
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
|
.ok_or(StatusCode::NOT_FOUND)?;
|
|
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;
|
|
}
|
|
|
|
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> {
|
|
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 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)?;
|
|
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;
|
|
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 })))
|
|
}
|
|
|
|
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;
|
|
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"
|
|
}
|
|
}
|