feat(auth): cap login guessing with a per-account budget

Failures from unknown addresses are capped at 100 per rolling 24 hours per
username, refused before Argon2 and before the hashing queue. Addresses with
a completed login in the last 30 days skip the budget, stored hashed on the
user. IPv6 counts per /48 for the pair throttle and the budget. Unknown names
take the same path, with their budget in the stand-in table. Crossing the cap
audits login.budget_exhausted once per account per 24 hours. Eviction drops
faded entries, then the least counted, not the oldest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas RayanandClaude Opus 5.5 committed 2026-11-05 06:27:38 -03:00
1 parent d48cf9d3f0
commit b9137e0948
7 files changed
+1128 -206

No files matched your search

+101
View File
@@ -86,6 +86,20 @@ fn fresh(transport: Transport) -> (tempfile::TempDir, Arc<AuthService>, Router)
(dir, auth, build_app(state))
}
fn fresh_with_state(
transport: Transport,
) -> (tempfile::TempDir, Arc<AuthService>, AppState, Router) {
let dir = tempfile::tempdir().unwrap();
let auth = Arc::new(AuthService::open(dir.path(), None).unwrap());
let state = AppState::new(
Arc::new(Storage::open(dir.path()).unwrap()),
auth.clone(),
transport,
);
let app = build_app(state.clone());
(dir, auth, state, app)
}
/// Server with `root` (admin, MFA active) and analyst `ana` (no MFA).
fn harness(transport: Transport) -> H {
let (dir, auth, app) = fresh(transport);
@@ -1180,3 +1194,90 @@ async fn auth_state_tells_whether_mfa_is_on() {
let on = send(&h.app, state(&cookie)).await;
assert_eq!(on.json()["mfa_enabled"], serde_json::json!(true));
}
async fn login_from(app: &Router, peer: IpAddr, user: &str, pw: &str) -> Reply {
let mut r = post_json(
"/api/auth/login",
serde_json::json!({"username": user, "password": pw}),
);
r.extensions_mut()
.insert(axum::extract::ConnectInfo(SocketAddr::new(peer, 4000)));
send(app, r).await
}
fn v4_peer(i: u32) -> IpAddr {
IpAddr::V4(std::net::Ipv4Addr::from(0x0a00_0000 + i))
}
fn spend_budget(auth: &AuthService, user: &str, n: u32, t: u64) {
for i in 0..n {
let attempt = auth.login_begin(user, v4_peer(i), t).unwrap();
let _ = auth.login_failed(attempt, t);
}
}
#[tokio::test]
async fn a_refused_login_takes_no_hashing_permit() {
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", 100, now());
let held = state
.argon2
.clone()
.acquire_many_owned(crate::auth_http::ARGON2_CONCURRENCY as u32)
.await
.unwrap();
let refused = tokio::time::timeout(
std::time::Duration::from_secs(5),
login_from(&app, v4_peer(500), "ana", PW),
)
.await
.expect("a refusal must not wait for a permit");
assert_eq!(refused.status, StatusCode::TOO_MANY_REQUESTS);
assert!(refused.headers.contains_key(header::RETRY_AFTER));
// An attempt that can still succeed does wait for one.
let waits = tokio::time::timeout(
std::time::Duration::from_millis(300),
login_from(&app, v4_peer(501), "root", PW),
)
.await;
assert!(waits.is_err());
drop(held);
// That cancelled attempt gave back what it held.
assert_eq!(
login_from(&app, v4_peer(501), "root", PW).await.status,
StatusCode::OK
);
}
#[tokio::test]
async fn parallel_requests_stop_at_the_cap() {
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", 96, now());
let mut tasks = Vec::new();
for i in 0..16 {
let app = app.clone();
tasks.push(tokio::spawn(async move {
login_from(&app, v4_peer(1000 + i), "ana", PW2).await.status
}));
}
let mut wrong = 0;
let mut refused = 0;
for t in tasks {
match t.await.unwrap() {
StatusCode::UNAUTHORIZED => wrong += 1,
StatusCode::TOO_MANY_REQUESTS => refused += 1,
other => panic!("{other}"),
}
}
assert_eq!((wrong, refused), (4, 12));
}