merge: worktree-agent-ac03eb441ec9759b0

# Conflicts:
#	docs/auth-endpoint-contract.md
This commit is contained in:
2026-11-16 21:37:44 +07:00
24 changed files with 654 additions and 110 deletions

View File

@@ -16,10 +16,10 @@ export TESSERA_VAULT_PASSPHRASE='choose a long private passphrase'
./target/release/tessera-hub ./target/release/tessera-hub
``` ```
The hub listens on **127.0.0.1:8787** unless `TESSERA_LISTEN` is set. Open [http://127.0.0.1:8787](http://127.0.0.1:8787). The OpenAPI document is at `/api-doc/openapi.json`. There is no default passphrase, and new vaults refuse the old published value `dev-vault-key`. Leave `TESSERA_SEED_DEMO` unset; `TESSERA_SEED_DEMO=1` writes demo backup history into the data directory. The hub listens on **127.0.0.1:8787** unless `TESSERA_LISTEN` is set. Open [http://127.0.0.1:8787](http://127.0.0.1:8787). The OpenAPI document is at `/api-doc/openapi.json` for signed-in operators (set `TESSERA_PUBLIC_OPENAPI=true` to publish it). There is no default passphrase, and new vaults refuse the old published value `dev-vault-key`. Leave `TESSERA_SEED_DEMO` unset; `TESSERA_SEED_DEMO=1` writes demo backup history into the data directory.
Authentication is required by default, including on loopback. Configure at least one of: the emergency operator Authentication is required by default, including on loopback. Configure at least one of: the emergency operator
(`TESSERA_OPERATOR_PASSWORD_HASH`), a shared API token (`TESSERA_ADMIN_TOKEN`, optionally with (`TESSERA_OPERATOR_PASSWORD_HASH`), a shared API token (`TESSERA_ADMIN_TOKEN`, at least 32 characters, optionally with
`TESSERA_ADMIN_TOKEN_EXPIRES`), or OIDC single sign-on. The hub refuses to start with none of them. For synthetic local `TESSERA_ADMIN_TOKEN_EXPIRES`), or OIDC single sign-on. The hub refuses to start with none of them. For synthetic local
development only, `TESSERA_LOCAL_DEVELOPMENT=true` allows anonymous loopback access. See development only, `TESSERA_LOCAL_DEVELOPMENT=true` allows anonymous loopback access. See
[docs/DATABASE-CAPTURE.md](docs/DATABASE-CAPTURE.md) for operator sign-in, OIDC, per-orbit access grants, downloads, [docs/DATABASE-CAPTURE.md](docs/DATABASE-CAPTURE.md) for operator sign-in, OIDC, per-orbit access grants, downloads,

View File

@@ -16,6 +16,9 @@ impl AdminGate {
.ok() .ok()
.map(|value| value.trim().to_string()) .map(|value| value.trim().to_string())
.filter(|value| !value.is_empty()); .filter(|value| !value.is_empty());
if let Some(token) = &token {
check_token_strength(token)?;
}
let local_development = match std::env::var("TESSERA_LOCAL_DEVELOPMENT").as_deref() { let local_development = match std::env::var("TESSERA_LOCAL_DEVELOPMENT").as_deref() {
Ok("1" | "true") => true, Ok("1" | "true") => true,
Ok("0" | "false" | "") | Err(std::env::VarError::NotPresent) => false, Ok("0" | "false" | "") | Err(std::env::VarError::NotPresent) => false,
@@ -99,6 +102,22 @@ impl AdminGate {
} }
} }
/// Shortest shared admin token the hub will start with.
pub const MIN_ADMIN_TOKEN_LEN: usize = 32;
fn check_token_strength(token: &str) -> anyhow::Result<()> {
anyhow::ensure!(
token.chars().count() >= MIN_ADMIN_TOKEN_LEN,
"TESSERA_ADMIN_TOKEN must be at least {MIN_ADMIN_TOKEN_LEN} characters (for example `openssl rand -hex 32`)"
);
Ok(())
}
/// True when the request carries an admin token (in either header).
pub(crate) fn presents_token(headers: &HeaderMap) -> bool {
presented_token(headers).is_some()
}
fn presented_token(headers: &HeaderMap) -> Option<&str> { fn presented_token(headers: &HeaderMap) -> Option<&str> {
if let Some(value) = headers if let Some(value) = headers
.get("x-tessera-admin-token") .get("x-tessera-admin-token")
@@ -152,6 +171,13 @@ mod tests {
SocketAddr::new(ip, 9) SocketAddr::new(ip, 9)
} }
#[test]
fn short_admin_tokens_are_refused() {
assert!(check_token_strength("short").is_err());
assert!(check_token_strength(&"x".repeat(31)).is_err());
assert!(check_token_strength(&"x".repeat(32)).is_ok());
}
#[test] #[test]
fn loopback_without_credentials_is_denied_even_behind_a_local_proxy() { fn loopback_without_credentials_is_denied_even_behind_a_local_proxy() {
let gate = AdminGate { let gate = AdminGate {
@@ -266,8 +292,6 @@ pub struct BrowserSession {
pub id: uuid::Uuid, pub id: uuid::Uuid,
pub csrf: String, pub csrf: String,
pub actor: String, pub actor: String,
/// Read by per-user revoke and the OIDC login path (M3/M5).
#[allow(dead_code)]
pub user_id: String, pub user_id: String,
pub auth_method: String, pub auth_method: String,
/// May use the management API. A signed-in user without a grant is `false`. /// May use the management API. A signed-in user without a grant is `false`.

View File

@@ -148,7 +148,7 @@ async fn world() -> World {
async fn world_with(exports: Option<crate::exports::ExportGate>) -> World { async fn world_with(exports: Option<crate::exports::ExportGate>) -> World {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await .await
.unwrap(); .unwrap();
if let Some(gate) = exports { if let Some(gate) = exports {

View File

@@ -34,7 +34,7 @@ fn every_registered_path_has_an_authorization_contract() {
async fn human_read_endpoints_reject_anonymous_and_outpost_tokens() { async fn human_read_endpoints_reject_anonymous_and_outpost_tokens() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let mut state = let mut state =
crate::state::HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") crate::state::HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await .await
.unwrap(); .unwrap();
state.sessions = crate::admin::SessionGate::fixture(state.db.clone()); state.sessions = crate::admin::SessionGate::fixture(state.db.clone());
@@ -44,6 +44,8 @@ async fn human_read_endpoints_reject_anonymous_and_outpost_tokens() {
.db .db
.insert_test_credential("synthetic-outpost", &outpost.to_string(), "fixture"); .insert_test_credential("synthetic-outpost", &outpost.to_string(), "fixture");
let app = router(state); let app = router(state);
// each request comes from its own source so the wrong-token throttle does not mask the 401s
let mut source = 0u32;
for row in CONTRACT.lines().filter(|line| line.starts_with("| /")) { for row in CONTRACT.lines().filter(|line| line.starts_with("| /")) {
let fields: Vec<_> = row.split('|').map(str::trim).collect(); let fields: Vec<_> = row.split('|').map(str::trim).collect();
if fields[3] != "human" || !fields[2].split(',').any(|method| method == "GET") { if fields[3] != "human" || !fields[2].split(',').any(|method| method == "GET") {
@@ -51,9 +53,10 @@ async fn human_read_endpoints_reject_anonymous_and_outpost_tokens() {
} }
let path = fields[1].replace(":id", "00000000-0000-0000-0000-000000000001"); let path = fields[1].replace(":id", "00000000-0000-0000-0000-000000000001");
for token in [None, Some("synthetic-outpost")] { for token in [None, Some("synthetic-outpost")] {
let mut request = Request::builder() source += 1;
.uri(&path) let mut request = Request::builder().uri(&path).extension(ConnectInfo(
.extension(ConnectInfo("127.0.0.1:9000".parse::<SocketAddr>().unwrap())); SocketAddr::from(([10, 0, (source >> 8) as u8, source as u8], 9000)),
));
if let Some(token) = token { if let Some(token) = token {
request = request request = request
.header(header::AUTHORIZATION, format!("Bearer {token}")) .header(header::AUTHORIZATION, format!("Bearer {token}"))
@@ -77,7 +80,7 @@ async fn human_read_endpoints_reject_anonymous_and_outpost_tokens() {
async fn local_proxy_never_enables_auth_when_credentials_are_absent() { async fn local_proxy_never_enables_auth_when_credentials_are_absent() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let mut state = let mut state =
crate::state::HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") crate::state::HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await .await
.unwrap(); .unwrap();
state.admin = crate::admin::AdminGate { state.admin = crate::admin::AdminGate {

View File

@@ -22,7 +22,7 @@ struct Harness {
async fn harness_with(configure: impl FnOnce(&mut HubState)) -> Harness { async fn harness_with(configure: impl FnOnce(&mut HubState)) -> Harness {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await .await
.unwrap(); .unwrap();
state.admin.token = Some(ADMIN.into()); state.admin.token = Some(ADMIN.into());

View File

@@ -23,7 +23,7 @@ struct Harness {
async fn harness_with(gate: Option<ExportGate>) -> Harness { async fn harness_with(gate: Option<ExportGate>) -> Harness {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await .await
.unwrap(); .unwrap();
state.admin.token = Some(ADMIN.into()); state.admin.token = Some(ADMIN.into());

View File

@@ -266,10 +266,11 @@ async fn job(
async fn claim( async fn claim(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap, headers: HeaderMap,
Path(application): Path<Uuid>, Path(application): Path<Uuid>,
) -> Result<Json<Option<CaptureLease>>, StatusCode> { ) -> Result<Json<Option<CaptureLease>>, StatusCode> {
let outpost = outpost(&state, &headers)?; let outpost = outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
let mut lease = state let mut lease = state
.db .db
.claim_capture(outpost, application, now()) .claim_capture(outpost, application, now())
@@ -288,11 +289,12 @@ async fn claim(
async fn report( async fn report(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap, headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
body: Result<Json<CaptureReport>, JsonRejection>, body: Result<Json<CaptureReport>, JsonRejection>,
) -> Result<StatusCode, StatusCode> { ) -> Result<StatusCode, StatusCode> {
let outpost = outpost(&state, &headers)?; let outpost = outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
let Json(body) = body.map_err(|_| StatusCode::UNPROCESSABLE_ENTITY)?; let Json(body) = body.map_err(|_| StatusCode::UNPROCESSABLE_ENTITY)?;
if !state if !state
.db .db
@@ -306,11 +308,12 @@ async fn report(
async fn upload( async fn upload(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap, headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
body: Body, body: Body,
) -> Result<Json<serde_json::Value>, StatusCode> { ) -> Result<Json<serde_json::Value>, StatusCode> {
let outpost = outpost(&state, &headers)?; let outpost = outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
let lease = Uuid::parse_str(header_value(&headers, "x-tessera-lease-id")?) let lease = Uuid::parse_str(header_value(&headers, "x-tessera-lease-id")?)
.map_err(|_| StatusCode::BAD_REQUEST)?; .map_err(|_| StatusCode::BAD_REQUEST)?;
let job = state let job = state
@@ -401,11 +404,12 @@ async fn upload(
async fn commit_restic( async fn commit_restic(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap, headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
Json(commit): Json<ResticCaptureCommit>, Json(commit): Json<ResticCaptureCommit>,
) -> Result<Json<serde_json::Value>, StatusCode> { ) -> Result<Json<serde_json::Value>, StatusCode> {
let outpost = outpost(&state, &headers)?; let outpost = outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
let job = state let job = state
.db .db
.capture_upload(outpost, id, commit.lease_id, now()) .capture_upload(outpost, id, commit.lease_id, now())
@@ -549,31 +553,43 @@ pub(super) fn header_value<'a>(headers: &'a HeaderMap, name: &str) -> Result<&'a
.ok_or(StatusCode::BAD_REQUEST) .ok_or(StatusCode::BAD_REQUEST)
} }
pub(super) fn outpost(state: &HubState, headers: &HeaderMap) -> Result<Uuid, StatusCode> { pub(super) fn outpost(
state: &HubState,
peer: Option<std::net::SocketAddr>,
headers: &HeaderMap,
) -> Result<Uuid, StatusCode> {
use crate::auth::{AuditAction, AuditOutcome, AuditResource, Principal}; use crate::auth::{AuditAction, AuditOutcome, AuditResource, Principal};
let result = authenticate_outpost(state, headers); let result = authenticate_outpost(state, headers);
let (actor, resource, outcome) = match result { match result {
Ok(id) => ( Ok(id) => {
Principal::Outpost(id),
AuditResource::Outpost(id),
AuditOutcome::Allowed,
),
Err(_) => (
Principal::Anonymous,
AuditResource::Api,
AuditOutcome::Denied,
),
};
state state
.db .db
.audit_event( .audit_event(
&actor, &Principal::Outpost(id),
AuditAction::Authentication, AuditAction::Authentication,
resource, AuditResource::Outpost(id),
outcome, AuditOutcome::Allowed,
Uuid::new_v4(), Uuid::new_v4(),
) )
.map_err(internal)?; .map_err(internal)?;
}
Err(_) => {
// One denial row per source per minute; a failed audit write must not
// change the refusal into a 500.
let source = state.limits.source(peer, headers);
if state.limits.audit_denial(source) {
if let Err(error) = state.db.audit_event(
&Principal::Anonymous,
AuditAction::Authentication,
AuditResource::Api,
AuditOutcome::Denied,
Uuid::new_v4(),
) {
tracing::error!(%error, "could not record a denied outpost authentication");
}
}
}
}
result result
} }

View File

@@ -248,7 +248,7 @@ fn config(idp: &Idp) -> OidcConfig {
async fn harness_with(min_refresh: Duration) -> Harness { async fn harness_with(min_refresh: Duration) -> Harness {
let idp = Idp::start().await; let idp = Idp::start().await;
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await .await
.unwrap(); .unwrap();
let config = config(&idp); let config = config(&idp);
@@ -788,7 +788,7 @@ async fn an_idp_outage_degrades_to_fixed_errors_and_never_a_session() {
#[tokio::test] #[tokio::test]
async fn oidc_endpoints_are_absent_when_oidc_is_not_configured() { async fn oidc_endpoints_are_absent_when_oidc_is_not_configured() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") let state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await .await
.unwrap(); .unwrap();
let app = crate::api::router(state); let app = crate::api::router(state);

View File

@@ -44,7 +44,7 @@ struct Lab {
async fn lab_with(configure: impl FnOnce(&mut HubState)) -> Lab { async fn lab_with(configure: impl FnOnce(&mut HubState)) -> Lab {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await .await
.unwrap(); .unwrap();
state.admin.token = Some(ADMIN.into()); state.admin.token = Some(ADMIN.into());

View File

@@ -370,10 +370,11 @@ async fn reconcile(
async fn claim( async fn claim(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap, headers: HeaderMap,
Path(target): Path<Uuid>, Path(target): Path<Uuid>,
) -> Result<Json<Option<RestoreLease>>, StatusCode> { ) -> Result<Json<Option<RestoreLease>>, StatusCode> {
let outpost = outpost(&state, &headers)?; let outpost = outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
state state
.db .db
.claim_restore(outpost, target, now()) .claim_restore(outpost, target, now())
@@ -381,8 +382,12 @@ async fn claim(
.map_err(internal) .map_err(internal)
} }
fn auth(state: &HubState, headers: &HeaderMap) -> Result<(Uuid, Uuid), StatusCode> { fn auth(
let outpost = outpost(state, headers)?; state: &HubState,
peer: Option<ConnectInfo<SocketAddr>>,
headers: &HeaderMap,
) -> Result<(Uuid, Uuid), StatusCode> {
let outpost = outpost(state, peer.map(|ConnectInfo(addr)| addr), headers)?;
let token = let token =
header_value(headers, "x-tessera-restore-token").map_err(|_| StatusCode::UNAUTHORIZED)?; header_value(headers, "x-tessera-restore-token").map_err(|_| StatusCode::UNAUTHORIZED)?;
Ok(( Ok((
@@ -393,10 +398,11 @@ fn auth(state: &HubState, headers: &HeaderMap) -> Result<(Uuid, Uuid), StatusCod
async fn payload( async fn payload(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap, headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
) -> Result<Response, StatusCode> { ) -> Result<Response, StatusCode> {
let (outpost, token) = auth(&state, &headers)?; let (outpost, token) = auth(&state, peer, &headers)?;
let (job, artifact, _) = state let (job, artifact, _) = state
.db .db
.restore_access(outpost, id, token, now()) .restore_access(outpost, id, token, now())
@@ -435,11 +441,12 @@ async fn payload(
async fn report( async fn report(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap, headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
body: Result<Json<RestoreProgress>, JsonRejection>, body: Result<Json<RestoreProgress>, JsonRejection>,
) -> Result<StatusCode, StatusCode> { ) -> Result<StatusCode, StatusCode> {
let (outpost, token) = auth(&state, &headers)?; let (outpost, token) = auth(&state, peer, &headers)?;
let Json(progress) = body.map_err(|_| StatusCode::UNPROCESSABLE_ENTITY)?; let Json(progress) = body.map_err(|_| StatusCode::UNPROCESSABLE_ENTITY)?;
// Why a step failed, in the agent's words. Cleaned again here: the agent is trusted with the job, not // Why a step failed, in the agent's words. Cleaned again here: the agent is trusted with the job, not
// with what ends up in the database and the log. // with what ends up in the database and the log.
@@ -462,11 +469,12 @@ async fn report(
async fn safety( async fn safety(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap, headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
body: Body, body: Body,
) -> Result<Json<serde_json::Value>, StatusCode> { ) -> Result<Json<serde_json::Value>, StatusCode> {
let (outpost, token) = auth(&state, &headers)?; let (outpost, token) = auth(&state, peer, &headers)?;
let (job, _, safety_id) = state let (job, _, safety_id) = state
.db .db
.restore_access(outpost, id, token, now()) .restore_access(outpost, id, token, now())
@@ -538,10 +546,11 @@ async fn safety(
async fn apply( async fn apply(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap, headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
) -> Result<StatusCode, StatusCode> { ) -> Result<StatusCode, StatusCode> {
let (outpost, token) = auth(&state, &headers)?; let (outpost, token) = auth(&state, peer, &headers)?;
if !state if !state
.db .db
.authorize_apply(outpost, id, token, now()) .authorize_apply(outpost, id, token, now())

View File

@@ -251,7 +251,6 @@ struct ReconstituteStartResponse {
pub(super) struct OperatorActor { pub(super) struct OperatorActor {
/// Display only. Never record this as "who did it": an IdP can call a user anything. /// Display only. Never record this as "who did it": an IdP can call a user anything.
pub(super) name: String, pub(super) name: String,
pub(super) browser: bool,
pub(super) principal: Principal, pub(super) principal: Principal,
pub(super) subject: Subject, pub(super) subject: Subject,
pub(super) request_id: Uuid, pub(super) request_id: Uuid,
@@ -289,16 +288,21 @@ pub(super) fn authenticate(
.unwrap_or(Principal::Anonymous); .unwrap_or(Principal::Anonymous);
let result = authenticate_inner(state, peer, headers, mutation, request_id, session); let result = authenticate_inner(state, peer, headers, mutation, request_id, session);
if result.is_err() { if result.is_err() {
state // One denial row per source per minute: an unauthenticated flood must not
.db // grow the audit table, and a failed audit write must not turn the 401/403
.audit_event( // into a 500.
let source = state.limits.source(Some(peer), headers);
if state.limits.audit_denial(source) {
if let Err(error) = state.db.audit_event(
&attempted, &attempted,
AuditAction::Authentication, AuditAction::Authentication,
AuditResource::Api, AuditResource::Api,
AuditOutcome::Denied, AuditOutcome::Denied,
request_id, request_id,
) ) {
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; tracing::error!(%error, "could not record a denied authentication");
}
}
} }
result result
} }
@@ -313,7 +317,6 @@ fn authenticate_inner(
) -> Result<OperatorActor, StatusCode> { ) -> Result<OperatorActor, StatusCode> {
let configured_admin = |name: &str, principal: Principal| OperatorActor { let configured_admin = |name: &str, principal: Principal| OperatorActor {
name: name.into(), name: name.into(),
browser: false,
principal, principal,
subject: Subject { subject: Subject {
user_id: None, user_id: None,
@@ -322,12 +325,22 @@ fn authenticate_inner(
}, },
request_id, request_id,
}; };
if state.admin.token.is_some() && state.admin.authorize(peer, headers).is_ok() { if state.admin.token.is_some() {
if state.admin.authorize(peer, headers).is_ok() {
return Ok(configured_admin( return Ok(configured_admin(
"api-token", "api-token",
Principal::Service("legacy-admin-token"), Principal::Service("legacy-admin-token"),
)); ));
} }
// A wrong token counts against the source's budget; past it the answer is 429.
if crate::admin::presents_token(headers)
&& !state
.limits
.admin_token_failure(state.limits.source(Some(peer), headers))
{
return Err(StatusCode::TOO_MANY_REQUESTS);
}
}
if let Some(session) = session { if let Some(session) = session {
if mutation { if mutation {
super::session::require_csrf(headers, &session.csrf.to_string())?; super::session::require_csrf(headers, &session.csrf.to_string())?;
@@ -336,7 +349,6 @@ fn authenticate_inner(
principal: session.principal(), principal: session.principal(),
subject: session.subject(), subject: session.subject(),
name: session.actor, name: session.actor,
browser: true,
request_id, request_id,
}); });
} }
@@ -407,14 +419,73 @@ pub fn router(state: HubState) -> Router {
.merge(super::relations::routes()) .merge(super::relations::routes())
.merge(super::refresh::routes()) .merge(super::refresh::routes())
.merge(super::restore::routes()) .merge(super::restore::routes())
.route("/api-doc/openapi.json", get(openapi_document))
.with_state(state); .with_state(state);
let api = api.route( let hsts = matches!(
"/api-doc/openapi.json", std::env::var("TESSERA_HSTS").as_deref(),
get(|| async { Json(ApiDoc::openapi()) }), Ok("1" | "true")
); );
api.fallback(spa_fallback)
.layer(TraceLayer::new_for_http().make_span_with(request_span))
.layer(axum::middleware::from_fn(move |request, next| {
security_headers(hsts, request, next)
}))
}
api.fallback(spa_fallback).layer(TraceLayer::new_for_http()) /// The log span for a request: method and path only. The query string is left out because it carries
/// OIDC `code` and `state` values (and may carry other secrets).
fn request_span(request: &axum::http::Request<axum::body::Body>) -> tracing::Span {
tracing::info_span!("request", method = %request.method(), path = %request.uri().path())
}
/// Policy for the bundled web app: everything from this origin. The stylesheet pulls the
/// Google Fonts CSS and font files, hence those two allowances.
const CONTENT_SECURITY_POLICY: &str = "default-src 'self'; script-src 'self'; \
style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; \
img-src 'self' data: blob:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'";
async fn security_headers(
hsts: bool,
request: axum::extract::Request,
next: axum::middleware::Next,
) -> axum::response::Response {
let mut response = next.run(request).await;
let headers = response.headers_mut();
headers.insert(
header::CONTENT_SECURITY_POLICY,
HeaderValue::from_static(CONTENT_SECURITY_POLICY),
);
headers.insert(
header::X_CONTENT_TYPE_OPTIONS,
HeaderValue::from_static("nosniff"),
);
headers.insert(header::REFERRER_POLICY, HeaderValue::from_static("no-referrer"));
headers.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY"));
if hsts {
headers.insert(
header::STRICT_TRANSPORT_SECURITY,
HeaderValue::from_static("max-age=31536000; includeSubDomains"),
);
}
response
}
/// The API description needs a signed-in operator or the admin token, unless
/// `TESSERA_PUBLIC_OPENAPI=true` publishes it.
async fn openapi_document(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<Json<utoipa::openapi::OpenApi>, StatusCode> {
let public = matches!(
std::env::var("TESSERA_PUBLIC_OPENAPI").as_deref(),
Ok("1" | "true")
);
if !public {
authenticate(&state, peer, &headers, false)?;
}
Ok(Json(ApiDoc::openapi()))
} }
#[utoipa::path(get, path = "/health", responses((status = 200, description = "ok")))] #[utoipa::path(get, path = "/health", responses((status = 200, description = "ok")))]
@@ -750,12 +821,13 @@ async fn start_reconstitute(
headers: HeaderMap, headers: HeaderMap,
Json(req): Json<ReconstituteRequest>, Json(req): Json<ReconstituteRequest>,
) -> Result<Json<ReconstituteStartResponse>, StatusCode> { ) -> Result<Json<ReconstituteStartResponse>, StatusCode> {
let actor = admin_write(&state, peer, &headers)?; admin_write(&state, peer, &headers)?;
let destination = if actor.browser { // Every caller, browser or API token, may only name a file inside the hub's exports directory,
browser_export_path(&state, &req.target_path)? // and never one that already exists.
} else { let destination = browser_export_path(&state, &req.target_path)?;
req.target_path.clone().into() if destination.symlink_metadata().is_ok() {
}; return Err(StatusCode::CONFLICT);
}
let vault = state.vault.read().await; let vault = state.vault.read().await;
if vault if vault
.get_snapshot(req.snapshot_id) .get_snapshot(req.snapshot_id)
@@ -785,6 +857,7 @@ async fn start_reconstitute(
let mut map = state_bg.reconstitute_sessions.write().await; let mut map = state_bg.reconstitute_sessions.write().await;
if let Some(s) = map.get_mut(&session_id) { if let Some(s) = map.get_mut(&session_id) {
if s.state == ReconstituteState::Aborted { if s.state == ReconstituteState::Aborted {
evict_reconstitute_later(&state_bg, session_id);
return; return;
} }
s.seconds_remaining = remaining; s.seconds_remaining = remaining;
@@ -798,6 +871,7 @@ async fn start_reconstitute(
return; return;
}; };
if s.state == ReconstituteState::Aborted { if s.state == ReconstituteState::Aborted {
evict_reconstitute_later(&state_bg, session_id);
return; return;
} }
s.state = ReconstituteState::Restoring; s.state = ReconstituteState::Restoring;
@@ -816,6 +890,7 @@ async fn start_reconstitute(
.db .db
.audit("reconstitute.done", &format!("session={session_id}")) .audit("reconstitute.done", &format!("session={session_id}"))
.await; .await;
evict_reconstitute_later(&state_bg, session_id);
}); });
Ok(Json(ReconstituteStartResponse { Ok(Json(ReconstituteStartResponse {
@@ -824,6 +899,19 @@ async fn start_reconstitute(
})) }))
} }
/// How long a finished restore session stays readable before its entry is dropped.
const RECONSTITUTE_RETAIN: std::time::Duration = std::time::Duration::from_secs(3600);
/// Drops a finished session from the in-memory map after `RECONSTITUTE_RETAIN`, so the map does
/// not grow for as long as the hub runs.
fn evict_reconstitute_later(state: &HubState, id: Uuid) {
let state = state.clone();
tokio::spawn(async move {
tokio::time::sleep(RECONSTITUTE_RETAIN).await;
state.reconstitute_sessions.write().await.remove(&id);
});
}
fn browser_export_path( fn browser_export_path(
state: &HubState, state: &HubState,
requested: &str, requested: &str,
@@ -1189,10 +1277,11 @@ fn require_legacy_upload_owner(
#[utoipa::path(post, path = "/api/v1/wormhole/upload/init", request_body = UploadInit, responses((status = 200)))] #[utoipa::path(post, path = "/api/v1/wormhole/upload/init", request_body = UploadInit, responses((status = 200)))]
async fn wormhole_upload_init( async fn wormhole_upload_init(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: axum::http::HeaderMap, headers: axum::http::HeaderMap,
Json(body): Json<UploadInit>, Json(body): Json<UploadInit>,
) -> Result<Json<serde_json::Value>, StatusCode> { ) -> Result<Json<serde_json::Value>, StatusCode> {
let outpost = super::jobs::outpost(&state, &headers)?; let outpost = super::jobs::outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
require_legacy_upload_owner(&state, body.orbit_id, outpost)?; require_legacy_upload_owner(&state, body.orbit_id, outpost)?;
reject_managed_orbit(&state, body.orbit_id)?; reject_managed_orbit(&state, body.orbit_id)?;
if state if state
@@ -1231,10 +1320,11 @@ async fn wormhole_upload_init(
#[utoipa::path(post, path = "/api/v1/wormhole/upload/chunk", request_body = UploadChunk, responses((status = 204)))] #[utoipa::path(post, path = "/api/v1/wormhole/upload/chunk", request_body = UploadChunk, responses((status = 204)))]
async fn wormhole_upload_chunk( async fn wormhole_upload_chunk(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: axum::http::HeaderMap, headers: axum::http::HeaderMap,
Json(body): Json<UploadChunk>, Json(body): Json<UploadChunk>,
) -> Result<StatusCode, StatusCode> { ) -> Result<StatusCode, StatusCode> {
let outpost = super::jobs::outpost(&state, &headers)?; let outpost = super::jobs::outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
let session = state let session = state
.db .db
.upload_session(&body.session_id.to_string()) .upload_session(&body.session_id.to_string())
@@ -1338,10 +1428,11 @@ pub(super) fn upload_token<'a>(
#[utoipa::path(post, path = "/api/v1/wormhole/restic/commit", request_body = ResticCommit, responses((status = 200)))] #[utoipa::path(post, path = "/api/v1/wormhole/restic/commit", request_body = ResticCommit, responses((status = 200)))]
async fn wormhole_restic_commit( async fn wormhole_restic_commit(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap, headers: HeaderMap,
Json(body): Json<ResticCommit>, Json(body): Json<ResticCommit>,
) -> Result<Json<serde_json::Value>, StatusCode> { ) -> Result<Json<serde_json::Value>, StatusCode> {
let outpost_id = super::jobs::outpost(&state, &headers)?; let outpost_id = super::jobs::outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
require_legacy_upload_owner(&state, body.orbit_id, outpost_id)?; require_legacy_upload_owner(&state, body.orbit_id, outpost_id)?;
if body.snapshot_id.len() != 64 || !body.snapshot_id.bytes().all(|b| b.is_ascii_hexdigit()) { if body.snapshot_id.len() != 64 || !body.snapshot_id.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err(StatusCode::BAD_REQUEST); return Err(StatusCode::BAD_REQUEST);
@@ -1469,18 +1560,33 @@ async fn spa_fallback(uri: Uri) -> impl IntoResponse {
path = "index.html".into(); path = "index.html".into();
} }
if let Some(file) = WEB_DIST.get_file(&path) { if let Some(file) = WEB_DIST.get_file(&path) {
let ct = content_type(&path); // Build output under /assets/ carries a content hash in its name.
let cache = if path.starts_with("assets/") {
"public, max-age=31536000, immutable"
} else {
"no-cache"
};
return ( return (
StatusCode::OK, StatusCode::OK,
[(header::CONTENT_TYPE, ct)], [
(header::CONTENT_TYPE, content_type(&path)),
(header::CACHE_CONTROL, cache),
],
file.contents(), file.contents(),
) )
.into_response(); .into_response();
} }
// A missing asset or API path is a 404, not the app shell.
if path.starts_with("assets/") || path.starts_with("api/") {
return (StatusCode::NOT_FOUND, "not found").into_response();
}
if let Some(index) = WEB_DIST.get_file("index.html") { if let Some(index) = WEB_DIST.get_file("index.html") {
return ( return (
StatusCode::OK, StatusCode::OK,
[(header::CONTENT_TYPE, "text/html")], [
(header::CONTENT_TYPE, "text/html; charset=utf-8"),
(header::CACHE_CONTROL, "no-cache"),
],
index.contents(), index.contents(),
) )
.into_response(); .into_response();
@@ -1489,14 +1595,22 @@ async fn spa_fallback(uri: Uri) -> impl IntoResponse {
} }
fn content_type(path: &str) -> &'static str { fn content_type(path: &str) -> &'static str {
if path.ends_with(".js") { let extension = path.rsplit('.').next().unwrap_or("").to_ascii_lowercase();
"application/javascript" match extension.as_str() {
} else if path.ends_with(".css") { "html" => "text/html; charset=utf-8",
"text/css" "js" | "mjs" => "text/javascript; charset=utf-8",
} else if path.ends_with(".svg") { "css" => "text/css; charset=utf-8",
"image/svg+xml" "svg" => "image/svg+xml",
} else { "png" => "image/png",
"text/html" "jpg" | "jpeg" => "image/jpeg",
"webp" => "image/webp",
"ico" => "image/x-icon",
"woff" => "font/woff",
"woff2" => "font/woff2",
"json" => "application/json",
"map" => "application/json",
"txt" => "text/plain; charset=utf-8",
_ => "application/octet-stream",
} }
} }
@@ -1507,10 +1621,252 @@ mod tests {
use axum::http::Request; use axum::http::Request;
use tower::ServiceExt; use tower::ServiceExt;
async fn denied_authentication_rows(dir: &std::path::Path) -> i64 {
rusqlite::Connection::open(dir.join("tessera.db"))
.unwrap()
.query_row(
"SELECT count(*) FROM audit_events WHERE action='authentication.check' AND outcome='denied'",
[],
|r| r.get(0),
)
.unwrap()
}
#[tokio::test]
async fn unauthenticated_floods_write_one_denial_row_per_source() {
let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await
.unwrap();
state.admin.token = Some("synthetic-admin-token-of-32-chars!".into());
let app = router(state);
let human = |ip: &str| {
Request::get("/api/v1/orbits")
.extension(ConnectInfo(format!("{ip}:9000").parse::<SocketAddr>().unwrap()))
.body(Body::empty())
.unwrap()
};
let outpost = |ip: &str| {
Request::post("/api/v1/wormhole/upload/init")
.extension(ConnectInfo(format!("{ip}:9000").parse::<SocketAddr>().unwrap()))
.header(header::CONTENT_TYPE, "application/json")
.header("x-tessera-upload-token", "wrong")
.body(Body::from(r#"{"orbit_id":"00000000-0000-0000-0000-000000000000","total_bytes":1}"#))
.unwrap()
};
for _ in 0..25 {
let r = app.clone().oneshot(human("203.0.113.5")).await.unwrap();
assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
}
assert_eq!(denied_authentication_rows(dir.path()).await, 1);
for _ in 0..25 {
let r = app.clone().oneshot(outpost("203.0.113.5")).await.unwrap();
assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
}
// the same source shares one budget across both entry points
assert_eq!(denied_authentication_rows(dir.path()).await, 1);
// another source still gets its own row
let r = app.clone().oneshot(outpost("203.0.113.6")).await.unwrap();
assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
assert_eq!(denied_authentication_rows(dir.path()).await, 2);
}
#[tokio::test]
async fn wrong_admin_tokens_are_throttled_per_source() {
let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await
.unwrap();
state.admin.token = Some("synthetic-admin-token-of-32-chars!".into());
let app = router(state);
let req = |ip: &str, token: &str| {
Request::get("/api/v1/orbits")
.extension(ConnectInfo(format!("{ip}:9000").parse::<SocketAddr>().unwrap()))
.header("x-tessera-admin-token", token)
.body(Body::empty())
.unwrap()
};
let mut limited = false;
for _ in 0..20 {
let r = app.clone().oneshot(req("203.0.113.20", "wrong")).await.unwrap();
limited |= r.status() == StatusCode::TOO_MANY_REQUESTS;
}
assert!(limited);
let r = app.oneshot(req("203.0.113.21", "wrong")).await.unwrap();
assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn reconstitute_targets_stay_inside_the_exports_directory_for_every_caller() {
let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await
.unwrap();
state.admin.token = Some("synthetic-admin-token-of-32-chars!".into());
let app = router(state);
let attempt = |path: &str| {
Request::post("/api/v1/reconstitute")
.extension(ConnectInfo("203.0.113.30:9000".parse::<SocketAddr>().unwrap()))
.header(header::AUTHORIZATION, "Bearer synthetic-admin-token-of-32-chars!")
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(
serde_json::json!({"snapshot_id": Uuid::new_v4(), "target_path": path}).to_string(),
))
.unwrap()
};
for path in ["/etc/passwd", "../escape", "a/b", "..", ""] {
let r = app.clone().oneshot(attempt(path)).await.unwrap();
assert_eq!(r.status(), StatusCode::BAD_REQUEST, "{path}");
}
// a plain file name passes confinement (the unknown snapshot is what stops it)
let r = app.clone().oneshot(attempt("dump.sql")).await.unwrap();
assert_eq!(r.status(), StatusCode::NOT_FOUND);
std::fs::write(dir.path().join("exports").join("taken.sql"), b"keep").unwrap();
let r = app.oneshot(attempt("taken.sql")).await.unwrap();
assert_eq!(r.status(), StatusCode::CONFLICT);
}
#[test]
fn request_logs_name_the_path_and_never_the_query() {
use std::sync::{Arc, Mutex};
#[derive(Clone, Default)]
struct Sink(Arc<Mutex<Vec<u8>>>);
impl std::io::Write for Sink {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Sink {
type Writer = Sink;
fn make_writer(&'a self) -> Sink {
self.clone()
}
}
let sink = Sink::default();
let subscriber = tracing_subscriber::fmt().with_writer(sink.clone()).finish();
tracing::subscriber::with_default(subscriber, || {
let request = Request::get("/api/v1/auth/oidc/callback?code=secret-code&state=secret-state")
.body(Body::empty())
.unwrap();
request_span(&request).in_scope(|| tracing::info!("handled"));
});
let logged = String::from_utf8(sink.0.lock().unwrap().clone()).unwrap();
assert!(logged.contains("/api/v1/auth/oidc/callback"), "{logged}");
assert!(!logged.contains("secret-code") && !logged.contains("secret-state"), "{logged}");
}
#[test]
fn content_types_are_right_and_unknown_is_never_html() {
assert_eq!(content_type("assets/x.png"), "image/png");
assert_eq!(content_type("assets/x.woff2"), "font/woff2");
assert_eq!(content_type("assets/x.woff"), "font/woff");
assert_eq!(content_type("favicon.ico"), "image/x-icon");
assert_eq!(content_type("assets/x.js.map"), "application/json");
assert_eq!(content_type("manifest.json"), "application/json");
assert_eq!(content_type("assets/x.bin"), "application/octet-stream");
assert_eq!(content_type("noextension"), "application/octet-stream");
}
#[tokio::test]
async fn the_api_description_is_not_served_to_anonymous_callers() {
let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await
.unwrap();
state.admin.token = Some("synthetic-admin-token-of-32-chars!".into());
let app = router(state);
let request = |token: Option<&str>| {
let mut r = Request::get("/api-doc/openapi.json")
.extension(ConnectInfo("203.0.113.50:9000".parse::<SocketAddr>().unwrap()));
if let Some(token) = token {
r = r.header(header::AUTHORIZATION, format!("Bearer {token}"));
}
r.body(Body::empty()).unwrap()
};
let anonymous = app.clone().oneshot(request(None)).await.unwrap();
assert_eq!(anonymous.status(), StatusCode::UNAUTHORIZED);
let signed_in = app
.oneshot(request(Some("synthetic-admin-token-of-32-chars!")))
.await
.unwrap();
assert_eq!(signed_in.status(), StatusCode::OK);
}
#[tokio::test]
async fn responses_carry_security_headers_and_assets_cache_for_a_year() {
let dir = tempfile::tempdir().unwrap();
let state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await
.unwrap();
let app = router(state);
let get = |uri: &str| {
Request::get(uri)
.extension(ConnectInfo("203.0.113.40:9000".parse::<SocketAddr>().unwrap()))
.body(Body::empty())
.unwrap()
};
for uri in ["/", "/health", "/api/v1/orbits"] {
let r = app.clone().oneshot(get(uri)).await.unwrap();
let h = r.headers();
let csp = h[header::CONTENT_SECURITY_POLICY].to_str().unwrap();
assert!(csp.contains("default-src 'self'") && csp.contains("frame-ancestors 'none'"));
assert_eq!(h[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
assert_eq!(h[header::REFERRER_POLICY], "no-referrer");
assert_eq!(h[header::X_FRAME_OPTIONS], "DENY");
}
let missing = app.clone().oneshot(get("/assets/nope.js")).await.unwrap();
assert_eq!(missing.status(), StatusCode::NOT_FOUND);
if let Some(file) = WEB_DIST.get_dir("assets").and_then(|d| d.files().next()) {
let uri = format!("/{}", file.path().display());
let r = app.oneshot(get(&uri)).await.unwrap();
assert_eq!(r.status(), StatusCode::OK);
assert_eq!(
r.headers()[header::CACHE_CONTROL],
"public, max-age=31536000, immutable"
);
}
}
#[tokio::test]
async fn a_failed_denial_audit_write_still_answers_401() {
let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await
.unwrap();
state.admin.token = Some("synthetic-admin-token-of-32-chars!".into());
let app = router(state);
rusqlite::Connection::open(dir.path().join("tessera.db"))
.unwrap()
.execute_batch("DROP TABLE audit_events")
.unwrap();
let human = Request::get("/api/v1/orbits")
.extension(ConnectInfo("203.0.113.9:9000".parse::<SocketAddr>().unwrap()))
.body(Body::empty())
.unwrap();
assert_eq!(
app.clone().oneshot(human).await.unwrap().status(),
StatusCode::UNAUTHORIZED
);
let outpost = Request::post("/api/v1/wormhole/upload/init")
.extension(ConnectInfo("203.0.113.10:9000".parse::<SocketAddr>().unwrap()))
.header(header::CONTENT_TYPE, "application/json")
.header("x-tessera-upload-token", "wrong")
.body(Body::from(r#"{"orbit_id":"00000000-0000-0000-0000-000000000000","total_bytes":1}"#))
.unwrap();
assert_eq!(
app.oneshot(outpost).await.unwrap().status(),
StatusCode::UNAUTHORIZED
);
}
#[tokio::test] #[tokio::test]
async fn legacy_uploads_are_owned_by_the_assigned_outpost() { async fn legacy_uploads_are_owned_by_the_assigned_outpost() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await .await
.unwrap(); .unwrap();
state.accept_plain_upload = true; state.accept_plain_upload = true;
@@ -1693,6 +2049,7 @@ mod tests {
); );
let mut commit = Box::pin(wormhole_restic_commit( let mut commit = Box::pin(wormhole_restic_commit(
State(state.clone()), State(state.clone()),
None,
owner_headers, owner_headers,
Json(ResticCommit { Json(ResticCommit {
orbit_id: orbit, orbit_id: orbit,
@@ -1721,7 +2078,7 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn orbit_creation_validates_cron_and_direct_run_preserves_wormhole_status() { async fn orbit_creation_validates_cron_and_direct_run_preserves_wormhole_status() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "test-vault") let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "test-vault-passphrase")
.await .await
.unwrap(); .unwrap();
state.admin.token = Some("fixture-admin".into()); state.admin.token = Some("fixture-admin".into());
@@ -1787,7 +2144,7 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn new_orbits_validate_source_access_and_keep_provider_internal() { async fn new_orbits_validate_source_access_and_keep_provider_internal() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "test-vault") let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "test-vault-passphrase")
.await .await
.unwrap(); .unwrap();
state.admin.token = Some("fixture-admin".into()); state.admin.token = Some("fixture-admin".into());
@@ -1843,7 +2200,7 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn orbit_responses_and_schema_hide_provider_config() { async fn orbit_responses_and_schema_hide_provider_config() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "test-vault") let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "test-vault-passphrase")
.await .await
.unwrap(); .unwrap();
state.admin.token = Some("fixture-admin".into()); state.admin.token = Some("fixture-admin".into());

View File

@@ -369,7 +369,7 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn operator_session_requires_csrf_and_expires_without_disabling_cli() { async fn operator_session_requires_csrf_and_expires_without_disabling_cli() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "fixture-vault") let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "fixture-vault-passphrase")
.await .await
.unwrap(); .unwrap();
state.sessions = SessionGate::fixture(state.db.clone()); state.sessions = SessionGate::fixture(state.db.clone());
@@ -507,7 +507,7 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn me_reports_the_caller_and_rejects_anonymous() { async fn me_reports_the_caller_and_rejects_anonymous() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "fixture-vault") let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "fixture-vault-passphrase")
.await .await
.unwrap(); .unwrap();
state.sessions = SessionGate::fixture(state.db.clone()); state.sessions = SessionGate::fixture(state.db.clone());

View File

@@ -51,12 +51,53 @@ impl Db {
)?; )?;
Ok(()) Ok(())
} }
/// Deletes structured audit events recorded before `cutoff` (unix seconds);
/// returns how many rows went.
pub fn prune_audit_events(&self, cutoff: i64) -> Result<usize> {
Ok(self
.conn
.lock()
.unwrap()
.execute("DELETE FROM audit_events WHERE at < ?1", params![cutoff])?)
}
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
#[tokio::test]
async fn pruning_removes_only_events_older_than_the_cutoff() {
let dir = tempfile::tempdir().unwrap();
let db = Db::connect(&dir.path().join("fixture.db")).await.unwrap();
db.migrate().await.unwrap();
for _ in 0..3 {
db.audit_event(
&Principal::Anonymous,
AuditAction::Authentication,
AuditResource::Api,
AuditOutcome::Denied,
Uuid::new_v4(),
)
.unwrap();
}
let now = chrono::Utc::now().timestamp();
db.conn
.lock()
.unwrap()
.execute("UPDATE audit_events SET at = ?1 WHERE id <= 2", params![now - 100 * 86_400])
.unwrap();
assert_eq!(db.prune_audit_events(now - 90 * 86_400).unwrap(), 2);
let left: i64 = db
.conn
.lock()
.unwrap()
.query_row("SELECT count(*) FROM audit_events", [], |r| r.get(0))
.unwrap();
assert_eq!(left, 1);
}
#[tokio::test] #[tokio::test]
async fn structured_audit_survives_reopen_and_preserves_legacy_events() { async fn structured_audit_survives_reopen_and_preserves_legacy_events() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();

View File

@@ -59,6 +59,7 @@ pub struct Limits {
oidc_login_source: Keyed, oidc_login_source: Keyed,
oidc_callback_source: Keyed, oidc_callback_source: Keyed,
audit_denial: Keyed, audit_denial: Keyed,
admin_token_failure: Keyed,
pub argon2: Arc<Semaphore>, pub argon2: Arc<Semaphore>,
trusted_proxies: Vec<IpAddr>, trusted_proxies: Vec<IpAddr>,
calls: AtomicU64, calls: AtomicU64,
@@ -75,6 +76,7 @@ impl Limits {
oidc_callback_source: RateLimiter::keyed(config.oidc_callback_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 // one audit row per source per minute, so a flood cannot fill the audit table
audit_denial: RateLimiter::keyed(per_minute(1, 1)), audit_denial: RateLimiter::keyed(per_minute(1, 1)),
admin_token_failure: RateLimiter::keyed(per_minute(10, 5)),
argon2: Arc::new(Semaphore::new(config.argon2_concurrency)), argon2: Arc::new(Semaphore::new(config.argon2_concurrency)),
trusted_proxies, trusted_proxies,
calls: AtomicU64::new(0), calls: AtomicU64::new(0),
@@ -131,6 +133,7 @@ impl Limits {
self.oidc_login_source.retain_recent(); self.oidc_login_source.retain_recent();
self.oidc_callback_source.retain_recent(); self.oidc_callback_source.retain_recent();
self.audit_denial.retain_recent(); self.audit_denial.retain_recent();
self.admin_token_failure.retain_recent();
} }
} }
@@ -154,6 +157,12 @@ impl Limits {
self.oidc_callback_source.check_key(&source).is_ok() self.oidc_callback_source.check_key(&source).is_ok()
} }
/// Counts one wrong admin token from `source`; false once that source has used up its budget.
pub fn admin_token_failure(&self, source: IpAddr) -> bool {
self.maintain();
self.admin_token_failure.check_key(&source).is_ok()
}
/// True at most once a minute per source: use it to decide whether a denial is audited. /// 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 { pub fn audit_denial(&self, source: IpAddr) -> bool {
self.audit_denial.check_key(&source).is_ok() self.audit_denial.check_key(&source).is_ok()

View File

@@ -30,6 +30,7 @@ async fn main() -> Result<()> {
let addr: SocketAddr = listen.parse()?; let addr: SocketAddr = listen.parse()?;
let admin = admin::AdminGate::from_env()?; let admin = admin::AdminGate::from_env()?;
admin.validate_listener(addr)?; admin.validate_listener(addr)?;
let audit_retention = scheduler::audit_retention_from_env()?;
let wormhole = mtls::from_env()?; let wormhole = mtls::from_env()?;
if let Some(config) = &wormhole { if let Some(config) = &wormhole {
admin.validate_listener(config.listen)?; admin.validate_listener(config.listen)?;
@@ -81,6 +82,7 @@ async fn main() -> Result<()> {
state.configure_offsite()?; state.configure_offsite()?;
state.reconcile_capture_catalog().await?; state.reconcile_capture_catalog().await?;
state.start_offsite_worker(); state.start_offsite_worker();
scheduler::start_audit_retention(state.db.clone(), audit_retention);
scheduler::start_orbit_scheduler(state.clone()).await?; scheduler::start_orbit_scheduler(state.clone()).await?;
refresh::start(state.clone()); refresh::start(state.clone());
if state.sessions.enabled() { if state.sessions.enabled() {

View File

@@ -75,7 +75,16 @@ pub async fn serve(mtls: WormholeMtls, app: Router) -> Result<()> {
mtls.listen mtls.listen
); );
loop { loop {
let (tcp, peer) = listener.accept().await.context("accept wormhole mTLS")?; let (tcp, peer) = match listener.accept().await {
Ok(accepted) => accepted,
Err(error) => {
// Out of file descriptors, an aborted handshake and the like pass; stopping the
// listener would end every Outpost's connection until a restart.
tracing::warn!(%error, "wormhole mTLS accept failed; continuing");
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
continue;
}
};
let acceptor = acceptor.clone(); let acceptor = acceptor.clone();
let app = app.clone(); let app = app.clone();
tokio::spawn(async move { tokio::spawn(async move {
@@ -191,7 +200,7 @@ mod tests {
}; };
let mut state = crate::state::HubState::bootstrap( let mut state = crate::state::HubState::bootstrap(
dir.path().join("hub").to_str().unwrap(), dir.path().join("hub").to_str().unwrap(),
"synthetic-vault", "synthetic-vault-passphrase",
) )
.await .await
.unwrap(); .unwrap();

View File

@@ -32,6 +32,45 @@ pub async fn start_orbit_scheduler(state: HubState) -> Result<()> {
Ok(()) Ok(())
} }
const DEFAULT_AUDIT_RETENTION_DAYS: i64 = 90;
/// `TESSERA_AUDIT_RETENTION_DAYS`: how long structured audit events are kept.
/// Unset means 90 days; `0` keeps them forever.
pub fn audit_retention_from_env() -> Result<Option<i64>> {
parse_audit_retention(std::env::var("TESSERA_AUDIT_RETENTION_DAYS").ok().as_deref())
}
fn parse_audit_retention(value: Option<&str>) -> Result<Option<i64>> {
let Some(value) = value.map(str::trim).filter(|v| !v.is_empty()) else {
return Ok(Some(DEFAULT_AUDIT_RETENTION_DAYS));
};
let days: i64 = value
.parse()
.ok()
.filter(|days| (0..=36_500).contains(days))
.context("TESSERA_AUDIT_RETENTION_DAYS must be a whole number of days (0 keeps everything)")?;
Ok((days > 0).then_some(days))
}
/// Prunes audit events once now and then every hour.
pub fn start_audit_retention(db: crate::db::Db, retention_days: Option<i64>) {
let Some(days) = retention_days else {
info!("audit retention disabled: audit events are kept forever");
return;
};
tokio::spawn(async move {
loop {
let cutoff = Utc::now().timestamp() - days * 86_400;
match db.prune_audit_events(cutoff) {
Ok(0) => {}
Ok(n) => info!("pruned {n} audit event(s) older than {days} days"),
Err(e) => error!("audit retention: {e}"),
}
sleep(Duration::from_secs(3600)).await;
}
});
}
pub(crate) fn orbit_schedule(expression: &str) -> Result<Schedule, cron::error::Error> { pub(crate) fn orbit_schedule(expression: &str) -> Result<Schedule, cron::error::Error> {
if expression.split_whitespace().count() == 5 { if expression.split_whitespace().count() == 5 {
Schedule::from_str(&format!("0 {expression}")) Schedule::from_str(&format!("0 {expression}"))
@@ -116,6 +155,16 @@ pub(crate) fn tick_capture_schedules(db: &crate::db::Db, now: DateTime<Utc>) ->
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn audit_retention_defaults_to_ninety_days_and_zero_disables_it() {
assert_eq!(parse_audit_retention(None).unwrap(), Some(90));
assert_eq!(parse_audit_retention(Some(" ")).unwrap(), Some(90));
assert_eq!(parse_audit_retention(Some("30")).unwrap(), Some(30));
assert_eq!(parse_audit_retention(Some("0")).unwrap(), None);
assert!(parse_audit_retention(Some("-1")).is_err());
assert!(parse_audit_retention(Some("soon")).is_err());
}
#[test] #[test]
fn orbit_cron_accepts_legacy_minutes_and_explicit_seconds() { fn orbit_cron_accepts_legacy_minutes_and_explicit_seconds() {
let before = Utc.with_ymd_and_hms(2026, 11, 10, 1, 59, 55).unwrap(); let before = Utc.with_ymd_and_hms(2026, 11, 10, 1, 59, 55).unwrap();

View File

@@ -409,7 +409,7 @@ mod tests {
#[test] #[test]
fn pg_dump_keeps_the_url_out_of_argv() { fn pg_dump_keeps_the_url_out_of_argv() {
let target = let target =
parse_postgres_url("postgres://migrator:s%3Acret@db.internal:5433/billing").unwrap(); parse_postgres_url("postgres://migrator:s%3Acret@example.invalid:5433/billing").unwrap();
assert_eq!(target.password, "s:cret"); assert_eq!(target.password, "s:cret");
let args = dump_args("custom").unwrap(); let args = dump_args("custom").unwrap();
let pgpass = write_pgpass(&target, false).unwrap(); let pgpass = write_pgpass(&target, false).unwrap();

View File

@@ -172,7 +172,7 @@ impl Offsite {
)?; )?;
let size = file.as_file().metadata()?.len(); let size = file.as_file().metadata()?.len();
file.as_file().sync_all()?; file.as_file().sync_all()?;
file.persist(dest)?; file.persist_noclobber(dest)?;
Ok(size) Ok(size)
} }

View File

@@ -43,6 +43,9 @@ struct OutpostRepository {
password: String, password: String,
} }
/// Shortest passphrase accepted for a new vault. Existing vaults keep opening with a warning.
pub const MIN_PASSPHRASE_CHARS: usize = 16;
impl Vault { impl Vault {
pub fn init(root: impl AsRef<Path>, passphrase: &str) -> Result<Self> { pub fn init(root: impl AsRef<Path>, passphrase: &str) -> Result<Self> {
if passphrase == "dev-vault-key" { if passphrase == "dev-vault-key" {
@@ -50,6 +53,10 @@ impl Vault {
"refusing to initialize a vault with the published dev passphrase; choose a private passphrase" "refusing to initialize a vault with the published dev passphrase; choose a private passphrase"
); );
} }
anyhow::ensure!(
passphrase.chars().count() >= MIN_PASSPHRASE_CHARS,
"the vault passphrase must be at least {MIN_PASSPHRASE_CHARS} characters"
);
let root = root.as_ref().to_path_buf(); let root = root.as_ref().to_path_buf();
fs::create_dir_all(root.join("data"))?; fs::create_dir_all(root.join("data"))?;
fs::create_dir_all(root.join("snapshots"))?; fs::create_dir_all(root.join("snapshots"))?;
@@ -81,6 +88,14 @@ impl Vault {
anyhow::bail!("vault not initialized"); anyhow::bail!("vault not initialized");
} }
restrict_dir(&root.join("keys"))?; restrict_dir(&root.join("keys"))?;
// Not refused: that would lock existing deployments out of their own backups.
if passphrase == "dev-vault-key" {
tracing::warn!("this vault uses the published dev passphrase; rotate it to a private one");
} else if passphrase.chars().count() < MIN_PASSPHRASE_CHARS {
tracing::warn!(
"the vault passphrase is shorter than {MIN_PASSPHRASE_CHARS} characters; a new vault would refuse it"
);
}
let salt = root.join("keys/tessera.salt"); let salt = root.join("keys/tessera.salt");
let key = VaultKey::derive_from_passphrase(passphrase, &salt)?; let key = VaultKey::derive_from_passphrase(passphrase, &salt)?;
let index = Self::load_index(&root)?; let index = Self::load_index(&root)?;
@@ -655,7 +670,8 @@ impl Vault {
} }
let len = temp.as_file().metadata()?.len(); let len = temp.as_file().metadata()?.len();
temp.as_file().sync_all()?; temp.as_file().sync_all()?;
temp.persist(dest)?; // never replace a file that is already there
temp.persist_noclobber(dest)?;
Ok(len) Ok(len)
} }
@@ -829,7 +845,7 @@ mod tests {
rand::rngs::StdRng::seed_from_u64(7).fill_bytes(&mut bytes); rand::rngs::StdRng::seed_from_u64(7).fill_bytes(&mut bytes);
let file = source.join("large.bin"); let file = source.join("large.bin");
fs::write(&file, &bytes).unwrap(); fs::write(&file, &bytes).unwrap();
let mut vault = Vault::init(dir.path().join("vault"), "secret").unwrap(); let mut vault = Vault::init(dir.path().join("vault"), "secret-test-passphrase").unwrap();
let manifest = SnapshotManifest { let manifest = SnapshotManifest {
snapshot_id: Uuid::new_v4(), snapshot_id: Uuid::new_v4(),
orbit_id: Uuid::new_v4(), orbit_id: Uuid::new_v4(),
@@ -882,7 +898,7 @@ mod tests {
#[test] #[test]
fn init_snap_list_restore() { fn init_snap_list_restore() {
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
let mut vault = Vault::init(dir.path(), "secret").unwrap(); let mut vault = Vault::init(dir.path(), "secret-test-passphrase").unwrap();
let manifest = SnapshotManifest { let manifest = SnapshotManifest {
snapshot_id: Uuid::new_v4(), snapshot_id: Uuid::new_v4(),
orbit_id: Uuid::new_v4(), orbit_id: Uuid::new_v4(),
@@ -905,7 +921,7 @@ mod tests {
#[test] #[test]
fn dry_run_writes_nothing() { fn dry_run_writes_nothing() {
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
let mut vault = Vault::init(dir.path(), "secret").unwrap(); let mut vault = Vault::init(dir.path(), "secret-test-passphrase").unwrap();
let manifest = SnapshotManifest { let manifest = SnapshotManifest {
snapshot_id: Uuid::new_v4(), snapshot_id: Uuid::new_v4(),
orbit_id: Uuid::new_v4(), orbit_id: Uuid::new_v4(),
@@ -922,7 +938,7 @@ mod tests {
#[test] #[test]
fn orbit_decay_keeps_other_orbits_recoverable() { fn orbit_decay_keeps_other_orbits_recoverable() {
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
let mut vault = Vault::init(dir.path(), "secret").unwrap(); let mut vault = Vault::init(dir.path(), "secret-test-passphrase").unwrap();
let orbit_id = Uuid::new_v4(); let orbit_id = Uuid::new_v4();
let other_id = Uuid::new_v4(); let other_id = Uuid::new_v4();
let now = DateTime::from_timestamp(1_730_000_000, 0).unwrap(); let now = DateTime::from_timestamp(1_730_000_000, 0).unwrap();
@@ -959,7 +975,7 @@ mod tests {
#[test] #[test]
fn new_snapshots_are_encrypted_and_legacy_json_still_reads() { fn new_snapshots_are_encrypted_and_legacy_json_still_reads() {
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
let mut vault = Vault::init(dir.path(), "secret").unwrap(); let mut vault = Vault::init(dir.path(), "secret-test-passphrase").unwrap();
let legacy_id = Uuid::new_v4(); let legacy_id = Uuid::new_v4();
let legacy = StoredSnapshot { let legacy = StoredSnapshot {
id: legacy_id, id: legacy_id,
@@ -1018,6 +1034,15 @@ mod tests {
assert_eq!(vault.restore_snapshot(snap.id, &out).unwrap(), 6); assert_eq!(vault.restore_snapshot(snap.id, &out).unwrap(), 6);
} }
#[test]
fn new_vaults_need_a_long_passphrase_but_existing_short_ones_still_open() {
let dir = tempfile::tempdir().unwrap();
assert!(Vault::init(dir.path(), "fifteen-chars-x").is_err());
assert!(Vault::init(dir.path(), "sixteen-chars-xx").is_ok());
// a vault made before the rule: same data, shorter passphrase never got in, so reopen with the long one
assert!(Vault::open(dir.path(), "sixteen-chars-xx").is_ok());
}
#[test] #[test]
fn init_rejects_published_dev_passphrase() { fn init_rejects_published_dev_passphrase() {
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();

View File

@@ -29,7 +29,7 @@ requests that arrive with forwarded-for headers claiming to be local.
| Route | Methods | Principal | Permission | Scope | Data allowed out | | Route | Methods | Principal | Permission | Scope | Data allowed out |
| --- | --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- | --- |
| /health | GET | public | — | — | static liveness | | /health | GET | public | — | — | static liveness |
| /api-doc/openapi.json | GET | public | — | — | schema without config or secrets | | /api-doc/openapi.json | GET | human | session.self | any signed-in caller | requires sign-in or the admin token; public only when TESSERA_PUBLIC_OPENAPI=true |
| /api/v1/operator/session | GET | public | — | current session | status, actor and CSRF token of the caller's own session; no-store | | /api/v1/operator/session | GET | public | — | current session | status, actor and CSRF token of the caller's own session; no-store |
| /api/v1/operator/session | DELETE | human | session.self | current session | nothing; CSRF required | | /api/v1/operator/session | DELETE | human | session.self | current session | nothing; CSRF required |
| /api/v1/me | GET | human | session.self | current principal | id, kind, auth method, display name, capabilities; no-store | | /api/v1/me | GET | human | session.self | current principal | id, kind, auth method, display name, capabilities; no-store |

View File

@@ -89,8 +89,8 @@ def main():
assert result["phase"] == "dump_failed" and result["snapshot_id"] is None, result assert result["phase"] == "dump_failed" and result["snapshot_id"] is None, result
continue continue
assert result["status"] == "completed", (name, result) assert result["status"] == "completed", (name, result)
target = root / f"{name}.sql" target = root / "hub" / "exports" / f"{name}.sql"
session = api("reconstitute", {"snapshot_id": result["snapshot_id"], "target_path": str(target)}) session = api("reconstitute", {"snapshot_id": result["snapshot_id"], "target_path": target.name})
wait_until(lambda: api(f"reconstitute/{session['session_id']}")["state"] == "completed") wait_until(lambda: api(f"reconstitute/{session['session_id']}")["state"] == "completed")
sql = target.read_text() sql = target.read_text()
assert all(marker in sql for marker in ("sample_view", "sample_routine", "sample_event", "backup 🛰")) assert all(marker in sql for marker in ("sample_view", "sample_routine", "sample_event", "backup 🛰"))

View File

@@ -125,8 +125,8 @@ def main():
assert failed["snapshot_id"] is None assert failed["snapshot_id"] is None
snapshots = api("snapshots") snapshots = api("snapshots")
assert {snap["id"] for snap in snapshots} == {successful["snapshot_id"], through_bastion["snapshot_id"]} assert {snap["id"] for snap in snapshots} == {successful["snapshot_id"], through_bastion["snapshot_id"]}
dump = root / "backup.dump" dump = root / "hub" / "exports" / "backup.dump"
session = api("reconstitute", {"snapshot_id": successful["snapshot_id"], "target_path": str(dump)}) session = api("reconstitute", {"snapshot_id": successful["snapshot_id"], "target_path": dump.name})
wait_until(lambda: api(f"reconstitute/{session['session_id']}")["state"] == "completed") wait_until(lambda: api(f"reconstitute/{session['session_id']}")["state"] == "completed")
command("pg_restore", *pg, "-d", "target_db", "--exit-on-error", dump) command("pg_restore", *pg, "-d", "target_db", "--exit-on-error", dump)
restored = command("psql", *pg, "-d", "target_db", "-Atc", restored = command("psql", *pg, "-d", "target_db", "-Atc",
@@ -174,7 +174,7 @@ def main():
}) })
assert "provider_config" not in legacy assert "provider_config" not in legacy
command(BIN / "tessera", "--hub-url", hub_url, "snap", "--orbit", "legacy-fixture", command(BIN / "tessera", "--hub-url", hub_url, "snap", "--orbit", "legacy-fixture",
env={**fixture_env(), "TESSERA_ADMIN_TOKEN": "fixture-admin"}, stdout=DEVNULL) env={**fixture_env(), "TESSERA_ADMIN_TOKEN": "fixture-admin-token-0123456789abcdef"}, stdout=DEVNULL)
assert any(snap["orbit_id"] == legacy["id"] for snap in api("snapshots")) assert any(snap["orbit_id"] == legacy["id"] for snap in api("snapshots"))
for log in (hub_log, agent_log): for log in (hub_log, agent_log):
log.seek(0) log.seek(0)

View File

@@ -49,7 +49,7 @@ def start_hub(cleanup: ExitStack, root: Path, settings=None, return_handle=False
hub_port = port() hub_port = port()
env = {**fixture_env(), "TESSERA_VAULT_PASSPHRASE": "fixture-private-vault-key", env = {**fixture_env(), "TESSERA_VAULT_PASSPHRASE": "fixture-private-vault-key",
"TESSERA_LISTEN": f"127.0.0.1:{hub_port}", "TESSERA_DATA_DIR": str(root / "hub"), "TESSERA_LISTEN": f"127.0.0.1:{hub_port}", "TESSERA_DATA_DIR": str(root / "hub"),
"TESSERA_ADMIN_TOKEN": "fixture-admin", **(settings or {})} "TESSERA_ADMIN_TOKEN": "fixture-admin-token-0123456789abcdef", **(settings or {})}
hub_url = f"http://127.0.0.1:{hub_port}" hub_url = f"http://127.0.0.1:{hub_port}"
log = cleanup.enter_context((root / "hub.log").open("w+")) log = cleanup.enter_context((root / "hub.log").open("w+"))
hub = Popen([BIN / "tessera-hub"], env=env, stdout=log, stderr=log) hub = Popen([BIN / "tessera-hub"], env=env, stdout=log, stderr=log)
@@ -57,7 +57,7 @@ def start_hub(cleanup: ExitStack, root: Path, settings=None, return_handle=False
def api(path, body=None, token=None, expected=200, extra=None, raw=False, method=None): def api(path, body=None, token=None, expected=200, extra=None, raw=False, method=None):
payload = body if isinstance(body, bytes) else json.dumps(body).encode() if body is not None else None payload = body if isinstance(body, bytes) else json.dumps(body).encode() if body is not None else None
headers = {"Authorization": "Bearer fixture-admin", "Content-Type": "application/json"} headers = {"Authorization": "Bearer fixture-admin-token-0123456789abcdef", "Content-Type": "application/json"}
if token: if token:
headers["X-Tessera-Upload-Token"] = token headers["X-Tessera-Upload-Token"] = token
headers.update(extra or {}) headers.update(extra or {})