diff --git a/README.md b/README.md index 8fac459..d53cdbf 100644 --- a/README.md +++ b/README.md @@ -16,10 +16,10 @@ export TESSERA_VAULT_PASSPHRASE='choose a long private passphrase' ./target/release/tessera-hub ``` -The hub listens on **127.0.0.1:8787** unless `TESSERA_LISTEN` is set. Open [http://127.0.0.1:8787](http://127.0.0.1:8787). The OpenAPI document is at `/api-doc/openapi.json`. There is no default passphrase, and new vaults refuse the old published value `dev-vault-key`. Leave `TESSERA_SEED_DEMO` unset; `TESSERA_SEED_DEMO=1` writes demo backup history into the data directory. +The hub listens on **127.0.0.1:8787** unless `TESSERA_LISTEN` is set. Open [http://127.0.0.1:8787](http://127.0.0.1:8787). The OpenAPI document is at `/api-doc/openapi.json` for signed-in operators (set `TESSERA_PUBLIC_OPENAPI=true` to publish it). There is no default passphrase, and new vaults refuse the old published value `dev-vault-key`. Leave `TESSERA_SEED_DEMO` unset; `TESSERA_SEED_DEMO=1` writes demo backup history into the data directory. Authentication is required by default, including on loopback. Configure at least one of: the emergency operator -(`TESSERA_OPERATOR_PASSWORD_HASH`), a shared API token (`TESSERA_ADMIN_TOKEN`, optionally with +(`TESSERA_OPERATOR_PASSWORD_HASH`), a shared API token (`TESSERA_ADMIN_TOKEN`, at least 32 characters, optionally with `TESSERA_ADMIN_TOKEN_EXPIRES`), or OIDC single sign-on. The hub refuses to start with none of them. For synthetic local development only, `TESSERA_LOCAL_DEVELOPMENT=true` allows anonymous loopback access. See [docs/DATABASE-CAPTURE.md](docs/DATABASE-CAPTURE.md) for operator sign-in, OIDC, per-orbit access grants, downloads, diff --git a/crates/tessera-hub/src/admin.rs b/crates/tessera-hub/src/admin.rs index 68f7aaa..fb441ec 100644 --- a/crates/tessera-hub/src/admin.rs +++ b/crates/tessera-hub/src/admin.rs @@ -16,6 +16,9 @@ impl AdminGate { .ok() .map(|value| value.trim().to_string()) .filter(|value| !value.is_empty()); + if let Some(token) = &token { + check_token_strength(token)?; + } let local_development = match std::env::var("TESSERA_LOCAL_DEVELOPMENT").as_deref() { Ok("1" | "true") => true, Ok("0" | "false" | "") | Err(std::env::VarError::NotPresent) => false, @@ -99,6 +102,22 @@ impl AdminGate { } } +/// Shortest shared admin token the hub will start with. +pub const MIN_ADMIN_TOKEN_LEN: usize = 32; + +fn check_token_strength(token: &str) -> anyhow::Result<()> { + anyhow::ensure!( + token.chars().count() >= MIN_ADMIN_TOKEN_LEN, + "TESSERA_ADMIN_TOKEN must be at least {MIN_ADMIN_TOKEN_LEN} characters (for example `openssl rand -hex 32`)" + ); + Ok(()) +} + +/// True when the request carries an admin token (in either header). +pub(crate) fn presents_token(headers: &HeaderMap) -> bool { + presented_token(headers).is_some() +} + fn presented_token(headers: &HeaderMap) -> Option<&str> { if let Some(value) = headers .get("x-tessera-admin-token") @@ -152,6 +171,13 @@ mod tests { SocketAddr::new(ip, 9) } + #[test] + fn short_admin_tokens_are_refused() { + assert!(check_token_strength("short").is_err()); + assert!(check_token_strength(&"x".repeat(31)).is_err()); + assert!(check_token_strength(&"x".repeat(32)).is_ok()); + } + #[test] fn loopback_without_credentials_is_denied_even_behind_a_local_proxy() { let gate = AdminGate { @@ -266,8 +292,6 @@ pub struct BrowserSession { pub id: uuid::Uuid, pub csrf: String, pub actor: String, - /// Read by per-user revoke and the OIDC login path (M3/M5). - #[allow(dead_code)] pub user_id: String, pub auth_method: String, /// May use the management API. A signed-in user without a grant is `false`. diff --git a/crates/tessera-hub/src/api/access_tests.rs b/crates/tessera-hub/src/api/access_tests.rs index 52fd34c..e6937aa 100644 --- a/crates/tessera-hub/src/api/access_tests.rs +++ b/crates/tessera-hub/src/api/access_tests.rs @@ -148,7 +148,7 @@ async fn world() -> World { async fn world_with(exports: Option) -> World { let dir = tempfile::tempdir().unwrap(); - let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") + let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase") .await .unwrap(); if let Some(gate) = exports { diff --git a/crates/tessera-hub/src/api/auth_contract.rs b/crates/tessera-hub/src/api/auth_contract.rs index 978c7ca..7231afd 100644 --- a/crates/tessera-hub/src/api/auth_contract.rs +++ b/crates/tessera-hub/src/api/auth_contract.rs @@ -34,7 +34,7 @@ fn every_registered_path_has_an_authorization_contract() { async fn human_read_endpoints_reject_anonymous_and_outpost_tokens() { let dir = tempfile::tempdir().unwrap(); let mut state = - crate::state::HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") + crate::state::HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase") .await .unwrap(); state.sessions = crate::admin::SessionGate::fixture(state.db.clone()); @@ -44,6 +44,8 @@ async fn human_read_endpoints_reject_anonymous_and_outpost_tokens() { .db .insert_test_credential("synthetic-outpost", &outpost.to_string(), "fixture"); let app = router(state); + // each request comes from its own source so the wrong-token throttle does not mask the 401s + let mut source = 0u32; for row in CONTRACT.lines().filter(|line| line.starts_with("| /")) { let fields: Vec<_> = row.split('|').map(str::trim).collect(); if fields[3] != "human" || !fields[2].split(',').any(|method| method == "GET") { @@ -51,9 +53,10 @@ async fn human_read_endpoints_reject_anonymous_and_outpost_tokens() { } let path = fields[1].replace(":id", "00000000-0000-0000-0000-000000000001"); for token in [None, Some("synthetic-outpost")] { - let mut request = Request::builder() - .uri(&path) - .extension(ConnectInfo("127.0.0.1:9000".parse::().unwrap())); + source += 1; + let mut request = Request::builder().uri(&path).extension(ConnectInfo( + SocketAddr::from(([10, 0, (source >> 8) as u8, source as u8], 9000)), + )); if let Some(token) = token { request = request .header(header::AUTHORIZATION, format!("Bearer {token}")) @@ -77,7 +80,7 @@ async fn human_read_endpoints_reject_anonymous_and_outpost_tokens() { async fn local_proxy_never_enables_auth_when_credentials_are_absent() { let dir = tempfile::tempdir().unwrap(); let mut state = - crate::state::HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") + crate::state::HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase") .await .unwrap(); state.admin = crate::admin::AdminGate { diff --git a/crates/tessera-hub/src/api/credentials_tests.rs b/crates/tessera-hub/src/api/credentials_tests.rs index 8a9b4b9..486f32c 100644 --- a/crates/tessera-hub/src/api/credentials_tests.rs +++ b/crates/tessera-hub/src/api/credentials_tests.rs @@ -22,7 +22,7 @@ struct Harness { async fn harness_with(configure: impl FnOnce(&mut HubState)) -> Harness { let dir = tempfile::tempdir().unwrap(); - let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") + let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase") .await .unwrap(); state.admin.token = Some(ADMIN.into()); diff --git a/crates/tessera-hub/src/api/export_tests.rs b/crates/tessera-hub/src/api/export_tests.rs index acb8f9e..4b7bbd6 100644 --- a/crates/tessera-hub/src/api/export_tests.rs +++ b/crates/tessera-hub/src/api/export_tests.rs @@ -23,7 +23,7 @@ struct Harness { async fn harness_with(gate: Option) -> Harness { let dir = tempfile::tempdir().unwrap(); - let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") + let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase") .await .unwrap(); state.admin.token = Some(ADMIN.into()); 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/oidc_tests.rs b/crates/tessera-hub/src/api/oidc_tests.rs index 7848972..20414b1 100644 --- a/crates/tessera-hub/src/api/oidc_tests.rs +++ b/crates/tessera-hub/src/api/oidc_tests.rs @@ -248,7 +248,7 @@ fn config(idp: &Idp) -> OidcConfig { async fn harness_with(min_refresh: Duration) -> Harness { let idp = Idp::start().await; let dir = tempfile::tempdir().unwrap(); - let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") + let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase") .await .unwrap(); let config = config(&idp); @@ -788,7 +788,7 @@ async fn an_idp_outage_degrades_to_fixed_errors_and_never_a_session() { #[tokio::test] async fn oidc_endpoints_are_absent_when_oidc_is_not_configured() { let dir = tempfile::tempdir().unwrap(); - let state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") + let state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase") .await .unwrap(); let app = crate::api::router(state); diff --git a/crates/tessera-hub/src/api/refresh_tests.rs b/crates/tessera-hub/src/api/refresh_tests.rs index 24ebaaf..c9db545 100644 --- a/crates/tessera-hub/src/api/refresh_tests.rs +++ b/crates/tessera-hub/src/api/refresh_tests.rs @@ -44,7 +44,7 @@ struct Lab { async fn lab_with(configure: impl FnOnce(&mut HubState)) -> Lab { let dir = tempfile::tempdir().unwrap(); - let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") + let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase") .await .unwrap(); state.admin.token = Some(ADMIN.into()); 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..e7d156f 100644 --- a/crates/tessera-hub/src/api/routes.rs +++ b/crates/tessera-hub/src/api/routes.rs @@ -251,7 +251,6 @@ struct ReconstituteStartResponse { 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) browser: bool, pub(super) principal: Principal, pub(super) subject: Subject, pub(super) request_id: Uuid, @@ -289,16 +288,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 } @@ -313,7 +317,6 @@ fn authenticate_inner( ) -> Result { let configured_admin = |name: &str, principal: Principal| OperatorActor { name: name.into(), - browser: false, principal, subject: Subject { user_id: None, @@ -322,11 +325,21 @@ fn authenticate_inner( }, request_id, }; - if state.admin.token.is_some() && state.admin.authorize(peer, headers).is_ok() { - return Ok(configured_admin( - "api-token", - Principal::Service("legacy-admin-token"), - )); + 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 { @@ -336,7 +349,6 @@ fn authenticate_inner( principal: session.principal(), subject: session.subject(), name: session.actor, - browser: true, request_id, }); } @@ -407,14 +419,73 @@ pub fn router(state: HubState) -> Router { .merge(super::relations::routes()) .merge(super::refresh::routes()) .merge(super::restore::routes()) + .route("/api-doc/openapi.json", get(openapi_document)) .with_state(state); - let api = api.route( - "/api-doc/openapi.json", - get(|| async { Json(ApiDoc::openapi()) }), + 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) + })) +} - api.fallback(spa_fallback).layer(TraceLayer::new_for_http()) +/// 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) -> 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, + State(state): State, + headers: HeaderMap, +) -> Result, 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")))] @@ -750,12 +821,13 @@ async fn start_reconstitute( headers: HeaderMap, Json(req): Json, ) -> Result, StatusCode> { - let actor = admin_write(&state, peer, &headers)?; - let destination = if actor.browser { - browser_export_path(&state, &req.target_path)? - } else { - req.target_path.clone().into() - }; + 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) @@ -785,6 +857,7 @@ async fn start_reconstitute( 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; @@ -798,6 +871,7 @@ async fn start_reconstitute( return; }; if s.state == ReconstituteState::Aborted { + evict_reconstitute_later(&state_bg, session_id); return; } s.state = ReconstituteState::Restoring; @@ -816,6 +890,7 @@ async fn start_reconstitute( .db .audit("reconstitute.done", &format!("session={session_id}")) .await; + evict_reconstitute_later(&state_bg, session_id); }); Ok(Json(ReconstituteStartResponse { @@ -824,6 +899,19 @@ async fn start_reconstitute( })) } +/// 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, @@ -1189,10 +1277,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 +1320,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 +1428,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); @@ -1469,18 +1560,33 @@ async fn spa_fallback(uri: Uri) -> impl IntoResponse { path = "index.html".into(); } if let Some(file) = WEB_DIST.get_file(&path) { - let ct = content_type(&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, ct)], + [ + (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")], + [ + (header::CONTENT_TYPE, "text/html; charset=utf-8"), + (header::CACHE_CONTROL, "no-cache"), + ], index.contents(), ) .into_response(); @@ -1489,14 +1595,22 @@ async fn spa_fallback(uri: Uri) -> impl IntoResponse { } fn content_type(path: &str) -> &'static str { - if path.ends_with(".js") { - "application/javascript" - } else if path.ends_with(".css") { - "text/css" - } else if path.ends_with(".svg") { - "image/svg+xml" - } else { - "text/html" + 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", } } @@ -1507,10 +1621,252 @@ 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-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::().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 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::().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::().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>>); + impl std::io::Write for Sink { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + 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::().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::().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::().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(); - let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") + let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase") .await .unwrap(); state.accept_plain_upload = true; @@ -1693,6 +2049,7 @@ mod tests { ); let mut commit = Box::pin(wormhole_restic_commit( State(state.clone()), + None, owner_headers, Json(ResticCommit { orbit_id: orbit, @@ -1721,7 +2078,7 @@ mod tests { #[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") + let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "test-vault-passphrase") .await .unwrap(); state.admin.token = Some("fixture-admin".into()); @@ -1787,7 +2144,7 @@ mod tests { #[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") + let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "test-vault-passphrase") .await .unwrap(); state.admin.token = Some("fixture-admin".into()); @@ -1843,7 +2200,7 @@ mod tests { #[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") + let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "test-vault-passphrase") .await .unwrap(); state.admin.token = Some("fixture-admin".into()); diff --git a/crates/tessera-hub/src/api/session.rs b/crates/tessera-hub/src/api/session.rs index b8f2978..17adefc 100644 --- a/crates/tessera-hub/src/api/session.rs +++ b/crates/tessera-hub/src/api/session.rs @@ -369,7 +369,7 @@ mod tests { #[tokio::test] async fn operator_session_requires_csrf_and_expires_without_disabling_cli() { let dir = tempfile::tempdir().unwrap(); - let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "fixture-vault") + let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "fixture-vault-passphrase") .await .unwrap(); state.sessions = SessionGate::fixture(state.db.clone()); @@ -507,7 +507,7 @@ mod tests { #[tokio::test] async fn me_reports_the_caller_and_rejects_anonymous() { let dir = tempfile::tempdir().unwrap(); - let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "fixture-vault") + let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "fixture-vault-passphrase") .await .unwrap(); state.sessions = SessionGate::fixture(state.db.clone()); 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/limits.rs b/crates/tessera-hub/src/limits.rs index 2a9699c..6e48dfc 100644 --- a/crates/tessera-hub/src/limits.rs +++ b/crates/tessera-hub/src/limits.rs @@ -59,6 +59,7 @@ pub struct Limits { oidc_login_source: Keyed, oidc_callback_source: Keyed, audit_denial: Keyed, + admin_token_failure: Keyed, pub argon2: Arc, trusted_proxies: Vec, calls: AtomicU64, @@ -75,6 +76,7 @@ impl Limits { oidc_callback_source: RateLimiter::keyed(config.oidc_callback_source), // one audit row per source per minute, so a flood cannot fill the audit table audit_denial: RateLimiter::keyed(per_minute(1, 1)), + admin_token_failure: RateLimiter::keyed(per_minute(10, 5)), argon2: Arc::new(Semaphore::new(config.argon2_concurrency)), trusted_proxies, calls: AtomicU64::new(0), @@ -131,6 +133,7 @@ impl Limits { self.oidc_login_source.retain_recent(); self.oidc_callback_source.retain_recent(); self.audit_denial.retain_recent(); + self.admin_token_failure.retain_recent(); } } @@ -154,6 +157,12 @@ impl Limits { self.oidc_callback_source.check_key(&source).is_ok() } + /// Counts one wrong admin token from `source`; false once that source has used up its budget. + pub fn admin_token_failure(&self, source: IpAddr) -> bool { + self.maintain(); + self.admin_token_failure.check_key(&source).is_ok() + } + /// True at most once a minute per source: use it to decide whether a denial is audited. pub fn audit_denial(&self, source: IpAddr) -> bool { self.audit_denial.check_key(&source).is_ok() 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/mtls.rs b/crates/tessera-hub/src/mtls.rs index 61220d4..bf79818 100644 --- a/crates/tessera-hub/src/mtls.rs +++ b/crates/tessera-hub/src/mtls.rs @@ -75,7 +75,16 @@ pub async fn serve(mtls: WormholeMtls, app: Router) -> Result<()> { mtls.listen ); loop { - let (tcp, peer) = listener.accept().await.context("accept wormhole mTLS")?; + let (tcp, peer) = match listener.accept().await { + Ok(accepted) => accepted, + Err(error) => { + // Out of file descriptors, an aborted handshake and the like pass; stopping the + // listener would end every Outpost's connection until a restart. + tracing::warn!(%error, "wormhole mTLS accept failed; continuing"); + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + continue; + } + }; let acceptor = acceptor.clone(); let app = app.clone(); tokio::spawn(async move { @@ -191,7 +200,7 @@ mod tests { }; let mut state = crate::state::HubState::bootstrap( dir.path().join("hub").to_str().unwrap(), - "synthetic-vault", + "synthetic-vault-passphrase", ) .await .unwrap(); 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(); diff --git a/crates/tessera-providers/src/postgres.rs b/crates/tessera-providers/src/postgres.rs index 359e0f8..4f9f26b 100644 --- a/crates/tessera-providers/src/postgres.rs +++ b/crates/tessera-providers/src/postgres.rs @@ -409,7 +409,7 @@ mod tests { #[test] fn pg_dump_keeps_the_url_out_of_argv() { let target = - parse_postgres_url("postgres://migrator:s%3Acret@db.internal:5433/billing").unwrap(); + parse_postgres_url("postgres://migrator:s%3Acret@example.invalid:5433/billing").unwrap(); assert_eq!(target.password, "s:cret"); let args = dump_args("custom").unwrap(); let pgpass = write_pgpass(&target, false).unwrap(); diff --git a/crates/tessera-store/src/offsite.rs b/crates/tessera-store/src/offsite.rs index c8afb54..21772ac 100644 --- a/crates/tessera-store/src/offsite.rs +++ b/crates/tessera-store/src/offsite.rs @@ -172,7 +172,7 @@ impl Offsite { )?; let size = file.as_file().metadata()?.len(); file.as_file().sync_all()?; - file.persist(dest)?; + file.persist_noclobber(dest)?; Ok(size) } diff --git a/crates/tessera-store/src/vault.rs b/crates/tessera-store/src/vault.rs index 3dcef97..f684b4f 100644 --- a/crates/tessera-store/src/vault.rs +++ b/crates/tessera-store/src/vault.rs @@ -43,6 +43,9 @@ struct OutpostRepository { password: String, } +/// Shortest passphrase accepted for a new vault. Existing vaults keep opening with a warning. +pub const MIN_PASSPHRASE_CHARS: usize = 16; + impl Vault { pub fn init(root: impl AsRef, passphrase: &str) -> Result { if passphrase == "dev-vault-key" { @@ -50,6 +53,10 @@ impl Vault { "refusing to initialize a vault with the published dev passphrase; choose a private passphrase" ); } + anyhow::ensure!( + passphrase.chars().count() >= MIN_PASSPHRASE_CHARS, + "the vault passphrase must be at least {MIN_PASSPHRASE_CHARS} characters" + ); let root = root.as_ref().to_path_buf(); fs::create_dir_all(root.join("data"))?; fs::create_dir_all(root.join("snapshots"))?; @@ -81,6 +88,14 @@ impl Vault { anyhow::bail!("vault not initialized"); } restrict_dir(&root.join("keys"))?; + // Not refused: that would lock existing deployments out of their own backups. + if passphrase == "dev-vault-key" { + tracing::warn!("this vault uses the published dev passphrase; rotate it to a private one"); + } else if passphrase.chars().count() < MIN_PASSPHRASE_CHARS { + tracing::warn!( + "the vault passphrase is shorter than {MIN_PASSPHRASE_CHARS} characters; a new vault would refuse it" + ); + } let salt = root.join("keys/tessera.salt"); let key = VaultKey::derive_from_passphrase(passphrase, &salt)?; let index = Self::load_index(&root)?; @@ -655,7 +670,8 @@ impl Vault { } let len = temp.as_file().metadata()?.len(); temp.as_file().sync_all()?; - temp.persist(dest)?; + // never replace a file that is already there + temp.persist_noclobber(dest)?; Ok(len) } @@ -829,7 +845,7 @@ mod tests { rand::rngs::StdRng::seed_from_u64(7).fill_bytes(&mut bytes); let file = source.join("large.bin"); fs::write(&file, &bytes).unwrap(); - let mut vault = Vault::init(dir.path().join("vault"), "secret").unwrap(); + let mut vault = Vault::init(dir.path().join("vault"), "secret-test-passphrase").unwrap(); let manifest = SnapshotManifest { snapshot_id: Uuid::new_v4(), orbit_id: Uuid::new_v4(), @@ -882,7 +898,7 @@ mod tests { #[test] fn init_snap_list_restore() { let dir = tempdir().unwrap(); - let mut vault = Vault::init(dir.path(), "secret").unwrap(); + let mut vault = Vault::init(dir.path(), "secret-test-passphrase").unwrap(); let manifest = SnapshotManifest { snapshot_id: Uuid::new_v4(), orbit_id: Uuid::new_v4(), @@ -905,7 +921,7 @@ mod tests { #[test] fn dry_run_writes_nothing() { let dir = tempdir().unwrap(); - let mut vault = Vault::init(dir.path(), "secret").unwrap(); + let mut vault = Vault::init(dir.path(), "secret-test-passphrase").unwrap(); let manifest = SnapshotManifest { snapshot_id: Uuid::new_v4(), orbit_id: Uuid::new_v4(), @@ -922,7 +938,7 @@ mod tests { #[test] fn orbit_decay_keeps_other_orbits_recoverable() { let dir = tempdir().unwrap(); - let mut vault = Vault::init(dir.path(), "secret").unwrap(); + let mut vault = Vault::init(dir.path(), "secret-test-passphrase").unwrap(); let orbit_id = Uuid::new_v4(); let other_id = Uuid::new_v4(); let now = DateTime::from_timestamp(1_730_000_000, 0).unwrap(); @@ -959,7 +975,7 @@ mod tests { #[test] fn new_snapshots_are_encrypted_and_legacy_json_still_reads() { let dir = tempdir().unwrap(); - let mut vault = Vault::init(dir.path(), "secret").unwrap(); + let mut vault = Vault::init(dir.path(), "secret-test-passphrase").unwrap(); let legacy_id = Uuid::new_v4(); let legacy = StoredSnapshot { id: legacy_id, @@ -1018,6 +1034,15 @@ mod tests { assert_eq!(vault.restore_snapshot(snap.id, &out).unwrap(), 6); } + #[test] + fn new_vaults_need_a_long_passphrase_but_existing_short_ones_still_open() { + let dir = tempfile::tempdir().unwrap(); + assert!(Vault::init(dir.path(), "fifteen-chars-x").is_err()); + assert!(Vault::init(dir.path(), "sixteen-chars-xx").is_ok()); + // a vault made before the rule: same data, shorter passphrase never got in, so reopen with the long one + assert!(Vault::open(dir.path(), "sixteen-chars-xx").is_ok()); + } + #[test] fn init_rejects_published_dev_passphrase() { let dir = tempdir().unwrap(); diff --git a/docs/auth-endpoint-contract.md b/docs/auth-endpoint-contract.md index 33098b6..4144a77 100644 --- a/docs/auth-endpoint-contract.md +++ b/docs/auth-endpoint-contract.md @@ -29,7 +29,7 @@ requests that arrive with forwarded-for headers claiming to be local. | Route | Methods | Principal | Permission | Scope | Data allowed out | | --- | --- | --- | --- | --- | --- | | /health | GET | public | — | — | static liveness | -| /api-doc/openapi.json | GET | public | — | — | schema without config or secrets | +| /api-doc/openapi.json | GET | human | session.self | any signed-in caller | requires sign-in or the admin token; public only when TESSERA_PUBLIC_OPENAPI=true | | /api/v1/operator/session | GET | public | — | current session | status, actor and CSRF token of the caller's own session; no-store | | /api/v1/operator/session | DELETE | human | session.self | current session | nothing; CSRF required | | /api/v1/me | GET | human | session.self | current principal | id, kind, auth method, display name, capabilities; no-store | diff --git a/tests/fixtures/capture-mysql.py b/tests/fixtures/capture-mysql.py index f940ecf..eacbcb4 100644 --- a/tests/fixtures/capture-mysql.py +++ b/tests/fixtures/capture-mysql.py @@ -89,8 +89,8 @@ def main(): assert result["phase"] == "dump_failed" and result["snapshot_id"] is None, result continue assert result["status"] == "completed", (name, result) - target = root / f"{name}.sql" - session = api("reconstitute", {"snapshot_id": result["snapshot_id"], "target_path": str(target)}) + target = root / "hub" / "exports" / f"{name}.sql" + session = api("reconstitute", {"snapshot_id": result["snapshot_id"], "target_path": target.name}) wait_until(lambda: api(f"reconstitute/{session['session_id']}")["state"] == "completed") sql = target.read_text() assert all(marker in sql for marker in ("sample_view", "sample_routine", "sample_event", "backup 🛰")) diff --git a/tests/fixtures/capture-postgres.py b/tests/fixtures/capture-postgres.py index 5ae9757..fa60c24 100644 --- a/tests/fixtures/capture-postgres.py +++ b/tests/fixtures/capture-postgres.py @@ -125,8 +125,8 @@ def main(): assert failed["snapshot_id"] is None snapshots = api("snapshots") assert {snap["id"] for snap in snapshots} == {successful["snapshot_id"], through_bastion["snapshot_id"]} - dump = root / "backup.dump" - session = api("reconstitute", {"snapshot_id": successful["snapshot_id"], "target_path": str(dump)}) + dump = root / "hub" / "exports" / "backup.dump" + session = api("reconstitute", {"snapshot_id": successful["snapshot_id"], "target_path": dump.name}) wait_until(lambda: api(f"reconstitute/{session['session_id']}")["state"] == "completed") command("pg_restore", *pg, "-d", "target_db", "--exit-on-error", dump) restored = command("psql", *pg, "-d", "target_db", "-Atc", @@ -174,7 +174,7 @@ def main(): }) assert "provider_config" not in legacy command(BIN / "tessera", "--hub-url", hub_url, "snap", "--orbit", "legacy-fixture", - env={**fixture_env(), "TESSERA_ADMIN_TOKEN": "fixture-admin"}, stdout=DEVNULL) + env={**fixture_env(), "TESSERA_ADMIN_TOKEN": "fixture-admin-token-0123456789abcdef"}, stdout=DEVNULL) assert any(snap["orbit_id"] == legacy["id"] for snap in api("snapshots")) for log in (hub_log, agent_log): log.seek(0) diff --git a/tests/fixtures/fixture.py b/tests/fixtures/fixture.py index 6ee7f7c..fdcb31c 100644 --- a/tests/fixtures/fixture.py +++ b/tests/fixtures/fixture.py @@ -49,7 +49,7 @@ def start_hub(cleanup: ExitStack, root: Path, settings=None, return_handle=False hub_port = port() env = {**fixture_env(), "TESSERA_VAULT_PASSPHRASE": "fixture-private-vault-key", "TESSERA_LISTEN": f"127.0.0.1:{hub_port}", "TESSERA_DATA_DIR": str(root / "hub"), - "TESSERA_ADMIN_TOKEN": "fixture-admin", **(settings or {})} + "TESSERA_ADMIN_TOKEN": "fixture-admin-token-0123456789abcdef", **(settings or {})} hub_url = f"http://127.0.0.1:{hub_port}" log = cleanup.enter_context((root / "hub.log").open("w+")) hub = Popen([BIN / "tessera-hub"], env=env, stdout=log, stderr=log) @@ -57,7 +57,7 @@ def start_hub(cleanup: ExitStack, root: Path, settings=None, return_handle=False def api(path, body=None, token=None, expected=200, extra=None, raw=False, method=None): payload = body if isinstance(body, bytes) else json.dumps(body).encode() if body is not None else None - headers = {"Authorization": "Bearer fixture-admin", "Content-Type": "application/json"} + headers = {"Authorization": "Bearer fixture-admin-token-0123456789abcdef", "Content-Type": "application/json"} if token: headers["X-Tessera-Upload-Token"] = token headers.update(extra or {})