fix(auth): keep a queued login from passing the cap

A reservation could expire while its request queued, and the guess was then
evaluated anyway. The wait for a hashing permit is now bounded to 30 s, and an
attempt whose reservation is gone is refused at permit time. At the cap, each
failure now reaches the disk, so a restart cannot reopen a slot.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas RayanandClaude Opus 5.5 committed 2026-11-05 07:01:16 -03:00
1 parent 4a48f2bd35
commit 9ef86ac425
5 files changed
+238 -67

No files matched your search

+37 -12
View File
@@ -7,8 +7,8 @@
use crate::web::{access_of, is_public, is_public_asset, Access, AppState};
use acaua_core::auth::{
csrf_matches, csrf_token, AuthService, LoginAttempt, NewSession, PendingMfa, Principal, Role,
Scope, TotpEnrollment, Via,
csrf_matches, csrf_token, AuthService, LoginAttempt, LoginStep, NewSession, PendingMfa,
Principal, Role, Scope, TotpEnrollment, Via,
};
use acaua_core::{AcauaError, AuthFailure};
use axum::extract::rejection::JsonRejection;
@@ -22,7 +22,7 @@ use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
pub const MAX_BODY_BYTES: usize = 64 * 1024;
pub const ARGON2_CONCURRENCY: usize = 8;
@@ -32,6 +32,8 @@ const PENDING_HEADER: &str = "x-acaua-pending";
const LOGIN_PAGE: &str = "/login.html";
const AUDIT_DEFAULT: usize = 200;
const AUDIT_MAX: usize = 1000;
/// The longest a login waits for a hashing permit.
const LOGIN_QUEUE_WAIT: Duration = Duration::from_secs(30);
/// A clock before 1970 fails closed: everything looks expired.
pub fn unix_now() -> u64 {
@@ -551,7 +553,7 @@ pub async fn login(
// or a flood of hopeless attempts would stand in front of the owner.
let auth = state.auth.clone();
let username = b.username;
let mut queued = blocking(move || {
let queued = blocking(move || {
let attempt = auth.login_begin(&username, ip, now)?;
Ok(QueuedLogin {
auth,
@@ -559,23 +561,46 @@ pub async fn login(
})
})
.await?;
let password = b.password;
let step = hashing(&state, move || {
let step = finish_queued(&state, queued, b.password, LOGIN_QUEUE_WAIT).await?;
Ok(step_reply(&state, &step))
}
/// Evaluates a queued login once a permit is free. Past `wait` it is refused
/// like any other throttled attempt, and gives back what it reserved.
pub(crate) async fn finish_queued(
state: &AppState,
mut queued: QueuedLogin,
password: String,
wait: Duration,
) -> Result<LoginStep, ApiError> {
// Only the queue is timed: once the hash runs, it runs to its answer. Leaving
// here drops `queued`, which gives back what the attempt reserved.
let permit = match tokio::time::timeout(wait, state.argon2.clone().acquire_owned()).await {
Ok(permit) => permit.map_err(|_| internal())?,
Err(_) => {
return Err(AuthFailure::Throttled {
retry_after_secs: wait.as_secs().max(1),
}
.into())
}
};
blocking(move || {
let _permit = permit;
let attempt = queued
.attempt
.take()
.ok_or(AuthFailure::InvalidCredentials)?;
queued.auth.login_finish(attempt, &password, now)
// The clock now, not at arrival: the queue took time.
queued.auth.login_finish(attempt, &password, unix_now())
})
.await?;
Ok(step_reply(&state, &step))
.await
}
/// A login between its checks and its evaluation. A client that disconnects
/// while queued made no guess, so what it reserved goes back.
struct QueuedLogin {
auth: Arc<AuthService>,
attempt: Option<LoginAttempt>,
pub(crate) struct QueuedLogin {
pub(crate) auth: Arc<AuthService>,
pub(crate) attempt: Option<LoginAttempt>,
}
impl Drop for QueuedLogin {
+47
View File
@@ -1281,3 +1281,50 @@ async fn parallel_requests_stop_at_the_cap() {
}
assert_eq!((wrong, refused), (4, 12));
}
#[tokio::test]
async fn a_login_stuck_in_the_queue_is_refused_and_gives_back_its_reservation() {
let (_d, auth, state, _app) = fresh_with_state(Transport::Local);
let code = auth.ensure_bootstrap(now()).unwrap().unwrap();
auth.complete_bootstrap(&code, "root", PW, peer(), now())
.unwrap();
auth.create_user("root", "ana", PW, Role::Analyst, now())
.unwrap();
spend_budget(&auth, "ana", 99, now());
let queued = crate::auth_http::QueuedLogin {
auth: auth.clone(),
attempt: Some(auth.login_begin("ana", v4_peer(700), now()).unwrap()),
};
assert!(
auth.login_begin("ana", v4_peer(701), now()).is_err(),
"full"
);
let held = state
.argon2
.clone()
.acquire_many_owned(crate::auth_http::ARGON2_CONCURRENCY as u32)
.await
.unwrap();
let done = tokio::time::timeout(
std::time::Duration::from_secs(5),
crate::auth_http::finish_queued(
&state,
queued,
PW.to_string(),
std::time::Duration::from_millis(50),
),
)
.await
.expect("the wait is bounded");
let Err(error) = done else {
panic!("expected a refusal")
};
let reply = error.into_response();
assert_eq!(reply.status(), StatusCode::TOO_MANY_REQUESTS);
assert!(reply.headers().contains_key(header::RETRY_AFTER));
drop(held);
assert!(
auth.login_begin("ana", v4_peer(702), now()).is_ok(),
"returned"
);
}