steid

@jamesgill /

steid/src/infrastructure/web/rate_limit.rs
Rust19.4 KBCode·Blame·History·Raw
1//! In-memory rate limiting for the endpoints where guessing is feasible.
2//!
3//! `/auth/login` and `/auth/setup` are the only places a secret can be attacked by
4//! repetition: a personal access token is 256 bits, but a human-chosen password is
5//! not, and the setup token is worth guessing for exactly as long as the instance is
6//! unclaimed. The limiter also caps how often an anonymous caller can make the server
7//! run Argon2, which is deliberately expensive.
8//!
9//! Fixed windows rather than a token bucket: a window is two integers and a
10//! comparison, it is trivial to reason about when reading a log, and the burst it
11//! permits at a window boundary — twice the limit across two adjacent windows — does
12//! not matter at these rates. A bucket's smoother refill buys nothing here.
13
14use std::{
15 collections::HashMap,
16 sync::Mutex,
17 time::{Duration, Instant},
18};
19
20use topcoat::{
21 context::{Cx, app_context},
22 router::{Body, Response, StatusCode, header::RETRY_AFTER, headers},
23};
24
25/// How long a window lasts.
26const WINDOW: Duration = Duration::from_secs(60);
27
28/// Attempts one client may make per window.
29///
30/// Ten a minute is far above what a person signing in ever needs — a mistyped
31/// password twice, then a password manager — and far below what makes guessing
32/// worthwhile: an online attack against even a weak six-character password would take
33/// centuries at this rate.
34const PER_CLIENT: u32 = 10;
35
36/// Attempts *everyone together* may make per window.
37///
38/// This is the backstop for a forged client key (see [`client_key`]). Without a peer
39/// address there is no way to prove a caller is who its headers claim, so an attacker
40/// who can forge a different `X-Forwarded-For` per request would otherwise get an
41/// unlimited number of per-client budgets. Sixty a minute is six independent people
42/// each hitting their own limit at once, which a single-owner instance will never see,
43/// and it turns key forgery from a bypass into a six-fold speed-up.
44///
45/// The cost is that a flood can lock out a legitimate sign-in for up to a minute.
46/// That is the right way round: a temporary denial of the login form is recoverable,
47/// a guessed password is not.
48const GLOBAL: u32 = 60;
49
50/// Distinct client keys tracked at once.
51///
52/// The map is keyed by something the caller influences, so it must not be allowed to
53/// grow with the number of keys an attacker can invent. Past this many live keys,
54/// expired entries are swept and any still-unknown key falls back to the global
55/// window alone — which is stricter, not laxer, so filling the map is not a way out.
56const MAX_KEYS: usize = 4096;
57
58/// Token authentications one client may make per window, on the git transport.
59///
60/// Far above [`PER_CLIENT`] because git is chatty and a person is not: one `git clone`
61/// authenticates two or three times, a `git push` twice, and a script fetching a
62/// handful of remotes in a loop makes a burst of them. Sixty a minute is roughly twenty
63/// clones a minute from one address — beyond anything a person or a CI job does — while
64/// still bounding the work an anonymous caller can force the server to do. That work is
65/// a SHA-256 and one indexed lookup, not an Argon2 hash, so this is a cap on volume
66/// rather than a defence against guessing: a token is 256 bits and cannot be guessed at
67/// any rate.
68const GIT_PER_CLIENT: u32 = 60;
69
70/// Git-transport authentications *everyone together* may make per window.
71///
72/// Ten independent clients each at their own limit, for the same reason [`GLOBAL`]
73/// exists: without a peer address a client key can be forged, and this is what keeps
74/// forging one from being an unlimited bypass.
75const GIT_GLOBAL: u32 = 600;
76
77/// The limiter guarding token authentication on the git transport.
78///
79/// A separate budget rather than a share of the sign-in one, because the two have
80/// nothing to do with each other: a clone would spend a person's login allowance in
81/// three requests, and a flood of clones must not be able to lock someone out of
82/// `/auth/login`. Same window, same client key, different numbers.
83#[derive(Debug)]
84pub struct GitAuthLimiter(RateLimiter);
85
86impl Default for GitAuthLimiter {
87 fn default() -> Self {
88 Self(RateLimiter::new(
89 WINDOW,
90 GIT_PER_CLIENT,
91 GIT_GLOBAL,
92 MAX_KEYS,
93 ))
94 }
95}
96
97/// Records a git-transport authentication attempt, and says how long to wait if the
98/// caller has spent its budget.
99///
100/// Returns the retry-after rather than a response, because the git routes answer with
101/// their own streaming body type and cannot use the one [`throttled`] builds.
102pub fn git_auth_throttled(cx: &Cx) -> Option<Duration> {
103 match app_context::<GitAuthLimiter>(cx).0.check(&client_key(cx)) {
104 Decision::Allowed => None,
105 Decision::Throttled(retry_after) => {
106 eprintln!("steid: rate limited a git authentication attempt");
107 Some(retry_after)
108 }
109 }
110}
111
112/// Archive downloads per client per minute.
113///
114/// An archive is a whole pack of the repository per request, on an anonymous endpoint
115/// that every tag row and the landing page now link to — the most expensive thing a
116/// stranger can ask for, and the first thing a crawler follows. Ten a minute is far
117/// above a person clicking and far below a bot walking the tags page.
118const ARCHIVE_PER_CLIENT: u32 = 10;
119
120/// Archive downloads across every client per minute. Bounds the total pack work the
121/// process will do for anonymous downloads, however many addresses ask.
122const ARCHIVE_GLOBAL: u32 = 60;
123
124/// The limiter for archive downloads. Its own budget, for the reason
125/// [`GitAuthLimiter`] has one: a download must not spend a sign-in allowance, and a
126/// flood of downloads must not lock anyone out of the login form.
127#[derive(Debug)]
128pub struct ArchiveLimiter(RateLimiter);
129
130impl Default for ArchiveLimiter {
131 fn default() -> Self {
132 Self(RateLimiter::new(
133 WINDOW,
134 ARCHIVE_PER_CLIENT,
135 ARCHIVE_GLOBAL,
136 MAX_KEYS,
137 ))
138 }
139}
140
141/// Records an archive download, and says how long to wait if the caller has spent
142/// its budget. Returns a duration rather than a response for the same reason
143/// [`git_auth_throttled`] does: the archive route streams its own body type.
144pub fn archive_throttled(cx: &Cx) -> Option<Duration> {
145 match app_context::<ArchiveLimiter>(cx).0.check(&client_key(cx)) {
146 Decision::Allowed => None,
147 Decision::Throttled(retry_after) => {
148 eprintln!("steid: rate limited an archive download");
149 Some(retry_after)
150 }
151 }
152}
153
154/// The shared limiter. One per process, held in Topcoat's app context.
155#[derive(Debug)]
156pub struct RateLimiter {
157 window: Duration,
158 per_client: u32,
159 global: u32,
160 max_keys: usize,
161 state: Mutex<State>,
162}
163
164#[derive(Debug)]
165struct State {
166 clients: HashMap<Box<str>, Window>,
167 global: Window,
168}
169
170/// A fixed window: when it opened, and how many attempts have landed in it.
171#[derive(Debug, Clone, Copy)]
172struct Window {
173 opened: Instant,
174 hits: u32,
175}
176
177impl Window {
178 fn new(now: Instant) -> Self {
179 Self {
180 opened: now,
181 hits: 0,
182 }
183 }
184
185 /// Records an attempt, rolling into a fresh window first if this one has expired.
186 fn record(&mut self, now: Instant, window: Duration) -> u32 {
187 if now.duration_since(self.opened) >= window {
188 *self = Self::new(now);
189 }
190
191 self.hits = self.hits.saturating_add(1);
192 self.hits
193 }
194
195 fn expired(&self, now: Instant, window: Duration) -> bool {
196 now.duration_since(self.opened) >= window
197 }
198
199 fn remaining(&self, now: Instant, window: Duration) -> Duration {
200 window.saturating_sub(now.duration_since(self.opened))
201 }
202}
203
204/// What the limiter decided about one attempt.
205#[derive(Debug, Clone, Copy, PartialEq, Eq)]
206pub enum Decision {
207 Allowed,
208 /// Refused, with how long until the window it exhausted rolls over.
209 Throttled(Duration),
210}
211
212impl Default for RateLimiter {
213 fn default() -> Self {
214 Self::new(WINDOW, PER_CLIENT, GLOBAL, MAX_KEYS)
215 }
216}
217
218impl RateLimiter {
219 /// Builds a limiter with explicit limits. Tests use this; `main` uses
220 /// [`Default`].
221 #[must_use]
222 pub fn new(window: Duration, per_client: u32, global: u32, max_keys: usize) -> Self {
223 Self {
224 window,
225 per_client,
226 global,
227 max_keys,
228 state: Mutex::new(State {
229 clients: HashMap::new(),
230 global: Window::new(Instant::now()),
231 }),
232 }
233 }
234
235 /// Records an attempt for `key` and says whether it may proceed.
236 pub fn check(&self, key: &str) -> Decision {
237 self.check_at(key, Instant::now())
238 }
239
240 /// [`check`](Self::check) with the clock supplied, so tests can move time.
241 fn check_at(&self, key: &str, now: Instant) -> Decision {
242 let mut state = self.state.lock().unwrap_or_else(|poisoned| {
243 // A panic while holding the lock would otherwise disable the limiter for
244 // the life of the process, which is the wrong way to fail.
245 self.state.clear_poison();
246 poisoned.into_inner()
247 });
248
249 // Every attempt counts against the global window, including one that is about
250 // to be refused for its own key: an attacker rotating keys still pays here.
251 let global_hits = state.global.record(now, self.window);
252 if global_hits > self.global {
253 return Decision::Throttled(state.global.remaining(now, self.window));
254 }
255
256 if !state.clients.contains_key(key) && state.clients.len() >= self.max_keys {
257 let window = self.window;
258 state.clients.retain(|_, entry| !entry.expired(now, window));
259
260 if state.clients.len() >= self.max_keys {
261 // Still full of live entries, so this attempt is covered by the
262 // global window only. Refusing to grow is what bounds the memory.
263 return Decision::Allowed;
264 }
265 }
266
267 let entry = state
268 .clients
269 .entry(key.into())
270 .or_insert_with(|| Window::new(now));
271
272 if entry.record(now, self.window) > self.per_client {
273 return Decision::Throttled(entry.remaining(now, self.window));
274 }
275
276 Decision::Allowed
277 }
278
279 /// How many client keys are currently held. For tests and diagnostics.
280 #[must_use]
281 pub fn tracked_keys(&self) -> usize {
282 self.state.lock().map_or(0, |state| state.clients.len())
283 }
284}
285
286/// Applies the shared limiter to this request, returning the 429 to send when the
287/// caller has spent its budget.
288///
289/// Call it first in a handler, before any password hashing or token comparison.
290pub fn throttled(cx: &Cx) -> Option<Response> {
291 match app_context::<RateLimiter>(cx).check(&client_key(cx)) {
292 Decision::Allowed => None,
293 Decision::Throttled(retry_after) => {
294 eprintln!("steid: rate limited an auth attempt");
295 Some(too_many_requests(retry_after))
296 }
297 }
298}
299
300/// The 429 itself. Deliberately a bare line of text: it says nothing about which
301/// limit was hit or what the instance is.
302fn too_many_requests(retry_after: Duration) -> Response {
303 let seconds = retry_after.as_secs().max(1);
304
305 let mut response = Response::new(Body::from("too many attempts, try again shortly\n"));
306 *response.status_mut() = StatusCode::TOO_MANY_REQUESTS;
307 response.headers_mut().insert(RETRY_AFTER, seconds.into());
308
309 response
310}
311
312/// What the limiter counts against — an approximation of the client's address.
313///
314/// **Topcoat 0.5 does not expose the peer address.** `internal_serve` discards it at
315/// accept time (`let (stream, _remote) = accepted?;`) and never puts it on the request
316/// extensions, so a handler has nothing but headers to go on. That constrains this
317/// entirely, and it is worth restating rather than rediscovering.
318///
319/// So: the **rightmost** `X-Forwarded-For` entry, then `X-Real-IP`, then a single
320/// shared key.
321///
322/// Rightmost, not leftmost, because a proxy *appends* the address it accepted the
323/// connection from. A client that sends its own `X-Forwarded-For: 1.2.3.4` gets
324/// `1.2.3.4, <real address>` by the time Steid sees it, so the last entry is the one
325/// the nearest proxy wrote and the only one it cannot forge. The leftmost entry —
326/// what "the real client IP" usually means — is exactly the attacker-controlled one.
327/// This assumes a single proxy hop; behind two, the rightmost entry is the inner
328/// proxy, and every client collapses onto one key. Stricter, so safe to be wrong
329/// about.
330///
331/// The trade-off this cannot escape: on an instance exposed **directly** to the
332/// internet, with no proxy appending anything, a caller can invent a fresh
333/// `X-Forwarded-For` per request and get a fresh per-client budget each time. The
334/// global window above is what keeps that from being a total bypass. Closing it
335/// properly needs the peer address, which means a change in Topcoat.
336fn client_key(cx: &Cx) -> String {
337 let headers = headers(cx);
338 let value = |name: &str| headers.get(name).and_then(|value| value.to_str().ok());
339
340 let forwarded = value("x-forwarded-for")
341 .and_then(|list| list.rsplit(',').next())
342 .and_then(address);
343
344 forwarded
345 .or_else(|| value("x-real-ip").and_then(address))
346 // No proxy header at all: everyone shares one window. Right for a directly
347 // exposed instance, where the alternative is no limit; a proxy that forwards
348 // neither header collapses its whole userbase into this key.
349 .unwrap_or_else(|| "direct".to_owned())
350}
351
352/// Accepts a header fragment only if it looks like an address, so a hostile header
353/// cannot become an arbitrarily large or arbitrarily weird map key.
354fn address(raw: &str) -> Option<String> {
355 /// Longest textual IPv6 address, with a zone and an embedded IPv4 tail.
356 const MAX: usize = 64;
357
358 let candidate = raw.trim();
359
360 let plausible = !candidate.is_empty()
361 && candidate.len() <= MAX
362 && candidate
363 .chars()
364 .all(|c| c.is_ascii_hexdigit() || matches!(c, '.' | ':' | '%' | '[' | ']'));
365
366 plausible.then(|| candidate.to_owned())
367}
368
369#[cfg(test)]
370mod tests {
371 use super::*;
372
373 fn limiter() -> RateLimiter {
374 RateLimiter::new(Duration::from_secs(60), 3, 100, 16)
375 }
376
377 #[test]
378 fn allows_attempts_up_to_the_limit() {
379 let limiter = limiter();
380 let now = Instant::now();
381
382 for _ in 0..3 {
383 assert_eq!(limiter.check_at("a", now), Decision::Allowed);
384 }
385 }
386
387 #[test]
388 fn refuses_the_attempt_after_the_limit() {
389 let limiter = limiter();
390 let now = Instant::now();
391
392 for _ in 0..3 {
393 limiter.check_at("a", now);
394 }
395
396 assert!(matches!(limiter.check_at("a", now), Decision::Throttled(_)));
397 }
398
399 #[test]
400 fn reports_how_long_until_the_window_rolls() {
401 let limiter = limiter();
402 let now = Instant::now();
403
404 for _ in 0..4 {
405 limiter.check_at("a", now);
406 }
407
408 let Decision::Throttled(retry_after) = limiter.check_at("a", now + Duration::from_secs(20))
409 else {
410 panic!("the key is over its limit");
411 };
412
413 assert_eq!(retry_after, Duration::from_secs(40));
414 }
415
416 #[test]
417 fn recovers_once_the_window_has_passed() {
418 let limiter = limiter();
419 let now = Instant::now();
420
421 for _ in 0..4 {
422 limiter.check_at("a", now);
423 }
424
425 assert_eq!(
426 limiter.check_at("a", now + Duration::from_secs(60)),
427 Decision::Allowed
428 );
429 }
430
431 #[test]
432 fn keys_are_independent() {
433 let limiter = limiter();
434 let now = Instant::now();
435
436 for _ in 0..4 {
437 limiter.check_at("a", now);
438 }
439
440 assert_eq!(limiter.check_at("b", now), Decision::Allowed);
441 }
442
443 #[test]
444 fn the_global_window_catches_a_caller_rotating_keys() {
445 let limiter = RateLimiter::new(Duration::from_secs(60), 3, 5, 16);
446 let now = Instant::now();
447
448 for index in 0..5 {
449 assert_eq!(
450 limiter.check_at(&format!("k{index}"), now),
451 Decision::Allowed
452 );
453 }
454
455 assert!(matches!(
456 limiter.check_at("k5", now),
457 Decision::Throttled(_)
458 ));
459 }
460
461 #[test]
462 fn the_map_does_not_grow_past_its_cap() {
463 let limiter = RateLimiter::new(Duration::from_secs(60), 3, u32::MAX, 16);
464 let now = Instant::now();
465
466 for index in 0..5_000 {
467 limiter.check_at(&format!("k{index}"), now);
468 }
469
470 assert!(limiter.tracked_keys() <= 16);
471 }
472
473 #[test]
474 fn expired_entries_are_swept_to_make_room() {
475 let limiter = RateLimiter::new(Duration::from_secs(60), 3, u32::MAX, 16);
476 let now = Instant::now();
477
478 for index in 0..16 {
479 limiter.check_at(&format!("old{index}"), now);
480 }
481
482 // A minute later every one of those has expired, so the newcomer is tracked
483 // rather than being waved through on the global window alone.
484 let later = now + Duration::from_secs(61);
485 for _ in 0..4 {
486 limiter.check_at("new", later);
487 }
488
489 assert!(matches!(
490 limiter.check_at("new", later),
491 Decision::Throttled(_)
492 ));
493 assert!(limiter.tracked_keys() <= 16);
494 }
495
496 #[test]
497 fn a_key_beyond_the_cap_is_still_covered_by_the_global_window() {
498 let limiter = RateLimiter::new(Duration::from_secs(60), 3, 20, 2);
499 let now = Instant::now();
500
501 for index in 0..20 {
502 limiter.check_at(&format!("k{index}"), now);
503 }
504
505 assert!(matches!(
506 limiter.check_at("k20", now),
507 Decision::Throttled(_)
508 ));
509 }
510
511 #[test]
512 fn an_address_is_accepted() {
513 assert_eq!(address(" 203.0.113.7 "), Some("203.0.113.7".to_owned()));
514 assert_eq!(address("2001:db8::1"), Some("2001:db8::1".to_owned()));
515 }
516
517 #[test]
518 fn a_hostile_header_value_is_rejected() {
519 assert_eq!(address(""), None);
520 assert_eq!(address("not an address"), None);
521 assert_eq!(address(&"9".repeat(65)), None);
522 }
523
524 #[test]
525 fn the_archive_limiter_allows_ten_downloads_a_minute_then_refuses() {
526 let limiter = ArchiveLimiter::default();
527 for _ in 0..ARCHIVE_PER_CLIENT {
528 assert!(matches!(limiter.0.check("a"), Decision::Allowed));
529 }
530 assert!(matches!(limiter.0.check("a"), Decision::Throttled(_)));
531 // Another client still has its own budget.
532 assert!(matches!(limiter.0.check("b"), Decision::Allowed));
533 }
534
535 #[test]
536 fn the_git_transport_gets_a_budget_a_clone_can_live_inside() {
537 // A `git clone` authenticates two or three times, so the sign-in limit of ten a
538 // minute would throttle the fourth clone in a minute. This is the check that the
539 // two budgets have not been quietly collapsed into one.
540 const { assert!(GIT_PER_CLIENT > PER_CLIENT * 4) };
541
542 let limiter = GitAuthLimiter::default();
543 let now = Instant::now();
544
545 for _ in 0..GIT_PER_CLIENT {
546 assert_eq!(limiter.0.check_at("a", now), Decision::Allowed);
547 }
548
549 assert!(matches!(
550 limiter.0.check_at("a", now),
551 Decision::Throttled(_)
552 ));
553 assert_eq!(
554 limiter.0.check_at("b", now),
555 Decision::Allowed,
556 "another client has its own budget"
557 );
558 }
559}