//! In-memory sliding-window failure counters that slow down password guessing. //! //! Each key keeps the instants of its recent failures, and is limited while it has `limit` of them //! inside [`WINDOW`]. An attempt first asks [`Throttle::reserve`], which counts it before the work //! is done and answers with the wait when the key is already limited. A success gives the count back //! with [`Throttle::refund`] (or drops the key with [`Throttle::clear`] where the old failures go too). //! Check and count are one step under one lock, so parallel attempts cannot all pass together. //! //! Memory is bounded. Expired instants and empty keys are pruned every few hundred attempts. At the key //! cap, expired keys go first; then the key whose latest failure is oldest is evicted, but never a key //! that is limited right now. When every key is limited, a new key is refused: fail closed. //! //! Email keys are capped too. An address that is too long or not plausible shares one fixed key, so a //! flood of junk addresses cannot grow the map or the key size. //! //! Each [`Throttle`] has one window for all its keys. The failure counters use [`WINDOW`]; the per-minute //! and per-hour counters of the OAuth endpoints and the account pages are separate instances, built with //! [`Throttle::per_minute`] and [`Throttle::email_changes`]. //! //! The counters live in one process. A restart clears them, and two processes would each count //! their own. `im` runs as one process, so this is the whole picture. use std::collections::{HashMap, VecDeque}; use std::net::IpAddr; use std::sync::{Mutex, MutexGuard}; use std::time::{Duration, Instant}; use im_core::names::parse_email; /// Length of the failure window. pub const WINDOW: Duration = Duration::from_secs(15 * 60); /// Failed sign-ins allowed per normalised email address inside [`WINDOW`]. Also counts wrong /// passwords on the security page, so guessing there locks sign-in too. pub const LOGIN_USER_LIMIT: usize = 10; /// Failed sign-ins allowed per client address inside [`WINDOW`]. pub const LOGIN_IP_LIMIT: usize = 30; /// Failed second-factor checks allowed per user inside [`WINDOW`]. pub const TWO_FACTOR_USER_LIMIT: usize = 10; /// Failed second-factor checks allowed per user inside [`TWO_FACTOR_DAY_WINDOW`]. It works beside /// [`TWO_FACTOR_USER_LIMIT`], so a guesser who pauses between windows still runs out. pub const TWO_FACTOR_DAY_LIMIT: usize = 30; /// Length of the second-factor day window: 24 hours. Kept on its own [`Throttle`] (see /// [`Throttle::two_factor_days`]), because a throttle has one window for all its keys. pub const TWO_FACTOR_DAY_WINDOW: Duration = Duration::from_secs(24 * 60 * 60); /// Reset-link requests allowed per normalised email address inside [`WINDOW`]. Every request counts, known /// address or not, so the limit leaks nothing about the account. pub const FORGOT_EMAIL_LIMIT: usize = 3; /// Reset-link requests allowed per client address inside [`WINDOW`]. pub const FORGOT_IP_LIMIT: usize = 20; /// Profile photo uploads allowed per account inside [`PHOTO_UPLOAD_WINDOW`]. Every upload counts, whether /// or not its picture is accepted, because each one costs a decode. pub const PHOTO_UPLOAD_LIMIT: usize = 10; /// Length of the photo upload window: one hour. Kept on its own [`Throttle`] (see /// [`Throttle::photo_uploads`]), because a throttle has one window for all its keys. pub const PHOTO_UPLOAD_WINDOW: Duration = Duration::from_secs(60 * 60); /// Length of the per-minute window of the OAuth endpoints and the audit of failed sign-ins. pub const MINUTE: Duration = Duration::from_secs(60); /// Length of the window of email-change requests: one hour. pub const EMAIL_CHANGE_WINDOW: Duration = Duration::from_secs(60 * 60); /// Email-change requests allowed per account inside [`EMAIL_CHANGE_WINDOW`]. Each one mails two addresses. pub const EMAIL_CHANGE_LIMIT: usize = 3; /// Code issuances allowed per browser session inside [`MINUTE`] at `/authorize`. A refused one is answered /// with the `temporarily_unavailable` redirect. pub const AUTHORIZE_SESSION_LIMIT: usize = 60; /// Requests allowed per authenticated client inside [`MINUTE`] at `/token`, over all its grants together. /// A client with many users shares this ceiling, so it is set well above one person's use. pub const TOKEN_CLIENT_LIMIT: usize = 1200; /// Requests allowed inside [`MINUTE`] for one refresh-token family, or for one authorization code, at /// `/token`. One person uses one chain or one code, so this is what limits a flood on a single one. pub const TOKEN_CHAIN_LIMIT: usize = 30; /// `LoginFailed` audit rows written per typed address inside [`MINUTE`], whether or not an account has that /// address, so the work done for a failure does not show which. Failures beyond it are still refused and /// counted; only their audit rows are skipped. pub const LOGIN_AUDIT_LIMIT: usize = 1; /// Maximum number of distinct keys tracked at once. A flood of random keys cannot grow memory past /// this. const MAX_KEYS: usize = 100_000; /// A full prune runs every this many attempts. const PRUNE_EVERY: u32 = 256; /// The part of an email key used for an address that is not plausible. Starts with `<`, which no valid /// address contains, so it never collides with a real address. const INVALID_ADDRESS: &str = ""; /// The most bytes of a raw, unparseable address that go into its key. Longer input is cut here, so the /// key stays bounded. const MAX_RAW_ADDRESS_BYTES: usize = 320; /// The failure counters of the process. Shared by every request through the app state. pub struct Throttle { window: Duration, max_keys: usize, state: Mutex, } #[derive(Default)] struct State { failures: HashMap, attempts: u32, } /// The failures of one key, and the limit they were counted against. struct Entry { stamps: VecDeque, limit: usize, } impl Default for Throttle { fn default() -> Self { Self::with_limits(WINDOW, MAX_KEYS) } } impl Throttle { /// The counters of profile photo uploads: one hour window, the same key cap. pub fn photo_uploads() -> Self { Self::with_limits(PHOTO_UPLOAD_WINDOW, MAX_KEYS) } /// The per-minute counters: `/authorize` per session, `/token` per client, and the audit of failed /// sign-ins. One minute window, the same key cap. pub fn per_minute() -> Self { Self::with_limits(MINUTE, MAX_KEYS) } /// The counters of email-change requests: one hour window, the same key cap. pub fn email_changes() -> Self { Self::with_limits(EMAIL_CHANGE_WINDOW, MAX_KEYS) } /// The day-long counters of second-factor checks: 24 hour window, the same key cap. pub fn two_factor_days() -> Self { Self::with_limits(TWO_FACTOR_DAY_WINDOW, MAX_KEYS) } /// Counters with a custom window and key cap. Tests use short windows. pub fn with_limits(window: Duration, max_keys: usize) -> Self { Self { window, max_keys: max_keys.max(1), state: Mutex::new(State::default()), } } /// Counts one attempt of `key` now, before the work is done. When the key already has `limit` /// failures inside the window, nothing is counted and the wait until it may try again comes back /// (at least one second when it is the key cap that refuses a new key). pub fn reserve(&self, key: &str, limit: usize, now: Instant) -> Result<(), Duration> { self.reserve_all(&[(key, limit)], now) } /// Counts one attempt against every key, or against none. All keys are checked under one lock. When /// one of them refuses, the keys already counted are given back, and the longest wait comes back. pub fn reserve_all(&self, keys: &[(&str, usize)], now: Instant) -> Result<(), Duration> { let mut state = self.lock(); state.attempts = state.attempts.wrapping_add(1); if state.attempts.is_multiple_of(PRUNE_EVERY) { self.prune_locked(&mut state, now); } let mut admitted = Vec::with_capacity(keys.len()); let mut wait: Option = None; for &(key, limit) in keys { match self.reserve_locked(&mut state, key, limit, now) { Ok(()) => admitted.push(key), Err(due) => wait = Some(wait.map_or(due, |longest| longest.max(due))), } } match wait { None => Ok(()), Some(due) => { for key in admitted { self.refund_locked(&mut state, key); } Err(due) } } } /// Takes back the newest counted attempt of `key`, for an attempt that succeeded. pub fn refund(&self, key: &str) { self.refund_locked(&mut self.lock(), key); } /// Forgets the failures of `key`, after a success. pub fn clear(&self, key: &str) { self.lock().failures.remove(key); } /// Counts one attempt of `key` under `limit`, with the lock already held. fn reserve_locked( &self, state: &mut State, key: &str, limit: usize, now: Instant, ) -> Result<(), Duration> { if !state.failures.contains_key(key) && state.failures.len() >= self.max_keys && !self.make_room_locked(state, now) { // Every key is limited right now: the new one is refused, which is the fail-closed answer. return Err(self.window); } let entry = state .failures .entry(key.to_owned()) .or_insert_with(|| Entry { stamps: VecDeque::new(), limit, }); entry.limit = limit; drop_expired(&mut entry.stamps, self.window, now); if entry.stamps.len() >= limit { return Err(wait_for(&entry.stamps, limit, self.window, now)); } entry.stamps.push_back(now); Ok(()) } /// Gives back the newest failure of `key`, and drops the key when nothing is left. fn refund_locked(&self, state: &mut State, key: &str) { let emptied = match state.failures.get_mut(key) { Some(entry) => { entry.stamps.pop_back(); entry.stamps.is_empty() } None => false, }; if emptied { state.failures.remove(key); } } /// Frees one slot for a new key. Expired failures go first. Then the key whose latest failure is the /// oldest is removed, but only among keys that are not limited now. Returns false when every key is /// limited, so nothing can be removed. fn make_room_locked(&self, state: &mut State, now: Instant) -> bool { let window = self.window; state.failures.retain(|_, entry| { drop_expired(&mut entry.stamps, window, now); !entry.stamps.is_empty() }); if state.failures.len() < self.max_keys { return true; } let victim = state .failures .iter() .filter(|(_, entry)| entry.stamps.len() < entry.limit) .min_by_key(|(_, entry)| entry.stamps.back().copied()) .map(|(key, _)| key.clone()); match victim { Some(key) => { state.failures.remove(&key); true } None => false, } } /// Drops expired failures and the keys left empty. fn prune_locked(&self, state: &mut State, now: Instant) { let window = self.window; state.failures.retain(|_, entry| { drop_expired(&mut entry.stamps, window, now); !entry.stamps.is_empty() }); } fn lock(&self) -> MutexGuard<'_, State> { // A poisoned lock still holds consistent counters, so the next caller uses it as it is. self.state.lock().unwrap_or_else(|e| e.into_inner()) } } /// Removes the failures that have left the window. fn drop_expired(timestamps: &mut VecDeque, window: Duration, now: Instant) { while let Some(front) = timestamps.front() { if now.saturating_duration_since(*front) < window { break; } timestamps.pop_front(); } } /// The wait until `stamps` drops below `limit` failures: the failure at this index is the last one to /// leave the window before the count does. fn wait_for(stamps: &VecDeque, limit: usize, window: Duration, now: Instant) -> Duration { let Some(index) = stamps.len().checked_sub(limit) else { return Duration::ZERO; }; stamps.get(index).map_or(Duration::ZERO, |oldest| { (*oldest + window).saturating_duration_since(now) }) } /// The part of an email key for `email`: the address itself when it is plausible, otherwise the marker /// and the raw text, trimmed, lowercased and cut to [`MAX_RAW_ADDRESS_BYTES`]. Each junk address gets its /// own key, so one junk address cannot lock out a real account whose stored address happens to be /// unparseable under the current rules. fn address_part(email: &str) -> String { match parse_email(email) { Ok(address) => address, Err(_) => { let raw = email.trim().to_lowercase(); // Cut on a character boundary at or below the cap. let cut = (0..=raw.len().min(MAX_RAW_ADDRESS_BYTES)) .rev() .find(|&i| raw.is_char_boundary(i)) .unwrap_or(0); format!("{INVALID_ADDRESS}{}", &raw[..cut]) } } } /// Throttle key for a normalised email address. pub fn user_key(email: &str) -> String { format!("user:{}", address_part(email)) } /// Throttle key for the reset-link requests of one normalised address. pub fn forgot_email_key(email: &str) -> String { format!("forgot:{}", address_part(email)) } /// Throttle key for the photo uploads of one user, by user id. pub fn photo_upload_key(user_id: &str) -> String { format!("photo:{user_id}") } /// Throttle key for the second factor of one user, by user id. pub fn two_factor_key(user_id: &str) -> String { format!("2fa:{user_id}") } /// Throttle key for the email-change requests of one user, by user id. pub fn email_change_key(user_id: &str) -> String { format!("email-change:{user_id}") } /// Throttle key for the code issuances of one browser session, by session id. pub fn authorize_session_key(session_id: &str) -> String { format!("authorize:{session_id}") } /// Throttle key for the token requests of one client, by client id. pub fn token_client_key(client_id: &str) -> String { format!("token:{client_id}") } /// Throttle key for the refresh requests of one token family (one chain) of a client. pub fn token_family_key(client_id: &str, family_id: &str) -> String { format!("token-family:{client_id}:{family_id}") } /// Throttle key for the code exchanges of one authorization code of a client, by the code's hash. pub fn token_code_key(client_id: &str, code_hash: &str) -> String { format!("token-code:{client_id}:{code_hash}") } /// Throttle key for the `LoginFailed` audit rows of one normalised address. Its own key, not the sign-in /// counter of the address, so the audit rows do not use up the sign-in attempts. pub fn login_audit_key(email: &str) -> String { format!("login-audit:{}", address_part(email)) } /// Throttle key for an address under a named scope, such as `login-ip`. pub fn ip_key(scope: &str, ip: IpAddr) -> String { format!("{scope}:{ip}") } #[cfg(test)] mod tests { use super::*; use std::sync::Arc; #[test] fn a_key_is_limited_at_the_threshold_and_free_when_the_window_passes() { let throttle = Throttle::with_limits(Duration::from_secs(60), 16); let t0 = Instant::now(); for i in 0..3 { let at = t0 + Duration::from_secs(i); assert!(throttle.reserve("k", 3, at).is_ok()); } let retry = throttle .reserve("k", 3, t0 + Duration::from_secs(10)) .expect_err("limited"); assert_eq!(retry, Duration::from_secs(50)); assert!( throttle .reserve("k", 3, t0 + Duration::from_secs(60)) .is_ok() ); } /// Twenty parallel wrong-password attempts against one key: only the limit's worth is counted and /// admitted, and the rest are refused. Check and count are one step, so none can slip past. #[test] fn parallel_reservations_admit_no_more_than_the_limit() { let throttle = Arc::new(Throttle::with_limits(WINDOW, MAX_KEYS)); let handles: Vec<_> = (0..20) .map(|_| { let throttle = Arc::clone(&throttle); std::thread::spawn(move || { throttle .reserve("login", LOGIN_USER_LIMIT, Instant::now()) .is_ok() }) }) .collect(); let admitted = handles .into_iter() .map(|handle| handle.join().expect("attempt thread")) .filter(|ok| *ok) .count(); assert_eq!(admitted, LOGIN_USER_LIMIT); } #[test] fn the_key_count_stays_at_the_cap() { let throttle = Throttle::with_limits(Duration::from_secs(10), 8); let t0 = Instant::now(); for i in 0..1000u64 { let _ = throttle.reserve(&format!("key-{i}"), 2, t0 + Duration::from_millis(i)); assert!(throttle.lock().failures.len() <= 8); } } }