fix: harden the vault before release
Require a private passphrase and loopback-or-token admin auth. New vaults use Argon2id; existing PBKDF2 vaults still open, and new snapshot metadata is encrypted. Wormhole tokens survive restart, offset uploads seal into the vault, and client-certificate uploads are real. Reject the command provider and keep Postgres passwords off the process arguments. Keep the interruptible canvas motion.
This commit is contained in:
@@ -1,7 +1,8 @@
|
||||
use crate::db::OrbitRow;
|
||||
use crate::state::{HubState, PairingEntry};
|
||||
use crate::state::HubState;
|
||||
use crate::upload::write_at;
|
||||
use axum::{
|
||||
extract::{Path, State},
|
||||
extract::{ConnectInfo, Path, State},
|
||||
http::{header, HeaderMap, HeaderValue, StatusCode, Uri},
|
||||
response::IntoResponse,
|
||||
routing::{get, post},
|
||||
@@ -9,8 +10,11 @@ use axum::{
|
||||
};
|
||||
use base64::Engine;
|
||||
use include_dir::{include_dir, Dir};
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
use std::net::SocketAddr;
|
||||
use tessera_core::manifest::SnapshotManifest;
|
||||
use tessera_core::reconstitute::{ReconstituteSession, ReconstituteState, RECONSTITUTE_GRACE_SECS};
|
||||
use tessera_core::wormhole::PairingState;
|
||||
use tower_http::trace::TraceLayer;
|
||||
use utoipa::OpenApi;
|
||||
use uuid::Uuid;
|
||||
@@ -109,6 +113,14 @@ struct ReconstituteStartResponse {
|
||||
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))
|
||||
@@ -141,7 +153,12 @@ async fn health() -> &'static str {
|
||||
}
|
||||
|
||||
#[utoipa::path(get, path = "/api/v1/snapshots", responses((status = 200, body = [SnapshotSummary])))]
|
||||
async fn list_snapshots(State(state): State<HubState>) -> Result<Json<Vec<SnapshotSummary>>, StatusCode> {
|
||||
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
|
||||
@@ -158,7 +175,12 @@ async fn list_snapshots(State(state): State<HubState>) -> Result<Json<Vec<Snapsh
|
||||
}
|
||||
|
||||
#[utoipa::path(get, path = "/api/v1/orbits", responses((status = 200, body = [OrbitRow])))]
|
||||
async fn list_orbits(State(state): State<HubState>) -> Result<Json<Vec<OrbitRow>>, StatusCode> {
|
||||
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()
|
||||
@@ -169,9 +191,12 @@ async fn list_orbits(State(state): State<HubState>) -> Result<Json<Vec<OrbitRow>
|
||||
|
||||
#[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> {
|
||||
require_admin(&state, peer, &headers)?;
|
||||
let row = OrbitRow {
|
||||
id: Uuid::new_v4(),
|
||||
name: req.name,
|
||||
@@ -190,19 +215,26 @@ async fn create_orbit(
|
||||
|
||||
#[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> {
|
||||
) -> 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
|
||||
(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)?;
|
||||
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))
|
||||
@@ -210,9 +242,12 @@ async fn trigger_orbit(
|
||||
|
||||
#[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,
|
||||
@@ -273,17 +308,23 @@ async fn start_reconstitute(
|
||||
}
|
||||
|
||||
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!(
|
||||
@@ -298,7 +339,12 @@ async fn abort_reconstitute(
|
||||
}
|
||||
|
||||
#[utoipa::path(post, path = "/api/v1/wormhole/pairing", responses((status = 200, body = PairingResponse)))]
|
||||
async fn pairing_start(State(state): State<HubState>) -> Json<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;
|
||||
@@ -312,14 +358,16 @@ async fn pairing_start(State(state): State<HubState>) -> Json<PairingResponse> {
|
||||
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.pairing_codes.write().await.push(PairingEntry {
|
||||
code: code.clone(),
|
||||
expires_at: expires,
|
||||
state: PairingState::CodeShown,
|
||||
outpost_id,
|
||||
upload_token: upload_token.clone(),
|
||||
});
|
||||
Json(PairingResponse { code, expires_at: expires })
|
||||
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)))]
|
||||
@@ -327,23 +375,28 @@ async fn pairing_claim(
|
||||
State(state): State<HubState>,
|
||||
Json(req): Json<ClaimRequest>,
|
||||
) -> Result<Json<ClaimResponse>, StatusCode> {
|
||||
let mut codes = state.pairing_codes.write().await;
|
||||
let now = chrono::Utc::now();
|
||||
let entry = codes
|
||||
.iter_mut()
|
||||
.find(|c| c.code == req.code && c.expires_at > now)
|
||||
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)?;
|
||||
entry.state = PairingState::Active;
|
||||
let hub_url =
|
||||
std::env::var("TESSERA_PUBLIC_URL").unwrap_or_else(|_| "http://127.0.0.1:8787".into());
|
||||
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: entry.outpost_id,
|
||||
upload_token: entry.upload_token.clone(),
|
||||
outpost_id,
|
||||
upload_token: claimed.0,
|
||||
hub_url,
|
||||
}))
|
||||
}
|
||||
@@ -354,16 +407,26 @@ async fn wormhole_upload_init(
|
||||
headers: axum::http::HeaderMap,
|
||||
Json(body): Json<UploadInit>,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
verify_upload_token(&state, &headers).await?;
|
||||
verify_upload_token(&state, &headers)?;
|
||||
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(),
|
||||
body.total_bytes.map(|t| t as i64),
|
||||
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 {
|
||||
seal_upload(&state, session_id, body.orbit_id, Vec::new()).await?;
|
||||
}
|
||||
}
|
||||
Ok(Json(serde_json::json!({ "session_id": session_id })))
|
||||
}
|
||||
|
||||
@@ -373,39 +436,141 @@ async fn wormhole_upload_chunk(
|
||||
headers: axum::http::HeaderMap,
|
||||
Json(body): Json<UploadChunk>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
verify_upload_token(&state, &headers).await?;
|
||||
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 tmp = state.data_dir.join("wormhole").join(format!("{}.part", body.session_id));
|
||||
if let Some(parent) = tmp.parent() {
|
||||
std::fs::create_dir_all(parent).ok();
|
||||
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)?;
|
||||
}
|
||||
use std::io::Write;
|
||||
let mut file = std::fs::OpenOptions::new()
|
||||
let mut file = OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&tmp)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(&path)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
file.write_all(&data).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 {
|
||||
let mut bytes = Vec::new();
|
||||
file.seek(SeekFrom::Start(0))
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
file.read_to_end(&mut bytes)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
if (bytes.len() as u64) < session.total {
|
||||
let _ = state.db.mark_upload_unsealed(&body.session_id.to_string());
|
||||
return Err(StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
bytes.truncate(session.total as usize);
|
||||
if let Err(status) = seal_upload(&state, body.session_id, session.orbit_id, bytes).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)
|
||||
}
|
||||
|
||||
async fn verify_upload_token(
|
||||
state: &HubState,
|
||||
headers: &axum::http::HeaderMap,
|
||||
) -> Result<(), StatusCode> {
|
||||
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> {
|
||||
if !state.accept_plain_upload {
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
}
|
||||
let token = headers
|
||||
.get("x-tessera-upload-token")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
if state.upload_token_valid(token).await {
|
||||
if state.upload_token_valid(token) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(StatusCode::UNAUTHORIZED)
|
||||
}
|
||||
}
|
||||
|
||||
async fn seal_upload(
|
||||
state: &HubState,
|
||||
session_id: Uuid,
|
||||
orbit_id: Uuid,
|
||||
bytes: Vec<u8>,
|
||||
) -> 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 decay = orbit
|
||||
.as_ref()
|
||||
.map(|orbit| orbit.decay_preset.clone())
|
||||
.unwrap_or_else(|| "week-of-dailies".into());
|
||||
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 snap_id = {
|
||||
let mut vault = state.vault.write().await;
|
||||
let snap = vault
|
||||
.snapshot(manifest, &bytes, false)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let _ = vault.prune_orbit_with_decay(orbit_id, &decay);
|
||||
snap.id
|
||||
};
|
||||
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() {
|
||||
|
||||
Reference in New Issue
Block a user