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 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 21:04:46 +07:00
parent d356c313ce
commit 2931032ab7
6 changed files with 250 additions and 42 deletions

View File

@@ -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<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, &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<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: axum::http::HeaderMap,
Json(body): Json<UploadChunk>,
) -> Result<StatusCode, StatusCode> {
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<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap,
Json(body): Json<ResticCommit>,
) -> Result<Json<serde_json::Value>, 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::<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 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::<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();
@@ -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,