Also removes OperatorActor.browser, unused since reconstitute targets are confined for every caller. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2258 lines
81 KiB
Rust
2258 lines
81 KiB
Rust
use crate::auth::{AuditAction, AuditOutcome, AuditResource, Permission, Principal, Subject};
|
|
use crate::db::OrbitRow;
|
|
use crate::state::{HubState, ManagedRetention};
|
|
use crate::upload::write_at;
|
|
use axum::{
|
|
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 rand::Rng;
|
|
use std::fs::{File, OpenOptions};
|
|
use std::net::SocketAddr;
|
|
use tessera_core::decay::RetentionPolicy;
|
|
use tessera_core::manifest::SnapshotManifest;
|
|
use tessera_core::reconstitute::{ReconstituteSession, ReconstituteState, RECONSTITUTE_GRACE_SECS};
|
|
use tessera_core::OutpostSummary;
|
|
use tower_http::trace::TraceLayer;
|
|
use utoipa::OpenApi;
|
|
use uuid::Uuid;
|
|
|
|
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,
|
|
bind_outpost,
|
|
start_reconstitute,
|
|
pairing_start,
|
|
pairing_claim,
|
|
rotate_outpost_token,
|
|
revoke_outpost,
|
|
wormhole_upload_init,
|
|
wormhole_upload_chunk,
|
|
wormhole_restic_commit,
|
|
),
|
|
components(schemas(
|
|
SnapshotSummary,
|
|
CaptureSnapshotSummary,
|
|
OrbitResponse,
|
|
CreateOrbitRequest,
|
|
OrbitSource,
|
|
OrbitAccess,
|
|
RetentionUpdate,
|
|
RetentionPolicy,
|
|
ReconstituteRequest,
|
|
ReconstituteSession,
|
|
PairingResponse,
|
|
ClaimRequest,
|
|
ClaimResponse,
|
|
RotateResponse,
|
|
UploadInit,
|
|
UploadChunk,
|
|
ResticCommit,
|
|
OutpostBinding,
|
|
))
|
|
)]
|
|
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>,
|
|
/// `capture` for a backup of an orbit, `safety` for the copy a restore took of its target before
|
|
/// overwriting it. Pickers leave the latter out.
|
|
kind: &'static str,
|
|
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 {
|
|
/// Display only. Never record this as "who did it": an IdP can call a user anything.
|
|
pub(super) name: String,
|
|
pub(super) principal: Principal,
|
|
pub(super) subject: Subject,
|
|
pub(super) request_id: Uuid,
|
|
}
|
|
|
|
impl OperatorActor {
|
|
/// Stable identity for job attribution and audit details (`oidc:<users.id>`, ...).
|
|
pub(super) fn id(&self) -> String {
|
|
self.principal.fields().0
|
|
}
|
|
}
|
|
|
|
impl std::fmt::Display for OperatorActor {
|
|
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
self.id().fmt(formatter)
|
|
}
|
|
}
|
|
|
|
/// Who is calling, and nothing more: no permission is checked here. A request
|
|
/// with no or a wrong credential is 401, a mutation without CSRF is 403. Every
|
|
/// handler must then choose a gate from `gate.rs` (`admin_only`, `scoped`,
|
|
/// `visible`); there is deliberately no "signed in is enough" path.
|
|
pub(super) fn authenticate(
|
|
state: &HubState,
|
|
peer: SocketAddr,
|
|
headers: &HeaderMap,
|
|
mutation: bool,
|
|
) -> Result<OperatorActor, StatusCode> {
|
|
let request_id = Uuid::new_v4();
|
|
// Resolve the session once: each lookup is a DB query and may slide the idle window.
|
|
let session = state.sessions.active(headers);
|
|
let attempted = session
|
|
.as_ref()
|
|
.map(|s| s.principal())
|
|
.unwrap_or(Principal::Anonymous);
|
|
let result = authenticate_inner(state, peer, headers, mutation, request_id, session);
|
|
if result.is_err() {
|
|
// One denial row per source per minute: an unauthenticated flood must not
|
|
// grow the audit table, and a failed audit write must not turn the 401/403
|
|
// into a 500.
|
|
let source = state.limits.source(Some(peer), headers);
|
|
if state.limits.audit_denial(source) {
|
|
if let Err(error) = state.db.audit_event(
|
|
&attempted,
|
|
AuditAction::Authentication,
|
|
AuditResource::Api,
|
|
AuditOutcome::Denied,
|
|
request_id,
|
|
) {
|
|
tracing::error!(%error, "could not record a denied authentication");
|
|
}
|
|
}
|
|
}
|
|
result
|
|
}
|
|
|
|
fn authenticate_inner(
|
|
state: &HubState,
|
|
peer: SocketAddr,
|
|
headers: &HeaderMap,
|
|
mutation: bool,
|
|
request_id: Uuid,
|
|
session: Option<crate::admin::BrowserSession>,
|
|
) -> Result<OperatorActor, StatusCode> {
|
|
let configured_admin = |name: &str, principal: Principal| OperatorActor {
|
|
name: name.into(),
|
|
principal,
|
|
subject: Subject {
|
|
user_id: None,
|
|
groups: vec![],
|
|
admin: true,
|
|
},
|
|
request_id,
|
|
};
|
|
if state.admin.token.is_some() {
|
|
if state.admin.authorize(peer, headers).is_ok() {
|
|
return Ok(configured_admin(
|
|
"api-token",
|
|
Principal::Service("legacy-admin-token"),
|
|
));
|
|
}
|
|
// A wrong token counts against the source's budget; past it the answer is 429.
|
|
if crate::admin::presents_token(headers)
|
|
&& !state
|
|
.limits
|
|
.admin_token_failure(state.limits.source(Some(peer), headers))
|
|
{
|
|
return Err(StatusCode::TOO_MANY_REQUESTS);
|
|
}
|
|
}
|
|
if let Some(session) = session {
|
|
if mutation {
|
|
super::session::require_csrf(headers, &session.csrf.to_string())?;
|
|
}
|
|
return Ok(OperatorActor {
|
|
principal: session.principal(),
|
|
subject: session.subject(),
|
|
name: session.actor,
|
|
request_id,
|
|
});
|
|
}
|
|
if !state.sessions.enabled() {
|
|
state.admin.authorize(peer, headers)?;
|
|
return Ok(configured_admin(
|
|
"local-development",
|
|
Principal::LocalDevelopment,
|
|
));
|
|
}
|
|
Err(StatusCode::UNAUTHORIZED)
|
|
}
|
|
|
|
/// Management endpoints that only a configured administrator may use.
|
|
pub(super) fn admin_read(
|
|
state: &HubState,
|
|
peer: SocketAddr,
|
|
headers: &HeaderMap,
|
|
) -> Result<OperatorActor, StatusCode> {
|
|
let actor = authenticate(state, peer, headers, false)?;
|
|
super::gate::admin_only(state, &actor)?;
|
|
Ok(actor)
|
|
}
|
|
|
|
pub(super) fn admin_write(
|
|
state: &HubState,
|
|
peer: SocketAddr,
|
|
headers: &HeaderMap,
|
|
) -> Result<OperatorActor, StatusCode> {
|
|
let actor = authenticate(state, peer, headers, true)?;
|
|
super::gate::admin_only(state, &actor)?;
|
|
Ok(actor)
|
|
}
|
|
|
|
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", put(rename_orbit))
|
|
.route("/api/v1/orbits/:id/retention", put(update_orbit_retention))
|
|
.route("/api/v1/orbits/:id/run", post(trigger_orbit))
|
|
.route("/api/v1/orbits/:id/outpost", put(bind_outpost))
|
|
.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/outposts/:id/rotate",
|
|
post(rotate_outpost_token),
|
|
)
|
|
.route("/api/v1/wormhole/outposts/:id/revoke", post(revoke_outpost))
|
|
.route("/api/v1/wormhole/upload/init", post(wormhole_upload_init))
|
|
.route("/api/v1/wormhole/upload/chunk", post(wormhole_upload_chunk))
|
|
.route(
|
|
"/api/v1/wormhole/restic/commit",
|
|
post(wormhole_restic_commit),
|
|
)
|
|
.merge(super::jobs::routes())
|
|
.merge(super::catalog::routes())
|
|
.merge(super::session::routes())
|
|
.merge(super::oidc::routes())
|
|
.merge(super::access::routes())
|
|
.merge(super::relations::routes())
|
|
.merge(super::refresh::routes())
|
|
.merge(super::restore::routes())
|
|
.route("/api-doc/openapi.json", get(openapi_document))
|
|
.with_state(state);
|
|
|
|
let hsts = matches!(
|
|
std::env::var("TESSERA_HSTS").as_deref(),
|
|
Ok("1" | "true")
|
|
);
|
|
api.fallback(spa_fallback)
|
|
.layer(TraceLayer::new_for_http().make_span_with(request_span))
|
|
.layer(axum::middleware::from_fn(move |request, next| {
|
|
security_headers(hsts, request, next)
|
|
}))
|
|
}
|
|
|
|
/// The log span for a request: method and path only. The query string is left out because it carries
|
|
/// OIDC `code` and `state` values (and may carry other secrets).
|
|
fn request_span(request: &axum::http::Request<axum::body::Body>) -> tracing::Span {
|
|
tracing::info_span!("request", method = %request.method(), path = %request.uri().path())
|
|
}
|
|
|
|
/// Policy for the bundled web app: everything from this origin. The stylesheet pulls the
|
|
/// Google Fonts CSS and font files, hence those two allowances.
|
|
const CONTENT_SECURITY_POLICY: &str = "default-src 'self'; script-src 'self'; \
|
|
style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; \
|
|
img-src 'self' data: blob:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'";
|
|
|
|
async fn security_headers(
|
|
hsts: bool,
|
|
request: axum::extract::Request,
|
|
next: axum::middleware::Next,
|
|
) -> axum::response::Response {
|
|
let mut response = next.run(request).await;
|
|
let headers = response.headers_mut();
|
|
headers.insert(
|
|
header::CONTENT_SECURITY_POLICY,
|
|
HeaderValue::from_static(CONTENT_SECURITY_POLICY),
|
|
);
|
|
headers.insert(
|
|
header::X_CONTENT_TYPE_OPTIONS,
|
|
HeaderValue::from_static("nosniff"),
|
|
);
|
|
headers.insert(header::REFERRER_POLICY, HeaderValue::from_static("no-referrer"));
|
|
headers.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY"));
|
|
if hsts {
|
|
headers.insert(
|
|
header::STRICT_TRANSPORT_SECURITY,
|
|
HeaderValue::from_static("max-age=31536000; includeSubDomains"),
|
|
);
|
|
}
|
|
response
|
|
}
|
|
|
|
/// The API description needs a signed-in operator or the admin token, unless
|
|
/// `TESSERA_PUBLIC_OPENAPI=true` publishes it.
|
|
async fn openapi_document(
|
|
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
|
State(state): State<HubState>,
|
|
headers: HeaderMap,
|
|
) -> Result<Json<utoipa::openapi::OpenApi>, StatusCode> {
|
|
let public = matches!(
|
|
std::env::var("TESSERA_PUBLIC_OPENAPI").as_deref(),
|
|
Ok("1" | "true")
|
|
);
|
|
if !public {
|
|
authenticate(&state, peer, &headers, false)?;
|
|
}
|
|
Ok(Json(ApiDoc::openapi()))
|
|
}
|
|
|
|
#[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> {
|
|
let actor = authenticate(&state, peer, &headers, false)?;
|
|
let visible = super::gate::visible(&state, &actor, Permission::SnapshotRead)?;
|
|
let vault = state.vault.read().await;
|
|
let snaps = vault
|
|
.list_snapshots()
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
let names = state
|
|
.db
|
|
.orbit_names()
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
let out = snaps
|
|
.into_iter()
|
|
.filter(|s| s.manifest.provider != "legacy-history")
|
|
.filter(|s| visible.contains(s.manifest.orbit_id))
|
|
.map(|s| SnapshotSummary {
|
|
id: s.id,
|
|
orbit_id: s.manifest.orbit_id,
|
|
taken_at: s.taken_at,
|
|
capture: CaptureSnapshotSummary::from_manifest(&s.manifest),
|
|
kind: if s.manifest.is_restore_safety() {
|
|
"safety"
|
|
} else {
|
|
"capture"
|
|
},
|
|
// the orbit's current name; the manifest keeps the one it was written under
|
|
orbit_name: names
|
|
.get(&s.manifest.orbit_id)
|
|
.cloned()
|
|
.unwrap_or(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> {
|
|
let actor = authenticate(&state, peer, &headers, false)?;
|
|
let visible = super::gate::visible(&state, &actor, Permission::OrbitRead)?;
|
|
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()
|
|
.filter(|row| visible.contains(row.id))
|
|
.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)> {
|
|
admin_write(&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,
|
|
))
|
|
}
|
|
|
|
#[derive(serde::Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct OrbitRename {
|
|
name: String,
|
|
}
|
|
|
|
/// Change an orbit's name and nothing else. Its snapshots are shown under the new name from now on.
|
|
async fn rename_orbit(
|
|
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
|
State(state): State<HubState>,
|
|
headers: HeaderMap,
|
|
Path(id): Path<Uuid>,
|
|
Json(req): Json<OrbitRename>,
|
|
) -> Result<StatusCode, StatusCode> {
|
|
let actor = admin_write(&state, peer, &headers)?;
|
|
let name = req.name.trim();
|
|
if name.is_empty() || name.len() > 128 || name.chars().any(char::is_control) {
|
|
return Err(StatusCode::BAD_REQUEST);
|
|
}
|
|
match state
|
|
.db
|
|
.rename_orbit(id, name)
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
|
{
|
|
None => return Err(StatusCode::NOT_FOUND),
|
|
Some(false) => return Err(StatusCode::CONFLICT),
|
|
Some(true) => {}
|
|
}
|
|
state
|
|
.db
|
|
.audit("orbit.renamed", &format!("actor={actor} orbit={id}"))
|
|
.await
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
Ok(StatusCode::NO_CONTENT)
|
|
}
|
|
|
|
#[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)> {
|
|
admin_write(&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)> {
|
|
let actor = authenticate(&state, peer, &headers, true)
|
|
.map_err(|status| (status, "unauthorized".into()))?;
|
|
let orbit = state
|
|
.db
|
|
.list_orbits()
|
|
.await
|
|
.map_err(|_| {
|
|
(
|
|
StatusCode::INTERNAL_SERVER_ERROR,
|
|
"could not read orbits".into(),
|
|
)
|
|
})?
|
|
.into_iter()
|
|
.find(|orbit| orbit.id == id);
|
|
// Gate on the id first: unknown and not-visible look the same to a caller without access.
|
|
super::gate::scoped(&state, &actor, Permission::CaptureRun, id)
|
|
.map_err(|status| (status, "not permitted".into()))?;
|
|
let orbit = orbit.ok_or((StatusCode::NOT_FOUND, "orbit not found".into()))?;
|
|
if orbit.provider == "wormhole" {
|
|
return Err((
|
|
StatusCode::CONFLICT,
|
|
"queue the capture through its Outpost profile or run the legacy agent".into(),
|
|
));
|
|
}
|
|
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> {
|
|
admin_write(&state, peer, &headers)?;
|
|
// Every caller, browser or API token, may only name a file inside the hub's exports directory,
|
|
// and never one that already exists.
|
|
let destination = browser_export_path(&state, &req.target_path)?;
|
|
if destination.symlink_metadata().is_ok() {
|
|
return Err(StatusCode::CONFLICT);
|
|
}
|
|
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 {
|
|
evict_reconstitute_later(&state_bg, session_id);
|
|
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 {
|
|
evict_reconstitute_later(&state_bg, session_id);
|
|
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;
|
|
evict_reconstitute_later(&state_bg, session_id);
|
|
});
|
|
|
|
Ok(Json(ReconstituteStartResponse {
|
|
session_id,
|
|
session,
|
|
}))
|
|
}
|
|
|
|
/// How long a finished restore session stays readable before its entry is dropped.
|
|
const RECONSTITUTE_RETAIN: std::time::Duration = std::time::Duration::from_secs(3600);
|
|
|
|
/// Drops a finished session from the in-memory map after `RECONSTITUTE_RETAIN`, so the map does
|
|
/// not grow for as long as the hub runs.
|
|
fn evict_reconstitute_later(state: &HubState, id: Uuid) {
|
|
let state = state.clone();
|
|
tokio::spawn(async move {
|
|
tokio::time::sleep(RECONSTITUTE_RETAIN).await;
|
|
state.reconstitute_sessions.write().await.remove(&id);
|
|
});
|
|
}
|
|
|
|
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> {
|
|
admin_read(&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> {
|
|
admin_write(&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> {
|
|
admin_read(&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> {
|
|
admin_write(&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);
|
|
// Only a digest of the code is stored, and no token exists yet: it is minted at claim.
|
|
state
|
|
.db
|
|
.insert_pairing(&Uuid::new_v4().to_string(), &code, expires.timestamp())
|
|
.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), (status = 429)))]
|
|
async fn pairing_claim(
|
|
peer: Option<ConnectInfo<SocketAddr>>,
|
|
State(state): State<HubState>,
|
|
headers: HeaderMap,
|
|
Json(req): Json<ClaimRequest>,
|
|
) -> Result<Json<ClaimResponse>, StatusCode> {
|
|
let source = state
|
|
.limits
|
|
.source(peer.map(|ConnectInfo(addr)| addr), &headers);
|
|
if !state.limits.claim_allowed(source) {
|
|
if state.limits.audit_denial(source) {
|
|
let _ = state.db.audit_event(
|
|
&Principal::Anonymous,
|
|
AuditAction::OutpostPair,
|
|
AuditResource::Api,
|
|
AuditOutcome::Denied,
|
|
Uuid::new_v4(),
|
|
);
|
|
}
|
|
return Err(StatusCode::TOO_MANY_REQUESTS);
|
|
}
|
|
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 claimed = state
|
|
.db
|
|
.claim_pairing(&req.code, name, chrono::Utc::now().timestamp())
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
let Some(claimed) = claimed else {
|
|
let _ = state.db.audit_event(
|
|
&Principal::Anonymous,
|
|
AuditAction::OutpostPair,
|
|
AuditResource::Api,
|
|
AuditOutcome::Failed,
|
|
Uuid::new_v4(),
|
|
);
|
|
return Err(StatusCode::GONE);
|
|
};
|
|
let outpost_id =
|
|
Uuid::parse_str(&claimed.outpost_id).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
state
|
|
.db
|
|
.audit_event(
|
|
&Principal::Outpost(outpost_id),
|
|
AuditAction::OutpostPair,
|
|
AuditResource::Outpost(outpost_id),
|
|
AuditOutcome::Succeeded,
|
|
Uuid::new_v4(),
|
|
)
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
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();
|
|
Ok(Json(ClaimResponse {
|
|
outpost_id,
|
|
upload_token: claimed.token,
|
|
hub_url,
|
|
}))
|
|
}
|
|
|
|
#[derive(serde::Deserialize)]
|
|
struct RotateQuery {
|
|
/// Minutes the previous token keeps working (default 60, 0 = cut at once, max 1440).
|
|
grace_minutes: Option<i64>,
|
|
}
|
|
|
|
#[derive(serde::Serialize, utoipa::ToSchema)]
|
|
struct RotateResponse {
|
|
outpost_id: Uuid,
|
|
upload_token: String,
|
|
expires_at: chrono::DateTime<chrono::Utc>,
|
|
previous_valid_until: Option<chrono::DateTime<chrono::Utc>>,
|
|
}
|
|
|
|
fn timestamp(seconds: i64) -> chrono::DateTime<chrono::Utc> {
|
|
chrono::DateTime::from_timestamp(seconds, 0).unwrap_or_default()
|
|
}
|
|
|
|
/// Issue a new upload token for a paired Outpost. The response is the only place
|
|
/// the token appears; the operator puts it on the agent within the grace window.
|
|
#[utoipa::path(post, path = "/api/v1/wormhole/outposts/{id}/rotate",
|
|
params(("id" = Uuid, Path, description = "paired Outpost")),
|
|
responses((status = 200, body = RotateResponse), (status = 404)))]
|
|
async fn rotate_outpost_token(
|
|
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
|
State(state): State<HubState>,
|
|
headers: HeaderMap,
|
|
Path(id): Path<Uuid>,
|
|
axum::extract::Query(query): axum::extract::Query<RotateQuery>,
|
|
) -> Result<(HeaderMap, Json<RotateResponse>), StatusCode> {
|
|
let actor = admin_write(&state, peer, &headers)?;
|
|
let grace = query.grace_minutes.unwrap_or(60);
|
|
if !(0..=1440).contains(&grace) {
|
|
return Err(StatusCode::BAD_REQUEST);
|
|
}
|
|
let now = chrono::Utc::now().timestamp();
|
|
let issued = state
|
|
.db
|
|
.rotate_credential(&id.to_string(), grace * 60, now)
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
let outcome = if issued.is_some() {
|
|
AuditOutcome::Succeeded
|
|
} else {
|
|
AuditOutcome::Failed
|
|
};
|
|
state
|
|
.db
|
|
.audit_event(
|
|
&actor.principal,
|
|
AuditAction::CredentialRotate,
|
|
AuditResource::Outpost(id),
|
|
outcome,
|
|
actor.request_id,
|
|
)
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
let issued = issued.ok_or(StatusCode::NOT_FOUND)?;
|
|
let mut response_headers = HeaderMap::new();
|
|
response_headers.insert(
|
|
axum::http::header::CACHE_CONTROL,
|
|
HeaderValue::from_static("no-store"),
|
|
);
|
|
Ok((
|
|
response_headers,
|
|
Json(RotateResponse {
|
|
outpost_id: id,
|
|
upload_token: issued.token,
|
|
expires_at: timestamp(issued.expires_at),
|
|
previous_valid_until: issued.previous_valid_until.map(timestamp),
|
|
}),
|
|
))
|
|
}
|
|
|
|
/// Revoke every credential of an Outpost. Its next request is refused; a leased
|
|
/// job it was running can no longer report. It has to be paired again.
|
|
#[utoipa::path(post, path = "/api/v1/wormhole/outposts/{id}/revoke",
|
|
params(("id" = Uuid, Path, description = "Outpost to revoke")),
|
|
responses((status = 204), (status = 404)))]
|
|
async fn revoke_outpost(
|
|
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
|
State(state): State<HubState>,
|
|
headers: HeaderMap,
|
|
Path(id): Path<Uuid>,
|
|
) -> Result<StatusCode, StatusCode> {
|
|
let actor = admin_write(&state, peer, &headers)?;
|
|
let known = state
|
|
.db
|
|
.revoke_outpost(&id.to_string(), chrono::Utc::now().timestamp())
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
let outcome = if known {
|
|
AuditOutcome::Succeeded
|
|
} else {
|
|
AuditOutcome::Failed
|
|
};
|
|
state
|
|
.db
|
|
.audit_event(
|
|
&actor.principal,
|
|
AuditAction::CredentialRevoke,
|
|
AuditResource::Outpost(id),
|
|
outcome,
|
|
actor.request_id,
|
|
)
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
if known {
|
|
Ok(StatusCode::NO_CONTENT)
|
|
} else {
|
|
Err(StatusCode::NOT_FOUND)
|
|
}
|
|
}
|
|
|
|
#[derive(serde::Deserialize, utoipa::ToSchema)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct OutpostBinding {
|
|
outpost_id: Uuid,
|
|
}
|
|
|
|
#[utoipa::path(put, path = "/api/v1/orbits/{id}/outpost", request_body = OutpostBinding,
|
|
params(("id" = Uuid, Path, description = "legacy orbit id")),
|
|
responses((status = 204), (status = 401), (status = 404)))]
|
|
async fn bind_outpost(
|
|
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
|
State(state): State<HubState>,
|
|
headers: HeaderMap,
|
|
Path(orbit): Path<Uuid>,
|
|
Json(binding): Json<OutpostBinding>,
|
|
) -> Result<StatusCode, StatusCode> {
|
|
let actor = admin_write(&state, peer, &headers)?;
|
|
let _vault = state.vault.write().await;
|
|
if !state
|
|
.db
|
|
.bind_legacy_outpost(orbit, binding.outpost_id)
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
|
{
|
|
return Err(StatusCode::NOT_FOUND);
|
|
}
|
|
state
|
|
.db
|
|
.audit(
|
|
"orbit.outpost_bound",
|
|
&format!("actor={actor} orbit={orbit} outpost={}", binding.outpost_id),
|
|
)
|
|
.await
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
state
|
|
.db
|
|
.audit_event(
|
|
&actor.principal,
|
|
AuditAction::OutpostBind,
|
|
AuditResource::Orbit(orbit),
|
|
AuditOutcome::Succeeded,
|
|
actor.request_id,
|
|
)
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
Ok(StatusCode::NO_CONTENT)
|
|
}
|
|
|
|
fn require_legacy_upload_owner(
|
|
state: &HubState,
|
|
orbit: Uuid,
|
|
outpost: Uuid,
|
|
) -> Result<(), StatusCode> {
|
|
let allowed = state
|
|
.db
|
|
.legacy_upload_owned_by(orbit, outpost)
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
state
|
|
.db
|
|
.audit_event(
|
|
&Principal::Outpost(outpost),
|
|
AuditAction::Authorization,
|
|
AuditResource::Orbit(orbit),
|
|
if allowed {
|
|
AuditOutcome::Allowed
|
|
} else {
|
|
AuditOutcome::Denied
|
|
},
|
|
Uuid::new_v4(),
|
|
)
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
if allowed {
|
|
Ok(())
|
|
} else {
|
|
Err(StatusCode::NOT_FOUND)
|
|
}
|
|
}
|
|
|
|
#[utoipa::path(post, path = "/api/v1/wormhole/upload/init", request_body = UploadInit, responses((status = 200)))]
|
|
async fn wormhole_upload_init(
|
|
State(state): State<HubState>,
|
|
peer: Option<ConnectInfo<SocketAddr>>,
|
|
headers: axum::http::HeaderMap,
|
|
Json(body): Json<UploadInit>,
|
|
) -> Result<Json<serde_json::Value>, StatusCode> {
|
|
let outpost = super::jobs::outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
|
|
require_legacy_upload_owner(&state, body.orbit_id, outpost)?;
|
|
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(),
|
|
outpost,
|
|
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, outpost, 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>,
|
|
peer: Option<ConnectInfo<SocketAddr>>,
|
|
headers: axum::http::HeaderMap,
|
|
Json(body): Json<UploadChunk>,
|
|
) -> Result<StatusCode, StatusCode> {
|
|
let outpost = super::jobs::outpost(&state, peer.map(|ConnectInfo(addr)| addr), &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.outpost_id.as_deref() != Some(outpost.to_string().as_str()) {
|
|
state
|
|
.db
|
|
.audit_event(
|
|
&Principal::Outpost(outpost),
|
|
AuditAction::Authorization,
|
|
AuditResource::UploadSession(body.session_id),
|
|
AuditOutcome::Denied,
|
|
Uuid::new_v4(),
|
|
)
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
return Err(StatusCode::NOT_FOUND);
|
|
}
|
|
require_legacy_upload_owner(&state, session.orbit_id, outpost)?;
|
|
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)
|
|
.truncate(false) // resumable upload: the part is written at offsets
|
|
.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, outpost, 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>,
|
|
peer: Option<ConnectInfo<SocketAddr>>,
|
|
headers: HeaderMap,
|
|
Json(body): Json<ResticCommit>,
|
|
) -> Result<Json<serde_json::Value>, StatusCode> {
|
|
let outpost_id = super::jobs::outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
|
|
require_legacy_upload_owner(&state, body.orbit_id, outpost_id)?;
|
|
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;
|
|
require_legacy_upload_owner(&state, orbit_id, outpost_id)?;
|
|
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,
|
|
outpost: 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;
|
|
require_legacy_upload_owner(state, orbit_id, outpost)?;
|
|
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) {
|
|
// Build output under /assets/ carries a content hash in its name.
|
|
let cache = if path.starts_with("assets/") {
|
|
"public, max-age=31536000, immutable"
|
|
} else {
|
|
"no-cache"
|
|
};
|
|
return (
|
|
StatusCode::OK,
|
|
[
|
|
(header::CONTENT_TYPE, content_type(&path)),
|
|
(header::CACHE_CONTROL, cache),
|
|
],
|
|
file.contents(),
|
|
)
|
|
.into_response();
|
|
}
|
|
// A missing asset or API path is a 404, not the app shell.
|
|
if path.starts_with("assets/") || path.starts_with("api/") {
|
|
return (StatusCode::NOT_FOUND, "not found").into_response();
|
|
}
|
|
if let Some(index) = WEB_DIST.get_file("index.html") {
|
|
return (
|
|
StatusCode::OK,
|
|
[
|
|
(header::CONTENT_TYPE, "text/html; charset=utf-8"),
|
|
(header::CACHE_CONTROL, "no-cache"),
|
|
],
|
|
index.contents(),
|
|
)
|
|
.into_response();
|
|
}
|
|
(StatusCode::NOT_FOUND, "not found").into_response()
|
|
}
|
|
|
|
fn content_type(path: &str) -> &'static str {
|
|
let extension = path.rsplit('.').next().unwrap_or("").to_ascii_lowercase();
|
|
match extension.as_str() {
|
|
"html" => "text/html; charset=utf-8",
|
|
"js" | "mjs" => "text/javascript; charset=utf-8",
|
|
"css" => "text/css; charset=utf-8",
|
|
"svg" => "image/svg+xml",
|
|
"png" => "image/png",
|
|
"jpg" | "jpeg" => "image/jpeg",
|
|
"webp" => "image/webp",
|
|
"ico" => "image/x-icon",
|
|
"woff" => "font/woff",
|
|
"woff2" => "font/woff2",
|
|
"json" => "application/json",
|
|
"map" => "application/json",
|
|
"txt" => "text/plain; charset=utf-8",
|
|
_ => "application/octet-stream",
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use axum::body::{to_bytes, Body};
|
|
use axum::http::Request;
|
|
use tower::ServiceExt;
|
|
|
|
async fn denied_authentication_rows(dir: &std::path::Path) -> i64 {
|
|
rusqlite::Connection::open(dir.join("tessera.db"))
|
|
.unwrap()
|
|
.query_row(
|
|
"SELECT count(*) FROM audit_events WHERE action='authentication.check' AND outcome='denied'",
|
|
[],
|
|
|r| r.get(0),
|
|
)
|
|
.unwrap()
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn unauthenticated_floods_write_one_denial_row_per_source() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
|
|
.await
|
|
.unwrap();
|
|
state.admin.token = Some("synthetic-admin-token-of-32-chars!".into());
|
|
let app = router(state);
|
|
let human = |ip: &str| {
|
|
Request::get("/api/v1/orbits")
|
|
.extension(ConnectInfo(format!("{ip}:9000").parse::<SocketAddr>().unwrap()))
|
|
.body(Body::empty())
|
|
.unwrap()
|
|
};
|
|
let outpost = |ip: &str| {
|
|
Request::post("/api/v1/wormhole/upload/init")
|
|
.extension(ConnectInfo(format!("{ip}:9000").parse::<SocketAddr>().unwrap()))
|
|
.header(header::CONTENT_TYPE, "application/json")
|
|
.header("x-tessera-upload-token", "wrong")
|
|
.body(Body::from(r#"{"orbit_id":"00000000-0000-0000-0000-000000000000","total_bytes":1}"#))
|
|
.unwrap()
|
|
};
|
|
for _ in 0..25 {
|
|
let r = app.clone().oneshot(human("203.0.113.5")).await.unwrap();
|
|
assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
|
|
}
|
|
assert_eq!(denied_authentication_rows(dir.path()).await, 1);
|
|
for _ in 0..25 {
|
|
let r = app.clone().oneshot(outpost("203.0.113.5")).await.unwrap();
|
|
assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
|
|
}
|
|
// the same source shares one budget across both entry points
|
|
assert_eq!(denied_authentication_rows(dir.path()).await, 1);
|
|
// another source still gets its own row
|
|
let r = app.clone().oneshot(outpost("203.0.113.6")).await.unwrap();
|
|
assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
|
|
assert_eq!(denied_authentication_rows(dir.path()).await, 2);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn wrong_admin_tokens_are_throttled_per_source() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
|
|
.await
|
|
.unwrap();
|
|
state.admin.token = Some("synthetic-admin-token-of-32-chars!".into());
|
|
let app = router(state);
|
|
let req = |ip: &str, token: &str| {
|
|
Request::get("/api/v1/orbits")
|
|
.extension(ConnectInfo(format!("{ip}:9000").parse::<SocketAddr>().unwrap()))
|
|
.header("x-tessera-admin-token", token)
|
|
.body(Body::empty())
|
|
.unwrap()
|
|
};
|
|
let mut limited = false;
|
|
for _ in 0..20 {
|
|
let r = app.clone().oneshot(req("203.0.113.20", "wrong")).await.unwrap();
|
|
limited |= r.status() == StatusCode::TOO_MANY_REQUESTS;
|
|
}
|
|
assert!(limited);
|
|
let r = app.oneshot(req("203.0.113.21", "wrong")).await.unwrap();
|
|
assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn reconstitute_targets_stay_inside_the_exports_directory_for_every_caller() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
|
|
.await
|
|
.unwrap();
|
|
state.admin.token = Some("synthetic-admin-token-of-32-chars!".into());
|
|
let app = router(state);
|
|
let attempt = |path: &str| {
|
|
Request::post("/api/v1/reconstitute")
|
|
.extension(ConnectInfo("203.0.113.30:9000".parse::<SocketAddr>().unwrap()))
|
|
.header(header::AUTHORIZATION, "Bearer synthetic-admin-token-of-32-chars!")
|
|
.header(header::CONTENT_TYPE, "application/json")
|
|
.body(Body::from(
|
|
serde_json::json!({"snapshot_id": Uuid::new_v4(), "target_path": path}).to_string(),
|
|
))
|
|
.unwrap()
|
|
};
|
|
for path in ["/etc/passwd", "../escape", "a/b", "..", ""] {
|
|
let r = app.clone().oneshot(attempt(path)).await.unwrap();
|
|
assert_eq!(r.status(), StatusCode::BAD_REQUEST, "{path}");
|
|
}
|
|
// a plain file name passes confinement (the unknown snapshot is what stops it)
|
|
let r = app.clone().oneshot(attempt("dump.sql")).await.unwrap();
|
|
assert_eq!(r.status(), StatusCode::NOT_FOUND);
|
|
std::fs::write(dir.path().join("exports").join("taken.sql"), b"keep").unwrap();
|
|
let r = app.oneshot(attempt("taken.sql")).await.unwrap();
|
|
assert_eq!(r.status(), StatusCode::CONFLICT);
|
|
}
|
|
|
|
#[test]
|
|
fn request_logs_name_the_path_and_never_the_query() {
|
|
use std::sync::{Arc, Mutex};
|
|
#[derive(Clone, Default)]
|
|
struct Sink(Arc<Mutex<Vec<u8>>>);
|
|
impl std::io::Write for Sink {
|
|
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
|
self.0.lock().unwrap().extend_from_slice(buf);
|
|
Ok(buf.len())
|
|
}
|
|
fn flush(&mut self) -> std::io::Result<()> {
|
|
Ok(())
|
|
}
|
|
}
|
|
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Sink {
|
|
type Writer = Sink;
|
|
fn make_writer(&'a self) -> Sink {
|
|
self.clone()
|
|
}
|
|
}
|
|
let sink = Sink::default();
|
|
let subscriber = tracing_subscriber::fmt().with_writer(sink.clone()).finish();
|
|
tracing::subscriber::with_default(subscriber, || {
|
|
let request = Request::get("/api/v1/auth/oidc/callback?code=secret-code&state=secret-state")
|
|
.body(Body::empty())
|
|
.unwrap();
|
|
request_span(&request).in_scope(|| tracing::info!("handled"));
|
|
});
|
|
let logged = String::from_utf8(sink.0.lock().unwrap().clone()).unwrap();
|
|
assert!(logged.contains("/api/v1/auth/oidc/callback"), "{logged}");
|
|
assert!(!logged.contains("secret-code") && !logged.contains("secret-state"), "{logged}");
|
|
}
|
|
|
|
#[test]
|
|
fn content_types_are_right_and_unknown_is_never_html() {
|
|
assert_eq!(content_type("assets/x.png"), "image/png");
|
|
assert_eq!(content_type("assets/x.woff2"), "font/woff2");
|
|
assert_eq!(content_type("assets/x.woff"), "font/woff");
|
|
assert_eq!(content_type("favicon.ico"), "image/x-icon");
|
|
assert_eq!(content_type("assets/x.js.map"), "application/json");
|
|
assert_eq!(content_type("manifest.json"), "application/json");
|
|
assert_eq!(content_type("assets/x.bin"), "application/octet-stream");
|
|
assert_eq!(content_type("noextension"), "application/octet-stream");
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn the_api_description_is_not_served_to_anonymous_callers() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
|
|
.await
|
|
.unwrap();
|
|
state.admin.token = Some("synthetic-admin-token-of-32-chars!".into());
|
|
let app = router(state);
|
|
let request = |token: Option<&str>| {
|
|
let mut r = Request::get("/api-doc/openapi.json")
|
|
.extension(ConnectInfo("203.0.113.50:9000".parse::<SocketAddr>().unwrap()));
|
|
if let Some(token) = token {
|
|
r = r.header(header::AUTHORIZATION, format!("Bearer {token}"));
|
|
}
|
|
r.body(Body::empty()).unwrap()
|
|
};
|
|
let anonymous = app.clone().oneshot(request(None)).await.unwrap();
|
|
assert_eq!(anonymous.status(), StatusCode::UNAUTHORIZED);
|
|
let signed_in = app
|
|
.oneshot(request(Some("synthetic-admin-token-of-32-chars!")))
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(signed_in.status(), StatusCode::OK);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn responses_carry_security_headers_and_assets_cache_for_a_year() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
|
|
.await
|
|
.unwrap();
|
|
let app = router(state);
|
|
let get = |uri: &str| {
|
|
Request::get(uri)
|
|
.extension(ConnectInfo("203.0.113.40:9000".parse::<SocketAddr>().unwrap()))
|
|
.body(Body::empty())
|
|
.unwrap()
|
|
};
|
|
for uri in ["/", "/health", "/api/v1/orbits"] {
|
|
let r = app.clone().oneshot(get(uri)).await.unwrap();
|
|
let h = r.headers();
|
|
let csp = h[header::CONTENT_SECURITY_POLICY].to_str().unwrap();
|
|
assert!(csp.contains("default-src 'self'") && csp.contains("frame-ancestors 'none'"));
|
|
assert_eq!(h[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
|
|
assert_eq!(h[header::REFERRER_POLICY], "no-referrer");
|
|
assert_eq!(h[header::X_FRAME_OPTIONS], "DENY");
|
|
}
|
|
let missing = app.clone().oneshot(get("/assets/nope.js")).await.unwrap();
|
|
assert_eq!(missing.status(), StatusCode::NOT_FOUND);
|
|
if let Some(file) = WEB_DIST.get_dir("assets").and_then(|d| d.files().next()) {
|
|
let uri = format!("/{}", file.path().display());
|
|
let r = app.oneshot(get(&uri)).await.unwrap();
|
|
assert_eq!(r.status(), StatusCode::OK);
|
|
assert_eq!(
|
|
r.headers()[header::CACHE_CONTROL],
|
|
"public, max-age=31536000, immutable"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn a_failed_denial_audit_write_still_answers_401() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
|
|
.await
|
|
.unwrap();
|
|
state.admin.token = Some("synthetic-admin-token-of-32-chars!".into());
|
|
let app = router(state);
|
|
rusqlite::Connection::open(dir.path().join("tessera.db"))
|
|
.unwrap()
|
|
.execute_batch("DROP TABLE audit_events")
|
|
.unwrap();
|
|
let human = Request::get("/api/v1/orbits")
|
|
.extension(ConnectInfo("203.0.113.9:9000".parse::<SocketAddr>().unwrap()))
|
|
.body(Body::empty())
|
|
.unwrap();
|
|
assert_eq!(
|
|
app.clone().oneshot(human).await.unwrap().status(),
|
|
StatusCode::UNAUTHORIZED
|
|
);
|
|
let outpost = Request::post("/api/v1/wormhole/upload/init")
|
|
.extension(ConnectInfo("203.0.113.10:9000".parse::<SocketAddr>().unwrap()))
|
|
.header(header::CONTENT_TYPE, "application/json")
|
|
.header("x-tessera-upload-token", "wrong")
|
|
.body(Body::from(r#"{"orbit_id":"00000000-0000-0000-0000-000000000000","total_bytes":1}"#))
|
|
.unwrap();
|
|
assert_eq!(
|
|
app.oneshot(outpost).await.unwrap().status(),
|
|
StatusCode::UNAUTHORIZED
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn legacy_uploads_are_owned_by_the_assigned_outpost() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
|
|
.await
|
|
.unwrap();
|
|
state.accept_plain_upload = true;
|
|
state.admin.token = Some("synthetic-admin".into());
|
|
let a = Uuid::new_v4();
|
|
let b = Uuid::new_v4();
|
|
for (id, token) in [(a, "outpost-a"), (b, "outpost-b")] {
|
|
state
|
|
.db
|
|
.insert_test_credential(token, &id.to_string(), "agent");
|
|
}
|
|
let orbit = Uuid::new_v4();
|
|
state
|
|
.db
|
|
.upsert_orbit(&OrbitRow {
|
|
id: orbit,
|
|
name: "synthetic".into(),
|
|
provider: "wormhole".into(),
|
|
provider_config: "{}".into(),
|
|
schedule: None,
|
|
decay_preset: "keep-all".into(),
|
|
retention: None,
|
|
dry_run: false,
|
|
last_status: "idle".into(),
|
|
})
|
|
.await
|
|
.unwrap();
|
|
// Synthetic legacy sessions have no owner and must never be adopted.
|
|
let old_session = Uuid::new_v4();
|
|
let conn = rusqlite::Connection::open(dir.path().join("tessera.db")).unwrap();
|
|
conn.execute(
|
|
"INSERT INTO upload_sessions(id,orbit_id,total,created_at) VALUES (?1,?2,1,'2026')",
|
|
rusqlite::params![old_session.to_string(), orbit.to_string()],
|
|
)
|
|
.unwrap();
|
|
let app = router(state.clone());
|
|
let request = |path: &str, token: &str, body: serde_json::Value| {
|
|
Request::post(path)
|
|
.header(header::CONTENT_TYPE, "application/json")
|
|
.header("x-tessera-upload-token", token)
|
|
.body(Body::from(body.to_string()))
|
|
.unwrap()
|
|
};
|
|
let init = serde_json::json!({"orbit_id":orbit,"total_bytes":2});
|
|
assert_eq!(
|
|
app.clone()
|
|
.oneshot(request(
|
|
"/api/v1/wormhole/upload/init",
|
|
"outpost-a",
|
|
init.clone()
|
|
))
|
|
.await
|
|
.unwrap()
|
|
.status(),
|
|
StatusCode::NOT_FOUND
|
|
);
|
|
let binding = |token: &str| {
|
|
Request::put(format!("/api/v1/orbits/{orbit}/outpost"))
|
|
.extension(ConnectInfo("127.0.0.1:9000".parse::<SocketAddr>().unwrap()))
|
|
.header(header::CONTENT_TYPE, "application/json")
|
|
.header(header::AUTHORIZATION, format!("Bearer {token}"))
|
|
.body(Body::from(serde_json::json!({"outpost_id":a}).to_string()))
|
|
.unwrap()
|
|
};
|
|
assert_eq!(
|
|
app.clone()
|
|
.oneshot(binding("outpost-a"))
|
|
.await
|
|
.unwrap()
|
|
.status(),
|
|
StatusCode::UNAUTHORIZED
|
|
);
|
|
assert_eq!(
|
|
app.clone()
|
|
.oneshot(binding("synthetic-admin"))
|
|
.await
|
|
.unwrap()
|
|
.status(),
|
|
StatusCode::NO_CONTENT
|
|
);
|
|
assert_eq!(
|
|
app.clone()
|
|
.oneshot(request(
|
|
"/api/v1/wormhole/upload/init",
|
|
"outpost-b",
|
|
init.clone()
|
|
))
|
|
.await
|
|
.unwrap()
|
|
.status(),
|
|
StatusCode::NOT_FOUND
|
|
);
|
|
let response = app
|
|
.clone()
|
|
.oneshot(request("/api/v1/wormhole/upload/init", "outpost-a", init))
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(response.status(), StatusCode::OK);
|
|
let json: serde_json::Value =
|
|
serde_json::from_slice(&to_bytes(response.into_body(), 1024).await.unwrap()).unwrap();
|
|
let session = json["session_id"].as_str().unwrap();
|
|
for (id, token, expected) in [
|
|
(session, "outpost-b", StatusCode::NOT_FOUND),
|
|
(&old_session.to_string(), "outpost-a", StatusCode::NOT_FOUND),
|
|
(session, "outpost-a", StatusCode::NO_CONTENT),
|
|
(session, "outpost-a", StatusCode::NO_CONTENT),
|
|
] {
|
|
let chunk = serde_json::json!({"session_id":id,"offset":0,"data_b64":"YQ=="});
|
|
assert_eq!(
|
|
app.clone()
|
|
.oneshot(request("/api/v1/wormhole/upload/chunk", token, chunk))
|
|
.await
|
|
.unwrap()
|
|
.status(),
|
|
expected
|
|
);
|
|
}
|
|
// Foreign Outpost cannot send the final chunk (which would seal).
|
|
let final_chunk = serde_json::json!({"session_id":session,"offset":1,"data_b64":"Yg=="});
|
|
assert_eq!(
|
|
app.clone()
|
|
.oneshot(request(
|
|
"/api/v1/wormhole/upload/chunk",
|
|
"outpost-b",
|
|
final_chunk.clone()
|
|
))
|
|
.await
|
|
.unwrap()
|
|
.status(),
|
|
StatusCode::NOT_FOUND
|
|
);
|
|
assert_eq!(
|
|
app.clone()
|
|
.oneshot(request(
|
|
"/api/v1/wormhole/upload/chunk",
|
|
"outpost-a",
|
|
final_chunk
|
|
))
|
|
.await
|
|
.unwrap()
|
|
.status(),
|
|
StatusCode::NO_CONTENT
|
|
);
|
|
let foreign_commit = serde_json::json!({"orbit_id":orbit,"snapshot_id":"a".repeat(64)});
|
|
assert_eq!(
|
|
app.oneshot(request(
|
|
"/api/v1/wormhole/restic/commit",
|
|
"outpost-b",
|
|
foreign_commit
|
|
))
|
|
.await
|
|
.unwrap()
|
|
.status(),
|
|
StatusCode::NOT_FOUND
|
|
);
|
|
|
|
// Queue rebinding ahead of a former-owner commit while both wait on the vault.
|
|
let guard = state.vault.read().await;
|
|
let mut admin_headers = HeaderMap::new();
|
|
admin_headers.insert(
|
|
header::AUTHORIZATION,
|
|
HeaderValue::from_static("Bearer synthetic-admin"),
|
|
);
|
|
let mut binding = Box::pin(bind_outpost(
|
|
ConnectInfo("127.0.0.1:9000".parse().unwrap()),
|
|
State(state.clone()),
|
|
admin_headers,
|
|
Path(orbit),
|
|
Json(OutpostBinding { outpost_id: b }),
|
|
));
|
|
use std::{future::Future, task::Poll};
|
|
assert!(matches!(
|
|
std::future::poll_fn(|cx| Poll::Ready(binding.as_mut().poll(cx))).await,
|
|
Poll::Pending
|
|
));
|
|
let mut owner_headers = HeaderMap::new();
|
|
owner_headers.insert(
|
|
"x-tessera-upload-token",
|
|
HeaderValue::from_static("outpost-a"),
|
|
);
|
|
let mut commit = Box::pin(wormhole_restic_commit(
|
|
State(state.clone()),
|
|
None,
|
|
owner_headers,
|
|
Json(ResticCommit {
|
|
orbit_id: orbit,
|
|
snapshot_id: "a".repeat(64),
|
|
}),
|
|
));
|
|
assert!(matches!(
|
|
std::future::poll_fn(|cx| Poll::Ready(commit.as_mut().poll(cx))).await,
|
|
Poll::Pending
|
|
));
|
|
drop(guard);
|
|
assert_eq!(binding.await.unwrap(), StatusCode::NO_CONTENT);
|
|
assert_eq!(commit.await.err(), Some(StatusCode::NOT_FOUND));
|
|
let denied: i64 = conn.query_row(
|
|
"SELECT count(*) FROM audit_events WHERE actor_id=?1 AND resource_type='orbit' AND resource_id=?2
|
|
AND action='authorization.check' AND outcome='denied'",
|
|
rusqlite::params![b.to_string(),orbit.to_string()], |r| r.get(0)).unwrap();
|
|
assert!(denied >= 2);
|
|
let denied_session: i64 = conn.query_row(
|
|
"SELECT count(*) FROM audit_events WHERE actor_id=?1 AND resource_type='upload_session'
|
|
AND resource_id=?2 AND outcome='denied'",
|
|
rusqlite::params![b.to_string(),session], |r| r.get(0)).unwrap();
|
|
assert_eq!(denied_session, 2);
|
|
}
|
|
|
|
#[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-passphrase")
|
|
.await
|
|
.unwrap();
|
|
state.admin.token = Some("fixture-admin".into());
|
|
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(header::AUTHORIZATION, "Bearer fixture-admin")
|
|
.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_test_credential("fixture-token", &outpost.to_string(), "agent");
|
|
assert!(state.db.bind_legacy_outpost(orbit.id, outpost).unwrap());
|
|
{
|
|
let conn = rusqlite::Connection::open(dir.path().join("tessera.db")).unwrap();
|
|
conn.execute("UPDATE outposts SET last_seen = NULL", [])
|
|
.unwrap();
|
|
}
|
|
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-passphrase")
|
|
.await
|
|
.unwrap();
|
|
state.admin.token = Some("fixture-admin".into());
|
|
let app = router(state);
|
|
for (source, access, config, expected) in [
|
|
(
|
|
"filesystem",
|
|
"hub",
|
|
serde_json::json!({"paths": ["/data/source"]}),
|
|
StatusCode::OK,
|
|
),
|
|
(
|
|
"filesystem",
|
|
"hub",
|
|
serde_json::json!({"paths": []}),
|
|
StatusCode::BAD_REQUEST,
|
|
),
|
|
(
|
|
"filesystem",
|
|
"outpost",
|
|
serde_json::json!({}),
|
|
StatusCode::OK,
|
|
),
|
|
("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")
|
|
.header(header::AUTHORIZATION, "Bearer fixture-admin")
|
|
.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-passphrase")
|
|
.await
|
|
.unwrap();
|
|
state.admin.token = Some("fixture-admin".into());
|
|
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")
|
|
.header(header::AUTHORIZATION, "Bearer fixture-admin")
|
|
.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"]
|
|
);
|
|
}
|
|
}
|