forge
Explore
Log in

Don't you dare go Hollow

in

Clone
★ 0

0 watching0 forksRustAGPL-3.0528.7 KiB9215377Tahinli27 days ago37 commits

throttle.rs165 lines, 6.7 KiBHistoryRawDownload
1//! Failure throttling in memory: a sliding window of failures per key, with a bounded number of keys.
2//!
3//! An attempt first asks [`Throttle::reserve`], which counts it as a failure and answers `429` with
4//! `Retry-After` when the key has reached its limit. A success gives the count back with
5//! [`Throttle::refund`]. Check and count are one step, so parallel attempts cannot pass together.
6//! Nothing is persisted, so a restart forgets the failures; that is accepted for a family instance and documented in the backlog.
7//!
8//! The key count is capped. When a new key would exceed the cap, the windows that have expired are
9//! dropped first, and then the key whose last failure is oldest. So an attacker who spreads guesses over
10//! many keys can only evict other keys, never grow the memory.
11
12use std::collections::HashMap;
13use std::sync::{Mutex, MutexGuard, PoisonError};
14use std::time::{Duration, Instant};
15
16/// Length of the sliding window for share-link passwords: 15 minutes.
17pub const PASSWORD_WINDOW: Duration = Duration::from_secs(15 * 60);
18
19/// Failed password attempts allowed against one link in a window, from all visitors together. This is a
20/// ceiling: it stops guesses spread over many addresses. The 101st is refused with `429`.
21pub const LINK_PASSWORD_LIMIT: usize = 100;
22
23/// Failed password attempts allowed from one client address against one link in a window. The eleventh is
24/// refused with `429`. Other visitors of the same link have their own count.
25pub const VISITOR_PASSWORD_LIMIT: usize = 10;
26
27/// Most keys held at once. Each key is a short string and a short list of instants.
28pub const MAX_KEYS: usize = 10_000;
29
30/// Failures per key within a sliding window, with a cap on the number of keys.
31pub struct Throttle {
32 failures: Mutex<HashMap<String, Vec<Instant>>>,
33 window: Duration,
34 limit: usize,
35 max_keys: usize,
36}
37
38impl Throttle {
39 /// A throttle that blocks a key after `limit` failures within `window`.
40 pub fn new(window: Duration, limit: usize, max_keys: usize) -> Self {
41 Self {
42 failures: Mutex::new(HashMap::new()),
43 window,
44 limit,
45 max_keys,
46 }
47 }
48
49 /// Locks the map. A poisoned lock is used as it is: a panic elsewhere must not open the throttle.
50 fn map(&self) -> MutexGuard<'_, HashMap<String, Vec<Instant>>> {
51 self.failures.lock().unwrap_or_else(PoisonError::into_inner)
52 }
53
54 /// Counts one attempt of `key` now, before the attempt is made. The check and the record are one step,
55 /// so parallel attempts cannot all pass before any of them is counted. When the key already has `limit`
56 /// failures in the window, nothing is recorded and the seconds to wait come back (at least one).
57 ///
58 /// A reserved attempt counts as a failure until [`Throttle::refund`] takes it back, which a success does.
59 pub fn reserve(&self, key: &str) -> std::result::Result<(), u64> {
60 let now = Instant::now();
61 let mut map = self.map();
62 if let Some(stamps) = map.get_mut(key) {
63 stamps.retain(|at| now.duration_since(*at) < self.window);
64 if stamps.len() >= self.limit {
65 return Err(self.wait_seconds(stamps, now));
66 }
67 stamps.push(now);
68 return Ok(());
69 }
70 if map.len() >= self.max_keys {
71 self.make_room(&mut map, now);
72 }
73 map.entry(key.to_owned()).or_default().push(now);
74 Ok(())
75 }
76
77 /// Takes back the newest counted attempt of `key`, for an attempt that succeeded.
78 pub fn refund(&self, key: &str) {
79 let emptied = match self.map().get_mut(key) {
80 Some(stamps) => {
81 stamps.pop();
82 stamps.is_empty()
83 }
84 None => false,
85 };
86 if emptied {
87 self.map().remove(key);
88 }
89 }
90
91 /// The seconds until the oldest failure that must leave the window before `key` may try again. Rounded
92 /// up, and at least one second, so `Retry-After` is never zero for a blocked key.
93 fn wait_seconds(&self, stamps: &[Instant], now: Instant) -> u64 {
94 // The key may try again once enough failures have left the window: the one at this index is the
95 // last to leave before the count drops below the limit.
96 let index = stamps.len() - self.limit;
97 let free_at = stamps[index] + self.window;
98 let wait = free_at.saturating_duration_since(now);
99 (wait.as_secs() + u64::from(wait.subsec_nanos() > 0)).max(1)
100 }
101
102 /// Frees one slot: expired windows go first, then the key with the oldest last failure.
103 fn make_room(&self, map: &mut HashMap<String, Vec<Instant>>, now: Instant) {
104 let window = self.window;
105 map.retain(|_, stamps| {
106 stamps.retain(|at| now.duration_since(*at) < window);
107 !stamps.is_empty()
108 });
109 if map.len() >= self.max_keys {
110 let oldest = map
111 .iter()
112 .min_by_key(|(_, stamps)| stamps.last().copied())
113 .map(|(key, _)| key.clone());
114 if let Some(key) = oldest {
115 map.remove(&key);
116 }
117 }
118 }
119}
120
121/// The two throttles of share-link passwords: one per link (by token hash), and one per link and client
122/// address (the key is the token hash, a colon, and the address).
123pub struct ShareThrottles {
124 /// Failures per link, from all visitors.
125 pub per_link: Throttle,
126 /// Failures per link and client address.
127 pub per_visitor: Throttle,
128}
129
130impl Default for ShareThrottles {
131 fn default() -> Self {
132 Self {
133 per_link: Throttle::new(PASSWORD_WINDOW, LINK_PASSWORD_LIMIT, MAX_KEYS),
134 per_visitor: Throttle::new(PASSWORD_WINDOW, VISITOR_PASSWORD_LIMIT, MAX_KEYS),
135 }
136 }
137}
138
139#[cfg(test)]
140mod tests {
141 use super::*;
142 use std::sync::Arc;
143
144 /// Ten parallel wrong guesses against one key with a limit of five: only the limit of them is counted and
145 /// admitted, and the rest are refused with a wait. The check and the record are one step, so none can slip
146 /// past.
147 #[test]
148 fn parallel_attempts_admit_no_more_than_the_limit() {
149 const LIMIT: usize = 5;
150 let throttle = Arc::new(Throttle::new(PASSWORD_WINDOW, LIMIT, MAX_KEYS));
151 let handles: Vec<_> = (0..10)
152 .map(|_| {
153 let throttle = Arc::clone(&throttle);
154 std::thread::spawn(move || throttle.reserve("link").is_ok())
155 })
156 .collect();
157 let admitted = handles
158 .into_iter()
159 .map(|handle| handle.join().expect("attempt thread"))
160 .filter(|ok| *ok)
161 .count();
162 assert_eq!(admitted, LIMIT);
163 assert!(throttle.reserve("link").is_err_and(|wait| wait >= 1));
164 }
165}