- downloads are named <orbit>_<time>_<engine>_<id8>.<ext> (schedule zone or UTC), orbit names are reduced to [a-z0-9_-], and the header carries filename and filename* - operators can change a profile's schedule and retention (absent = keep, null = clear), validated like registration, audited, and a changed schedule never replays slots that already passed Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
599 lines
20 KiB
Rust
599 lines
20 KiB
Rust
use super::routes::{admin_write, authenticate, upload_token};
|
|
use crate::auth::Permission;
|
|
use crate::state::HubState;
|
|
use axum::{
|
|
body::{Body, HttpBody},
|
|
extract::{rejection::JsonRejection, ConnectInfo, Path, Query, State},
|
|
http::{header, HeaderMap, StatusCode},
|
|
routing::{get, post},
|
|
Json, Router,
|
|
};
|
|
use base64::Engine;
|
|
use sha2::{Digest, Sha256};
|
|
use std::{net::SocketAddr, pin::Pin, time::Duration};
|
|
use tessera_core::job::{
|
|
CaptureEvent, CaptureFormat, CaptureJob, CaptureLease, CaptureProfile, CaptureReport,
|
|
ResticCaptureCommit,
|
|
};
|
|
use tessera_core::{restore::DatabaseIdentity, SnapshotManifest};
|
|
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
|
|
use uuid::Uuid;
|
|
|
|
pub(super) fn routes() -> Router<HubState> {
|
|
Router::new()
|
|
.route(
|
|
"/api/v1/capture-profiles",
|
|
get(profiles).post(register_profile),
|
|
)
|
|
.route(
|
|
"/api/v1/capture-profiles/:id",
|
|
axum::routing::put(update_profile),
|
|
)
|
|
.route("/api/v1/capture-profiles/:id/jobs", post(enqueue))
|
|
.route("/api/v1/capture-jobs", get(history))
|
|
.route("/api/v1/capture-jobs/:id", get(job))
|
|
.route("/api/v1/capture-jobs/:id/events", get(events))
|
|
.route("/api/v1/wormhole/capture/:application/claim", post(claim))
|
|
.route("/api/v1/wormhole/capture/:id/report", post(report))
|
|
.route("/api/v1/wormhole/capture/:id/payload", post(upload))
|
|
.route("/api/v1/wormhole/capture/:id/restic", post(commit_restic))
|
|
}
|
|
|
|
async fn profiles(
|
|
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
|
State(state): State<HubState>,
|
|
headers: HeaderMap,
|
|
) -> Result<Json<Vec<CaptureProfile>>, StatusCode> {
|
|
let actor = authenticate(&state, peer, &headers, false)?;
|
|
let visible = super::gate::visible(&state, &actor, Permission::OrbitRead)?;
|
|
let profiles = state.db.capture_profiles().map_err(internal)?;
|
|
Ok(Json(
|
|
profiles
|
|
.into_iter()
|
|
.filter(|profile| visible.contains(profile.orbit_id))
|
|
.collect(),
|
|
))
|
|
}
|
|
|
|
async fn register_profile(
|
|
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
|
State(state): State<HubState>,
|
|
headers: HeaderMap,
|
|
Json(profile): Json<CaptureProfile>,
|
|
) -> Result<(StatusCode, Json<CaptureProfile>), StatusCode> {
|
|
let actor = admin_write(&state, peer, &headers)?;
|
|
if profile
|
|
.retention
|
|
.is_some_and(|retention| !retention.is_valid())
|
|
{
|
|
return Err(StatusCode::BAD_REQUEST);
|
|
}
|
|
if let Some(schedule) = &profile.schedule {
|
|
crate::scheduler::capture_schedule(schedule).ok_or(StatusCode::BAD_REQUEST)?;
|
|
}
|
|
let _vault = state.vault.write().await;
|
|
if !state
|
|
.db
|
|
.register_capture_profile(&profile, now())
|
|
.map_err(internal)?
|
|
{
|
|
return Err(StatusCode::CONFLICT);
|
|
}
|
|
state
|
|
.db
|
|
.audit(
|
|
"capture.profile_registered",
|
|
&format!("actor={actor} application={}", profile.application_id),
|
|
)
|
|
.await
|
|
.map_err(internal)?;
|
|
Ok((StatusCode::CREATED, Json(profile)))
|
|
}
|
|
|
|
/// Editable parts of a profile. A field that is absent stays as it is; `null` clears it. Anything else
|
|
/// (format, orbit, Outpost) is part of the profile's identity and is refused.
|
|
#[derive(serde::Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct ProfileUpdate {
|
|
#[serde(default, deserialize_with = "present")]
|
|
schedule: Option<Option<tessera_core::job::CaptureSchedule>>,
|
|
#[serde(default, deserialize_with = "present")]
|
|
retention: Option<Option<tessera_core::decay::CaptureRetention>>,
|
|
}
|
|
|
|
/// Tell `null` from an absent field: `Some(None)` for null, `Some(Some(v))` for a value.
|
|
fn present<'de, D, T>(deserializer: D) -> Result<Option<Option<T>>, D::Error>
|
|
where
|
|
D: serde::Deserializer<'de>,
|
|
T: serde::Deserialize<'de>,
|
|
{
|
|
<Option<T> as serde::Deserialize>::deserialize(deserializer).map(Some)
|
|
}
|
|
|
|
async fn update_profile(
|
|
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
|
State(state): State<HubState>,
|
|
headers: HeaderMap,
|
|
Path(id): Path<Uuid>,
|
|
Json(update): Json<ProfileUpdate>,
|
|
) -> Result<Json<CaptureProfile>, StatusCode> {
|
|
let actor = admin_write(&state, peer, &headers)?;
|
|
if let Some(Some(retention)) = &update.retention {
|
|
if !retention.is_valid() {
|
|
return Err(StatusCode::BAD_REQUEST);
|
|
}
|
|
}
|
|
if let Some(Some(schedule)) = &update.schedule {
|
|
crate::scheduler::capture_schedule(schedule).ok_or(StatusCode::BAD_REQUEST)?;
|
|
}
|
|
let mut fields = Vec::new();
|
|
if update.schedule.is_some() {
|
|
fields.push("schedule");
|
|
}
|
|
if update.retention.is_some() {
|
|
fields.push("retention");
|
|
}
|
|
let _vault = state.vault.write().await;
|
|
let profile = state
|
|
.db
|
|
.update_capture_profile(
|
|
id,
|
|
crate::db::ProfileChange {
|
|
schedule: update.schedule,
|
|
retention: update.retention,
|
|
},
|
|
now(),
|
|
)
|
|
.map_err(internal)?
|
|
.ok_or(StatusCode::NOT_FOUND)?;
|
|
state
|
|
.db
|
|
.audit(
|
|
"capture.profile_updated",
|
|
&format!("actor={actor} application={id} fields={}", fields.join(",")),
|
|
)
|
|
.await
|
|
.map_err(internal)?;
|
|
Ok(Json(profile))
|
|
}
|
|
|
|
async fn enqueue(
|
|
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
|
State(state): State<HubState>,
|
|
headers: HeaderMap,
|
|
Path(id): Path<Uuid>,
|
|
) -> Result<(StatusCode, Json<CaptureJob>), StatusCode> {
|
|
let actor = authenticate(&state, peer, &headers, true)?;
|
|
let orbit = state.db.orbit_of_application(id).map_err(internal)?;
|
|
match orbit {
|
|
Some(orbit) => super::gate::scoped(&state, &actor, Permission::CaptureRun, orbit)?,
|
|
// no such application: administrators learn that, everyone else cannot tell it from "not visible"
|
|
None => {
|
|
super::gate::admin_only(&state, &actor).map_err(|_| StatusCode::NOT_FOUND)?;
|
|
return Err(StatusCode::NOT_FOUND);
|
|
}
|
|
}
|
|
let job = state
|
|
.db
|
|
.enqueue_capture(id, &actor.id(), now())
|
|
.map_err(internal)?
|
|
.ok_or(StatusCode::NOT_FOUND)?;
|
|
Ok((StatusCode::ACCEPTED, Json(job)))
|
|
}
|
|
|
|
#[derive(serde::Deserialize)]
|
|
struct JobFilter {
|
|
application_id: Option<Uuid>,
|
|
status: Option<String>,
|
|
limit: Option<u16>,
|
|
}
|
|
|
|
async fn history(
|
|
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
|
State(state): State<HubState>,
|
|
headers: HeaderMap,
|
|
Query(filter): Query<JobFilter>,
|
|
) -> Result<Json<Vec<CaptureJob>>, StatusCode> {
|
|
let actor = authenticate(&state, peer, &headers, false)?;
|
|
let visible = super::gate::visible(&state, &actor, Permission::OrbitRead)?;
|
|
if let Some(application) = filter.application_id {
|
|
let orbit = state
|
|
.db
|
|
.orbit_of_application(application)
|
|
.map_err(internal)?;
|
|
if !orbit.is_some_and(|orbit| visible.contains(orbit)) {
|
|
return Err(StatusCode::NOT_FOUND);
|
|
}
|
|
}
|
|
if filter
|
|
.status
|
|
.as_deref()
|
|
.is_some_and(|status| !matches!(status, "queued" | "running" | "completed" | "failed"))
|
|
{
|
|
return Err(StatusCode::BAD_REQUEST);
|
|
}
|
|
state
|
|
.db
|
|
.capture_jobs(
|
|
filter.application_id,
|
|
filter.status.as_deref(),
|
|
filter.limit.unwrap_or(50).clamp(1, 200),
|
|
visible.restriction().as_deref(),
|
|
)
|
|
.map(Json)
|
|
.map_err(internal)
|
|
}
|
|
|
|
/// A capture job, if the caller may read its orbit; otherwise 404.
|
|
fn job_in_scope(
|
|
state: &HubState,
|
|
actor: &super::routes::OperatorActor,
|
|
id: Uuid,
|
|
) -> Result<CaptureJob, StatusCode> {
|
|
let job = state.db.capture_job(id).map_err(internal)?;
|
|
match job {
|
|
Some(job) => {
|
|
super::gate::scoped(state, actor, Permission::OrbitRead, job.profile.orbit_id)?;
|
|
Ok(job)
|
|
}
|
|
None => {
|
|
super::gate::admin_only(state, actor).map_err(|_| StatusCode::NOT_FOUND)?;
|
|
Err(StatusCode::NOT_FOUND)
|
|
}
|
|
}
|
|
}
|
|
|
|
async fn events(
|
|
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
|
State(state): State<HubState>,
|
|
headers: HeaderMap,
|
|
Path(id): Path<Uuid>,
|
|
) -> Result<Json<Vec<CaptureEvent>>, StatusCode> {
|
|
let actor = authenticate(&state, peer, &headers, false)?;
|
|
let job = job_in_scope(&state, &actor, id)?;
|
|
state.db.capture_events(job.id).map(Json).map_err(internal)
|
|
}
|
|
|
|
async fn job(
|
|
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
|
State(state): State<HubState>,
|
|
headers: HeaderMap,
|
|
Path(id): Path<Uuid>,
|
|
) -> Result<Json<CaptureJob>, StatusCode> {
|
|
let actor = authenticate(&state, peer, &headers, false)?;
|
|
job_in_scope(&state, &actor, id).map(Json)
|
|
}
|
|
|
|
async fn claim(
|
|
State(state): State<HubState>,
|
|
headers: HeaderMap,
|
|
Path(application): Path<Uuid>,
|
|
) -> Result<Json<Option<CaptureLease>>, StatusCode> {
|
|
let outpost = outpost(&state, &headers)?;
|
|
let mut lease = state
|
|
.db
|
|
.claim_capture(outpost, application, now())
|
|
.map_err(internal)?;
|
|
if let Some(lease) = &mut lease {
|
|
lease.restic |= lease.profile.format == CaptureFormat::Filesystem
|
|
|| state
|
|
.vault
|
|
.read()
|
|
.await
|
|
.outpost_repository_configured(lease.profile.orbit_id)
|
|
.map_err(internal)?;
|
|
}
|
|
Ok(Json(lease))
|
|
}
|
|
|
|
async fn report(
|
|
State(state): State<HubState>,
|
|
headers: HeaderMap,
|
|
Path(id): Path<Uuid>,
|
|
body: Result<Json<CaptureReport>, JsonRejection>,
|
|
) -> Result<StatusCode, StatusCode> {
|
|
let outpost = outpost(&state, &headers)?;
|
|
let Json(body) = body.map_err(|_| StatusCode::UNPROCESSABLE_ENTITY)?;
|
|
if !state
|
|
.db
|
|
.report_capture(outpost, id, body, now())
|
|
.map_err(internal)?
|
|
{
|
|
return Err(StatusCode::CONFLICT);
|
|
}
|
|
Ok(StatusCode::NO_CONTENT)
|
|
}
|
|
|
|
async fn upload(
|
|
State(state): State<HubState>,
|
|
headers: HeaderMap,
|
|
Path(id): Path<Uuid>,
|
|
body: Body,
|
|
) -> Result<Json<serde_json::Value>, StatusCode> {
|
|
let outpost = outpost(&state, &headers)?;
|
|
let lease = Uuid::parse_str(header_value(&headers, "x-tessera-lease-id")?)
|
|
.map_err(|_| StatusCode::BAD_REQUEST)?;
|
|
let job = state
|
|
.db
|
|
.capture_upload(outpost, id, lease, now())
|
|
.map_err(internal)?
|
|
.ok_or(StatusCode::CONFLICT)?;
|
|
if job.profile.format == CaptureFormat::Filesystem
|
|
|| state
|
|
.db
|
|
.restic_required(job.profile.orbit_id)
|
|
.map_err(internal)?
|
|
|| state
|
|
.vault
|
|
.read()
|
|
.await
|
|
.outpost_repository_configured(job.profile.orbit_id)
|
|
.map_err(internal)?
|
|
{
|
|
return Err(StatusCode::CONFLICT);
|
|
}
|
|
let identity = headers
|
|
.get("x-tessera-source-identity")
|
|
.map(|header| {
|
|
let decoded = base64::engine::general_purpose::URL_SAFE_NO_PAD
|
|
.decode(header.as_bytes())
|
|
.map_err(|_| StatusCode::BAD_REQUEST)?;
|
|
let identity: DatabaseIdentity =
|
|
serde_json::from_slice(&decoded).map_err(|_| StatusCode::BAD_REQUEST)?;
|
|
if !job
|
|
.profile
|
|
.format
|
|
.engine()
|
|
.is_some_and(|engine| identity.valid(engine))
|
|
{
|
|
return Err(StatusCode::BAD_REQUEST);
|
|
}
|
|
Ok(identity)
|
|
})
|
|
.transpose()?;
|
|
let (file, expected) = receive_payload(&state, &headers, body, job.profile.format).await?;
|
|
if let Some(snapshot) = job.snapshot_id {
|
|
return Ok(Json(serde_json::json!({ "snapshot_id": snapshot })));
|
|
}
|
|
let orbit_id = job.profile.orbit_id;
|
|
let manifest = capture_manifest(&state, &job, identity, Some(hex::encode(expected))).await?;
|
|
let vault = state.vault.clone().read_owned().await;
|
|
let db = state.db.clone();
|
|
let offsite_enabled = state.offsite.is_some();
|
|
let (snapshot, created) = tokio::task::spawn_blocking(move || {
|
|
// SQLite fencing covers metadata publication. Restic work happens before the transaction.
|
|
let prepared = if vault.has_published_snapshot(id)? {
|
|
None
|
|
} else {
|
|
Some(vault.prepare_payload(manifest, file, false)?)
|
|
};
|
|
let mut wrote = false;
|
|
let published = db.publish_capture(outpost, id, lease, offsite_enabled, |_| {
|
|
if !vault.has_published_snapshot(id)? {
|
|
vault.publish_prepared(
|
|
prepared
|
|
.as_ref()
|
|
.ok_or_else(|| anyhow::anyhow!("prepared snapshot missing"))?,
|
|
)?;
|
|
wrote = true;
|
|
}
|
|
Ok(())
|
|
})?;
|
|
// Preserve a prepared copy on an ambiguous commit error for reconciliation.
|
|
if !wrote {
|
|
if let Some(snap) = prepared.as_ref() {
|
|
if let Err(error) = vault.discard_prepared(snap) {
|
|
tracing::warn!(%id, %error, "could not discard unpublished capture");
|
|
}
|
|
}
|
|
}
|
|
Ok::<_, anyhow::Error>(published)
|
|
})
|
|
.await
|
|
.map_err(internal)?
|
|
.map_err(internal)?
|
|
.ok_or(StatusCode::CONFLICT)?;
|
|
if created && state.prune_orbit(orbit_id).await.is_err() {
|
|
tracing::warn!(%id, %orbit_id, "could not apply capture retention");
|
|
}
|
|
Ok(Json(serde_json::json!({ "snapshot_id": snapshot })))
|
|
}
|
|
|
|
async fn commit_restic(
|
|
State(state): State<HubState>,
|
|
headers: HeaderMap,
|
|
Path(id): Path<Uuid>,
|
|
Json(commit): Json<ResticCaptureCommit>,
|
|
) -> Result<Json<serde_json::Value>, StatusCode> {
|
|
let outpost = outpost(&state, &headers)?;
|
|
let job = state
|
|
.db
|
|
.capture_upload(outpost, id, commit.lease_id, now())
|
|
.map_err(internal)?
|
|
.ok_or(StatusCode::CONFLICT)?;
|
|
if let Some(snapshot) = job.snapshot_id {
|
|
return Ok(Json(serde_json::json!({ "snapshot_id": snapshot })));
|
|
}
|
|
let engine = job.profile.format.engine();
|
|
if commit
|
|
.identity
|
|
.as_ref()
|
|
.is_some_and(|identity| !engine.is_some_and(|engine| identity.valid(engine)))
|
|
|| (engine.is_some()
|
|
&& !commit.sha256.as_ref().is_some_and(|hash| {
|
|
hash.len() == 64 && hash.bytes().all(|byte| byte.is_ascii_hexdigit())
|
|
}))
|
|
|| (engine.is_none() && commit.sha256.is_some())
|
|
{
|
|
return Err(StatusCode::BAD_REQUEST);
|
|
}
|
|
let orbit_id = job.profile.orbit_id;
|
|
let manifest = capture_manifest(&state, &job, commit.identity, commit.sha256).await?;
|
|
let vault = state.vault.clone().read_owned().await;
|
|
let db = state.db.clone();
|
|
let offsite = state.offsite.is_some() && engine.is_some();
|
|
let (snapshot, created) = tokio::task::spawn_blocking(move || {
|
|
let prepared = vault.prepare_outpost_capture(manifest, outpost, &commit.snapshot_id)?;
|
|
db.publish_capture(outpost, id, commit.lease_id, offsite, |_| {
|
|
if !vault.has_published_snapshot(id)? {
|
|
vault.publish_prepared(&prepared)?;
|
|
}
|
|
Ok(())
|
|
})
|
|
})
|
|
.await
|
|
.map_err(internal)?
|
|
.map_err(internal)?
|
|
.ok_or(StatusCode::CONFLICT)?;
|
|
if created && state.prune_orbit(orbit_id).await.is_err() {
|
|
tracing::warn!(%id, %orbit_id, "could not apply capture retention");
|
|
}
|
|
Ok(Json(serde_json::json!({ "snapshot_id": snapshot })))
|
|
}
|
|
|
|
async fn capture_manifest(
|
|
state: &HubState,
|
|
job: &CaptureJob,
|
|
identity: Option<DatabaseIdentity>,
|
|
digest: Option<String>,
|
|
) -> Result<SnapshotManifest, StatusCode> {
|
|
let id = job.id;
|
|
let orbit_id = job.profile.orbit_id;
|
|
let orbit = state
|
|
.db
|
|
.list_orbits()
|
|
.await
|
|
.map_err(internal)?
|
|
.into_iter()
|
|
.find(|orbit| orbit.id == orbit_id)
|
|
.ok_or(StatusCode::NOT_FOUND)?;
|
|
let (engine, format) = match job.profile.format {
|
|
CaptureFormat::PostgresCustom => ("postgres", "custom"),
|
|
CaptureFormat::PostgresSql => ("postgres", "plain"),
|
|
CaptureFormat::MysqlSql => ("mysql", "plain"),
|
|
CaptureFormat::Filesystem => ("filesystem", "tar"),
|
|
};
|
|
Ok(SnapshotManifest {
|
|
snapshot_id: id,
|
|
orbit_id,
|
|
orbit_name: orbit.name,
|
|
labels: vec![engine.into()],
|
|
provider: engine.into(),
|
|
paths: vec![],
|
|
restore_hints: serde_json::json!({
|
|
"engine": engine, "format": format, "job_id": id, "outpost_id": job.profile.outpost_id,
|
|
"application_id": job.profile.application_id, "sha256": digest,
|
|
"queued_at": job.created_at, "uploaded_at": now(), "source_identity": identity
|
|
}),
|
|
})
|
|
}
|
|
|
|
pub(super) async fn receive_payload(
|
|
state: &HubState,
|
|
headers: &HeaderMap,
|
|
mut body: Body,
|
|
format: CaptureFormat,
|
|
) -> Result<(std::fs::File, [u8; 32]), StatusCode> {
|
|
let length = header_value(headers, header::CONTENT_LENGTH.as_str())?
|
|
.parse::<u64>()
|
|
.map_err(|_| StatusCode::BAD_REQUEST)?;
|
|
if length == 0 || length > 100 * 1024 * 1024 * 1024 {
|
|
return Err(StatusCode::PAYLOAD_TOO_LARGE);
|
|
}
|
|
let mut expected = [0u8; 32];
|
|
hex::decode_to_slice(header_value(headers, "x-tessera-sha256")?, &mut expected)
|
|
.map_err(|_| StatusCode::BAD_REQUEST)?;
|
|
|
|
let file = tempfile::tempfile_in(&state.data_dir).map_err(internal)?;
|
|
let mut file = tokio::fs::File::from_std(file);
|
|
let mut digest = Sha256::new();
|
|
let mut bytes = 0;
|
|
loop {
|
|
let next = std::future::poll_fn(|cx| Pin::new(&mut body).poll_frame(cx));
|
|
let Some(frame) = tokio::time::timeout(Duration::from_secs(30), next)
|
|
.await
|
|
.map_err(|_| StatusCode::REQUEST_TIMEOUT)?
|
|
else {
|
|
break;
|
|
};
|
|
let frame = frame.map_err(|_| StatusCode::BAD_REQUEST)?;
|
|
if let Ok(chunk) = frame.into_data() {
|
|
bytes += chunk.len() as u64;
|
|
if bytes > length {
|
|
return Err(StatusCode::BAD_REQUEST);
|
|
}
|
|
digest.update(&chunk);
|
|
file.write_all(&chunk).await.map_err(internal)?;
|
|
}
|
|
}
|
|
if bytes != length || digest.finalize()[..] != expected {
|
|
return Err(StatusCode::UNPROCESSABLE_ENTITY);
|
|
}
|
|
file.flush().await.map_err(internal)?;
|
|
if format == CaptureFormat::PostgresCustom {
|
|
let mut signature = [0; 5];
|
|
file.seek(std::io::SeekFrom::Start(0))
|
|
.await
|
|
.map_err(internal)?;
|
|
if file.read_exact(&mut signature).await.is_err() || &signature != b"PGDMP" {
|
|
return Err(StatusCode::UNPROCESSABLE_ENTITY);
|
|
}
|
|
}
|
|
Ok((file.into_std().await, expected))
|
|
}
|
|
|
|
pub(super) fn header_value<'a>(headers: &'a HeaderMap, name: &str) -> Result<&'a str, StatusCode> {
|
|
headers
|
|
.get(name)
|
|
.and_then(|value| value.to_str().ok())
|
|
.ok_or(StatusCode::BAD_REQUEST)
|
|
}
|
|
|
|
pub(super) fn outpost(state: &HubState, headers: &HeaderMap) -> Result<Uuid, StatusCode> {
|
|
use crate::auth::{AuditAction, AuditOutcome, AuditResource, Principal};
|
|
let result = authenticate_outpost(state, headers);
|
|
let (actor, resource, outcome) = match result {
|
|
Ok(id) => (
|
|
Principal::Outpost(id),
|
|
AuditResource::Outpost(id),
|
|
AuditOutcome::Allowed,
|
|
),
|
|
Err(_) => (
|
|
Principal::Anonymous,
|
|
AuditResource::Api,
|
|
AuditOutcome::Denied,
|
|
),
|
|
};
|
|
state
|
|
.db
|
|
.audit_event(
|
|
&actor,
|
|
AuditAction::Authentication,
|
|
resource,
|
|
outcome,
|
|
Uuid::new_v4(),
|
|
)
|
|
.map_err(internal)?;
|
|
result
|
|
}
|
|
|
|
fn authenticate_outpost(state: &HubState, headers: &HeaderMap) -> Result<Uuid, StatusCode> {
|
|
let token = upload_token(state, headers)?;
|
|
let id = state
|
|
.db
|
|
.upload_token_outpost(token, chrono::Utc::now().timestamp())
|
|
.map_err(internal)?
|
|
.ok_or(StatusCode::UNAUTHORIZED)?;
|
|
let id = Uuid::parse_str(&id).map_err(internal)?;
|
|
state.db.touch_outpost(id).map_err(internal)?;
|
|
Ok(id)
|
|
}
|
|
|
|
pub(super) fn now() -> i64 {
|
|
chrono::Utc::now().timestamp()
|
|
}
|
|
|
|
pub(super) fn internal(_: impl std::fmt::Display) -> StatusCode {
|
|
StatusCode::INTERNAL_SERVER_ERROR
|
|
}
|