fix(auth): throttle bootstrap and require reauth for user changes

Bootstrap takes the client IP, is limited per IP, and writes no audit line
once an admin exists. Creating, changing the role of or deleting a user now
needs a session with recent reauthentication; API tokens are refused.
/api/analyze and /api/update return fixed messages and log the detail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas RayanandClaude Opus 5.5 committed 2026-11-04 19:56:59 -03:00
1 parent 2b1bc63340
commit 5ad89d5be5
6 files changed
+218 -39

No files matched your search

+150 -2
View File
@@ -91,7 +91,9 @@ fn harness(transport: Transport) -> H {
let (dir, auth, app) = fresh(transport);
let t = now();
let code = auth.ensure_bootstrap(t).unwrap().unwrap();
let pending = auth.complete_bootstrap(&code, "root", PW, t).unwrap();
let pending = auth
.complete_bootstrap(&code, "root", PW, peer(), t)
.unwrap();
let e = auth.start_enrollment_pending(&pending.token, t).unwrap();
let recovery = auth
.confirm_enrollment_pending(&pending.token, &totp(&e.uri, t), t)
@@ -424,7 +426,10 @@ async fn analyst_forbidden_on_admin_routes() {
let h = harness(Transport::Local);
let cookie = h.analyst_cookie().await;
let csrf = h.csrf(&cookie).await;
for route in ALL_ROUTES.iter().filter(|r| r.access == Access::Admin) {
for route in ALL_ROUTES
.iter()
.filter(|r| matches!(r.access, Access::Admin | Access::AdminRecentSession))
{
let r = send(
&h.app,
request(verb_method(route.verb), route.path)
@@ -948,3 +953,146 @@ fn login_step_debug_never_prints_the_token() {
});
assert!(!format!("{step:?}").contains("s3cret"));
}
// ---- Fix round 1 ----
const BOOTSTRAP_REFUSAL: &str = r#"{"error":"invalid setup code"}"#;
#[tokio::test]
async fn bootstrap_after_setup_writes_no_audit_and_has_one_reply() {
let h = harness(Transport::Local);
let before = h.auth.audit_tail(1000).unwrap().len();
for body in [
serde_json::json!({"code": "x", "username": "new", "password": PW}),
serde_json::json!({"code": "x", "username": "", "password": "short"}),
] {
let r = send(&h.app, post_json("/api/auth/bootstrap", body)).await;
assert_eq!(r.status, StatusCode::UNAUTHORIZED);
assert_eq!(r.body, BOOTSTRAP_REFUSAL);
}
assert_eq!(h.auth.audit_tail(1000).unwrap().len(), before);
}
#[tokio::test]
async fn bootstrap_guesses_are_throttled_per_ip_and_audited_with_it() {
let (_d, auth, app) = fresh(Transport::Local);
auth.ensure_bootstrap(now()).unwrap().unwrap();
let guess = || {
post_json(
"/api/auth/bootstrap",
serde_json::json!({"code": "wrong", "username": "root", "password": PW}),
)
};
for _ in 0..20 {
let r = send(&app, guess()).await;
assert_eq!(r.status, StatusCode::UNAUTHORIZED);
}
let before = auth.audit_tail(1000).unwrap();
let r = send(&app, guess()).await;
assert_eq!(r.status, StatusCode::TOO_MANY_REQUESTS);
assert!(r.headers.contains_key(header::RETRY_AFTER));
assert_eq!(auth.audit_tail(1000).unwrap().len(), before.len());
let last = serde_json::to_string(before.last().unwrap()).unwrap();
assert!(last.contains(&peer().to_string()), "{last}");
}
#[tokio::test]
async fn user_mutations_need_a_session_with_recent_reauth() {
let h = harness(Transport::Local);
let cookie = h.admin_cookie().await;
let new_user = serde_json::json!({"username": "bob", "password": PW2, "role": "admin"});
let users = "/api/admin/users";
let stale = h
.mutate(&cookie, Method::POST, users, new_user.clone())
.await;
assert_eq!(stale.status, StatusCode::FORBIDDEN);
assert_eq!(stale.body, r#"{"error":"recent authentication required"}"#);
for method in [Method::PATCH, Method::DELETE] {
let r = h
.mutate(
&cookie,
method,
users,
serde_json::json!({"id": "x", "role": "analyst"}),
)
.await;
assert_eq!(r.status, StatusCode::FORBIDDEN);
}
// `token_from` reauthenticates this same session.
let token = h.token_from(&cookie, Scope::Admin);
for (method, body) in [
(Method::POST, new_user.clone()),
(
Method::PATCH,
serde_json::json!({"id": "x", "role": "analyst"}),
),
(Method::DELETE, serde_json::json!({"id": "x"})),
] {
let r = send(
&h.app,
request(method.clone(), users)
.header(header::AUTHORIZATION, format!("Bearer {token}"))
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(body.to_string()))
.unwrap(),
)
.await;
assert_eq!(r.status, StatusCode::FORBIDDEN, "{method}");
}
assert!(h
.auth
.list_users()
.unwrap()
.iter()
.all(|u| u.username != "bob"));
// Reads stay open to an admin token.
let read = send(
&h.app,
request(Method::GET, users)
.header(header::AUTHORIZATION, format!("Bearer {token}"))
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(read.status, StatusCode::OK);
let made = h.mutate(&cookie, Method::POST, users, new_user).await;
assert_eq!(made.status, StatusCode::OK, "{}", made.body);
let id = made.json()["id"].as_str().unwrap().to_string();
let role = h
.mutate(
&cookie,
Method::PATCH,
users,
serde_json::json!({"id": id, "role": "analyst"}),
)
.await;
assert_eq!(role.status, StatusCode::OK, "{}", role.body);
let gone = h
.mutate(
&cookie,
Method::DELETE,
users,
serde_json::json!({"id": id}),
)
.await;
assert_eq!(gone.status, StatusCode::OK, "{}", gone.body);
}
#[tokio::test]
async fn analyze_failure_has_a_fixed_message() {
let h = harness(Transport::Local);
let cookie = h.admin_cookie().await;
let r = h
.mutate(
&cookie,
Method::POST,
"/api/analyze",
serde_json::json!({"path": "/nao/existe"}),
)
.await;
assert_eq!(r.status, StatusCode::BAD_REQUEST);
assert_eq!(r.body, r#"{"error":"analysis failed"}"#);
}