//! Failure throttling in memory: a sliding window of failures per key, with a bounded number of keys. //! //! An attempt first asks [`Throttle::reserve`], which counts it as a failure and answers `429` with //! `Retry-After` when the key has reached its limit. A success gives the count back with //! [`Throttle::refund`]. Check and count are one step, so parallel attempts cannot pass together. //! Nothing is persisted, so a restart forgets the failures; that is accepted for a family instance and documented in the backlog. //! //! The key count is capped. When a new key would exceed the cap, the windows that have expired are //! dropped first, and then the key whose last failure is oldest. So an attacker who spreads guesses over //! many keys can only evict other keys, never grow the memory. use std::collections::HashMap; use std::sync::{Mutex, MutexGuard, PoisonError}; use std::time::{Duration, Instant}; /// Length of the sliding window for share-link passwords: 15 minutes. pub const PASSWORD_WINDOW: Duration = Duration::from_secs(15 * 60); /// Failed password attempts allowed against one link in a window, from all visitors together. This is a /// ceiling: it stops guesses spread over many addresses. The 101st is refused with `429`. pub const LINK_PASSWORD_LIMIT: usize = 100; /// Failed password attempts allowed from one client address against one link in a window. The eleventh is /// refused with `429`. Other visitors of the same link have their own count. pub const VISITOR_PASSWORD_LIMIT: usize = 10; /// Most keys held at once. Each key is a short string and a short list of instants. pub const MAX_KEYS: usize = 10_000; /// Failures per key within a sliding window, with a cap on the number of keys. pub struct Throttle { failures: Mutex>>, window: Duration, limit: usize, max_keys: usize, } impl Throttle { /// A throttle that blocks a key after `limit` failures within `window`. pub fn new(window: Duration, limit: usize, max_keys: usize) -> Self { Self { failures: Mutex::new(HashMap::new()), window, limit, max_keys, } } /// Locks the map. A poisoned lock is used as it is: a panic elsewhere must not open the throttle. fn map(&self) -> MutexGuard<'_, HashMap>> { self.failures.lock().unwrap_or_else(PoisonError::into_inner) } /// Counts one attempt of `key` now, before the attempt is made. The check and the record are one step, /// so parallel attempts cannot all pass before any of them is counted. When the key already has `limit` /// failures in the window, nothing is recorded and the seconds to wait come back (at least one). /// /// A reserved attempt counts as a failure until [`Throttle::refund`] takes it back, which a success does. pub fn reserve(&self, key: &str) -> std::result::Result<(), u64> { let now = Instant::now(); let mut map = self.map(); if let Some(stamps) = map.get_mut(key) { stamps.retain(|at| now.duration_since(*at) < self.window); if stamps.len() >= self.limit { return Err(self.wait_seconds(stamps, now)); } stamps.push(now); return Ok(()); } if map.len() >= self.max_keys { self.make_room(&mut map, now); } map.entry(key.to_owned()).or_default().push(now); Ok(()) } /// Takes back the newest counted attempt of `key`, for an attempt that succeeded. pub fn refund(&self, key: &str) { let emptied = match self.map().get_mut(key) { Some(stamps) => { stamps.pop(); stamps.is_empty() } None => false, }; if emptied { self.map().remove(key); } } /// The seconds until the oldest failure that must leave the window before `key` may try again. Rounded /// up, and at least one second, so `Retry-After` is never zero for a blocked key. fn wait_seconds(&self, stamps: &[Instant], now: Instant) -> u64 { // The key may try again once enough failures have left the window: the one at this index is the // last to leave before the count drops below the limit. let index = stamps.len() - self.limit; let free_at = stamps[index] + self.window; let wait = free_at.saturating_duration_since(now); (wait.as_secs() + u64::from(wait.subsec_nanos() > 0)).max(1) } /// Frees one slot: expired windows go first, then the key with the oldest last failure. fn make_room(&self, map: &mut HashMap>, now: Instant) { let window = self.window; map.retain(|_, stamps| { stamps.retain(|at| now.duration_since(*at) < window); !stamps.is_empty() }); if map.len() >= self.max_keys { let oldest = map .iter() .min_by_key(|(_, stamps)| stamps.last().copied()) .map(|(key, _)| key.clone()); if let Some(key) = oldest { map.remove(&key); } } } } /// The two throttles of share-link passwords: one per link (by token hash), and one per link and client /// address (the key is the token hash, a colon, and the address). pub struct ShareThrottles { /// Failures per link, from all visitors. pub per_link: Throttle, /// Failures per link and client address. pub per_visitor: Throttle, } impl Default for ShareThrottles { fn default() -> Self { Self { per_link: Throttle::new(PASSWORD_WINDOW, LINK_PASSWORD_LIMIT, MAX_KEYS), per_visitor: Throttle::new(PASSWORD_WINDOW, VISITOR_PASSWORD_LIMIT, MAX_KEYS), } } } #[cfg(test)] mod tests { use super::*; use std::sync::Arc; /// Ten parallel wrong guesses against one key with a limit of five: only the limit of them is counted and /// admitted, and the rest are refused with a wait. The check and the record are one step, so none can slip /// past. #[test] fn parallel_attempts_admit_no_more_than_the_limit() { const LIMIT: usize = 5; let throttle = Arc::new(Throttle::new(PASSWORD_WINDOW, LIMIT, MAX_KEYS)); let handles: Vec<_> = (0..10) .map(|_| { let throttle = Arc::clone(&throttle); std::thread::spawn(move || throttle.reserve("link").is_ok()) }) .collect(); let admitted = handles .into_iter() .map(|handle| handle.join().expect("attempt thread")) .filter(|ok| *ok) .count(); assert_eq!(admitted, LIMIT); assert!(throttle.reserve("link").is_err_and(|wait| wait >= 1)); } }