//! HTTP-level checks for Outpost credentials, limits and the legacy admin token. use crate::admin::{AdminGate, SessionGate}; use crate::limits::{LimitConfig, Limits}; use crate::state::HubState; use axum::body::{to_bytes, Body}; use axum::extract::ConnectInfo; use axum::http::{header, Request, Response, StatusCode}; use governor::Quota; use serde_json::{json, Value}; use std::net::SocketAddr; use std::num::NonZeroU32; use std::sync::Arc; use tower::ServiceExt; const ADMIN: &str = "synthetic-admin-token"; struct Harness { app: axum::Router, state: HubState, dir: tempfile::TempDir, } 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-passphrase") .await .unwrap(); state.admin.token = Some(ADMIN.into()); configure(&mut state); let app = crate::api::router(state.clone()); Harness { app, state, dir } } async fn harness() -> Harness { harness_with(|_| {}).await } fn request( method: &str, uri: &str, peer: &str, auth: Option<&str>, body: Option, ) -> Request { let mut builder = Request::builder() .method(method) .uri(uri) .extension(ConnectInfo( format!("{peer}:4000").parse::().unwrap(), )); if let Some(token) = auth { builder = builder.header("x-tessera-admin-token", token); } match body { Some(json) => builder .header(header::CONTENT_TYPE, "application/json") .body(Body::from(json.to_string())) .unwrap(), None => builder.body(Body::empty()).unwrap(), } } fn as_outpost(mut request: Request, token: &str) -> Request { request .headers_mut() .insert("x-tessera-upload-token", token.parse().unwrap()); request } async fn json_of(response: Response) -> Value { serde_json::from_slice(&to_bytes(response.into_body(), 1 << 20).await.unwrap()) .unwrap_or(Value::Null) } impl Harness { async fn call(&self, request: Request) -> Response { self.app.clone().oneshot(request).await.unwrap() } async fn status(&self, request: Request) -> StatusCode { self.call(request).await.status() } /// The real HTTP pairing path: start (admin) then claim (agent). async fn pair(&self, name: &str) -> (String, String) { let start = self .call(request( "POST", "/api/v1/wormhole/pairing", "127.0.0.1", Some(ADMIN), None, )) .await; assert_eq!(start.status(), StatusCode::OK); let code = json_of(start).await["code"].as_str().unwrap().to_string(); let claim = self .call(request( "POST", "/api/v1/wormhole/claim", "198.51.100.20", None, Some(json!({"code": code, "outpost_name": name})), )) .await; assert_eq!(claim.status(), StatusCode::OK); let body = json_of(claim).await; ( body["outpost_id"].as_str().unwrap().to_string(), body["upload_token"].as_str().unwrap().to_string(), ) } /// An Outpost-authenticated request: 401 only if the token is refused. async fn outpost_status(&self, token: &str, path: &str) -> StatusCode { self.status(as_outpost( request( "POST", path, "198.51.100.20", None, Some(json!({"orbit_id": "00000000-0000-0000-0000-000000000001", "total_bytes": 1})), ), token, )) .await } fn db_file(&self) -> std::path::PathBuf { self.dir.path().join("tessera.db") } fn scalar(&self, sql: &str) -> T { rusqlite::Connection::open(self.db_file()) .unwrap() .query_row(sql, [], |r| r.get(0)) .unwrap() } } const UPLOAD: &str = "/api/v1/wormhole/upload/init"; const LEASED: &str = "/api/v1/wormhole/capture/00000000-0000-0000-0000-000000000001/claim"; #[tokio::test] async fn pairing_over_http_mints_the_token_at_claim_and_stores_only_digests() { let h = harness().await; let (outpost, token) = h.pair("agent-one").await; assert_eq!(token.len(), 64); assert_ne!( h.outpost_status(&token, UPLOAD).await, StatusCode::UNAUTHORIZED, "the minted token authenticates" ); assert_eq!( h.outpost_status("not-the-token", UPLOAD).await, StatusCode::UNAUTHORIZED ); // the code works exactly once let again = h .call(request( "POST", "/api/v1/wormhole/claim", "198.51.100.20", None, Some(json!({"code": "WHATEVER", "outpost_name": "x"})), )) .await; assert_eq!(again.status(), StatusCode::GONE); // neither the token nor the code is anywhere on disk let code: String = { // recover nothing from the DB: ask for a second pairing and look for it afterwards let start = h .call(request( "POST", "/api/v1/wormhole/pairing", "127.0.0.1", Some(ADMIN), None, )) .await; json_of(start).await["code"].as_str().unwrap().to_string() }; let mut bytes = Vec::new(); for suffix in ["", "-wal", "-journal"] { let mut name = h.db_file().into_os_string(); name.push(suffix); bytes.extend(std::fs::read(name).unwrap_or_default()); } assert!( bytes.windows(9).any(|w| w == b"agent-one"), "sanity: the scan really reads the database file" ); for secret in [token.as_str(), code.as_str()] { assert!( !bytes.windows(secret.len()).any(|w| w == secret.as_bytes()), "clear-text secret on disk" ); } let audited: i64 = h.scalar(&format!("SELECT COUNT(*) FROM audit_events WHERE action='outpost.pair' AND outcome='succeeded' AND actor_id='{outpost}'")); assert_eq!(audited, 1); let leaked: i64 = h.scalar(&format!("SELECT COUNT(*) FROM audit_events WHERE actor_id||action||coalesce(resource_id,'') LIKE '%{token}%'")); assert_eq!(leaked, 0); } #[tokio::test] async fn revoking_an_outpost_refuses_it_on_its_very_next_request() { let h = harness().await; let (outpost, token) = h.pair("agent-one").await; assert_ne!( h.outpost_status(&token, UPLOAD).await, StatusCode::UNAUTHORIZED ); assert_ne!( h.outpost_status(&token, LEASED).await, StatusCode::UNAUTHORIZED, "lease-bearing endpoint accepts it before" ); let revoke = |auth| { request( "POST", &format!("/api/v1/wormhole/outposts/{outpost}/revoke"), "127.0.0.1", auth, None, ) }; assert_eq!( h.status(revoke(None)).await, StatusCode::UNAUTHORIZED, "anonymous cannot revoke" ); assert_eq!( h.status(as_outpost(revoke(None), &token)).await, StatusCode::UNAUTHORIZED, "an Outpost cannot revoke itself or others" ); assert_eq!(h.status(revoke(Some(ADMIN))).await, StatusCode::NO_CONTENT); assert_eq!( h.outpost_status(&token, UPLOAD).await, StatusCode::UNAUTHORIZED ); assert_eq!( h.outpost_status(&token, LEASED).await, StatusCode::UNAUTHORIZED, "the lease-bearing path is refused too" ); // a revoked Outpost cannot be rotated back to life, an unknown one is 404 let rotate = request( "POST", &format!("/api/v1/wormhole/outposts/{outpost}/rotate"), "127.0.0.1", Some(ADMIN), None, ); assert_eq!(h.status(rotate).await, StatusCode::NOT_FOUND); let unknown = request( "POST", "/api/v1/wormhole/outposts/00000000-0000-0000-0000-00000000dead/revoke", "127.0.0.1", Some(ADMIN), None, ); assert_eq!(h.status(unknown).await, StatusCode::NOT_FOUND); let events: Vec<(String, String)> = { let conn = rusqlite::Connection::open(h.db_file()).unwrap(); let mut stmt = conn.prepare("SELECT action, outcome FROM audit_events WHERE action LIKE 'outpost.credential_%' ORDER BY id").unwrap(); stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?))) .unwrap() .collect::>() .unwrap() }; assert_eq!( events, [ ( "outpost.credential_revoke".to_string(), "succeeded".to_string() ), ( "outpost.credential_rotate".to_string(), "failed".to_string() ), ( "outpost.credential_revoke".to_string(), "failed".to_string() ), ] ); } #[tokio::test] async fn rotation_returns_the_new_token_once_and_bounds_the_old_one() { let h = harness().await; let (outpost, old) = h.pair("agent-one").await; let rotate = |query: &str| { request( "POST", &format!("/api/v1/wormhole/outposts/{outpost}/rotate{query}"), "127.0.0.1", Some(ADMIN), None, ) }; // default grace: both work let first = h.call(rotate("")).await; assert_eq!(first.status(), StatusCode::OK); assert_eq!(first.headers()[header::CACHE_CONTROL], "no-store"); let first = json_of(first).await; let fresh = first["upload_token"].as_str().unwrap().to_string(); assert!(first["previous_valid_until"].is_string()); assert_ne!( h.outpost_status(&old, UPLOAD).await, StatusCode::UNAUTHORIZED ); assert_ne!( h.outpost_status(&fresh, UPLOAD).await, StatusCode::UNAUTHORIZED ); // grace 0 ends every older token immediately let second = json_of(h.call(rotate("?grace_minutes=0")).await).await; assert!(second["previous_valid_until"].is_null()); assert_eq!( h.outpost_status(&old, UPLOAD).await, StatusCode::UNAUTHORIZED ); assert_eq!( h.outpost_status(&fresh, UPLOAD).await, StatusCode::UNAUTHORIZED ); assert_ne!( h.outpost_status(second["upload_token"].as_str().unwrap(), UPLOAD) .await, StatusCode::UNAUTHORIZED ); assert_eq!( h.status(rotate("?grace_minutes=5000")).await, StatusCode::BAD_REQUEST ); assert_eq!( h.status(request( "POST", &format!("/api/v1/wormhole/outposts/{outpost}/rotate"), "127.0.0.1", None, None )) .await, StatusCode::UNAUTHORIZED ); } #[tokio::test] async fn pairing_claims_are_limited_per_source_and_a_spoofed_header_does_not_help() { let h = harness().await; let claim = |peer: &str| { let mut r = request( "POST", "/api/v1/wormhole/claim", peer, None, Some(json!({"code": "GUESS", "outpost_name": "x"})), ); r.headers_mut() .insert("x-forwarded-for", "198.51.100.77".parse().unwrap()); r }; let mut codes = Vec::new(); for _ in 0..8 { codes.push(h.status(claim("203.0.113.5")).await); } assert_eq!( codes.iter().filter(|c| **c == StatusCode::GONE).count(), 5, "burst of five guesses" ); assert_eq!( codes .iter() .filter(|c| **c == StatusCode::TOO_MANY_REQUESTS) .count(), 3 ); assert_eq!( h.status(claim("203.0.113.6")).await, StatusCode::GONE, "another source still has its own budget" ); let denied: i64 = h.scalar( "SELECT COUNT(*) FROM audit_events WHERE action='outpost.pair' AND outcome='denied'", ); assert_eq!(denied, 1, "a flood is audited once, not once per request"); } fn operator_state(state: &mut HubState) { state.sessions = SessionGate::fixture(state.db.clone()); } #[tokio::test] async fn an_emergency_login_flood_from_one_source_does_not_lock_out_a_legitimate_user() { let h = harness_with(operator_state).await; let login = |peer: &str, password: &str| { request( "POST", "/api/v1/operator/login", peer, None, Some(json!({"password": password})), ) }; let mut attacker = Vec::new(); for _ in 0..20 { let mut r = login("203.0.113.9", "wrong-guess"); r.headers_mut() .insert("x-forwarded-for", "192.0.2.1".parse().unwrap()); attacker.push(h.status(r).await); } assert_eq!( attacker .iter() .filter(|s| **s == StatusCode::UNAUTHORIZED) .count(), 5 ); assert_eq!( attacker .iter() .filter(|s| **s == StatusCode::TOO_MANY_REQUESTS) .count(), 15 ); // the attacker with the right password is still refused while over budget ... assert_eq!( h.status(login("203.0.113.9", "fixture-operator-password")) .await, StatusCode::TOO_MANY_REQUESTS ); // ... and a different source signs in fine assert_eq!( h.status(login("198.51.100.1", "fixture-operator-password")) .await, StatusCode::OK ); let denied: i64 = h .scalar("SELECT COUNT(*) FROM audit_events WHERE action='auth.login' AND outcome='denied'"); assert_eq!(denied, 1, "one audit row per source per minute"); let passwords: i64 = h.scalar("SELECT COUNT(*) FROM audit_events WHERE actor_id||action LIKE '%wrong-guess%'"); assert_eq!(passwords, 0); } #[tokio::test] async fn argon2_work_is_bounded_and_the_permit_is_released_after_each_login() { // no permits: refused at once rather than queued behind hashing let none = harness_with(|state| { operator_state(state); state.limits = Arc::new(Limits::new( LimitConfig { argon2_concurrency: 0, ..LimitConfig::default() }, vec![], )); }) .await; let login = |peer: &str| { request( "POST", "/api/v1/operator/login", peer, None, Some(json!({"password": "fixture-operator-password"})), ) }; let started = std::time::Instant::now(); assert_eq!( none.status(login("203.0.113.1")).await, StatusCode::TOO_MANY_REQUESTS ); assert!( started.elapsed() < std::time::Duration::from_millis(500), "no hashing was started" ); // one permit, generous budgets: sequential logins all succeed, so the permit is returned let one = harness_with(|state| { operator_state(state); let loose = Quota::per_second(NonZeroU32::new(1000).unwrap()); state.limits = Arc::new(Limits::new( LimitConfig { argon2_concurrency: 1, login_source: loose, login_account: loose, ..LimitConfig::default() }, vec![], )); }) .await; for _ in 0..4 { assert_eq!(one.status(login("203.0.113.1")).await, StatusCode::OK); } } #[tokio::test] async fn the_shared_admin_token_stops_working_after_its_end_date() { let ok = harness_with(|state| { state.admin = AdminGate { token: Some(ADMIN.into()), token_expires_at: Some(chrono::Utc::now().timestamp() + 3600), ..Default::default() } }) .await; assert_eq!( ok.status(request( "GET", "/api/v1/orbits", "127.0.0.1", Some(ADMIN), None )) .await, StatusCode::OK ); let actor: String = ok.scalar("SELECT actor_id FROM audit_events WHERE action='authorization.check' AND outcome='allowed' LIMIT 1"); assert_eq!( actor, "legacy-admin-token", "every use is attributed to the legacy token in the audit log" ); let past = harness_with(|state| { state.admin = AdminGate { token: Some(ADMIN.into()), token_expires_at: Some(chrono::Utc::now().timestamp() - 1), ..Default::default() } }) .await; assert_eq!( past.status(request( "GET", "/api/v1/orbits", "127.0.0.1", Some(ADMIN), None )) .await, StatusCode::UNAUTHORIZED ); // an expired token must not silently fall back to anonymous development access either let dev = harness_with(|state| { state.admin = AdminGate { token: Some(ADMIN.into()), token_expires_at: Some(1), local_development: true, } }) .await; assert_eq!( dev.status(request("GET", "/api/v1/orbits", "127.0.0.1", None, None)) .await, StatusCode::UNAUTHORIZED ); assert!(!dev.state.admin.token_active()); } #[tokio::test] async fn sso_endpoints_are_rate_limited_per_source() { let h = harness().await; // OIDC disabled answers 404 before limiting; exercise the limiter directly let source = h.state.limits.source( Some("203.0.113.1:1".parse().unwrap()), &axum::http::HeaderMap::new(), ); let allowed = (0..60) .filter(|_| h.state.limits.oidc_login_allowed(source)) .count(); assert_eq!(allowed, 15, "burst, then refused"); let other = h.state.limits.source( Some("203.0.113.2:1".parse().unwrap()), &axum::http::HeaderMap::new(), ); assert!(h.state.limits.oidc_login_allowed(other)); } // ---- pairing, the ways it must say no ---- const START: &str = "/api/v1/wormhole/pairing"; const CLAIM: &str = "/api/v1/wormhole/claim"; /// A different source address each time, so the per-source claim limit does not interfere. fn fresh_peer() -> String { static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(1); let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); format!("192.0.{}.{}", (n >> 8) & 255, n & 255) } impl Harness { async fn start_code(&self) -> String { let start = self .call(request("POST", START, "127.0.0.1", Some(ADMIN), None)) .await; assert_eq!(start.status(), StatusCode::OK); json_of(start).await["code"].as_str().unwrap().to_string() } async fn claim(&self, _peer: &str, body: Value) -> Response { self.call(request("POST", CLAIM, &fresh_peer(), None, Some(body))) .await } fn outposts(&self) -> i64 { self.scalar("SELECT COUNT(*) FROM outposts") } fn credentials(&self) -> i64 { self.scalar("SELECT COUNT(*) FROM outpost_credentials") } } #[tokio::test] async fn only_an_admin_can_start_a_pairing() { let h = harness().await; for auth in [None, Some("wrong-token"), Some("")] { let status = h .status(request("POST", START, "127.0.0.1", auth, None)) .await; assert!( status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN, "{auth:?} must not start a pairing, got {status}" ); } // a paired agent's upload token is not an operator credential either let (_, token) = h.pair("agent").await; let status = h .status(as_outpost( request("POST", START, "198.51.100.20", None, None), &token, )) .await; assert!( status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN, "an outpost token must not start a pairing, got {status}" ); let codes: i64 = h.scalar("SELECT COUNT(*) FROM pairing_codes WHERE consumed_at IS NULL"); assert_eq!(codes, 0, "a refused request leaves no code behind"); } #[tokio::test] async fn a_started_code_is_twelve_unambiguous_characters_valid_for_about_ten_minutes() { let h = harness().await; let start = h .call(request("POST", START, "127.0.0.1", Some(ADMIN), None)) .await; let body = json_of(start).await; let code = body["code"].as_str().unwrap(); assert_eq!(code.len(), 12); assert!( code.chars() .all(|c| "23456789ABCDEFGHJKLMNPQRSTUVWXYZ".contains(c)), "no 0/O/1/I lookalikes: {code}" ); let expires = chrono::DateTime::parse_from_rfc3339(body["expires_at"].as_str().unwrap()) .unwrap() .timestamp(); let in_secs = expires - chrono::Utc::now().timestamp(); assert!((595..=600).contains(&in_secs), "expires in {in_secs}s"); assert_ne!(code, h.start_code().await, "codes are not repeated"); } #[tokio::test] async fn a_claim_that_is_refused_creates_no_outpost_and_no_credential() { let h = harness().await; let code = h.start_code().await; let lower = code.to_lowercase(); let spaced = format!(" {code} "); let truncated = code[..11].to_string(); for wrong in [ lower.as_str(), spaced.as_str(), truncated.as_str(), "", "AAAAAAAAAAAA", "'; DROP TABLE pairing_codes;--", ] { let response = h .claim("198.51.100.20", json!({"code": wrong, "outpost_name": "x"})) .await; assert_eq!(response.status(), StatusCode::GONE, "code {wrong:?}"); } assert_eq!((h.outposts(), h.credentials()), (0, 0)); let failed: i64 = h.scalar( "SELECT COUNT(*) FROM audit_events WHERE action='outpost.pair' AND outcome='failed'", ); assert_eq!(failed, 6, "every refusal is audited"); let leaked: i64 = h.scalar(&format!( "SELECT COUNT(*) FROM audit_events WHERE actor_id||action||coalesce(resource_id,'') LIKE '%{code}%'" )); assert_eq!(leaked, 0, "the code is never written to the audit log"); // the real code still works afterwards: wrong guesses do not burn it let ok = h .claim( "198.51.100.20", json!({"code": code, "outpost_name": "real"}), ) .await; assert_eq!(ok.status(), StatusCode::OK); } #[tokio::test] async fn a_claim_with_a_bad_name_is_refused_before_the_code_is_spent() { let h = harness().await; let code = h.start_code().await; let too_long = "n".repeat(129); for name in [ "", " ", "\t\n", "tab\there", "nul\u{0}byte", too_long.as_str(), ] { let response = h .claim("198.51.100.20", json!({"code": code, "outpost_name": name})) .await; assert_eq!(response.status(), StatusCode::BAD_REQUEST, "name {name:?}"); } assert_eq!(h.outposts(), 0); let longest = "n".repeat(128); let ok = h .claim( "198.51.100.20", json!({"code": code, "outpost_name": longest}), ) .await; assert_eq!(ok.status(), StatusCode::OK, "128 characters is allowed"); assert_eq!(h.outposts(), 1); } #[tokio::test] async fn malformed_claims_are_client_errors_and_never_touch_a_code() { let h = harness().await; let code = h.start_code().await; for body in [ json!({}), json!({"code": code}), json!({"outpost_name": "x"}), json!({"code": 12345, "outpost_name": "x"}), json!({"code": null, "outpost_name": "x"}), json!({"code": ["a"], "outpost_name": "x"}), ] { let status = h.claim("198.51.100.20", body.clone()).await.status(); assert!( status.is_client_error() && status != StatusCode::GONE, "{body} gave {status}" ); } let good = format!(r#"{{"code":"{code}","outpost_name":"x"}}"#); let raw = |content_type: Option<&str>, body: &str| { let mut builder = Request::builder() .method("POST") .uri(CLAIM) .extension(ConnectInfo( format!("{}:4000", fresh_peer()) .parse::() .unwrap(), )); if let Some(content_type) = content_type { builder = builder.header(header::CONTENT_TYPE, content_type); } builder.body(Body::from(body.to_string())).unwrap() }; for request in [ raw(Some("application/json"), "{not json"), raw(None, &good), raw(Some("text/plain"), &good), ] { let status = h.status(request).await; assert!(status.is_client_error(), "got {status}"); } assert_eq!((h.outposts(), h.credentials()), (0, 0)); let ok = h .claim("198.51.100.20", json!({"code": code, "outpost_name": "x"})) .await; assert_eq!( ok.status(), StatusCode::OK, "the code survived every bad request" ); } #[tokio::test] async fn an_enormous_code_is_refused_without_trouble() { let h = harness().await; let huge = "A".repeat(1 << 20); let status = h .claim("198.51.100.20", json!({"code": huge, "outpost_name": "x"})) .await .status(); assert!( status == StatusCode::GONE || status == StatusCode::PAYLOAD_TOO_LARGE, "got {status}" ); assert_eq!((h.outposts(), h.credentials()), (0, 0)); } #[tokio::test] async fn a_claimed_code_cannot_be_replayed_and_the_replay_is_audited() { let h = harness().await; let code = h.start_code().await; let first = h .claim( "198.51.100.20", json!({"code": code, "outpost_name": "first"}), ) .await; assert_eq!(first.status(), StatusCode::OK); let second = h .claim( "198.51.100.21", json!({"code": code, "outpost_name": "second"}), ) .await; assert_eq!(second.status(), StatusCode::GONE); assert_eq!((h.outposts(), h.credentials()), (1, 1), "no second outpost"); let failed: i64 = h.scalar( "SELECT COUNT(*) FROM audit_events WHERE action='outpost.pair' AND outcome='failed'", ); assert_eq!(failed, 1); } #[tokio::test] async fn an_expired_code_is_refused_and_old_ones_are_swept_by_the_next_pairing() { let h = harness().await; let now = chrono::Utc::now().timestamp(); h.state .db .insert_pairing("old-outpost", "STALECODE234", now - 1) .unwrap(); h.state .db .insert_pairing("ancient-outpost", "ANCIENTCODE2", now - 200_000) .unwrap(); let response = h .claim( "198.51.100.20", json!({"code": "STALECODE234", "outpost_name": "late"}), ) .await; assert_eq!(response.status(), StatusCode::GONE); assert_eq!((h.outposts(), h.credentials()), (0, 0)); h.start_code().await; // a code that expired a moment ago lingers (the claim still refuses it); one a day old is deleted let rows: i64 = h.scalar("SELECT COUNT(*) FROM pairing_codes"); assert_eq!(rows, 2, "the recent stale code and the fresh one remain"); }