From 2931032ab743f0f45b743b0e108190780eb3834a Mon Sep 17 00:00:00 2001 From: Adnan Zahir Date: Mon, 16 Nov 2026 21:04:46 +0700 Subject: [PATCH] fix: throttle denied-authentication audit rows per source, never turn a denial into a 500, prune old audit events Co-Authored-By: Claude Sonnet 5.5 --- crates/tessera-hub/src/api/jobs.rs | 70 ++++++++++------- crates/tessera-hub/src/api/restore.rs | 23 ++++-- crates/tessera-hub/src/api/routes.rs | 107 ++++++++++++++++++++++++-- crates/tessera-hub/src/db/audit.rs | 41 ++++++++++ crates/tessera-hub/src/main.rs | 2 + crates/tessera-hub/src/scheduler.rs | 49 ++++++++++++ 6 files changed, 250 insertions(+), 42 deletions(-) diff --git a/crates/tessera-hub/src/api/jobs.rs b/crates/tessera-hub/src/api/jobs.rs index 8ca9a05..ce2aa2e 100644 --- a/crates/tessera-hub/src/api/jobs.rs +++ b/crates/tessera-hub/src/api/jobs.rs @@ -266,10 +266,11 @@ async fn job( async fn claim( State(state): State, + peer: Option>, headers: HeaderMap, Path(application): Path, ) -> Result>, StatusCode> { - let outpost = outpost(&state, &headers)?; + let outpost = outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?; let mut lease = state .db .claim_capture(outpost, application, now()) @@ -288,11 +289,12 @@ async fn claim( async fn report( State(state): State, + peer: Option>, headers: HeaderMap, Path(id): Path, body: Result, JsonRejection>, ) -> Result { - let outpost = outpost(&state, &headers)?; + let outpost = outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?; let Json(body) = body.map_err(|_| StatusCode::UNPROCESSABLE_ENTITY)?; if !state .db @@ -306,11 +308,12 @@ async fn report( async fn upload( State(state): State, + peer: Option>, headers: HeaderMap, Path(id): Path, body: Body, ) -> Result, StatusCode> { - let outpost = outpost(&state, &headers)?; + let outpost = outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?; let lease = Uuid::parse_str(header_value(&headers, "x-tessera-lease-id")?) .map_err(|_| StatusCode::BAD_REQUEST)?; let job = state @@ -401,11 +404,12 @@ async fn upload( async fn commit_restic( State(state): State, + peer: Option>, headers: HeaderMap, Path(id): Path, Json(commit): Json, ) -> Result, StatusCode> { - let outpost = outpost(&state, &headers)?; + let outpost = outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?; let job = state .db .capture_upload(outpost, id, commit.lease_id, now()) @@ -549,31 +553,43 @@ pub(super) fn header_value<'a>(headers: &'a HeaderMap, name: &str) -> Result<&'a .ok_or(StatusCode::BAD_REQUEST) } -pub(super) fn outpost(state: &HubState, headers: &HeaderMap) -> Result { +pub(super) fn outpost( + state: &HubState, + peer: Option, + headers: &HeaderMap, +) -> Result { 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)?; + match result { + Ok(id) => { + state + .db + .audit_event( + &Principal::Outpost(id), + AuditAction::Authentication, + AuditResource::Outpost(id), + AuditOutcome::Allowed, + Uuid::new_v4(), + ) + .map_err(internal)?; + } + Err(_) => { + // One denial row per source per minute; a failed audit write must not + // change the refusal into a 500. + let source = state.limits.source(peer, headers); + if state.limits.audit_denial(source) { + if let Err(error) = state.db.audit_event( + &Principal::Anonymous, + AuditAction::Authentication, + AuditResource::Api, + AuditOutcome::Denied, + Uuid::new_v4(), + ) { + tracing::error!(%error, "could not record a denied outpost authentication"); + } + } + } + } result } diff --git a/crates/tessera-hub/src/api/restore.rs b/crates/tessera-hub/src/api/restore.rs index 48161ac..323757d 100644 --- a/crates/tessera-hub/src/api/restore.rs +++ b/crates/tessera-hub/src/api/restore.rs @@ -370,10 +370,11 @@ async fn reconcile( async fn claim( State(state): State, + peer: Option>, headers: HeaderMap, Path(target): Path, ) -> Result>, StatusCode> { - let outpost = outpost(&state, &headers)?; + let outpost = outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?; state .db .claim_restore(outpost, target, now()) @@ -381,8 +382,12 @@ async fn claim( .map_err(internal) } -fn auth(state: &HubState, headers: &HeaderMap) -> Result<(Uuid, Uuid), StatusCode> { - let outpost = outpost(state, headers)?; +fn auth( + state: &HubState, + peer: Option>, + headers: &HeaderMap, +) -> Result<(Uuid, Uuid), StatusCode> { + let outpost = outpost(state, peer.map(|ConnectInfo(addr)| addr), headers)?; let token = header_value(headers, "x-tessera-restore-token").map_err(|_| StatusCode::UNAUTHORIZED)?; Ok(( @@ -393,10 +398,11 @@ fn auth(state: &HubState, headers: &HeaderMap) -> Result<(Uuid, Uuid), StatusCod async fn payload( State(state): State, + peer: Option>, headers: HeaderMap, Path(id): Path, ) -> Result { - let (outpost, token) = auth(&state, &headers)?; + let (outpost, token) = auth(&state, peer, &headers)?; let (job, artifact, _) = state .db .restore_access(outpost, id, token, now()) @@ -435,11 +441,12 @@ async fn payload( async fn report( State(state): State, + peer: Option>, headers: HeaderMap, Path(id): Path, body: Result, JsonRejection>, ) -> Result { - let (outpost, token) = auth(&state, &headers)?; + let (outpost, token) = auth(&state, peer, &headers)?; let Json(progress) = body.map_err(|_| StatusCode::UNPROCESSABLE_ENTITY)?; // Why a step failed, in the agent's words. Cleaned again here: the agent is trusted with the job, not // with what ends up in the database and the log. @@ -462,11 +469,12 @@ async fn report( async fn safety( State(state): State, + peer: Option>, headers: HeaderMap, Path(id): Path, body: Body, ) -> Result, StatusCode> { - let (outpost, token) = auth(&state, &headers)?; + let (outpost, token) = auth(&state, peer, &headers)?; let (job, _, safety_id) = state .db .restore_access(outpost, id, token, now()) @@ -538,10 +546,11 @@ async fn safety( async fn apply( State(state): State, + peer: Option>, headers: HeaderMap, Path(id): Path, ) -> Result { - let (outpost, token) = auth(&state, &headers)?; + let (outpost, token) = auth(&state, peer, &headers)?; if !state .db .authorize_apply(outpost, id, token, now()) diff --git a/crates/tessera-hub/src/api/routes.rs b/crates/tessera-hub/src/api/routes.rs index 8c67717..23cd3e6 100644 --- a/crates/tessera-hub/src/api/routes.rs +++ b/crates/tessera-hub/src/api/routes.rs @@ -289,16 +289,21 @@ pub(super) fn authenticate( .unwrap_or(Principal::Anonymous); let result = authenticate_inner(state, peer, headers, mutation, request_id, session); if result.is_err() { - state - .db - .audit_event( + // 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, - ) - .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + ) { + tracing::error!(%error, "could not record a denied authentication"); + } + } } result } @@ -1189,10 +1194,11 @@ fn require_legacy_upload_owner( #[utoipa::path(post, path = "/api/v1/wormhole/upload/init", request_body = UploadInit, responses((status = 200)))] async fn wormhole_upload_init( State(state): State, + peer: Option>, headers: axum::http::HeaderMap, Json(body): Json, ) -> Result, StatusCode> { - let outpost = super::jobs::outpost(&state, &headers)?; + 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 @@ -1231,10 +1237,11 @@ async fn wormhole_upload_init( #[utoipa::path(post, path = "/api/v1/wormhole/upload/chunk", request_body = UploadChunk, responses((status = 204)))] async fn wormhole_upload_chunk( State(state): State, + peer: Option>, headers: axum::http::HeaderMap, Json(body): Json, ) -> Result { - let outpost = super::jobs::outpost(&state, &headers)?; + let outpost = super::jobs::outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?; let session = state .db .upload_session(&body.session_id.to_string()) @@ -1338,10 +1345,11 @@ pub(super) fn upload_token<'a>( #[utoipa::path(post, path = "/api/v1/wormhole/restic/commit", request_body = ResticCommit, responses((status = 200)))] async fn wormhole_restic_commit( State(state): State, + peer: Option>, headers: HeaderMap, Json(body): Json, ) -> Result, StatusCode> { - let outpost_id = super::jobs::outpost(&state, &headers)?; + 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); @@ -1507,6 +1515,88 @@ mod tests { 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") + .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::().unwrap())) + .body(Body::empty()) + .unwrap() + }; + let outpost = |ip: &str| { + Request::post("/api/v1/wormhole/upload/init") + .extension(ConnectInfo(format!("{ip}:9000").parse::().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 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") + .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::().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::().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(); @@ -1693,6 +1783,7 @@ mod tests { ); let mut commit = Box::pin(wormhole_restic_commit( State(state.clone()), + None, owner_headers, Json(ResticCommit { orbit_id: orbit, diff --git a/crates/tessera-hub/src/db/audit.rs b/crates/tessera-hub/src/db/audit.rs index 053e56c..3817f58 100644 --- a/crates/tessera-hub/src/db/audit.rs +++ b/crates/tessera-hub/src/db/audit.rs @@ -51,12 +51,53 @@ impl Db { )?; Ok(()) } + + /// Deletes structured audit events recorded before `cutoff` (unix seconds); + /// returns how many rows went. + pub fn prune_audit_events(&self, cutoff: i64) -> Result { + Ok(self + .conn + .lock() + .unwrap() + .execute("DELETE FROM audit_events WHERE at < ?1", params![cutoff])?) + } } #[cfg(test)] mod tests { use super::*; + #[tokio::test] + async fn pruning_removes_only_events_older_than_the_cutoff() { + let dir = tempfile::tempdir().unwrap(); + let db = Db::connect(&dir.path().join("fixture.db")).await.unwrap(); + db.migrate().await.unwrap(); + for _ in 0..3 { + db.audit_event( + &Principal::Anonymous, + AuditAction::Authentication, + AuditResource::Api, + AuditOutcome::Denied, + Uuid::new_v4(), + ) + .unwrap(); + } + let now = chrono::Utc::now().timestamp(); + db.conn + .lock() + .unwrap() + .execute("UPDATE audit_events SET at = ?1 WHERE id <= 2", params![now - 100 * 86_400]) + .unwrap(); + assert_eq!(db.prune_audit_events(now - 90 * 86_400).unwrap(), 2); + let left: i64 = db + .conn + .lock() + .unwrap() + .query_row("SELECT count(*) FROM audit_events", [], |r| r.get(0)) + .unwrap(); + assert_eq!(left, 1); + } + #[tokio::test] async fn structured_audit_survives_reopen_and_preserves_legacy_events() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/tessera-hub/src/main.rs b/crates/tessera-hub/src/main.rs index 373826c..c208eab 100644 --- a/crates/tessera-hub/src/main.rs +++ b/crates/tessera-hub/src/main.rs @@ -30,6 +30,7 @@ async fn main() -> Result<()> { let addr: SocketAddr = listen.parse()?; let admin = admin::AdminGate::from_env()?; admin.validate_listener(addr)?; + let audit_retention = scheduler::audit_retention_from_env()?; let wormhole = mtls::from_env()?; if let Some(config) = &wormhole { admin.validate_listener(config.listen)?; @@ -81,6 +82,7 @@ async fn main() -> Result<()> { state.configure_offsite()?; state.reconcile_capture_catalog().await?; state.start_offsite_worker(); + scheduler::start_audit_retention(state.db.clone(), audit_retention); scheduler::start_orbit_scheduler(state.clone()).await?; refresh::start(state.clone()); if state.sessions.enabled() { diff --git a/crates/tessera-hub/src/scheduler.rs b/crates/tessera-hub/src/scheduler.rs index 9abc2bc..d35ef6f 100644 --- a/crates/tessera-hub/src/scheduler.rs +++ b/crates/tessera-hub/src/scheduler.rs @@ -32,6 +32,45 @@ pub async fn start_orbit_scheduler(state: HubState) -> Result<()> { Ok(()) } +const DEFAULT_AUDIT_RETENTION_DAYS: i64 = 90; + +/// `TESSERA_AUDIT_RETENTION_DAYS`: how long structured audit events are kept. +/// Unset means 90 days; `0` keeps them forever. +pub fn audit_retention_from_env() -> Result> { + parse_audit_retention(std::env::var("TESSERA_AUDIT_RETENTION_DAYS").ok().as_deref()) +} + +fn parse_audit_retention(value: Option<&str>) -> Result> { + let Some(value) = value.map(str::trim).filter(|v| !v.is_empty()) else { + return Ok(Some(DEFAULT_AUDIT_RETENTION_DAYS)); + }; + let days: i64 = value + .parse() + .ok() + .filter(|days| (0..=36_500).contains(days)) + .context("TESSERA_AUDIT_RETENTION_DAYS must be a whole number of days (0 keeps everything)")?; + Ok((days > 0).then_some(days)) +} + +/// Prunes audit events once now and then every hour. +pub fn start_audit_retention(db: crate::db::Db, retention_days: Option) { + let Some(days) = retention_days else { + info!("audit retention disabled: audit events are kept forever"); + return; + }; + tokio::spawn(async move { + loop { + let cutoff = Utc::now().timestamp() - days * 86_400; + match db.prune_audit_events(cutoff) { + Ok(0) => {} + Ok(n) => info!("pruned {n} audit event(s) older than {days} days"), + Err(e) => error!("audit retention: {e}"), + } + sleep(Duration::from_secs(3600)).await; + } + }); +} + pub(crate) fn orbit_schedule(expression: &str) -> Result { if expression.split_whitespace().count() == 5 { Schedule::from_str(&format!("0 {expression}")) @@ -116,6 +155,16 @@ pub(crate) fn tick_capture_schedules(db: &crate::db::Db, now: DateTime) -> mod tests { use super::*; + #[test] + fn audit_retention_defaults_to_ninety_days_and_zero_disables_it() { + assert_eq!(parse_audit_retention(None).unwrap(), Some(90)); + assert_eq!(parse_audit_retention(Some(" ")).unwrap(), Some(90)); + assert_eq!(parse_audit_retention(Some("30")).unwrap(), Some(30)); + assert_eq!(parse_audit_retention(Some("0")).unwrap(), None); + assert!(parse_audit_retention(Some("-1")).is_err()); + assert!(parse_audit_retention(Some("soon")).is_err()); + } + #[test] fn orbit_cron_accepts_legacy_minutes_and_explicit_seconds() { let before = Utc.with_ymd_and_hms(2026, 11, 10, 1, 59, 55).unwrap();