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:
1 parent
2b1bc63340
commit
5ad89d5be5
6 files changed
+218
-39
No files matched your search
@@ -359,6 +359,15 @@ async fn gate(
|
||||
}
|
||||
}
|
||||
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 {
|
||||
@@ -496,12 +505,13 @@ pub struct BootstrapBody {
|
||||
|
||||
pub async fn bootstrap(
|
||||
State(state): State<AppState>,
|
||||
Extension(ClientIp(ip)): Extension<ClientIp>,
|
||||
JsonBody(b): JsonBody<BootstrapBody>,
|
||||
) -> Result<Response, ApiError> {
|
||||
let auth = state.auth.clone();
|
||||
let now = unix_now();
|
||||
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?;
|
||||
Ok(pending_reply("mfa_enroll_required", &pending))
|
||||
@@ -818,7 +828,7 @@ pub async fn tokens_revoke(
|
||||
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> {
|
||||
let auth = state.auth.clone();
|
||||
|
||||
+23
-18
@@ -90,6 +90,9 @@ pub enum Access {
|
||||
SessionOrPending,
|
||||
/// Administrator role, and Admin scope when through a token.
|
||||
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 {
|
||||
@@ -117,7 +120,7 @@ const fn route(
|
||||
/// entries also in `PUBLIC_ROUTES` is never consulted.
|
||||
pub const ALL_ROUTES: &[RouteDef] = {
|
||||
use auth_http as a;
|
||||
use Access::{Admin, Authenticated, Session, SessionOrPending};
|
||||
use Access::{Admin, AdminRecentSession, Authenticated, Session, SessionOrPending};
|
||||
use Verb::{Delete, Get, Patch, Post};
|
||||
&[
|
||||
route(Get, "/api/health", Authenticated, || get(health)),
|
||||
@@ -167,11 +170,13 @@ pub const ALL_ROUTES: &[RouteDef] = {
|
||||
delete(a::tokens_revoke)
|
||||
}),
|
||||
route(Get, "/api/admin/users", Admin, || get(a::users_list)),
|
||||
route(Post, "/api/admin/users", Admin, || post(a::users_create)),
|
||||
route(Patch, "/api/admin/users", Admin, || {
|
||||
route(Post, "/api/admin/users", AdminRecentSession, || {
|
||||
post(a::users_create)
|
||||
}),
|
||||
route(Patch, "/api/admin/users", AdminRecentSession, || {
|
||||
patch(a::users_set_role)
|
||||
}),
|
||||
route(Delete, "/api/admin/users", Admin, || {
|
||||
route(Delete, "/api/admin/users", AdminRecentSession, || {
|
||||
delete(a::users_delete)
|
||||
}),
|
||||
route(Get, "/api/admin/audit", Admin, || get(a::audit)),
|
||||
@@ -255,6 +260,18 @@ struct AnalyzeRequest {
|
||||
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> {
|
||||
Json(Health { status: "ok" })
|
||||
}
|
||||
@@ -295,13 +312,7 @@ async fn analyze(
|
||||
*state.report() = Some(report.clone());
|
||||
Json(report).into_response()
|
||||
}
|
||||
Ok(Err(error)) => (
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(ErrorBody {
|
||||
error: error.to_string(),
|
||||
}),
|
||||
)
|
||||
.into_response(),
|
||||
Ok(Err(error)) => failure(StatusCode::BAD_REQUEST, "analysis failed", &error),
|
||||
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;
|
||||
match outcome {
|
||||
Ok(Ok(status)) => Json::<UpdateStatus>(status).into_response(),
|
||||
Ok(Err(error)) => (
|
||||
StatusCode::BAD_GATEWAY,
|
||||
Json(ErrorBody {
|
||||
error: error.to_string(),
|
||||
}),
|
||||
)
|
||||
.into_response(),
|
||||
Ok(Err(error)) => failure(StatusCode::BAD_GATEWAY, "update check failed", &error),
|
||||
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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"}"#);
|
||||
}
|
||||
Reference in new issue
Block a user