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:
2026-11-14 14:06:18 +07:00
parent 618681fa7f
commit 54abd02250
22 changed files with 1376 additions and 164 deletions

58
Cargo.lock generated
View File

@@ -46,6 +46,12 @@ dependencies = [
"memchr",
]
[[package]]
name = "allocator-api2"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
[[package]]
name = "android_system_properties"
version = "0.1.6"
@@ -961,6 +967,12 @@ version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
[[package]]
name = "futures-timer"
version = "3.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af43fadb8a98512d547e37b4e92e0ced13e205c061b87b4623eff01d918d6968"
[[package]]
name = "futures-util"
version = "0.3.34"
@@ -1025,6 +1037,25 @@ dependencies = [
"polyval",
]
[[package]]
name = "governor"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9efcab3c1958580ff1f25a2a41be1668f7603d849bb63af523b208a3cc1223b8"
dependencies = [
"cfg-if",
"futures-sink",
"futures-timer",
"futures-util",
"hashbrown 0.16.1",
"nonzero_ext",
"parking_lot",
"portable-atomic",
"smallvec",
"spinning_top",
"web-time",
]
[[package]]
name = "group"
version = "0.14.0"
@@ -1067,6 +1098,17 @@ version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
[[package]]
name = "hashbrown"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
dependencies = [
"allocator-api2",
"equivalent",
"foldhash",
]
[[package]]
name = "hashbrown"
version = "0.17.1"
@@ -1681,6 +1723,12 @@ dependencies = [
"minimal-lexical",
]
[[package]]
name = "nonzero_ext"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38bf9645c8b145698bb0b18a4637dcacbc421ea49bef2317e4fd8065a387cf21"
[[package]]
name = "nu-ansi-term"
version = "0.50.3"
@@ -2830,6 +2878,15 @@ version = "0.9.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
[[package]]
name = "spinning_top"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9cf02766a1eb909bc7653557c66b384e44edc3ad979e6257c6173c65ea51bc7d"
dependencies = [
"lock_api",
]
[[package]]
name = "spki"
version = "0.7.3"
@@ -3031,6 +3088,7 @@ dependencies = [
"chrono",
"chrono-tz",
"cron",
"governor",
"hex",
"hmac 0.12.1",
"hyper",

View File

@@ -35,6 +35,7 @@ uuid.workspace = true
hex.workspace = true
sha2.workspace = true
base64 = "0.22"
governor = { version = "=0.10.4", default-features = false, features = ["std"] }
openidconnect = { version = "=4.1.0", default-features = false, features = ["reqwest", "rustls-tls"] }
tempfile.workspace = true
indexmap = "=2.2.6"

View File

@@ -1,9 +1,12 @@
use axum::http::{HeaderMap, StatusCode};
use std::net::SocketAddr;
#[derive(Clone, Debug)]
#[derive(Clone, Debug, Default)]
pub struct AdminGate {
pub token: Option<String>,
/// Unix time after which the shared admin token is refused. The token is a
/// transition aid for CLI/automation, not a permanent credential.
pub token_expires_at: Option<i64>,
pub local_development: bool,
}
@@ -18,7 +21,11 @@ impl AdminGate {
Ok("0" | "false" | "") | Err(std::env::VarError::NotPresent) => false,
_ => anyhow::bail!("TESSERA_LOCAL_DEVELOPMENT must be true, false, 1 or 0"),
};
Ok(Self { token, local_development })
let token_expires_at = match std::env::var("TESSERA_ADMIN_TOKEN_EXPIRES").ok().map(|v| v.trim().to_string()).filter(|v| !v.is_empty()) {
None => None,
Some(value) => Some(parse_end_date(&value)?),
};
Ok(Self { token, token_expires_at, local_development })
}
pub fn validate_listener(&self, addr: SocketAddr) -> anyhow::Result<()> {
@@ -27,7 +34,25 @@ impl AdminGate {
Ok(())
}
/// The shared admin token is configured and not past its end date.
pub fn token_active(&self) -> bool {
self.token.is_some() && !self.token_expired(chrono::Utc::now().timestamp())
}
pub fn token_expired(&self, now: i64) -> bool {
self.token_expires_at.is_some_and(|end| now >= end)
}
pub fn log_policy(&self) {
if let Some(end) = self.token_expires_at {
if self.token_expired(chrono::Utc::now().timestamp()) {
tracing::warn!("TESSERA_ADMIN_TOKEN is past its end date ({end}) and is refused; remove it or set a new date");
} else if self.token.is_some() {
tracing::info!("TESSERA_ADMIN_TOKEN is accepted until unix time {end}; plan to replace it with SSO/service access");
}
} else if self.token.is_some() {
tracing::warn!("TESSERA_ADMIN_TOKEN has no end date; set TESSERA_ADMIN_TOKEN_EXPIRES so the shared token cannot stay indefinitely");
}
if self.local_development && self.token.is_none() {
tracing::warn!(
"explicit local development mode: loopback APIs allow anonymous access; do not proxy this listener"
@@ -42,6 +67,7 @@ impl AdminGate {
pub fn authorize(&self, peer: SocketAddr, headers: &HeaderMap) -> Result<(), StatusCode> {
let presented = presented_token(headers);
match &self.token {
Some(_) if self.token_expired(chrono::Utc::now().timestamp()) => Err(StatusCode::UNAUTHORIZED),
Some(expected) => {
if presented.is_some_and(|value| tokens_match(expected, value)) {
Ok(())
@@ -79,6 +105,16 @@ fn presented_token(headers: &HeaderMap) -> Option<&str> {
}
}
/// `2026-12-31` (end of that day, UTC) or a full RFC 3339 timestamp.
fn parse_end_date(value: &str) -> anyhow::Result<i64> {
if let Ok(time) = chrono::DateTime::parse_from_rfc3339(value) {
return Ok(time.timestamp());
}
let date = chrono::NaiveDate::parse_from_str(value, "%Y-%m-%d")
.map_err(|_| anyhow::anyhow!("TESSERA_ADMIN_TOKEN_EXPIRES must be YYYY-MM-DD or an RFC 3339 timestamp"))?;
Ok(date.and_hms_opt(23, 59, 59).unwrap().and_utc().timestamp())
}
pub(crate) fn tokens_match(expected: &str, presented: &str) -> bool {
let expected = expected.as_bytes();
let presented = presented.as_bytes();
@@ -101,7 +137,7 @@ mod tests {
#[test]
fn loopback_without_credentials_is_denied_even_behind_a_local_proxy() {
let gate = AdminGate { token: None, local_development: false };
let gate = AdminGate { token: None, local_development: false, ..Default::default() };
let headers = HeaderMap::new();
assert!(gate
.authorize(peer(IpAddr::V4(Ipv4Addr::LOCALHOST)), &headers)
@@ -119,6 +155,7 @@ mod tests {
let gate = AdminGate {
token: Some("secret-token".into()),
local_development: false,
..Default::default()
};
let mut headers = HeaderMap::new();
assert!(gate
@@ -150,7 +187,7 @@ mod tests {
#[test]
fn development_is_explicit_loopback_only_and_rejects_forwarded_requests() {
let gate = AdminGate { token: None, local_development: true };
let gate = AdminGate { token: None, local_development: true, ..Default::default() };
for addr in ["127.0.0.1:8787", "[::1]:8787"] {
assert!(gate.validate_listener(addr.parse().unwrap()).is_ok());
assert!(gate.authorize(addr.parse().unwrap(), &HeaderMap::new()).is_ok());
@@ -178,7 +215,6 @@ pub struct SessionGate {
/// Fingerprint of the OIDC configuration (issuer, client, admin mapping).
/// OIDC sessions only count while the same configuration is active.
oidc_fp: Option<String>,
attempts: std::sync::Arc<std::sync::Mutex<std::collections::VecDeque<std::time::Instant>>>,
}
struct OperatorConfig {
@@ -256,7 +292,7 @@ impl SessionGate {
Err(std::env::VarError::NotPresent) => None,
Err(_) => anyhow::bail!("operator password hash must be UTF-8"),
};
Ok(Self { config, db, oidc_fp, attempts: Default::default() })
Ok(Self { config, db, oidc_fp })
}
/// Any browser login method is configured (emergency password and/or OIDC).
@@ -306,14 +342,6 @@ impl SessionGate {
pub fn login(&self, headers: &HeaderMap, password: &str) -> Result<BrowserSession, StatusCode> {
use argon2::PasswordVerifier;
let config = self.config.as_ref().ok_or(StatusCode::NOT_FOUND)?;
{
let mut attempts = self.attempts.lock().unwrap();
attempts.retain(|attempt| attempt.elapsed() < std::time::Duration::from_secs(60));
if attempts.len() >= 10 {
return Err(StatusCode::TOO_MANY_REQUESTS);
}
attempts.push_back(std::time::Instant::now());
}
let hash = argon2::PasswordHash::new(&config.password_hash)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
argon2::Argon2::default()
@@ -438,13 +466,12 @@ impl SessionGate {
})),
db,
oidc_fp: None,
attempts: Default::default(),
}
}
/// Same database, no operator configured (hash unset after a restart).
pub fn without_operator(db: crate::db::Db) -> Self {
Self { config: None, db, oidc_fp: None, attempts: Default::default() }
Self { config: None, db, oidc_fp: None }
}
pub fn with_oidc(mut self, fingerprint: &str) -> Self {

View File

@@ -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);

View 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));
}

View File

@@ -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)?;

View File

@@ -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;

View File

@@ -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) => {

View File

@@ -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();

View File

@@ -86,15 +86,31 @@ 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))
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 {

View File

@@ -31,6 +31,9 @@ pub enum AuditAction {
Login,
Logout,
OutpostBind,
OutpostPair,
CredentialRotate,
CredentialRevoke,
}
impl AuditAction {
@@ -41,6 +44,9 @@ impl AuditAction {
Self::Login => "auth.login",
Self::Logout => "auth.logout",
Self::OutpostBind => "orbit.outpost_bind",
Self::OutpostPair => "outpost.pair",
Self::CredentialRotate => "outpost.credential_rotate",
Self::CredentialRevoke => "outpost.credential_revoke",
}
}
}

View File

@@ -3,6 +3,7 @@ mod restore;
mod audit;
pub mod sessions;
pub(crate) mod oidc_login;
pub(crate) mod credentials;
pub(crate) use restore::restore_target_mismatch;
use anyhow::Result;
@@ -75,14 +76,6 @@ impl Db {
total INTEGER,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS wormhole_tokens (
token TEXT PRIMARY KEY,
outpost_id TEXT NOT NULL,
code TEXT NOT NULL,
state TEXT NOT NULL,
expires_at TEXT NOT NULL,
outpost_name TEXT
);
CREATE TABLE IF NOT EXISTS upload_ranges (
session_id TEXT NOT NULL,
start_off INTEGER NOT NULL,
@@ -98,11 +91,7 @@ impl Db {
)?;
ensure_column(&conn, "orbits", "retention", "TEXT")?;
ensure_column(&conn, "orbits", "outpost_id", "TEXT REFERENCES outposts(id)")?;
conn.execute(
"INSERT OR IGNORE INTO outposts(id, name, pairing_state)
SELECT outpost_id, outpost_name, 'active' FROM wormhole_tokens WHERE state = 'active'",
[],
)?;
credentials::migrate(&conn)?;
jobs::migrate(&conn)?;
restore::migrate(&conn)?;
audit::migrate(&conn)?;
@@ -256,49 +245,6 @@ impl Db {
)?)
}
pub fn insert_wormhole_token(
&self,
token: &str,
outpost_id: &str,
code: &str,
expires_at: &str,
) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"INSERT INTO wormhole_tokens (token, outpost_id, code, state, expires_at) VALUES (?1, ?2, ?3, 'code_shown', ?4)",
params![token, outpost_id, code, expires_at],
)?;
Ok(())
}
pub fn claim_wormhole_code(
&self,
code: &str,
outpost_name: &str,
now: &str,
) -> Result<Option<(String, String)>> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction()?;
let claimed: Option<(String, String)> = tx.query_row(
"UPDATE wormhole_tokens SET state = 'active', outpost_name = ?2
WHERE token = (SELECT token FROM wormhole_tokens
WHERE code = ?1 AND state = 'code_shown' AND expires_at > ?3
ORDER BY expires_at DESC LIMIT 1)
RETURNING token, outpost_id",
params![code, outpost_name, now],
|row| Ok((row.get(0)?, row.get(1)?)),
).optional()?;
if let Some((_, outpost)) = &claimed {
tx.execute(
"INSERT INTO outposts(id, name, last_seen, pairing_state) VALUES (?1, ?2, ?3, 'active')
ON CONFLICT(id) DO UPDATE SET name = excluded.name, last_seen = excluded.last_seen, pairing_state = 'active'",
params![outpost, outpost_name, now],
)?;
}
tx.commit()?;
Ok(claimed)
}
pub fn list_outposts(&self) -> Result<Vec<OutpostSummary>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare("SELECT id, name, last_seen, pairing_state FROM outposts ORDER BY name, id")?;
@@ -321,14 +267,6 @@ impl Db {
Ok(())
}
pub fn upload_token_outpost(&self, token: &str) -> Result<Option<String>> {
let conn = self.conn.lock().unwrap();
Ok(conn.query_row(
"SELECT outpost_id FROM wormhole_tokens WHERE token = ?1 AND state = 'active' LIMIT 1",
params![token], |row| row.get(0),
).optional()?)
}
pub fn upload_session(&self, id: &str) -> Result<Option<UploadSession>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(

View File

@@ -0,0 +1,426 @@
//! Outpost pairing codes and upload credentials.
//!
//! Neither the pairing code nor the upload token is stored in clear: only a
//! SHA-256 digest of each. The token is generated at claim time and handed to
//! the agent exactly once. Both are high-entropy random values, so a plain
//! digest lookup is appropriate (there is nothing to brute-force offline).
use super::*;
use rand::RngCore;
use sha2::{Digest, Sha256};
pub const DEFAULT_LIFETIME_DAYS: i64 = 365;
/// Lifetime of a newly issued or migrated credential (`TESSERA_OUTPOST_TOKEN_DAYS`).
pub fn lifetime_secs() -> i64 {
std::env::var("TESSERA_OUTPOST_TOKEN_DAYS")
.ok()
.and_then(|v| v.trim().parse::<i64>().ok())
.filter(|days| (1..=3650).contains(days))
.unwrap_or(DEFAULT_LIFETIME_DAYS)
* 86_400
}
pub fn digest(kind: &str, secret: &str) -> String {
hex::encode(Sha256::digest(format!("tessera-{kind}-v1:{secret}")))
}
/// 256 random bits from the OS CSPRNG, hex encoded.
pub fn new_token() -> String {
let mut bytes = [0u8; 32];
rand::rngs::OsRng.fill_bytes(&mut bytes);
hex::encode(bytes)
}
#[derive(Debug)]
pub struct Issued {
pub token: String,
pub outpost_id: String,
pub expires_at: i64,
/// Set for a rotation: until when the previous credential still works.
pub previous_valid_until: Option<i64>,
}
pub(super) fn migrate(conn: &Connection) -> Result<()> {
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS pairing_codes (
code_digest TEXT PRIMARY KEY,
outpost_id TEXT NOT NULL,
expires_at INTEGER NOT NULL,
consumed_at INTEGER
);
CREATE TABLE IF NOT EXISTS outpost_credentials (
id TEXT PRIMARY KEY,
outpost_id TEXT NOT NULL,
token_digest TEXT NOT NULL UNIQUE,
state TEXT NOT NULL CHECK(state IN ('active','revoked')),
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL,
revoked_at INTEGER,
source TEXT NOT NULL DEFAULT 'pairing'
);
CREATE INDEX IF NOT EXISTS outpost_credentials_outpost ON outpost_credentials(outpost_id, state);",
)?;
let legacy: bool = conn.query_row(
"SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name='wormhole_tokens')",
[],
|row| row.get(0),
)?;
if legacy {
migrate_legacy(conn)?;
}
Ok(())
}
/// One-time move of `wormhole_tokens` (clear-text token and code) into digests.
///
/// * Active tokens keep working: they get a fresh lifetime from now. The old
/// `expires_at` was the *pairing code's* expiry and says nothing about the token.
/// * Unclaimed codes keep their own expiry; their pre-minted token is discarded.
/// * `secure_delete` is on for this connection while the clear text is dropped,
/// so freed pages are zeroed instead of left in the file. Old backups and
/// copies of the database still contain the tokens: rotate them.
fn migrate_legacy(conn: &Connection) -> Result<()> {
let now = chrono::Utc::now().timestamp();
let lifetime = lifetime_secs();
conn.execute_batch("PRAGMA secure_delete = ON;")?;
let result = (|| -> Result<()> {
conn.execute_batch("BEGIN IMMEDIATE")?;
let moved = (|| -> Result<(usize, usize)> {
let mut active = 0;
let mut codes = 0;
let rows: Vec<(String, String, String, String, Option<String>, String)> = {
let mut stmt = conn.prepare("SELECT token, outpost_id, code, state, outpost_name, expires_at FROM wormhole_tokens")?;
let mapped = stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?)))?;
mapped.collect::<rusqlite::Result<_>>()?
};
for (token, outpost, code, state, name, expires) in rows {
if state == "active" {
conn.execute(
"INSERT OR IGNORE INTO outposts(id, name, pairing_state) VALUES (?1, ?2, 'active')",
params![outpost, name],
)?;
conn.execute(
"INSERT OR IGNORE INTO outpost_credentials(id,outpost_id,token_digest,state,created_at,expires_at,source)
VALUES (?1,?2,?3,'active',?4,?5,'migrated')",
params![Uuid::new_v4().to_string(), outpost, digest("outpost-token", &token), now, now + lifetime],
)?;
active += 1;
} else if state == "code_shown" {
let expires_at = chrono::DateTime::parse_from_rfc3339(&expires).map(|t| t.timestamp()).unwrap_or(0);
conn.execute(
"INSERT OR IGNORE INTO pairing_codes(code_digest,outpost_id,expires_at) VALUES (?1,?2,?3)",
params![digest("pairing-code", &code), outpost, expires_at],
)?;
codes += 1;
}
}
conn.execute_batch("DROP TABLE wormhole_tokens")?;
Ok((active, codes))
})();
match moved {
Ok((active, codes)) => {
conn.execute_batch("COMMIT")?;
tracing::warn!(
"migrated {active} Outpost token(s) and {codes} pairing code(s) to digests; \
copies of the old database still hold the clear-text tokens, so rotate them"
);
Ok(())
}
Err(error) => {
let _ = conn.execute_batch("ROLLBACK");
Err(error)
}
}
})();
conn.execute_batch("PRAGMA secure_delete = OFF;")?;
result
}
impl Db {
pub fn insert_pairing(&self, outpost_id: &str, code: &str, expires_at: i64) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute("DELETE FROM pairing_codes WHERE expires_at <= ?1 OR consumed_at IS NOT NULL", params![expires_at - 86_400])?;
conn.execute(
"INSERT INTO pairing_codes(code_digest, outpost_id, expires_at) VALUES (?1, ?2, ?3)",
params![digest("pairing-code", code), outpost_id, expires_at],
)?;
Ok(())
}
/// Consume a pairing code and mint the upload token. The single UPDATE …
/// RETURNING is what makes a code usable once; the `Db` mutex additionally
/// serialises callers. The token exists in clear only in the return value.
pub fn claim_pairing(&self, code: &str, outpost_name: &str, now: i64) -> Result<Option<Issued>> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction()?;
let outpost: Option<String> = tx
.query_row(
"UPDATE pairing_codes SET consumed_at = ?2
WHERE code_digest = ?1 AND consumed_at IS NULL AND expires_at > ?2
RETURNING outpost_id",
params![digest("pairing-code", code), now],
|row| row.get(0),
)
.optional()?;
let Some(outpost) = outpost else { return Ok(None) };
let token = new_token();
let expires_at = now + lifetime_secs();
tx.execute(
"INSERT INTO outposts(id, name, last_seen, pairing_state) VALUES (?1, ?2, ?3, 'active')
ON CONFLICT(id) DO UPDATE SET name = excluded.name, last_seen = excluded.last_seen, pairing_state = 'active'",
params![outpost, outpost_name, chrono::Utc::now().to_rfc3339()],
)?;
tx.execute(
"INSERT INTO outpost_credentials(id,outpost_id,token_digest,state,created_at,expires_at,source)
VALUES (?1,?2,?3,'active',?4,?5,'pairing')",
params![Uuid::new_v4().to_string(), outpost, digest("outpost-token", &token), now, expires_at],
)?;
tx.commit()?;
Ok(Some(Issued { token, outpost_id: outpost, expires_at, previous_valid_until: None }))
}
/// The Outpost a presented token belongs to, if it is active and unexpired.
pub fn upload_token_outpost(&self, token: &str, now: i64) -> Result<Option<String>> {
let conn = self.conn.lock().unwrap();
Ok(conn
.query_row(
"SELECT outpost_id FROM outpost_credentials
WHERE token_digest = ?1 AND state = 'active' AND expires_at > ?2",
params![digest("outpost-token", token), now],
|row| row.get(0),
)
.optional()?)
}
/// Issue a new credential for a paired Outpost. Older active credentials keep
/// working for `grace_secs` (0 = they stop immediately), so an operator has a
/// bounded window to put the new token on the agent. Returns `None` for an
/// unknown or revoked Outpost: it must be paired again.
pub fn rotate_credential(&self, outpost: &str, grace_secs: i64, now: i64) -> Result<Option<Issued>> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction()?;
let paired: bool = tx.query_row(
"SELECT EXISTS(SELECT 1 FROM outposts WHERE id = ?1 AND pairing_state = 'active')",
params![outpost],
|row| row.get(0),
)?;
if !paired {
return Ok(None);
}
let until = now + grace_secs.max(0);
tx.execute(
"UPDATE outpost_credentials SET expires_at = MIN(expires_at, ?3)
WHERE outpost_id = ?1 AND state = 'active' AND expires_at > ?2",
params![outpost, now, until],
)?;
let token = new_token();
let expires_at = now + lifetime_secs();
tx.execute(
"INSERT INTO outpost_credentials(id,outpost_id,token_digest,state,created_at,expires_at,source)
VALUES (?1,?2,?3,'active',?4,?5,'rotation')",
params![Uuid::new_v4().to_string(), outpost, digest("outpost-token", &token), now, expires_at],
)?;
tx.commit()?;
Ok(Some(Issued {
token,
outpost_id: outpost.to_string(),
expires_at,
previous_valid_until: (grace_secs > 0).then_some(until),
}))
}
/// Revoke every credential of an Outpost, effective on its next request.
/// Returns false when the Outpost is unknown.
pub fn revoke_outpost(&self, outpost: &str, now: i64) -> Result<bool> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction()?;
tx.execute(
"UPDATE outpost_credentials SET state='revoked', revoked_at=?2 WHERE outpost_id=?1 AND state='active'",
params![outpost, now],
)?;
let known = tx.execute("UPDATE outposts SET pairing_state='revoked' WHERE id=?1", params![outpost])? == 1;
tx.commit()?;
Ok(known)
}
/// Test fixture: a paired Outpost whose token is a chosen string.
#[cfg(test)]
pub fn insert_test_credential(&self, token: &str, outpost: &str, name: &str) {
let conn = self.conn.lock().unwrap();
let now = chrono::Utc::now().timestamp();
conn.execute(
"INSERT INTO outposts(id, name, last_seen, pairing_state) VALUES (?1, ?2, ?3, 'active')
ON CONFLICT(id) DO UPDATE SET pairing_state='active'",
params![outpost, name, chrono::Utc::now().to_rfc3339()],
)
.unwrap();
conn.execute(
"INSERT INTO outpost_credentials(id,outpost_id,token_digest,state,created_at,expires_at,source)
VALUES (?1,?2,?3,'active',?4,?5,'pairing')",
params![Uuid::new_v4().to_string(), outpost, digest("outpost-token", token), now, now + lifetime_secs()],
)
.unwrap();
}
}
#[cfg(test)]
mod tests {
use super::*;
async fn db() -> (tempfile::TempDir, Db, std::path::PathBuf) {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("t.db");
let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap();
(dir, db, path)
}
/// Every byte SQLite may have left on disk for this database.
fn disk_bytes(path: &std::path::Path) -> Vec<u8> {
let mut all = Vec::new();
for suffix in ["", "-wal", "-journal", "-shm"] {
let mut name = path.as_os_str().to_owned();
name.push(suffix);
if let Ok(bytes) = std::fs::read(std::path::PathBuf::from(name)) {
all.extend(bytes);
}
}
all
}
fn contains(haystack: &[u8], needle: &str) -> bool {
haystack.windows(needle.len()).any(|w| w == needle.as_bytes())
}
#[tokio::test]
async fn the_code_and_token_are_never_stored_in_clear() {
let (_dir, db, path) = db().await;
let outpost = Uuid::new_v4().to_string();
db.insert_pairing(&outpost, "ABCDEFGH2345", 10_000).unwrap();
let issued = db.claim_pairing("ABCDEFGH2345", "agent", 100).unwrap().unwrap();
assert_eq!(issued.token.len(), 64);
assert_eq!(db.upload_token_outpost(&issued.token, 101).unwrap().as_deref(), Some(outpost.as_str()));
drop(db);
let bytes = disk_bytes(&path);
assert!(contains(&bytes, "agent"), "sanity: the scan really reads the database file");
assert!(!contains(&bytes, &issued.token), "token in the database file");
assert!(!contains(&bytes, "ABCDEFGH2345"), "pairing code in the database file");
}
#[tokio::test]
async fn a_code_works_once_and_only_before_it_expires() {
let (_dir, db, _) = db().await;
let outpost = Uuid::new_v4().to_string();
db.insert_pairing(&outpost, "CODE-ONE", 1_000).unwrap();
assert!(db.claim_pairing("WRONG", "a", 10).unwrap().is_none());
assert!(db.claim_pairing("CODE-ONE", "a", 10).unwrap().is_some());
assert!(db.claim_pairing("CODE-ONE", "a", 11).unwrap().is_none(), "replay");
db.insert_pairing(&outpost, "CODE-TWO", 1_000).unwrap();
assert!(db.claim_pairing("CODE-TWO", "a", 1_000).unwrap().is_none(), "expired at its deadline");
}
#[tokio::test]
async fn concurrent_claims_of_one_code_yield_exactly_one_token() {
// The Db mutex serialises these, so this shows the statement is atomic
// (one consumer per code), not that SQLite arbitrates a race.
let (_dir, db, _) = db().await;
db.insert_pairing(&Uuid::new_v4().to_string(), "RACE-CODE", 1_000_000).unwrap();
let handles: Vec<_> = (0..8)
.map(|_| {
let db = db.clone();
std::thread::spawn(move || db.claim_pairing("RACE-CODE", "a", 5).unwrap().is_some())
})
.collect();
let winners = handles.into_iter().map(|h| h.join().unwrap()).filter(|won| *won).count();
assert_eq!(winners, 1);
}
#[tokio::test]
async fn revoked_and_expired_tokens_are_rejected_on_the_next_lookup() {
let (_dir, db, _) = db().await;
let outpost = Uuid::new_v4().to_string();
db.insert_pairing(&outpost, "C", 1_000).unwrap();
let issued = db.claim_pairing("C", "agent", 10).unwrap().unwrap();
assert!(db.upload_token_outpost(&issued.token, issued.expires_at - 1).unwrap().is_some());
assert!(db.upload_token_outpost(&issued.token, issued.expires_at).unwrap().is_none(), "expiry");
assert!(db.upload_token_outpost(&issued.token, 20).unwrap().is_some());
assert!(db.revoke_outpost(&outpost, 21).unwrap());
assert!(db.upload_token_outpost(&issued.token, 22).unwrap().is_none(), "revoked");
assert!(db.rotate_credential(&outpost, 60, 23).unwrap().is_none(), "a revoked Outpost must be paired again");
assert!(!db.revoke_outpost(&Uuid::new_v4().to_string(), 1).unwrap());
}
#[tokio::test]
async fn rotation_has_an_explicit_grace_window() {
let (_dir, db, _) = db().await;
let outpost = Uuid::new_v4().to_string();
db.insert_pairing(&outpost, "C", 1_000).unwrap();
let first = db.claim_pairing("C", "agent", 10).unwrap().unwrap();
let second = db.rotate_credential(&outpost, 300, 100).unwrap().unwrap();
assert_eq!(second.previous_valid_until, Some(400));
assert_ne!(first.token, second.token);
assert!(db.upload_token_outpost(&first.token, 399).unwrap().is_some(), "old token inside the grace window");
assert!(db.upload_token_outpost(&first.token, 400).unwrap().is_none(), "and not after it");
assert!(db.upload_token_outpost(&second.token, 400).unwrap().is_some());
// grace 0 cuts the old token at once
let third = db.rotate_credential(&outpost, 0, 500).unwrap().unwrap();
assert_eq!(third.previous_valid_until, None);
assert!(db.upload_token_outpost(&second.token, 500).unwrap().is_none());
assert!(db.upload_token_outpost(&third.token, 500).unwrap().is_some());
// an unknown outpost cannot be rotated into existence
assert!(db.rotate_credential(&Uuid::new_v4().to_string(), 0, 1).unwrap().is_none());
}
/// A pre-M4 database: clear-text tokens and codes in `wormhole_tokens`.
fn legacy_database(path: &std::path::Path) {
let conn = Connection::open(path).unwrap();
conn.execute_batch(
"CREATE TABLE outposts (id TEXT PRIMARY KEY, name TEXT, last_seen TEXT, pairing_state TEXT NOT NULL DEFAULT 'unpaired');
CREATE TABLE wormhole_tokens (token TEXT PRIMARY KEY, outpost_id TEXT NOT NULL, code TEXT NOT NULL, state TEXT NOT NULL, expires_at TEXT NOT NULL, outpost_name TEXT);",
)
.unwrap();
// paired long ago: the *code* expiry is in the past and must not become the token expiry
conn.execute("INSERT INTO wormhole_tokens VALUES ('LEGACY-ACTIVE-TOKEN-0001','11111111-1111-1111-1111-111111111111','LEGACYCODE1','active','2020-01-01T00:00:00+00:00','old-agent')", []).unwrap();
let future = (chrono::Utc::now() + chrono::Duration::minutes(5)).to_rfc3339();
conn.execute("INSERT INTO wormhole_tokens VALUES ('PREMINTED-TOKEN-0002','22222222-2222-2222-2222-222222222222','LEGACYCODE2','code_shown',?1,NULL)", params![future]).unwrap();
conn.execute("INSERT INTO wormhole_tokens VALUES ('PREMINTED-TOKEN-0003','33333333-3333-3333-3333-333333333333','LEGACYCODE3','code_shown','2020-01-01T00:00:00+00:00',NULL)", []).unwrap();
}
#[tokio::test]
async fn legacy_clear_text_tokens_are_migrated_in_place_and_scrubbed() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("legacy.db");
legacy_database(&path);
let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap();
let now = chrono::Utc::now().timestamp();
// the paired agent keeps working with its existing token
assert_eq!(
db.upload_token_outpost("LEGACY-ACTIVE-TOKEN-0001", now).unwrap().as_deref(),
Some("11111111-1111-1111-1111-111111111111")
);
assert!(db.upload_token_outpost("LEGACY-ACTIVE-TOKEN-0001", now + lifetime_secs() + 10).unwrap().is_none());
// an unclaimed code can still be claimed once, but its pre-minted token is gone
let claimed = db.claim_pairing("LEGACYCODE2", "new-agent", now).unwrap().unwrap();
assert_ne!(claimed.token, "PREMINTED-TOKEN-0002");
assert!(db.upload_token_outpost("PREMINTED-TOKEN-0002", now).unwrap().is_none());
assert!(db.claim_pairing("LEGACYCODE3", "late-agent", now).unwrap().is_none(), "expired code stays expired");
// the old table and every clear-text copy are gone, including freed pages
let exists: bool = db.conn.lock().unwrap()
.query_row("SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE name='wormhole_tokens')", [], |r| r.get(0)).unwrap();
assert!(!exists);
let state: String = db.conn.lock().unwrap()
.query_row("SELECT pairing_state FROM outposts WHERE id='11111111-1111-1111-1111-111111111111'", [], |r| r.get(0)).unwrap();
assert_eq!(state, "active");
drop(db);
let bytes = disk_bytes(&path);
assert!(contains(&bytes, "old-agent") || contains(&bytes, "new-agent"), "sanity: the scan really reads the database file");
for secret in ["LEGACY-ACTIVE-TOKEN-0001", "PREMINTED-TOKEN-0002", "PREMINTED-TOKEN-0003", "LEGACYCODE1", "LEGACYCODE2", "LEGACYCODE3"] {
assert!(!contains(&bytes, secret), "{secret} still on disk");
}
// migrating again changes nothing
let again = Db::connect(&path).await.unwrap();
again.migrate().await.unwrap();
assert!(again.upload_token_outpost("LEGACY-ACTIVE-TOKEN-0001", now).unwrap().is_some());
}
}

View File

@@ -113,7 +113,7 @@ impl Db {
SELECT 1 FROM orbits WHERE id = ?2 AND provider = 'wormhole' AND dry_run = 0
AND COALESCE(json_extract(provider_config, '$.source'), ?6) = ?6
)
AND EXISTS (SELECT 1 FROM wormhole_tokens WHERE outpost_id = ?3 AND state = 'active')
AND EXISTS (SELECT 1 FROM outpost_credentials WHERE outpost_id = ?3 AND state = 'active' AND expires_at > ?5)
ON CONFLICT DO NOTHING",
params![profile.application_id.to_string(), profile.orbit_id.to_string(),
profile.outpost_id.to_string(), serde_json::to_string(profile)?, now,
@@ -146,7 +146,7 @@ impl Db {
"INSERT INTO capture_jobs (id, application_id, actor, created_at, updated_at, schedule_slot)
SELECT ?1, application_id, 'scheduler', ?4, ?4, ?3 FROM capture_profiles p
WHERE application_id = ?2
AND EXISTS (SELECT 1 FROM wormhole_tokens WHERE outpost_id = p.outpost_id AND state = 'active')
AND EXISTS (SELECT 1 FROM outpost_credentials WHERE outpost_id = p.outpost_id AND state = 'active' AND expires_at > ?4)
ON CONFLICT(application_id, schedule_slot) DO NOTHING",
params![Uuid::new_v4().to_string(), application.to_string(), slot, now],
)?;
@@ -165,7 +165,7 @@ impl Db {
"INSERT INTO capture_jobs (id, application_id, actor, created_at, updated_at)
SELECT ?1, application_id, ?3, ?4, ?4 FROM capture_profiles p
WHERE application_id = ?2
AND EXISTS (SELECT 1 FROM wormhole_tokens WHERE outpost_id = p.outpost_id AND state = 'active')",
AND EXISTS (SELECT 1 FROM outpost_credentials WHERE outpost_id = p.outpost_id AND state = 'active' AND expires_at > ?4)",
params![id.to_string(), application_id.to_string(), actor, now],
)?;
capture_job(&conn, id)
@@ -490,11 +490,7 @@ mod tests {
assert!(!db.register_capture_profile(&a, 100).unwrap());
assert!(db.enqueue_capture(app, "fixture", 100).unwrap().is_none());
for (id, token) in [(outpost, "token-a"), (other, "token-b")] {
db.insert_wormhole_token(token, &id.to_string(), token, "9999")
.unwrap();
db.claim_wormhole_code(token, "agent", "2026")
.unwrap()
.unwrap();
db.insert_test_credential(token, &id.to_string(), "agent");
}
assert!(db.register_capture_profile(&a, 100).unwrap());
assert!(db.register_capture_profile(&b, 100).unwrap());
@@ -585,8 +581,7 @@ mod tests {
let db = Db::connect(std::path::Path::new(":memory:")).await.unwrap();
db.migrate().await.unwrap();
let outpost = Uuid::new_v4();
db.insert_wormhole_token("token", &outpost.to_string(), "code", "9999").unwrap();
db.claim_wormhole_code("code", "agent", "2026").unwrap().unwrap();
db.insert_test_credential("token", &outpost.to_string(), "agent");
let profile = profile(&db, outpost).await;
let app = profile.application_id;
let now = chrono::Utc::now().timestamp();
@@ -621,11 +616,7 @@ mod tests {
let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap();
let outpost = Uuid::new_v4();
db.insert_wormhole_token("test", &outpost.to_string(), "code", "9999")
.unwrap();
db.claim_wormhole_code("code", "fixture", "2026")
.unwrap()
.unwrap();
db.insert_test_credential("test", &outpost.to_string(), "agent");
let mut a = profile(&db, outpost).await;
let mut b = profile(&db, outpost).await;
a.schedule = Some(CaptureSchedule {

View File

@@ -86,7 +86,7 @@ impl Db {
"INSERT INTO restore_targets(id, application_id, outpost_id, identity, profile)
SELECT ?1, ?2, ?3, ?4, ?5
WHERE EXISTS (SELECT 1 FROM capture_profiles WHERE application_id = ?2)
AND EXISTS (SELECT 1 FROM wormhole_tokens WHERE outpost_id = ?3 AND state = 'active')
AND EXISTS (SELECT 1 FROM outpost_credentials WHERE outpost_id = ?3 AND state = 'active' AND expires_at > ?6)
ON CONFLICT DO NOTHING",
params![
target.id.to_string(),
@@ -94,6 +94,7 @@ impl Db {
target.outpost_id.to_string(),
serde_json::to_string(&(target.engine, &target.identity))?,
serde_json::to_string(target)?,
chrono::Utc::now().timestamp(),
],
)?;
Ok(changed == 1)
@@ -107,11 +108,11 @@ impl Db {
pub fn restore_targets_with_activity(&self, application: Uuid) -> Result<Vec<(RestoreTarget, bool)>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT t.profile, EXISTS (SELECT 1 FROM wormhole_tokens
WHERE outpost_id = t.outpost_id AND state = 'active')
"SELECT t.profile, EXISTS (SELECT 1 FROM outpost_credentials
WHERE outpost_id = t.outpost_id AND state = 'active' AND expires_at > ?2)
FROM restore_targets t WHERE t.application_id = ?1 ORDER BY t.id",
)?;
let rows = stmt.query_map([application.to_string()], |row| Ok((json(row, 0)?, row.get(1)?)))?;
let rows = stmt.query_map(params![application.to_string(), chrono::Utc::now().timestamp()], |row| Ok((json(row, 0)?, row.get(1)?)))?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
@@ -128,8 +129,8 @@ impl Db {
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
let registered: Option<RestoreTarget> = tx.query_row(
"SELECT t.profile FROM restore_targets t WHERE t.id = ?1 AND t.application_id = ?2
AND EXISTS (SELECT 1 FROM wormhole_tokens WHERE outpost_id = t.outpost_id AND state = 'active')",
params![target.to_string(), application.to_string()],
AND EXISTS (SELECT 1 FROM outpost_credentials WHERE outpost_id = t.outpost_id AND state = 'active' AND expires_at > ?3)",
params![target.to_string(), application.to_string(), now],
|row| json(row, 0),
).optional()?;
let Some(registered) = registered else {
@@ -438,11 +439,7 @@ mod tests {
let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap();
let outpost = Uuid::new_v4();
db.insert_wormhole_token("synthetic-token", &outpost.to_string(), "code", "9999")
.unwrap();
db.claim_wormhole_code("code", "fixture", "2026")
.unwrap()
.unwrap();
db.insert_test_credential("synthetic-token", &outpost.to_string(), "agent");
let orbit = Uuid::new_v4();
db.upsert_orbit(&OrbitRow {
id: orbit,

View File

@@ -0,0 +1,235 @@
//! Request limiting for the unauthenticated and expensive endpoints.
//!
//! Limits are per *source*, so one noisy client cannot use up the budget of
//! the others. The source is the TCP peer. `X-Forwarded-For` is honoured only
//! when the peer is a configured trusted proxy (`TESSERA_TRUSTED_PROXIES`),
//! walking the header right to left past trusted hops. IPv6 sources are keyed by
//! their /64. State is in memory and per hub process: it resets on restart and
//! is not shared between replicas.
use axum::http::HeaderMap;
use governor::{clock::DefaultClock, state::keyed::DefaultKeyedStateStore, state::InMemoryState, state::NotKeyed, Quota, RateLimiter};
use std::net::{IpAddr, Ipv6Addr, SocketAddr};
use std::num::NonZeroU32;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use tokio::sync::Semaphore;
type Keyed = RateLimiter<IpAddr, DefaultKeyedStateStore<IpAddr>, DefaultClock>;
type Direct = RateLimiter<NotKeyed, InMemoryState, DefaultClock>;
pub struct LimitConfig {
pub login_source: Quota,
/// Ceiling for the single emergency account across all sources. Deliberately
/// looser than the per-source quota: a tight account lock would let anyone
/// lock the break-glass operator out.
pub login_account: Quota,
pub claim_source: Quota,
pub claim_global: Quota,
pub oidc_login_source: Quota,
pub oidc_callback_source: Quota,
pub argon2_concurrency: usize,
}
fn per_minute(rate: u32, burst: u32) -> Quota {
Quota::per_minute(NonZeroU32::new(rate).unwrap()).allow_burst(NonZeroU32::new(burst).unwrap())
}
impl Default for LimitConfig {
fn default() -> Self {
Self {
login_source: per_minute(10, 5),
login_account: per_minute(60, 30),
claim_source: per_minute(10, 5),
claim_global: per_minute(120, 60),
oidc_login_source: per_minute(30, 15),
oidc_callback_source: per_minute(60, 30),
argon2_concurrency: 2,
}
}
}
pub struct Limits {
login_source: Keyed,
login_account: Direct,
claim_source: Keyed,
claim_global: Direct,
oidc_login_source: Keyed,
oidc_callback_source: Keyed,
audit_denial: Keyed,
pub argon2: Arc<Semaphore>,
trusted_proxies: Vec<IpAddr>,
calls: AtomicU64,
}
impl Limits {
pub fn new(config: LimitConfig, trusted_proxies: Vec<IpAddr>) -> Self {
Self {
login_source: RateLimiter::keyed(config.login_source),
login_account: RateLimiter::direct(config.login_account),
claim_source: RateLimiter::keyed(config.claim_source),
claim_global: RateLimiter::direct(config.claim_global),
oidc_login_source: RateLimiter::keyed(config.oidc_login_source),
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)),
argon2: Arc::new(Semaphore::new(config.argon2_concurrency)),
trusted_proxies,
calls: AtomicU64::new(0),
}
}
pub fn from_env() -> anyhow::Result<Self> {
let mut proxies = Vec::new();
if let Ok(list) = std::env::var("TESSERA_TRUSTED_PROXIES") {
for item in list.split(',').map(str::trim).filter(|s| !s.is_empty()) {
proxies.push(item.parse::<IpAddr>().map_err(|_| anyhow::anyhow!("TESSERA_TRUSTED_PROXIES: invalid IP {item}"))?);
}
}
Ok(Self::new(LimitConfig::default(), proxies))
}
/// The rate-limit key for a request. `None` peer (should not happen) maps to
/// one strict shared bucket instead of bypassing limits.
pub fn source(&self, peer: Option<SocketAddr>, headers: &HeaderMap) -> IpAddr {
let Some(peer) = peer else { return IpAddr::V6(Ipv6Addr::UNSPECIFIED) };
let mut client = peer.ip();
if self.trusted_proxies.contains(&client) {
let forwarded: Vec<&str> = headers
.get_all("x-forwarded-for")
.iter()
.filter_map(|v| v.to_str().ok())
.flat_map(|line| line.split(','))
.map(str::trim)
.collect();
for hop in forwarded.iter().rev() {
match hop.parse::<IpAddr>() {
Ok(ip) if self.trusted_proxies.contains(&ip) => continue,
Ok(ip) => {
client = ip;
break;
}
Err(_) => break, // malformed: stay on the proxy's own address
}
}
}
normalize(client)
}
fn maintain(&self) {
if self.calls.fetch_add(1, Ordering::Relaxed) % 512 == 511 {
self.login_source.retain_recent();
self.claim_source.retain_recent();
self.oidc_login_source.retain_recent();
self.oidc_callback_source.retain_recent();
self.audit_denial.retain_recent();
}
}
pub fn login_allowed(&self, source: IpAddr) -> bool {
self.maintain();
self.login_source.check_key(&source).is_ok() && self.login_account.check().is_ok()
}
pub fn claim_allowed(&self, source: IpAddr) -> bool {
self.maintain();
self.claim_source.check_key(&source).is_ok() && self.claim_global.check().is_ok()
}
pub fn oidc_login_allowed(&self, source: IpAddr) -> bool {
self.maintain();
self.oidc_login_source.check_key(&source).is_ok()
}
pub fn oidc_callback_allowed(&self, source: IpAddr) -> bool {
self.maintain();
self.oidc_callback_source.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()
}
}
/// IPv4-mapped IPv6 becomes IPv4; other IPv6 addresses collapse to their /64.
fn normalize(ip: IpAddr) -> IpAddr {
match ip {
IpAddr::V4(_) => ip,
IpAddr::V6(v6) => match v6.to_ipv4_mapped() {
Some(v4) => IpAddr::V4(v4),
None => {
let mut octets = v6.octets();
octets[8..].fill(0);
IpAddr::V6(Ipv6Addr::from(octets))
}
},
}
}
#[cfg(test)]
mod tests {
use super::*;
use axum::http::HeaderValue;
fn peer(ip: &str) -> Option<SocketAddr> {
Some(SocketAddr::new(ip.parse().unwrap(), 4000))
}
fn headers(xff: &str) -> HeaderMap {
let mut h = HeaderMap::new();
h.insert("x-forwarded-for", HeaderValue::from_str(xff).unwrap());
h
}
fn limits(proxies: &[&str]) -> Limits {
Limits::new(LimitConfig::default(), proxies.iter().map(|p| p.parse().unwrap()).collect())
}
#[test]
fn one_source_cannot_use_up_another_sources_login_budget() {
let l = limits(&[]);
let a = l.source(peer("203.0.113.1"), &HeaderMap::new());
let b = l.source(peer("203.0.113.2"), &HeaderMap::new());
let mut allowed = 0;
for _ in 0..50 {
allowed += l.login_allowed(a) as u32;
}
assert_eq!(allowed, 5, "burst of 5, then refused");
assert!(l.login_allowed(b), "an unrelated source is unaffected");
}
#[test]
fn forwarded_for_is_ignored_unless_the_peer_is_a_trusted_proxy() {
let l = limits(&["10.0.0.1"]);
let spoof = headers("198.51.100.9");
assert_eq!(l.source(peer("203.0.113.7"), &spoof), "203.0.113.7".parse::<IpAddr>().unwrap(), "untrusted peer cannot choose its key");
assert_eq!(l.source(peer("10.0.0.1"), &spoof), "198.51.100.9".parse::<IpAddr>().unwrap());
// client-supplied prefix is ignored: walk right to left, skipping trusted hops
let chain = headers("1.1.1.1, 198.51.100.9, 10.0.0.1");
assert_eq!(l.source(peer("10.0.0.1"), &chain), "198.51.100.9".parse::<IpAddr>().unwrap());
// junk or missing header falls back to the proxy itself
assert_eq!(l.source(peer("10.0.0.1"), &headers("not-an-ip")), "10.0.0.1".parse::<IpAddr>().unwrap());
assert_eq!(l.source(peer("10.0.0.1"), &HeaderMap::new()), "10.0.0.1".parse::<IpAddr>().unwrap());
}
#[test]
fn ipv6_sources_share_a_budget_per_64_and_mapped_v4_is_v4() {
let l = limits(&[]);
let a = l.source(peer("2001:db8:1:2::1"), &HeaderMap::new());
let b = l.source(peer("2001:db8:1:2:ffff::9"), &HeaderMap::new());
let c = l.source(peer("2001:db8:1:3::1"), &HeaderMap::new());
assert_eq!(a, b);
assert_ne!(a, c);
assert_eq!(l.source(peer("::ffff:192.0.2.5"), &HeaderMap::new()), "192.0.2.5".parse::<IpAddr>().unwrap());
assert_eq!(l.source(None, &HeaderMap::new()), IpAddr::V6(Ipv6Addr::UNSPECIFIED));
}
#[test]
fn denials_are_audited_at_most_once_a_minute_per_source() {
let l = limits(&[]);
let a: IpAddr = "203.0.113.1".parse().unwrap();
assert!(l.audit_denial(a));
assert!(!l.audit_denial(a));
assert!(l.audit_denial("203.0.113.2".parse().unwrap()));
}
}

View File

@@ -2,6 +2,7 @@ mod admin;
mod auth;
mod api;
mod db;
mod limits;
mod mtls;
mod oidc;
mod scheduler;
@@ -46,7 +47,7 @@ async fn main() -> Result<()> {
}
let mut state = HubState::bootstrap(&data_dir, &vault_pass).await?;
anyhow::ensure!(state.sessions.enabled() || state.admin.token.is_some() || state.admin.local_development,
anyhow::ensure!(state.sessions.enabled() || state.admin.token_active() || state.admin.local_development,
"configure a named emergency operator and/or TESSERA_ADMIN_TOKEN; anonymous local access requires explicit TESSERA_LOCAL_DEVELOPMENT=true");
if std::env::var("TESSERA_SEED_DEMO")

View File

@@ -78,7 +78,7 @@ pub async fn serve(mtls: WormholeMtls, app: Router) -> Result<()> {
mtls.listen
);
loop {
let (tcp, _) = listener.accept().await.context("accept wormhole mTLS")?;
let (tcp, peer) = listener.accept().await.context("accept wormhole mTLS")?;
let acceptor = acceptor.clone();
let app = app.clone();
tokio::spawn(async move {
@@ -86,7 +86,7 @@ pub async fn serve(mtls: WormholeMtls, app: Router) -> Result<()> {
return;
};
let io = TokioIo::new(tls);
let service = TowerToHyperService::new(HyperApp(app));
let service = TowerToHyperService::new(HyperApp(app, peer));
let _ = hyper::server::conn::http1::Builder::new()
.serve_connection(io, service)
.await;
@@ -95,7 +95,7 @@ pub async fn serve(mtls: WormholeMtls, app: Router) -> Result<()> {
}
#[derive(Clone)]
struct HyperApp(Router);
struct HyperApp(Router, SocketAddr);
impl Service<Request<Incoming>> for HyperApp {
type Response = Response;
@@ -108,9 +108,13 @@ impl Service<Request<Incoming>> for HyperApp {
fn call(&mut self, request: Request<Incoming>) -> Self::Future {
let app = self.0.clone();
let mut request = request.map(Body::new);
// The TLS listener has no `into_make_service_with_connect_info`; supply the peer here
// so handlers that rate limit by source see the real address.
request.extensions_mut().insert(axum::extract::ConnectInfo(self.1));
Box::pin(async move {
Ok(app
.oneshot(request.map(Body::new))
.oneshot(request)
.await
.unwrap_or_else(|error| match error {}))
})
@@ -138,3 +142,78 @@ pub fn load_ca(path: &Path) -> Result<RootCertStore> {
}
Ok(roots)
}
#[cfg(test)]
mod tests {
use super::*;
use rcgen::{BasicConstraints, CertificateParams, DnType, ExtendedKeyUsagePurpose, IsCa, KeyPair};
/// Agents reach pairing and upload routes over mTLS. Those handlers rate limit
/// by source, which needs the peer address; this proves it is supplied on that
/// listener (without it every agent request would fail in the extractor).
#[tokio::test]
async fn agent_requests_over_mtls_carry_their_peer_address() {
let ca_key = KeyPair::generate().unwrap();
let mut ca_params = CertificateParams::new(vec![]).unwrap();
ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
ca_params.distinguished_name.push(DnType::CommonName, "tessera-test-ca");
let ca = ca_params.self_signed(&ca_key).unwrap();
let server_key = KeyPair::generate().unwrap();
let server = CertificateParams::new(vec!["localhost".into()]).unwrap().signed_by(&server_key, &ca, &ca_key).unwrap();
let client_key = KeyPair::generate().unwrap();
let mut client_params = CertificateParams::new(vec!["agent".into()]).unwrap();
client_params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth];
let client = client_params.signed_by(&client_key, &ca, &ca_key).unwrap();
let dir = tempfile::tempdir().unwrap();
let write = |name: &str, pem: String| {
let path = dir.path().join(name);
std::fs::write(&path, pem).unwrap();
path
};
let port = {
let probe = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
probe.local_addr().unwrap().port()
};
let mtls = WormholeMtls {
listen: SocketAddr::from(([127, 0, 0, 1], port)),
cert: load_certs(&write("server.pem", server.pem())).unwrap(),
key: load_key(&write("server.key", server_key.serialize_pem())).unwrap(),
client_ca: load_ca(&write("ca.pem", ca.pem())).unwrap(),
};
let mut state = crate::state::HubState::bootstrap(dir.path().join("hub").to_str().unwrap(), "synthetic-vault").await.unwrap();
state.admin.token = Some("synthetic-admin".into());
tokio::spawn(mtls_serve(mtls, crate::api::router(state)));
let identity = openidconnect::reqwest::Identity::from_pem(format!("{}{}", client.pem(), client_key.serialize_pem()).as_bytes()).unwrap();
let trusted = openidconnect::reqwest::Certificate::from_pem(ca.pem().as_bytes()).unwrap();
let with_cert = openidconnect::reqwest::Client::builder()
.add_root_certificate(trusted.clone())
.identity(identity)
.build()
.unwrap();
// `pairing` requires `ConnectInfo<SocketAddr>` (no fallback), so a 200 proves the peer is supplied.
let url = format!("https://localhost:{port}/api/v1/wormhole/pairing");
let body = serde_json::json!({});
let mut answer = None;
for _ in 0..50 {
match with_cert.post(&url).header("x-tessera-admin-token", "synthetic-admin").header("content-type", "application/json").body(body.to_string()).send().await {
Ok(response) => {
answer = Some(response.status().as_u16());
break;
}
Err(_) => tokio::time::sleep(std::time::Duration::from_millis(100)).await,
}
}
assert_eq!(answer, Some(200), "a handler that requires ConnectInfo ran, so the peer address was supplied");
// without a client certificate the TLS handshake itself is refused
let anonymous = openidconnect::reqwest::Client::builder().add_root_certificate(trusted).build().unwrap();
assert!(anonymous.post(&url).header("x-tessera-admin-token", "synthetic-admin").header("content-type", "application/json").body(body.to_string()).send().await.is_err());
}
fn mtls_serve(mtls: WormholeMtls, app: Router) -> impl Future<Output = ()> {
async move {
let _ = serve(mtls, app).await;
}
}
}

View File

@@ -41,6 +41,7 @@ pub struct HubState {
pub admin: AdminGate,
pub sessions: SessionGate,
pub oidc: Option<std::sync::Arc<crate::oidc::OidcProvider>>,
pub limits: Arc<crate::limits::Limits>,
pub wormhole_mtls: bool,
/// Token uploads are accepted on this listener. Plain HTTP turns this off
/// when wormhole mTLS is required, so those routes are not a bypass.
@@ -73,6 +74,7 @@ impl HubState {
active_orbits: Arc::new(Mutex::new(HashSet::new())),
admin,
sessions: SessionGate::from_env(db.clone(), oidc_config.as_ref().map(|c| c.fingerprint()))?,
limits: Arc::new(crate::limits::Limits::from_env()?),
oidc: oidc_config.map(|c| crate::oidc::OidcProvider::new(c).map(Arc::new)).transpose()?,
wormhole_mtls: false,
accept_plain_upload: true,

View File

@@ -213,3 +213,49 @@ Behaviour to know about:
- No IdP token is stored or sent to the browser; the browser only receives the
Tessera session cookie.
## Outpost credentials, rotation and request limits
**Storage.** The hub keeps only SHA-256 digests of pairing codes and Outpost upload
tokens. A pairing code is shown once (10 minute lifetime, single use). The upload
token does not exist until the agent claims the code; it is returned once and never
stored or logged. Tokens are 256-bit random values. They expire after
`TESSERA_OUTPOST_TOKEN_DAYS` days (default 365).
**Upgrading an existing hub.** On first start the old clear-text `wormhole_tokens`
table is moved to digests and dropped, with `secure_delete` on so freed pages are
zeroed. Paired agents keep working with their current token and get a fresh
lifetime from the migration (the old `expires_at` was the pairing code's expiry).
Copies and backups of the old database still contain the clear-text tokens:
**rotate every Outpost token after upgrading** and treat old backups as sensitive.
Do not downgrade to a binary that predates this change; it would not understand the
new tables. Back up `tessera.db` first and rehearse on a copy.
**Rotate** (admin only). `POST /api/v1/wormhole/outposts/{id}/rotate?grace_minutes=60`
returns the new `upload_token` once. The previous token keeps working for the grace
period (default 60, maximum 1440, `0` cuts it at once) so you can put the new value
in the agent's `TESSERA_UPLOAD_TOKEN` and restart it. There is no agent
self-rotation yet: the operator delivers the new token.
**Revoke** (admin only). `POST /api/v1/wormhole/outposts/{id}/revoke` refuses every
token of that Outpost on its next request; it must be paired again. Both actions are
audited (`outpost.credential_rotate`, `outpost.credential_revoke`).
**Limits.** Unauthenticated and expensive endpoints are limited per source with
`governor`: emergency login (5 burst, 10/min per source, plus a looser 60/min account
ceiling), pairing claim (5 burst, 10/min per source, 120/min overall), SSO start and
callback. At most 2 Argon2 verifications run at once; further attempts get `429`
immediately. A denial is written to the audit log at most once a minute per source.
- The source is the TCP peer address. `X-Forwarded-For` is only used when the peer
is listed in `TESSERA_TRUSTED_PROXIES` (comma-separated IPs), read right to left
past trusted hops. Behind a reverse proxy **set this**, otherwise every user
shares the proxy's budget. IPv6 sources are keyed by /64.
- The account ceiling is deliberately looser than the per-source limit. With one
break-glass account, a tight account lock would let anyone lock the operator out.
- Limiter state is in memory: it resets when the hub restarts and is not shared
between hub processes.
**Shared admin token.** `TESSERA_ADMIN_TOKEN` is a transition aid. Set
`TESSERA_ADMIN_TOKEN_EXPIRES` (`YYYY-MM-DD`, end of that day UTC, or an RFC 3339
timestamp) and the hub refuses the token after that time. Without it the hub logs a
warning at start. Every use is audited as the `legacy-admin-token` service principal.

View File

@@ -33,7 +33,9 @@ admin/browser. Semua status/data job hanya di scope owner/admin yang berizin.
| /api/v1/reconstitute/:id | GET,DELETE | human | recovery.manage | restore session→snapshot→orbit | status aman; cancel sebelum apply |
| /api/v1/wormhole/outposts | GET | human | outpost.manage | admin | nama/status; tanpa token |
| /api/v1/wormhole/pairing | POST | human | outpost.manage | admin | code berumur pendek |
| /api/v1/wormhole/claim | POST | public | pairing.consume | one-time code | token baru sekali ke claimant; limiter |
| /api/v1/wormhole/claim | POST | public | pairing.consume | one-time code | token baru sekali ke claimant; limiter per sumber + global, kode tersimpan sebagai digest |
| /api/v1/wormhole/outposts/:id/rotate | POST | human | outpost.manage | paired Outpost | token baru sekali (no-store); token lama hidup selama grace; audit |
| /api/v1/wormhole/outposts/:id/revoke | POST | human | outpost.manage | Outpost | tidak ada; semua kredensial ditolak pada request berikutnya; audit |
| /api/v1/wormhole/upload/init | POST | outpost | upload.assigned | orbit owner | session ID milik owner |
| /api/v1/wormhole/upload/chunk | POST | outpost | upload.assigned | session owner + orbit owner | tidak ada |
| /api/v1/wormhole/restic/commit | POST | outpost | upload.assigned | orbit owner + repository owner | snapshot ID owner |

View File

@@ -49,13 +49,17 @@ Bukti: `cargo test --workspace` hijau (hub 51 tes, stabil 5/5 run). Tes end-to-e
Belum ada / batas: RP-initiated logout dan back-channel logout (logout hanya mengakhiri sesi Tessera, sesi IdP tetap), re-auth dan `max_age` untuk akses sensitif, ES256/PS256 (hanya RS256), limiter pada `/login` dan `/callback` (M4; yang ada hanya batas 500 transaksi pending), revokasi perubahan grup IdP hanya saat sign-in berikutnya (maksimal 8 jam), uji dengan IdP organisasi target, uji logout/MFA di IdP target.
Catatan operasional: image Keycloak 26.1 tertinggal di Docker lokal (~500 MB), container sudah dihapus.
## M4 — Hardening kredensial
## M4 — Hardening kredensial (selesai di working tree, belum di-commit, 14 November 2026)
Hasil: tidak ada rahasia aktif yang tersimpan mentah dan login tidak bisa dibanjiri.
- Token Outpost/service disimpan sebagai digest, migrasi di tempat, rotate/revoke/expiry, audit. Pairing code berupa digest sekali pakai.
- `governor` untuk login darurat dan claim: kunci per sumber tepercaya plus backoff akun, kuota global tidak mengunci semua user. Semaphore untuk hashing Argon2.
- Token shared admin lama hanya untuk transisi, ada tanggal berakhir dan audit.
Selesai bila: DB baru tidak memuat token aktif mentah, token dicabut ditolak di request berikutnya, flood satu sumber tidak menghabiskan kuota user lain.
Hasil: tidak ada rahasia aktif yang tersimpan mentah dan endpoint publik tidak bisa dibanjiri.
- Pairing code dan token Outpost hanya tersimpan sebagai digest SHA-256 (`db/credentials.rs`: `pairing_codes`, `outpost_credentials`). Token dibuat saat klaim (256 bit dari OsRng) dan hanya ada di respons klaim. Masa berlaku `TESSERA_OUTPOST_TOKEN_DAYS` (default 365).
- Migrasi di tempat dari `wormhole_tokens`: token aktif tetap berfungsi dan mendapat masa berlaku baru dari waktu migrasi (expiry lama adalah expiry kode, bukan token); kode belum terpakai tetap dengan expiry-nya, token pra-cetak dibuang; tabel lama di-drop dengan `secure_delete`. Tidak ada referensi `wormhole_tokens` di luar migrasi.
- Rotate (`POST /wormhole/outposts/:id/rotate?grace_minutes=`; token lama hidup selama grace, 0 = langsung putus) dan revoke (`.../revoke`), keduanya admin-only dan diaudit. Outpost yang dicabut ditolak pada request berikutnya, termasuk di endpoint yang membawa lease, dan harus di-pair ulang.
- `governor` per sumber untuk login darurat, klaim pairing, dan SSO login/callback; plafon akun dan klaim global lebih longgar; semaphore Argon2 (2 permit) dengan `try_acquire` dan permit dibawa ke dalam `spawn_blocking`. Sumber = alamat peer; `X-Forwarded-For` hanya dari `TESSERA_TRUSTED_PROXIES`, dibaca kanan ke kiri; IPv6 per /64; penolakan diaudit maksimal sekali per menit per sumber.
- Listener mTLS sekarang menyuplai alamat peer ke handler.
- Token admin bersama bisa diberi tanggal akhir (`TESSERA_ADMIN_TOKEN_EXPIRES`); lewat tanggal ditolak (dan tidak jatuh ke mode development anonim); tiap pemakaian tercatat sebagai `legacy-admin-token`.
Bukti: `cargo test --workspace` hijau (hub 70 tes), `cargo audit` hanya `proc-macro-error`, `cargo deny` ok. Tes: tidak ada token/kode mentah di file DB (termasuk `-wal`/`-journal`, dengan sanity check bahwa scan benar-benar membaca file), klaim sekali pakai, expiry/revoke/rotasi dengan clock injeksi, migrasi legacy (token aktif dengan expiry lama tetap jalan, scrub, idempoten), pairing→claim lewat HTTP nyata, revoke → 401 di endpoint upload dan endpoint lease, flood satu sumber tidak menghabiskan kuota sumber lain dan header palsu tidak membantu, audit penolakan sekali per menit, Argon2 terbatas dan permit dilepas, token admin kedaluwarsa, tes lewat listener mTLS sungguhan (gagal 500 bila penyisipan peer dilepas). Proses nyata pada DB bergaya lama dengan token sintetis: migrasi, token lama tetap 200, tidak ada teks mentah di file DB, pairing/rotate/revoke via HTTP, audit sesuai, tidak ada token di DB maupun log.
Belum ada / batas: rotasi oleh agen sendiri (operator yang mengantar token baru; grace window jadi jembatannya), tanggal akhir token admin sengaja tetap opsional (keputusan Sen, 14 November 2026; peringatan saat start bila `TESSERA_ADMIN_TOKEN_EXPIRES` tidak diset, jadi token bisa tetap permanen sampai tanggal itu dipasang), limiter di memori (reset saat restart, tidak dibagi antar proses), tidak ada `Retry-After` di respons 429, endpoint list Outpost belum menampilkan status/expiry kredensial, tidak ada UI untuk rotate/revoke, backup DB lama masih memuat token mentah sehingga rotasi setelah upgrade wajib. Migrasi hanya diuji pada salinan; belum dijalankan pada hub produksi.
## M5 — Hak akses per scope