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:
@@ -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.
|
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
|
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,
|
||||||
|
|||||||
@@ -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 {
|
||||||
|
|||||||
@@ -327,12 +327,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())?;
|
||||||
@@ -1565,6 +1575,31 @@ mod tests {
|
|||||||
assert_eq!(denied_authentication_rows(dir.path()).await, 2);
|
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]
|
#[tokio::test]
|
||||||
async fn a_failed_denial_audit_write_still_answers_401() {
|
async fn a_failed_denial_audit_write_still_answers_401() {
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
|||||||
@@ -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()
|
||||||
|
|||||||
2
tests/fixtures/capture-postgres.py
vendored
2
tests/fixtures/capture-postgres.py
vendored
@@ -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)
|
||||||
|
|||||||
4
tests/fixtures/fixture.py
vendored
4
tests/fixtures/fixture.py
vendored
@@ -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 {})
|
||||||
|
|||||||
Reference in New Issue
Block a user