forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

throttle.rs446 lines, 17.2 KiBHistoryRawDownload
1//! In-memory sliding-window failure counters that slow down password guessing.
2//!
3//! Each key keeps the instants of its recent failures, and is limited while it has `limit` of them
4//! inside [`WINDOW`]. An attempt first asks [`Throttle::reserve`], which counts it before the work
5//! is done and answers with the wait when the key is already limited. A success gives the count back
6//! with [`Throttle::refund`] (or drops the key with [`Throttle::clear`] where the old failures go too).
7//! Check and count are one step under one lock, so parallel attempts cannot all pass together.
8//!
9//! Memory is bounded. Expired instants and empty keys are pruned every few hundred attempts. At the key
10//! cap, expired keys go first; then the key whose latest failure is oldest is evicted, but never a key
11//! that is limited right now. When every key is limited, a new key is refused: fail closed.
12//!
13//! Email keys are capped too. An address that is too long or not plausible shares one fixed key, so a
14//! flood of junk addresses cannot grow the map or the key size.
15//!
16//! Each [`Throttle`] has one window for all its keys. The failure counters use [`WINDOW`]; the per-minute
17//! and per-hour counters of the OAuth endpoints and the account pages are separate instances, built with
18//! [`Throttle::per_minute`] and [`Throttle::email_changes`].
19//!
20//! The counters live in one process. A restart clears them, and two processes would each count
21//! their own. `im` runs as one process, so this is the whole picture.
22
23use std::collections::{HashMap, VecDeque};
24use std::net::IpAddr;
25use std::sync::{Mutex, MutexGuard};
26use std::time::{Duration, Instant};
27
28use im_core::names::parse_email;
29
30/// Length of the failure window.
31pub const WINDOW: Duration = Duration::from_secs(15 * 60);
32
33/// Failed sign-ins allowed per normalised email address inside [`WINDOW`]. Also counts wrong
34/// passwords on the security page, so guessing there locks sign-in too.
35pub const LOGIN_USER_LIMIT: usize = 10;
36
37/// Failed sign-ins allowed per client address inside [`WINDOW`].
38pub const LOGIN_IP_LIMIT: usize = 30;
39
40/// Failed second-factor checks allowed per user inside [`WINDOW`].
41pub const TWO_FACTOR_USER_LIMIT: usize = 10;
42
43/// Failed second-factor checks allowed per user inside [`TWO_FACTOR_DAY_WINDOW`]. It works beside
44/// [`TWO_FACTOR_USER_LIMIT`], so a guesser who pauses between windows still runs out.
45pub const TWO_FACTOR_DAY_LIMIT: usize = 30;
46
47/// Length of the second-factor day window: 24 hours. Kept on its own [`Throttle`] (see
48/// [`Throttle::two_factor_days`]), because a throttle has one window for all its keys.
49pub const TWO_FACTOR_DAY_WINDOW: Duration = Duration::from_secs(24 * 60 * 60);
50
51/// Reset-link requests allowed per normalised email address inside [`WINDOW`]. Every request counts, known
52/// address or not, so the limit leaks nothing about the account.
53pub const FORGOT_EMAIL_LIMIT: usize = 3;
54
55/// Reset-link requests allowed per client address inside [`WINDOW`].
56pub const FORGOT_IP_LIMIT: usize = 20;
57
58/// Profile photo uploads allowed per account inside [`PHOTO_UPLOAD_WINDOW`]. Every upload counts, whether
59/// or not its picture is accepted, because each one costs a decode.
60pub const PHOTO_UPLOAD_LIMIT: usize = 10;
61
62/// Length of the photo upload window: one hour. Kept on its own [`Throttle`] (see
63/// [`Throttle::photo_uploads`]), because a throttle has one window for all its keys.
64pub const PHOTO_UPLOAD_WINDOW: Duration = Duration::from_secs(60 * 60);
65
66/// Length of the per-minute window of the OAuth endpoints and the audit of failed sign-ins.
67pub const MINUTE: Duration = Duration::from_secs(60);
68
69/// Length of the window of email-change requests: one hour.
70pub const EMAIL_CHANGE_WINDOW: Duration = Duration::from_secs(60 * 60);
71
72/// Email-change requests allowed per account inside [`EMAIL_CHANGE_WINDOW`]. Each one mails two addresses.
73pub const EMAIL_CHANGE_LIMIT: usize = 3;
74
75/// Code issuances allowed per browser session inside [`MINUTE`] at `/authorize`. A refused one is answered
76/// with the `temporarily_unavailable` redirect.
77pub const AUTHORIZE_SESSION_LIMIT: usize = 60;
78
79/// Requests allowed per authenticated client inside [`MINUTE`] at `/token`, over all its grants together.
80/// A client with many users shares this ceiling, so it is set well above one person's use.
81pub const TOKEN_CLIENT_LIMIT: usize = 1200;
82
83/// Requests allowed inside [`MINUTE`] for one refresh-token family, or for one authorization code, at
84/// `/token`. One person uses one chain or one code, so this is what limits a flood on a single one.
85pub const TOKEN_CHAIN_LIMIT: usize = 30;
86
87/// `LoginFailed` audit rows written per typed address inside [`MINUTE`], whether or not an account has that
88/// address, so the work done for a failure does not show which. Failures beyond it are still refused and
89/// counted; only their audit rows are skipped.
90pub const LOGIN_AUDIT_LIMIT: usize = 1;
91
92/// Maximum number of distinct keys tracked at once. A flood of random keys cannot grow memory past
93/// this.
94const MAX_KEYS: usize = 100_000;
95
96/// A full prune runs every this many attempts.
97const PRUNE_EVERY: u32 = 256;
98
99/// The part of an email key used for an address that is not plausible. Starts with `<`, which no valid
100/// address contains, so it never collides with a real address.
101const INVALID_ADDRESS: &str = "<invalid>";
102
103/// The most bytes of a raw, unparseable address that go into its key. Longer input is cut here, so the
104/// key stays bounded.
105const MAX_RAW_ADDRESS_BYTES: usize = 320;
106
107/// The failure counters of the process. Shared by every request through the app state.
108pub struct Throttle {
109 window: Duration,
110 max_keys: usize,
111 state: Mutex<State>,
112}
113
114#[derive(Default)]
115struct State {
116 failures: HashMap<String, Entry>,
117 attempts: u32,
118}
119
120/// The failures of one key, and the limit they were counted against.
121struct Entry {
122 stamps: VecDeque<Instant>,
123 limit: usize,
124}
125
126impl Default for Throttle {
127 fn default() -> Self {
128 Self::with_limits(WINDOW, MAX_KEYS)
129 }
130}
131
132impl Throttle {
133 /// The counters of profile photo uploads: one hour window, the same key cap.
134 pub fn photo_uploads() -> Self {
135 Self::with_limits(PHOTO_UPLOAD_WINDOW, MAX_KEYS)
136 }
137
138 /// The per-minute counters: `/authorize` per session, `/token` per client, and the audit of failed
139 /// sign-ins. One minute window, the same key cap.
140 pub fn per_minute() -> Self {
141 Self::with_limits(MINUTE, MAX_KEYS)
142 }
143
144 /// The counters of email-change requests: one hour window, the same key cap.
145 pub fn email_changes() -> Self {
146 Self::with_limits(EMAIL_CHANGE_WINDOW, MAX_KEYS)
147 }
148
149 /// The day-long counters of second-factor checks: 24 hour window, the same key cap.
150 pub fn two_factor_days() -> Self {
151 Self::with_limits(TWO_FACTOR_DAY_WINDOW, MAX_KEYS)
152 }
153
154 /// Counters with a custom window and key cap. Tests use short windows.
155 pub fn with_limits(window: Duration, max_keys: usize) -> Self {
156 Self {
157 window,
158 max_keys: max_keys.max(1),
159 state: Mutex::new(State::default()),
160 }
161 }
162
163 /// Counts one attempt of `key` now, before the work is done. When the key already has `limit`
164 /// failures inside the window, nothing is counted and the wait until it may try again comes back
165 /// (at least one second when it is the key cap that refuses a new key).
166 pub fn reserve(&self, key: &str, limit: usize, now: Instant) -> Result<(), Duration> {
167 self.reserve_all(&[(key, limit)], now)
168 }
169
170 /// Counts one attempt against every key, or against none. All keys are checked under one lock. When
171 /// one of them refuses, the keys already counted are given back, and the longest wait comes back.
172 pub fn reserve_all(&self, keys: &[(&str, usize)], now: Instant) -> Result<(), Duration> {
173 let mut state = self.lock();
174 state.attempts = state.attempts.wrapping_add(1);
175 if state.attempts.is_multiple_of(PRUNE_EVERY) {
176 self.prune_locked(&mut state, now);
177 }
178 let mut admitted = Vec::with_capacity(keys.len());
179 let mut wait: Option<Duration> = None;
180 for &(key, limit) in keys {
181 match self.reserve_locked(&mut state, key, limit, now) {
182 Ok(()) => admitted.push(key),
183 Err(due) => wait = Some(wait.map_or(due, |longest| longest.max(due))),
184 }
185 }
186 match wait {
187 None => Ok(()),
188 Some(due) => {
189 for key in admitted {
190 self.refund_locked(&mut state, key);
191 }
192 Err(due)
193 }
194 }
195 }
196
197 /// Takes back the newest counted attempt of `key`, for an attempt that succeeded.
198 pub fn refund(&self, key: &str) {
199 self.refund_locked(&mut self.lock(), key);
200 }
201
202 /// Forgets the failures of `key`, after a success.
203 pub fn clear(&self, key: &str) {
204 self.lock().failures.remove(key);
205 }
206
207 /// Counts one attempt of `key` under `limit`, with the lock already held.
208 fn reserve_locked(
209 &self,
210 state: &mut State,
211 key: &str,
212 limit: usize,
213 now: Instant,
214 ) -> Result<(), Duration> {
215 if !state.failures.contains_key(key)
216 && state.failures.len() >= self.max_keys
217 && !self.make_room_locked(state, now)
218 {
219 // Every key is limited right now: the new one is refused, which is the fail-closed answer.
220 return Err(self.window);
221 }
222 let entry = state
223 .failures
224 .entry(key.to_owned())
225 .or_insert_with(|| Entry {
226 stamps: VecDeque::new(),
227 limit,
228 });
229 entry.limit = limit;
230 drop_expired(&mut entry.stamps, self.window, now);
231 if entry.stamps.len() >= limit {
232 return Err(wait_for(&entry.stamps, limit, self.window, now));
233 }
234 entry.stamps.push_back(now);
235 Ok(())
236 }
237
238 /// Gives back the newest failure of `key`, and drops the key when nothing is left.
239 fn refund_locked(&self, state: &mut State, key: &str) {
240 let emptied = match state.failures.get_mut(key) {
241 Some(entry) => {
242 entry.stamps.pop_back();
243 entry.stamps.is_empty()
244 }
245 None => false,
246 };
247 if emptied {
248 state.failures.remove(key);
249 }
250 }
251
252 /// Frees one slot for a new key. Expired failures go first. Then the key whose latest failure is the
253 /// oldest is removed, but only among keys that are not limited now. Returns false when every key is
254 /// limited, so nothing can be removed.
255 fn make_room_locked(&self, state: &mut State, now: Instant) -> bool {
256 let window = self.window;
257 state.failures.retain(|_, entry| {
258 drop_expired(&mut entry.stamps, window, now);
259 !entry.stamps.is_empty()
260 });
261 if state.failures.len() < self.max_keys {
262 return true;
263 }
264 let victim = state
265 .failures
266 .iter()
267 .filter(|(_, entry)| entry.stamps.len() < entry.limit)
268 .min_by_key(|(_, entry)| entry.stamps.back().copied())
269 .map(|(key, _)| key.clone());
270 match victim {
271 Some(key) => {
272 state.failures.remove(&key);
273 true
274 }
275 None => false,
276 }
277 }
278
279 /// Drops expired failures and the keys left empty.
280 fn prune_locked(&self, state: &mut State, now: Instant) {
281 let window = self.window;
282 state.failures.retain(|_, entry| {
283 drop_expired(&mut entry.stamps, window, now);
284 !entry.stamps.is_empty()
285 });
286 }
287
288 fn lock(&self) -> MutexGuard<'_, State> {
289 // A poisoned lock still holds consistent counters, so the next caller uses it as it is.
290 self.state.lock().unwrap_or_else(|e| e.into_inner())
291 }
292}
293
294/// Removes the failures that have left the window.
295fn drop_expired(timestamps: &mut VecDeque<Instant>, window: Duration, now: Instant) {
296 while let Some(front) = timestamps.front() {
297 if now.saturating_duration_since(*front) < window {
298 break;
299 }
300 timestamps.pop_front();
301 }
302}
303
304/// The wait until `stamps` drops below `limit` failures: the failure at this index is the last one to
305/// leave the window before the count does.
306fn wait_for(stamps: &VecDeque<Instant>, limit: usize, window: Duration, now: Instant) -> Duration {
307 let Some(index) = stamps.len().checked_sub(limit) else {
308 return Duration::ZERO;
309 };
310 stamps.get(index).map_or(Duration::ZERO, |oldest| {
311 (*oldest + window).saturating_duration_since(now)
312 })
313}
314
315/// The part of an email key for `email`: the address itself when it is plausible, otherwise the marker
316/// and the raw text, trimmed, lowercased and cut to [`MAX_RAW_ADDRESS_BYTES`]. Each junk address gets its
317/// own key, so one junk address cannot lock out a real account whose stored address happens to be
318/// unparseable under the current rules.
319fn address_part(email: &str) -> String {
320 match parse_email(email) {
321 Ok(address) => address,
322 Err(_) => {
323 let raw = email.trim().to_lowercase();
324 // Cut on a character boundary at or below the cap.
325 let cut = (0..=raw.len().min(MAX_RAW_ADDRESS_BYTES))
326 .rev()
327 .find(|&i| raw.is_char_boundary(i))
328 .unwrap_or(0);
329 format!("{INVALID_ADDRESS}{}", &raw[..cut])
330 }
331 }
332}
333
334/// Throttle key for a normalised email address.
335pub fn user_key(email: &str) -> String {
336 format!("user:{}", address_part(email))
337}
338
339/// Throttle key for the reset-link requests of one normalised address.
340pub fn forgot_email_key(email: &str) -> String {
341 format!("forgot:{}", address_part(email))
342}
343
344/// Throttle key for the photo uploads of one user, by user id.
345pub fn photo_upload_key(user_id: &str) -> String {
346 format!("photo:{user_id}")
347}
348
349/// Throttle key for the second factor of one user, by user id.
350pub fn two_factor_key(user_id: &str) -> String {
351 format!("2fa:{user_id}")
352}
353
354/// Throttle key for the email-change requests of one user, by user id.
355pub fn email_change_key(user_id: &str) -> String {
356 format!("email-change:{user_id}")
357}
358
359/// Throttle key for the code issuances of one browser session, by session id.
360pub fn authorize_session_key(session_id: &str) -> String {
361 format!("authorize:{session_id}")
362}
363
364/// Throttle key for the token requests of one client, by client id.
365pub fn token_client_key(client_id: &str) -> String {
366 format!("token:{client_id}")
367}
368
369/// Throttle key for the refresh requests of one token family (one chain) of a client.
370pub fn token_family_key(client_id: &str, family_id: &str) -> String {
371 format!("token-family:{client_id}:{family_id}")
372}
373
374/// Throttle key for the code exchanges of one authorization code of a client, by the code's hash.
375pub fn token_code_key(client_id: &str, code_hash: &str) -> String {
376 format!("token-code:{client_id}:{code_hash}")
377}
378
379/// Throttle key for the `LoginFailed` audit rows of one normalised address. Its own key, not the sign-in
380/// counter of the address, so the audit rows do not use up the sign-in attempts.
381pub fn login_audit_key(email: &str) -> String {
382 format!("login-audit:{}", address_part(email))
383}
384
385/// Throttle key for an address under a named scope, such as `login-ip`.
386pub fn ip_key(scope: &str, ip: IpAddr) -> String {
387 format!("{scope}:{ip}")
388}
389
390#[cfg(test)]
391mod tests {
392 use super::*;
393 use std::sync::Arc;
394
395 #[test]
396 fn a_key_is_limited_at_the_threshold_and_free_when_the_window_passes() {
397 let throttle = Throttle::with_limits(Duration::from_secs(60), 16);
398 let t0 = Instant::now();
399 for i in 0..3 {
400 let at = t0 + Duration::from_secs(i);
401 assert!(throttle.reserve("k", 3, at).is_ok());
402 }
403 let retry = throttle
404 .reserve("k", 3, t0 + Duration::from_secs(10))
405 .expect_err("limited");
406 assert_eq!(retry, Duration::from_secs(50));
407 assert!(
408 throttle
409 .reserve("k", 3, t0 + Duration::from_secs(60))
410 .is_ok()
411 );
412 }
413
414 /// Twenty parallel wrong-password attempts against one key: only the limit's worth is counted and
415 /// admitted, and the rest are refused. Check and count are one step, so none can slip past.
416 #[test]
417 fn parallel_reservations_admit_no_more_than_the_limit() {
418 let throttle = Arc::new(Throttle::with_limits(WINDOW, MAX_KEYS));
419 let handles: Vec<_> = (0..20)
420 .map(|_| {
421 let throttle = Arc::clone(&throttle);
422 std::thread::spawn(move || {
423 throttle
424 .reserve("login", LOGIN_USER_LIMIT, Instant::now())
425 .is_ok()
426 })
427 })
428 .collect();
429 let admitted = handles
430 .into_iter()
431 .map(|handle| handle.join().expect("attempt thread"))
432 .filter(|ok| *ok)
433 .count();
434 assert_eq!(admitted, LOGIN_USER_LIMIT);
435 }
436
437 #[test]
438 fn the_key_count_stays_at_the_cap() {
439 let throttle = Throttle::with_limits(Duration::from_secs(10), 8);
440 let t0 = Instant::now();
441 for i in 0..1000u64 {
442 let _ = throttle.reserve(&format!("key-{i}"), 2, t0 + Duration::from_millis(i));
443 assert!(throttle.lock().failures.len() <= 8);
444 }
445 }
446}