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

+12 -2
View File
@@ -359,6 +359,15 @@ async fn gate(
} }
} }
Access::Admin => require_admin(&principal)?, Access::Admin => require_admin(&principal)?,
Access::AdminRecentSession => {
require_admin(&principal)?;
if principal.via != Via::Session {
return Err(forbidden().into());
}
if !principal.recent_auth {
return Err(ApiError::from(AuthFailure::ReauthRequired).into());
}
}
} }
if let Credential::Cookie(token) = cred { if let Credential::Cookie(token) = cred {
@@ -496,12 +505,13 @@ pub struct BootstrapBody {
pub async fn bootstrap( pub async fn bootstrap(
State(state): State<AppState>, State(state): State<AppState>,
Extension(ClientIp(ip)): Extension<ClientIp>,
JsonBody(b): JsonBody<BootstrapBody>, JsonBody(b): JsonBody<BootstrapBody>,
) -> Result<Response, ApiError> { ) -> Result<Response, ApiError> {
let auth = state.auth.clone(); let auth = state.auth.clone();
let now = unix_now(); let now = unix_now();
let pending = hashing(&state, move || { let pending = hashing(&state, move || {
auth.complete_bootstrap(&b.code, &b.username, &b.password, now) auth.complete_bootstrap(&b.code, &b.username, &b.password, ip, now)
}) })
.await?; .await?;
Ok(pending_reply("mfa_enroll_required", &pending)) Ok(pending_reply("mfa_enroll_required", &pending))
@@ -818,7 +828,7 @@ pub async fn tokens_revoke(
Ok(ok_reply()) Ok(ok_reply())
} }
// ---- Admin handlers (the gate already ran `require_admin`) ---------------- // ---- Admin handlers (the gate already ran its admin check) ----------------
pub async fn users_list(State(state): State<AppState>) -> Result<Response, ApiError> { pub async fn users_list(State(state): State<AppState>) -> Result<Response, ApiError> {
let auth = state.auth.clone(); let auth = state.auth.clone();
+23 -18
View File
@@ -90,6 +90,9 @@ pub enum Access {
SessionOrPending, SessionOrPending,
/// Administrator role, and Admin scope when through a token. /// Administrator role, and Admin scope when through a token.
Admin, Admin,
/// Administrator in a session that reauthenticated recently, never a
/// token: otherwise a hijacked session could create an admin outliving it.
AdminRecentSession,
} }
pub struct RouteDef { pub struct RouteDef {
@@ -117,7 +120,7 @@ const fn route(
/// entries also in `PUBLIC_ROUTES` is never consulted. /// entries also in `PUBLIC_ROUTES` is never consulted.
pub const ALL_ROUTES: &[RouteDef] = { pub const ALL_ROUTES: &[RouteDef] = {
use auth_http as a; use auth_http as a;
use Access::{Admin, Authenticated, Session, SessionOrPending}; use Access::{Admin, AdminRecentSession, Authenticated, Session, SessionOrPending};
use Verb::{Delete, Get, Patch, Post}; use Verb::{Delete, Get, Patch, Post};
&[ &[
route(Get, "/api/health", Authenticated, || get(health)), route(Get, "/api/health", Authenticated, || get(health)),
@@ -167,11 +170,13 @@ pub const ALL_ROUTES: &[RouteDef] = {
delete(a::tokens_revoke) delete(a::tokens_revoke)
}), }),
route(Get, "/api/admin/users", Admin, || get(a::users_list)), route(Get, "/api/admin/users", Admin, || get(a::users_list)),
route(Post, "/api/admin/users", Admin, || post(a::users_create)), route(Post, "/api/admin/users", AdminRecentSession, || {
route(Patch, "/api/admin/users", Admin, || { post(a::users_create)
}),
route(Patch, "/api/admin/users", AdminRecentSession, || {
patch(a::users_set_role) patch(a::users_set_role)
}), }),
route(Delete, "/api/admin/users", Admin, || { route(Delete, "/api/admin/users", AdminRecentSession, || {
delete(a::users_delete) delete(a::users_delete)
}), }),
route(Get, "/api/admin/audit", Admin, || get(a::audit)), route(Get, "/api/admin/audit", Admin, || get(a::audit)),
@@ -255,6 +260,18 @@ struct AnalyzeRequest {
path: String, path: String,
} }
/// The detail (paths, command output) goes to the log, not to the caller.
fn failure(status: StatusCode, message: &str, detail: &acaua_core::AcauaError) -> Response {
tracing::error!(error = %detail, "{message}");
(
status,
Json(ErrorBody {
error: message.to_string(),
}),
)
.into_response()
}
async fn health() -> Json<Health> { async fn health() -> Json<Health> {
Json(Health { status: "ok" }) Json(Health { status: "ok" })
} }
@@ -295,13 +312,7 @@ async fn analyze(
*state.report() = Some(report.clone()); *state.report() = Some(report.clone());
Json(report).into_response() Json(report).into_response()
} }
Ok(Err(error)) => ( Ok(Err(error)) => failure(StatusCode::BAD_REQUEST, "analysis failed", &error),
StatusCode::BAD_REQUEST,
Json(ErrorBody {
error: error.to_string(),
}),
)
.into_response(),
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(), Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
} }
} }
@@ -332,13 +343,7 @@ async fn update_check() -> Response {
let outcome = tokio::task::spawn_blocking(|| update::check(env!("CARGO_PKG_VERSION"))).await; let outcome = tokio::task::spawn_blocking(|| update::check(env!("CARGO_PKG_VERSION"))).await;
match outcome { match outcome {
Ok(Ok(status)) => Json::<UpdateStatus>(status).into_response(), Ok(Ok(status)) => Json::<UpdateStatus>(status).into_response(),
Ok(Err(error)) => ( Ok(Err(error)) => failure(StatusCode::BAD_GATEWAY, "update check failed", &error),
StatusCode::BAD_GATEWAY,
Json(ErrorBody {
error: error.to_string(),
}),
)
.into_response(),
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(), Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
} }
} }
+150 -2
View File
@@ -91,7 +91,9 @@ fn harness(transport: Transport) -> H {
let (dir, auth, app) = fresh(transport); let (dir, auth, app) = fresh(transport);
let t = now(); let t = now();
let code = auth.ensure_bootstrap(t).unwrap().unwrap(); 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 e = auth.start_enrollment_pending(&pending.token, t).unwrap();
let recovery = auth let recovery = auth
.confirm_enrollment_pending(&pending.token, &totp(&e.uri, t), t) .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 h = harness(Transport::Local);
let cookie = h.analyst_cookie().await; let cookie = h.analyst_cookie().await;
let csrf = h.csrf(&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( let r = send(
&h.app, &h.app,
request(verb_method(route.verb), route.path) request(verb_method(route.verb), route.path)
@@ -948,3 +953,146 @@ fn login_step_debug_never_prints_the_token() {
}); });
assert!(!format!("{step:?}").contains("s3cret")); 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"}"#);
}
+21 -5
View File
@@ -326,20 +326,28 @@ impl AuthService {
/// Creates the first admin. Bad input does not burn the code. The result /// Creates the first admin. Bad input does not burn the code. The result
/// is an enrollment-stage pending token: there is no session until MFA. /// is an enrollment-stage pending token: there is no session until MFA.
///
/// Anyone can call this, so it must not let them grow the audit log: once
/// an admin exists the refusal writes nothing, and before that wrong codes
/// are limited per IP.
pub fn complete_bootstrap( pub fn complete_bootstrap(
&self, &self,
code: &str, code: &str,
username: &str, username: &str,
password: &str, password: &str,
ip: IpAddr,
now: u64, now: u64,
) -> Result<PendingMfa> { ) -> Result<PendingMfa> {
if self.has_admin()? {
return Err(AuthFailure::BootstrapInvalid.into());
}
let name = validate_username(username)?; let name = validate_username(username)?;
validate_password(password)?; validate_password(password)?;
self.ips.acquire(ip, now).map_err(throttled)?;
let code_hash = hash_token(code); let code_hash = hash_token(code);
// Checked first so a wrong code costs no Argon2 work. // Checked first so a wrong code costs no Argon2 work.
if !self.store.read(|st| bootstrap_valid(st, &code_hash, now))? { if !self.store.read(|st| bootstrap_valid(st, &code_hash, now))? {
self.log("bootstrap.complete", None, None, false, None)?; return self.refuse_bootstrap(ip);
return Err(AuthFailure::BootstrapInvalid.into());
} }
let password_hash = hash_password(password)?; let password_hash = hash_password(password)?;
// Checked and consumed in one closure: concurrent requests get one win. // Checked and consumed in one closure: concurrent requests get one win.
@@ -360,13 +368,21 @@ impl AuthService {
Ok(Some(self.seal_pending(&id, 0, PENDING_PURPOSE, now)?)) Ok(Some(self.seal_pending(&id, 0, PENDING_PURPOSE, now)?))
})?; })?;
let Some(pending) = done else { let Some(pending) = done else {
self.log("bootstrap.complete", None, None, false, None)?; return self.refuse_bootstrap(ip);
return Err(AuthFailure::BootstrapInvalid.into());
}; };
self.log("bootstrap.complete", Some(&name), None, true, None)?; self.ips.release(ip);
self.log("bootstrap.complete", Some(&name), Some(ip), true, None)?;
Ok(pending) Ok(pending)
} }
/// Losing a race to the first admin is not worth an audit line either.
fn refuse_bootstrap(&self, ip: IpAddr) -> Result<PendingMfa> {
if !self.has_admin()? {
self.log("bootstrap.complete", None, Some(ip), false, None)?;
}
Err(AuthFailure::BootstrapInvalid.into())
}
fn seal_pending( fn seal_pending(
&self, &self,
user_id: &str, user_id: &str,
+11 -11
View File
@@ -69,7 +69,7 @@ fn enroll(s: &AuthService, id: &str, now: u64) -> Vec<String> {
/// First admin, enrolled. Returns its id. /// First admin, enrolled. Returns its id.
fn admin(s: &AuthService) -> String { fn admin(s: &AuthService) -> String {
let code = s.ensure_bootstrap(T0).unwrap().unwrap(); let code = s.ensure_bootstrap(T0).unwrap().unwrap();
s.complete_bootstrap(&code, "root", PW, T0).unwrap(); s.complete_bootstrap(&code, "root", PW, ip(), T0).unwrap();
let id = uid(s, "root"); let id = uid(s, "root");
enroll(s, &id, T0); enroll(s, &id, T0);
id id
@@ -106,16 +106,16 @@ fn bootstrap_code_single_use_and_expires() {
); );
assert_eq!( assert_eq!(
failure(s.complete_bootstrap("wrong", "root", PW, T0)), failure(s.complete_bootstrap("wrong", "root", PW, ip(), T0)),
AuthFailure::BootstrapInvalid AuthFailure::BootstrapInvalid
); );
assert_eq!( assert_eq!(
failure(s.complete_bootstrap(&code, "root", PW, T0 + 3601)), failure(s.complete_bootstrap(&code, "root", PW, ip(), T0 + 3601)),
AuthFailure::BootstrapInvalid AuthFailure::BootstrapInvalid
); );
// A weak password does not burn the code. // A weak password does not burn the code.
assert!(matches!( assert!(matches!(
s.complete_bootstrap(&code, "root", "short", T0) s.complete_bootstrap(&code, "root", "short", ip(), T0)
.unwrap_err(), .unwrap_err(),
AcauaError::InvalidInput(_) AcauaError::InvalidInput(_)
)); ));
@@ -123,13 +123,13 @@ fn bootstrap_code_single_use_and_expires() {
let renewed = s.ensure_bootstrap(T0 + 10).unwrap().unwrap(); let renewed = s.ensure_bootstrap(T0 + 10).unwrap().unwrap();
assert_ne!(renewed, code); assert_ne!(renewed, code);
assert_eq!( assert_eq!(
failure(s.complete_bootstrap(&code, "root", PW, T0 + 10)), failure(s.complete_bootstrap(&code, "root", PW, ip(), T0 + 10)),
AuthFailure::BootstrapInvalid AuthFailure::BootstrapInvalid
); );
s.complete_bootstrap(&renewed, "root", PW, T0 + 3610) s.complete_bootstrap(&renewed, "root", PW, ip(), T0 + 3610)
.unwrap(); .unwrap();
assert_eq!( assert_eq!(
failure(s.complete_bootstrap(&renewed, "other", PW, T0 + 3610)), failure(s.complete_bootstrap(&renewed, "other", PW, ip(), T0 + 3610)),
AuthFailure::BootstrapInvalid AuthFailure::BootstrapInvalid
); );
assert_eq!(s.ensure_bootstrap(T0 + 3620).unwrap(), None); assert_eq!(s.ensure_bootstrap(T0 + 3620).unwrap(), None);
@@ -145,7 +145,7 @@ fn bootstrap_code_is_consumed_once_under_concurrency() {
.map(|i| { .map(|i| {
let (s, code) = (&s, &code); let (s, code) = (&s, &code);
sc.spawn(move || { sc.spawn(move || {
s.complete_bootstrap(code, &format!("adm{i}"), PW, T0) s.complete_bootstrap(code, &format!("adm{i}"), PW, ip(), T0)
.is_ok() .is_ok()
}) })
}) })
@@ -163,7 +163,7 @@ fn bootstrap_code_is_consumed_once_under_concurrency() {
fn admin_cannot_finish_login_without_mfa() { fn admin_cannot_finish_login_without_mfa() {
let (_d, s) = svc(); let (_d, s) = svc();
let code = s.ensure_bootstrap(T0).unwrap().unwrap(); let code = s.ensure_bootstrap(T0).unwrap().unwrap();
let boot = s.complete_bootstrap(&code, "root", PW, T0).unwrap(); let boot = s.complete_bootstrap(&code, "root", PW, ip(), T0).unwrap();
let id = uid(&s, "root"); let id = uid(&s, "root");
let LoginStep::MfaEnrollRequired(p) = s.login("root", PW, ip(), T0).unwrap() else { let LoginStep::MfaEnrollRequired(p) = s.login("root", PW, ip(), T0).unwrap() else {
panic!("admin must enroll"); panic!("admin must enroll");
@@ -712,7 +712,7 @@ fn session_of_any(s: &AuthService, id: &str) {
fn audit_records_operations_without_secrets() { fn audit_records_operations_without_secrets() {
let (_d, s) = svc(); let (_d, s) = svc();
let code = s.ensure_bootstrap(T0).unwrap().unwrap(); let code = s.ensure_bootstrap(T0).unwrap().unwrap();
s.complete_bootstrap(&code, "root", PW, T0).unwrap(); s.complete_bootstrap(&code, "root", PW, ip(), T0).unwrap();
let id = uid(&s, "root"); let id = uid(&s, "root");
let codes = enroll(&s, &id, T0); let codes = enroll(&s, &id, T0);
// A password typed into the username field must not reach the log. // A password typed into the username field must not reach the log.
@@ -950,7 +950,7 @@ fn change_password_clears_flag_and_refuses_the_same_password() {
fn first_admin(s: &AuthService) -> PendingMfa { fn first_admin(s: &AuthService) -> PendingMfa {
let code = s.ensure_bootstrap(T0).unwrap().unwrap(); let code = s.ensure_bootstrap(T0).unwrap().unwrap();
s.complete_bootstrap(&code, "root", PW, T0).unwrap() s.complete_bootstrap(&code, "root", PW, ip(), T0).unwrap()
} }
fn root_id(s: &AuthService) -> String { fn root_id(s: &AuthService) -> String {
+1 -1
View File
@@ -607,7 +607,7 @@ mod tests {
/// Bootstraps `root` (admin, MFA enrolled). /// Bootstraps `root` (admin, MFA enrolled).
fn root(s: &AuthService) -> String { fn root(s: &AuthService) -> String {
let code = s.ensure_bootstrap(T0).unwrap().unwrap(); let code = s.ensure_bootstrap(T0).unwrap().unwrap();
s.complete_bootstrap(&code, "root", PW, T0).unwrap(); s.complete_bootstrap(&code, "root", PW, ip(), T0).unwrap();
let id = uid(s, "root"); let id = uid(s, "root");
enroll(s, &id, T0); enroll(s, &id, T0);
id id