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:
@@ -40,20 +40,7 @@ async fn human_read_endpoints_reject_anonymous_and_outpost_tokens() {
|
||||
state.sessions = crate::admin::SessionGate::fixture(state.db.clone());
|
||||
state.admin.token = Some("synthetic-admin".into());
|
||||
let outpost = uuid::Uuid::new_v4();
|
||||
state
|
||||
.db
|
||||
.insert_wormhole_token(
|
||||
"synthetic-outpost",
|
||||
&outpost.to_string(),
|
||||
"synthetic-code",
|
||||
"9999",
|
||||
)
|
||||
.unwrap();
|
||||
state
|
||||
.db
|
||||
.claim_wormhole_code("synthetic-code", "fixture", "2026")
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
state.db.insert_test_credential("synthetic-outpost", &outpost.to_string(), "fixture");
|
||||
let app = router(state);
|
||||
for row in CONTRACT.lines().filter(|line| line.starts_with("| /")) {
|
||||
let fields: Vec<_> = row.split('|').map(str::trim).collect();
|
||||
@@ -94,6 +81,7 @@ async fn local_proxy_never_enables_auth_when_credentials_are_absent() {
|
||||
state.admin = crate::admin::AdminGate {
|
||||
token: None,
|
||||
local_development: false,
|
||||
..Default::default()
|
||||
};
|
||||
assert!(!state.sessions.enabled());
|
||||
let app = router(state);
|
||||
|
||||
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));
|
||||
}
|
||||
@@ -422,7 +422,7 @@ fn authenticate_outpost(state: &HubState, headers: &HeaderMap) -> Result<Uuid, S
|
||||
let token = upload_token(state, headers)?;
|
||||
let id = state
|
||||
.db
|
||||
.upload_token_outpost(token)
|
||||
.upload_token_outpost(token, chrono::Utc::now().timestamp())
|
||||
.map_err(internal)?
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
let id = Uuid::parse_str(&id).map_err(internal)?;
|
||||
|
||||
@@ -9,6 +9,8 @@ mod session;
|
||||
mod auth_contract;
|
||||
#[cfg(test)]
|
||||
mod oidc_tests;
|
||||
#[cfg(test)]
|
||||
mod credentials_tests;
|
||||
|
||||
pub use orbit::run_orbit_internal;
|
||||
pub use routes::router;
|
||||
|
||||
@@ -5,13 +5,14 @@ use crate::auth::{AuditAction, AuditOutcome, AuditResource, Principal};
|
||||
use crate::oidc::OidcError;
|
||||
use crate::state::HubState;
|
||||
use axum::{
|
||||
extract::{Query, State},
|
||||
extract::{ConnectInfo, Query, State},
|
||||
http::{header, HeaderMap, HeaderValue, StatusCode},
|
||||
response::{IntoResponse, Redirect, Response},
|
||||
routing::get,
|
||||
Router,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use std::net::SocketAddr;
|
||||
|
||||
const CORRELATION: &str = "__Host-tessera-oidc";
|
||||
|
||||
@@ -59,8 +60,12 @@ fn correlation_from(headers: &HeaderMap) -> Option<String> {
|
||||
})
|
||||
}
|
||||
|
||||
async fn login(State(state): State<HubState>) -> Response {
|
||||
async fn login(peer: Option<ConnectInfo<SocketAddr>>, State(state): State<HubState>, headers: HeaderMap) -> Response {
|
||||
let Some(oidc) = state.oidc.clone() else { return StatusCode::NOT_FOUND.into_response() };
|
||||
let source = state.limits.source(peer.map(|ConnectInfo(a)| a), &headers);
|
||||
if !state.limits.oidc_login_allowed(source) {
|
||||
return StatusCode::TOO_MANY_REQUESTS.into_response();
|
||||
}
|
||||
let begun = match oidc.begin().await {
|
||||
Ok(begun) => begun,
|
||||
Err(_) => return failure(&state, "unavailable", StatusCode::SERVICE_UNAVAILABLE).await,
|
||||
@@ -76,8 +81,17 @@ async fn login(State(state): State<HubState>) -> Response {
|
||||
response
|
||||
}
|
||||
|
||||
async fn callback(State(state): State<HubState>, headers: HeaderMap, Query(query): Query<CallbackQuery>) -> Response {
|
||||
async fn callback(
|
||||
peer: Option<ConnectInfo<SocketAddr>>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Query(query): Query<CallbackQuery>,
|
||||
) -> Response {
|
||||
let Some(oidc) = state.oidc.clone() else { return StatusCode::NOT_FOUND.into_response() };
|
||||
let source = state.limits.source(peer.map(|ConnectInfo(a)| a), &headers);
|
||||
if !state.limits.oidc_callback_allowed(source) {
|
||||
return StatusCode::TOO_MANY_REQUESTS.into_response();
|
||||
}
|
||||
let outcome = complete(&state, &oidc, &headers, query).await;
|
||||
let mut response = match outcome {
|
||||
Ok(session) => {
|
||||
|
||||
@@ -37,6 +37,8 @@ static WEB_DIST: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/../../web/dist");
|
||||
start_reconstitute,
|
||||
pairing_start,
|
||||
pairing_claim,
|
||||
rotate_outpost_token,
|
||||
revoke_outpost,
|
||||
wormhole_upload_init,
|
||||
wormhole_upload_chunk,
|
||||
wormhole_restic_commit,
|
||||
@@ -55,6 +57,7 @@ static WEB_DIST: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/../../web/dist");
|
||||
PairingResponse,
|
||||
ClaimRequest,
|
||||
ClaimResponse,
|
||||
RotateResponse,
|
||||
UploadInit,
|
||||
UploadChunk,
|
||||
ResticCommit,
|
||||
@@ -325,6 +328,8 @@ pub fn router(state: HubState) -> Router {
|
||||
.route("/api/v1/wormhole/outposts", get(outposts))
|
||||
.route("/api/v1/wormhole/pairing", post(pairing_start))
|
||||
.route("/api/v1/wormhole/claim", post(pairing_claim))
|
||||
.route("/api/v1/wormhole/outposts/:id/rotate", post(rotate_outpost_token))
|
||||
.route("/api/v1/wormhole/outposts/:id/revoke", post(revoke_outpost))
|
||||
.route("/api/v1/wormhole/upload/init", post(wormhole_upload_init))
|
||||
.route("/api/v1/wormhole/upload/chunk", post(wormhole_upload_chunk))
|
||||
.route(
|
||||
@@ -737,16 +742,10 @@ async fn pairing_start(
|
||||
(0..12).map(|_| ALPHABET[random.gen_range(0..ALPHABET.len())] as char).collect()
|
||||
};
|
||||
let expires = chrono::Utc::now() + chrono::Duration::minutes(10);
|
||||
let outpost_id = Uuid::new_v4();
|
||||
let upload_token = hex::encode(Uuid::new_v4().as_bytes());
|
||||
// Only a digest of the code is stored, and no token exists yet: it is minted at claim.
|
||||
state
|
||||
.db
|
||||
.insert_wormhole_token(
|
||||
&upload_token,
|
||||
&outpost_id.to_string(),
|
||||
&code,
|
||||
&expires.to_rfc3339(),
|
||||
)
|
||||
.insert_pairing(&Uuid::new_v4().to_string(), &code, expires.timestamp())
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
Ok(Json(PairingResponse {
|
||||
code,
|
||||
@@ -754,21 +753,40 @@ async fn pairing_start(
|
||||
}))
|
||||
}
|
||||
|
||||
#[utoipa::path(post, path = "/api/v1/wormhole/claim", request_body = ClaimRequest, responses((status = 200, body = ClaimResponse)))]
|
||||
#[utoipa::path(post, path = "/api/v1/wormhole/claim", request_body = ClaimRequest, responses((status = 200, body = ClaimResponse), (status = 429)))]
|
||||
async fn pairing_claim(
|
||||
peer: Option<ConnectInfo<SocketAddr>>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Json(req): Json<ClaimRequest>,
|
||||
) -> Result<Json<ClaimResponse>, StatusCode> {
|
||||
let source = state.limits.source(peer.map(|ConnectInfo(addr)| addr), &headers);
|
||||
if !state.limits.claim_allowed(source) {
|
||||
if state.limits.audit_denial(source) {
|
||||
let _ = state.db.audit_event(&Principal::Anonymous, AuditAction::OutpostPair,
|
||||
AuditResource::Api, AuditOutcome::Denied, Uuid::new_v4());
|
||||
}
|
||||
return Err(StatusCode::TOO_MANY_REQUESTS);
|
||||
}
|
||||
let name = req.outpost_name.trim();
|
||||
if name.is_empty() || name.len() > 128 || name.chars().any(char::is_control) {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
let claimed = state
|
||||
.db
|
||||
.claim_wormhole_code(&req.code, name, &now)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.ok_or(StatusCode::GONE)?;
|
||||
.claim_pairing(&req.code, name, chrono::Utc::now().timestamp())
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let Some(claimed) = claimed else {
|
||||
let _ = state.db.audit_event(&Principal::Anonymous, AuditAction::OutpostPair,
|
||||
AuditResource::Api, AuditOutcome::Failed, Uuid::new_v4());
|
||||
return Err(StatusCode::GONE);
|
||||
};
|
||||
let outpost_id = Uuid::parse_str(&claimed.outpost_id).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
state
|
||||
.db
|
||||
.audit_event(&Principal::Outpost(outpost_id), AuditAction::OutpostPair,
|
||||
AuditResource::Outpost(outpost_id), AuditOutcome::Succeeded, Uuid::new_v4())
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let hub_url = std::env::var("TESSERA_PUBLIC_URL").unwrap_or_else(|_| {
|
||||
if state.wormhole_mtls {
|
||||
"https://127.0.0.1:8788".into()
|
||||
@@ -776,19 +794,97 @@ async fn pairing_claim(
|
||||
"http://127.0.0.1:8787".into()
|
||||
}
|
||||
});
|
||||
state
|
||||
.db
|
||||
.audit("wormhole.paired", name)
|
||||
.await
|
||||
.ok();
|
||||
let outpost_id = Uuid::parse_str(&claimed.1).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
state.db.audit("wormhole.paired", name).await.ok();
|
||||
Ok(Json(ClaimResponse {
|
||||
outpost_id,
|
||||
upload_token: claimed.0,
|
||||
upload_token: claimed.token,
|
||||
hub_url,
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct RotateQuery {
|
||||
/// Minutes the previous token keeps working (default 60, 0 = cut at once, max 1440).
|
||||
grace_minutes: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize, utoipa::ToSchema)]
|
||||
struct RotateResponse {
|
||||
outpost_id: Uuid,
|
||||
upload_token: String,
|
||||
expires_at: chrono::DateTime<chrono::Utc>,
|
||||
previous_valid_until: Option<chrono::DateTime<chrono::Utc>>,
|
||||
}
|
||||
|
||||
fn timestamp(seconds: i64) -> chrono::DateTime<chrono::Utc> {
|
||||
chrono::DateTime::from_timestamp(seconds, 0).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Issue a new upload token for a paired Outpost. The response is the only place
|
||||
/// the token appears; the operator puts it on the agent within the grace window.
|
||||
#[utoipa::path(post, path = "/api/v1/wormhole/outposts/{id}/rotate",
|
||||
params(("id" = Uuid, Path, description = "paired Outpost")),
|
||||
responses((status = 200, body = RotateResponse), (status = 404)))]
|
||||
async fn rotate_outpost_token(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
axum::extract::Query(query): axum::extract::Query<RotateQuery>,
|
||||
) -> Result<(HeaderMap, Json<RotateResponse>), StatusCode> {
|
||||
let actor = require_admin_mutation(&state, peer, &headers)?;
|
||||
let grace = query.grace_minutes.unwrap_or(60);
|
||||
if !(0..=1440).contains(&grace) {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
let now = chrono::Utc::now().timestamp();
|
||||
let issued = state
|
||||
.db
|
||||
.rotate_credential(&id.to_string(), grace * 60, now)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let outcome = if issued.is_some() { AuditOutcome::Succeeded } else { AuditOutcome::Failed };
|
||||
state
|
||||
.db
|
||||
.audit_event(&actor.principal, AuditAction::CredentialRotate, AuditResource::Outpost(id), outcome, actor.request_id)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let issued = issued.ok_or(StatusCode::NOT_FOUND)?;
|
||||
let mut response_headers = HeaderMap::new();
|
||||
response_headers.insert(axum::http::header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
|
||||
Ok((
|
||||
response_headers,
|
||||
Json(RotateResponse {
|
||||
outpost_id: id,
|
||||
upload_token: issued.token,
|
||||
expires_at: timestamp(issued.expires_at),
|
||||
previous_valid_until: issued.previous_valid_until.map(timestamp),
|
||||
}),
|
||||
))
|
||||
}
|
||||
|
||||
/// Revoke every credential of an Outpost. Its next request is refused; a leased
|
||||
/// job it was running can no longer report. It has to be paired again.
|
||||
#[utoipa::path(post, path = "/api/v1/wormhole/outposts/{id}/revoke",
|
||||
params(("id" = Uuid, Path, description = "Outpost to revoke")),
|
||||
responses((status = 204), (status = 404)))]
|
||||
async fn revoke_outpost(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
let actor = require_admin_mutation(&state, peer, &headers)?;
|
||||
let known = state
|
||||
.db
|
||||
.revoke_outpost(&id.to_string(), chrono::Utc::now().timestamp())
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let outcome = if known { AuditOutcome::Succeeded } else { AuditOutcome::Failed };
|
||||
state
|
||||
.db
|
||||
.audit_event(&actor.principal, AuditAction::CredentialRevoke, AuditResource::Outpost(id), outcome, actor.request_id)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
if known { Ok(StatusCode::NO_CONTENT) } else { Err(StatusCode::NOT_FOUND) }
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, utoipa::ToSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct OutpostBinding {
|
||||
@@ -1140,9 +1236,8 @@ mod tests {
|
||||
state.admin.token = Some("synthetic-admin".into());
|
||||
let a = Uuid::new_v4();
|
||||
let b = Uuid::new_v4();
|
||||
for (id, token, code) in [(a, "outpost-a", "code-a"), (b, "outpost-b", "code-b")] {
|
||||
state.db.insert_wormhole_token(token, &id.to_string(), code, "9999").unwrap();
|
||||
state.db.claim_wormhole_code(code, token, "2026").unwrap().unwrap();
|
||||
for (id, token) in [(a, "outpost-a"), (b, "outpost-b")] {
|
||||
state.db.insert_test_credential(token, &id.to_string(), "agent");
|
||||
}
|
||||
let orbit = Uuid::new_v4();
|
||||
state.db.upsert_orbit(&OrbitRow {
|
||||
@@ -1257,8 +1352,7 @@ mod tests {
|
||||
assert_eq!(state.db.list_orbits().await.unwrap()[1].last_status, "idle");
|
||||
|
||||
let outpost = Uuid::new_v4();
|
||||
state.db.insert_wormhole_token("fixture-token", &outpost.to_string(), "fixture-code", "9999").unwrap();
|
||||
state.db.claim_wormhole_code("fixture-code", "fixture", "2026").unwrap().unwrap();
|
||||
state.db.insert_test_credential("fixture-token", &outpost.to_string(), "agent");
|
||||
assert!(state.db.bind_legacy_outpost(orbit.id, outpost).unwrap());
|
||||
{
|
||||
let conn = rusqlite::Connection::open(dir.path().join("tessera.db")).unwrap();
|
||||
|
||||
@@ -86,17 +86,33 @@ async fn me(
|
||||
}
|
||||
|
||||
async fn login(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Json(input): Json<Login>,
|
||||
) -> Result<(HeaderMap, Json<Status>), StatusCode> {
|
||||
// Cheap checks first: per-source budget, then the account ceiling, then a
|
||||
// bounded number of concurrent Argon2 verifications. A flood is refused
|
||||
// before it can cost CPU or memory, and it only spends its own source's budget.
|
||||
let source = state.limits.source(Some(peer), &headers);
|
||||
if !state.limits.login_allowed(source) {
|
||||
if state.limits.audit_denial(source) {
|
||||
let _ = state.db.audit_event(&Principal::Anonymous, AuditAction::Login, AuditResource::Session,
|
||||
AuditOutcome::Denied, uuid::Uuid::new_v4());
|
||||
}
|
||||
return Err(StatusCode::TOO_MANY_REQUESTS);
|
||||
}
|
||||
if input.password.is_empty() || input.password.len() > 1024 {
|
||||
return Err(StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
let permit = state.limits.argon2.clone().try_acquire_owned().map_err(|_| StatusCode::TOO_MANY_REQUESTS)?;
|
||||
let gate = state.sessions.clone();
|
||||
let attempt = tokio::task::spawn_blocking(move || gate.login(&headers, &input.password))
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let attempt = tokio::task::spawn_blocking(move || {
|
||||
let _permit = permit; // released when hashing is done, not when the handler returns
|
||||
gate.login(&headers, &input.password)
|
||||
})
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let (principal, outcome) = match &attempt {
|
||||
Ok(session) => (Principal::Emergency(session.actor.clone()), AuditOutcome::Succeeded),
|
||||
Err(_) => (Principal::Anonymous, AuditOutcome::Failed),
|
||||
|
||||
Reference in New Issue
Block a user