feat: store Outpost credentials as digests and rate limit public endpoints (auth M4)
Credentials - pairing codes and Outpost upload tokens are stored only as SHA-256 digests; the token is minted at claim (256-bit OsRng) and returned once - the old clear-text wormhole_tokens table is migrated in place and dropped with secure_delete; active tokens keep working with a fresh lifetime - admin rotate (with grace window) and revoke endpoints, audited; a revoked Outpost is refused on its next request - optional end date for the shared admin token (TESSERA_ADMIN_TOKEN_EXPIRES) Limits - governor per-source limits for emergency login, pairing claim and SSO start/callback; X-Forwarded-For only from TESSERA_TRUSTED_PROXIES; IPv6 by /64 - at most two concurrent Argon2 verifications, refused immediately when busy - denials audited at most once a minute per source - the mTLS listener now supplies the peer address to handlers Existing hubs: rotate every Outpost token after upgrading; old database copies still contain the clear-text tokens. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
285
crates/tessera-hub/src/api/credentials_tests.rs
Normal file
285
crates/tessera-hub/src/api/credentials_tests.rs
Normal file
@@ -0,0 +1,285 @@
|
||||
//! 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").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<Value>) -> Request<Body> {
|
||||
let mut builder = Request::builder()
|
||||
.method(method)
|
||||
.uri(uri)
|
||||
.extension(ConnectInfo(format!("{peer}:4000").parse::<SocketAddr>().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<Body>, token: &str) -> Request<Body> {
|
||||
request.headers_mut().insert("x-tessera-upload-token", token.parse().unwrap());
|
||||
request
|
||||
}
|
||||
|
||||
async fn json_of(response: Response<Body>) -> 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<Body>) -> Response<Body> {
|
||||
self.app.clone().oneshot(request).await.unwrap()
|
||||
}
|
||||
|
||||
async fn status(&self, request: Request<Body>) -> 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<T: rusqlite::types::FromSql>(&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::<Result<_, _>>().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));
|
||||
}
|
||||
Reference in New Issue
Block a user