fix: refuse admin tokens under 32 characters and throttle wrong token attempts per source

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 21:07:04 +07:00
parent 2931032ab7
commit 9219319ff3
6 changed files with 79 additions and 9 deletions

View File

@@ -19,7 +19,7 @@ export TESSERA_VAULT_PASSPHRASE='choose a long private passphrase'
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.
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
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,

View File

@@ -16,6 +16,9 @@ impl AdminGate {
.ok()
.map(|value| value.trim().to_string())
.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() {
Ok("1" | "true") => true,
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> {
if let Some(value) = headers
.get("x-tessera-admin-token")
@@ -152,6 +171,13 @@ mod tests {
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]
fn loopback_without_credentials_is_denied_even_behind_a_local_proxy() {
let gate = AdminGate {

View File

@@ -327,11 +327,21 @@ fn authenticate_inner(
},
request_id,
};
if state.admin.token.is_some() && state.admin.authorize(peer, headers).is_ok() {
return Ok(configured_admin(
"api-token",
Principal::Service("legacy-admin-token"),
));
if state.admin.token.is_some() {
if state.admin.authorize(peer, headers).is_ok() {
return Ok(configured_admin(
"api-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 mutation {
@@ -1565,6 +1575,31 @@ mod tests {
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")
.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 a_failed_denial_audit_write_still_answers_401() {
let dir = tempfile::tempdir().unwrap();

View File

@@ -59,6 +59,7 @@ pub struct Limits {
oidc_login_source: Keyed,
oidc_callback_source: Keyed,
audit_denial: Keyed,
admin_token_failure: Keyed,
pub argon2: Arc<Semaphore>,
trusted_proxies: Vec<IpAddr>,
calls: AtomicU64,
@@ -75,6 +76,7 @@ impl Limits {
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)),
admin_token_failure: RateLimiter::keyed(per_minute(10, 5)),
argon2: Arc::new(Semaphore::new(config.argon2_concurrency)),
trusted_proxies,
calls: AtomicU64::new(0),
@@ -131,6 +133,7 @@ impl Limits {
self.oidc_login_source.retain_recent();
self.oidc_callback_source.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()
}
/// 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.
pub fn audit_denial(&self, source: IpAddr) -> bool {
self.audit_denial.check_key(&source).is_ok()

View File

@@ -174,7 +174,7 @@ def main():
})
assert "provider_config" not in legacy
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"))
for log in (hub_log, agent_log):
log.seek(0)

View File

@@ -49,7 +49,7 @@ def start_hub(cleanup: ExitStack, root: Path, settings=None, return_handle=False
hub_port = port()
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_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}"
log = cleanup.enter_context((root / "hub.log").open("w+"))
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):
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:
headers["X-Tessera-Upload-Token"] = token
headers.update(extra or {})